text
stringlengths 3
1.05M
|
---|
#Menor e Maior valor
a = int(input('Digite o 1º número. '))
b = int(input('Digite o 2º número. '))
c = int(input('Digite o 3º número. '))
d = int(input('Digite o 4º número. '))
e = int(input('Digite o 5º número. '))
menor = a
if b <= a and b <= c and b <= d and b <= e:
menor = b
if c <= a and c <= b and c <= d and c <= e:
menor =c
if d <= a and d <= b and d <= c and d <= e:
menor = d
if e <= a and e <= b and e <= c and e <= d:
menor = e
maior = a
if b >= a and b >= c and b >= d and b >= e:
maior = b
if c >= a and c >= b and c >= d and c >= e:
maior =c
if d >= a and d >= b and d >= c and d >= e:
maior = d
if e >= a and e >= b and e >= c and e >= d:
maior = e
print('O menor valor digitado é: {}'.format(menor))
print('O maior valor digitado é: {}'.format(maior))
|
#ifndef HERO_H_
#define HERO_H_
#include <vector>
#include "Defines.h"
#include "Structs.h"
class Hero {
public:
Hero() = delete;
Hero(const std::string &name,
const int maxMana,
const int baseManaRegenRate) {
_name = name;
_maxMana = maxMana;
_currMana = maxMana;
_manaRegenRate = baseManaRegenRate;
}
virtual ~Hero() = default;
virtual void castSpell(const SpellType spell) = 0;
virtual void regenerateMana() = 0;
virtual void generateSpells() = 0;
protected:
std::vector<Spell> _spells;
std::string _name;
int _maxMana;
int _currMana;
int _manaRegenRate;
};
#endif /* HERO_H_ */
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
__all__ = [
'ApiEndpointResponse',
'StorageAccountResponse',
]
@pulumi.output_type
class ApiEndpointResponse(dict):
"""
The properties for a Media Services REST API endpoint.
"""
def __init__(__self__, *,
endpoint: Optional[str] = None,
major_version: Optional[str] = None):
"""
The properties for a Media Services REST API endpoint.
:param str endpoint: The Media Services REST endpoint.
:param str major_version: The version of Media Services REST API.
"""
if endpoint is not None:
pulumi.set(__self__, "endpoint", endpoint)
if major_version is not None:
pulumi.set(__self__, "major_version", major_version)
@property
@pulumi.getter
def endpoint(self) -> Optional[str]:
"""
The Media Services REST endpoint.
"""
return pulumi.get(self, "endpoint")
@property
@pulumi.getter(name="majorVersion")
def major_version(self) -> Optional[str]:
"""
The version of Media Services REST API.
"""
return pulumi.get(self, "major_version")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class StorageAccountResponse(dict):
"""
The properties of a storage account associated with this resource.
"""
def __init__(__self__, *,
id: str,
is_primary: bool):
"""
The properties of a storage account associated with this resource.
:param str id: The id of the storage account resource. Media Services relies on tables and queues as well as blobs, so the primary storage account must be a Standard Storage account (either Microsoft.ClassicStorage or Microsoft.Storage). Blob only storage accounts can be added as secondary storage accounts (isPrimary false).
:param bool is_primary: Is this storage account resource the primary storage account for the Media Service resource. Blob only storage must set this to false.
"""
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "is_primary", is_primary)
@property
@pulumi.getter
def id(self) -> str:
"""
The id of the storage account resource. Media Services relies on tables and queues as well as blobs, so the primary storage account must be a Standard Storage account (either Microsoft.ClassicStorage or Microsoft.Storage). Blob only storage accounts can be added as secondary storage accounts (isPrimary false).
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="isPrimary")
def is_primary(self) -> bool:
"""
Is this storage account resource the primary storage account for the Media Service resource. Blob only storage must set this to false.
"""
return pulumi.get(self, "is_primary")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
|
/*
* Copyright (c) 2017 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#ifndef KERN_MONOTONIC_H
#define KERN_MONOTONIC_H
#include <stdbool.h>
#include <stdint.h>
#include <sys/cdefs.h>
__BEGIN_DECLS
extern bool mt_debug;
extern _Atomic uint64_t mt_pmis;
extern _Atomic uint64_t mt_retrograde;
void mt_fixed_counts(uint64_t *counts);
void mt_cur_thread_fixed_counts(uint64_t *counts);
void mt_cur_task_fixed_counts(uint64_t *counts);
uint64_t mt_cur_cpu_instrs(void);
uint64_t mt_cur_cpu_cycles(void);
uint64_t mt_cur_thread_instrs(void);
uint64_t mt_cur_thread_cycles(void);
__END_DECLS
#if MACH_KERNEL_PRIVATE
#include <kern/thread.h>
#include <kern/task.h>
#include <stdbool.h>
__BEGIN_DECLS
#if defined(__arm__) || defined(__arm64__)
#include <arm/cpu_data_internal.h>
#elif defined(__x86_64__)
#include <i386/cpu_data.h>
#else /* !defined(__arm__) && !defined(__arm64__) && !defined(__x86_64__) */
#error unsupported architecture
#endif /* !defined(__arm__) && !defined(__arm64__) && !defined(__x86_64__) */
void mt_update_fixed_counts(void);
void mt_update_task(task_t task, thread_t thread);
bool mt_update_thread(thread_t thread);
int mt_fixed_thread_counts(thread_t thread, uint64_t *counts_out);
int mt_fixed_task_counts(task_t task, uint64_t *counts_out);
/*
* Private API for the platform layers.
*/
/*
* Called once early in boot, before CPU initialization occurs (where
* `mt_cpu_up` is called).
*
* This allows monotonic to detect if the hardware supports performance counters
* and install the global PMI handler.
*/
void mt_early_init(void);
/*
* Called when a core is idling and exiting from idle.
*/
void mt_cpu_idle(cpu_data_t *cpu);
void mt_cpu_run(cpu_data_t *cpu);
/*
* Called when a core is shutting down or powering up.
*/
void mt_cpu_down(cpu_data_t *cpu);
void mt_cpu_up(cpu_data_t *cpu);
/*
* Called while single-threaded when the system is going to sleep.
*/
void mt_sleep(void);
/*
* Called on each CPU as the system is waking from sleep.
*/
void mt_wake_per_core(void);
#if __ARM_CLUSTER_COUNT__
/*
* Called when a cluster is initialized.
*/
void mt_cluster_init(void);
#endif /* __ARM_CLUSTER_COUNT__ */
/*
* "Up-call" to the Mach layer to update counters from a PMI.
*/
uint64_t mt_cpu_update_count(cpu_data_t *cpu, unsigned int ctr);
/*
* Private API for the scheduler.
*/
/*
* Called when a thread is switching off-core or expires its quantum.
*/
void mt_sched_update(thread_t thread);
/*
* Called when a thread is terminating to save its counters into the task. The
* task lock must be held and the thread should be removed from the task's
* thread list in that same critical section.
*/
void mt_terminate_update(task_t task, thread_t thread);
/*
* Private API for the performance controller callout.
*/
void mt_perfcontrol(uint64_t *instrs, uint64_t *cycles);
/*
* Private API for stackshot.
*/
void mt_stackshot_thread(thread_t thread, uint64_t *instrs, uint64_t *cycles);
void mt_stackshot_task(task_t task, uint64_t *instrs, uint64_t *cycles);
/*
* Private API for microstackshot.
*/
typedef void (*mt_pmi_fn)(bool user_mode, void *ctx);
int mt_microstackshot_start(unsigned int ctr, uint64_t period, mt_pmi_fn fn,
void *ctx);
int mt_microstackshot_stop(void);
__END_DECLS
#endif /* MACH_KERNEL_PRIVATE */
#endif /* !defined(KERN_MONOTONIC_H) */
|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for getting information about the server. """
import asyncio
from asyncio import create_subprocess_exec as asyncrunapp
from asyncio.subprocess import PIPE as asyncPIPE
from platform import python_version, uname
from shutil import which
from os import remove
from telethon import version
from telethon import __version__, version
import platform
import sys
import time
from datetime import datetime
import psutil
from userbot import ALIVE_LOGO, ALIVE_NAME, BOT_VER, CMD_HELP, StartTime, bot
from userbot.events import register
# ================= CONSTANT =================
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else uname().node
# ============================================
modules = CMD_HELP
async def get_readable_time(seconds: int) -> str:
count = 0
up_time = ""
time_list = []
time_suffix_list = ["s", "m", "h", "days"]
while count < 4:
count += 1
remainder, result = divmod(
seconds, 60) if count < 3 else divmod(
seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
seconds = int(remainder)
for x in range(len(time_list)):
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
up_time += time_list.pop() + ", "
time_list.reverse()
up_time += ":".join(time_list)
return up_time
@register(outgoing=True, pattern=r"^\.spc")
async def psu(event):
uname = platform.uname()
softw = "**System Information**\n"
softw += f"`System : {uname.system}`\n"
softw += f"`Release : {uname.release}`\n"
softw += f"`Version : {uname.version}`\n"
softw += f"`Machine : {uname.machine}`\n"
# Boot Time
boot_time_timestamp = psutil.boot_time()
bt = datetime.fromtimestamp(boot_time_timestamp)
softw += f"`Boot Time: {bt.day}/{bt.month}/{bt.year} {bt.hour}:{bt.minute}:{bt.second}`\n"
# CPU Cores
cpuu = "**CPU Info**\n"
cpuu += "`Physical cores : " + \
str(psutil.cpu_count(logical=False)) + "`\n"
cpuu += "`Total cores : " + \
str(psutil.cpu_count(logical=True)) + "`\n"
# CPU frequencies
cpufreq = psutil.cpu_freq()
cpuu += f"`Max Frequency : {cpufreq.max:.2f}Mhz`\n"
cpuu += f"`Min Frequency : {cpufreq.min:.2f}Mhz`\n"
cpuu += f"`Current Frequency: {cpufreq.current:.2f}Mhz`\n\n"
# CPU usage
cpuu += "**CPU Usage Per Core**\n"
for i, percentage in enumerate(psutil.cpu_percent(percpu=True)):
cpuu += f"`Core {i} : {percentage}%`\n"
cpuu += "**Total CPU Usage**\n"
cpuu += f"`All Core: {psutil.cpu_percent()}%`\n"
# RAM Usage
svmem = psutil.virtual_memory()
memm = "**Memory Usage**\n"
memm += f"`Total : {get_size(svmem.total)}`\n"
memm += f"`Available : {get_size(svmem.available)}`\n"
memm += f"`Used : {get_size(svmem.used)}`\n"
memm += f"`Percentage: {svmem.percent}%`\n"
# Bandwidth Usage
bw = "**Bandwith Usage**\n"
bw += f"`Upload : {get_size(psutil.net_io_counters().bytes_sent)}`\n"
bw += f"`Download: {get_size(psutil.net_io_counters().bytes_recv)}`\n"
help_string = f"{str(softw)}\n"
help_string += f"{str(cpuu)}\n"
help_string += f"{str(memm)}\n"
help_string += f"{str(bw)}\n"
help_string += "**Engine Info**\n"
help_string += f"`Python {sys.version}`\n"
help_string += f"`Telethon {__version__}`"
await event.edit(help_string)
def get_size(bytes, suffix="B"):
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor
@register(outgoing=True, pattern=r"^\.sysd$")
async def sysdetails(sysd):
if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"):
try:
fetch = await asyncrunapp(
"neofetch",
"--stdout",
stdout=asyncPIPE,
stderr=asyncPIPE,
)
stdout, stderr = await fetch.communicate()
result = str(stdout.decode().strip()) + \
str(stderr.decode().strip())
await sysd.edit("`" + result + "`")
except FileNotFoundError:
await sysd.edit("`Install neofetch first !!`")
@register(outgoing=True, pattern=r"^\.botver$")
async def bot_ver(event):
if event.text[0].isalpha() or event.text[0] in ("/", "#", "@", "!"):
return
if which("git") is not None:
ver = await asyncrunapp(
"git",
"describe",
"--all",
"--long",
stdout=asyncPIPE,
stderr=asyncPIPE,
)
stdout, stderr = await ver.communicate()
verout = str(stdout.decode().strip()) + str(stderr.decode().strip())
rev = await asyncrunapp(
"git",
"rev-list",
"--all",
"--count",
stdout=asyncPIPE,
stderr=asyncPIPE,
)
stdout, stderr = await rev.communicate()
revout = str(stdout.decode().strip()) + str(stderr.decode().strip())
await event.edit(
"`╭►▻►▻►▻►▻►▻►◄◅◄◅◄◅◄◅◄◅╮\n "
"` 🌀 Exor Version: \n "
f"{verout}"
"` \n"
" Revision: "
f"{revout}🇲🇨\n"
"╰►▻►▻►▻►▻►▻►◄◅◄◅◄◅◄◅◄◅╯ "
)
else:
await event.edit(
"Shame that you don't have git, you're running - 'v1.beta.4' anyway!"
)
@register(outgoing=True, pattern=r"^\.pip(?: |$)(.*)")
async def pipcheck(pip):
if pip.text[0].isalpha() or pip.text[0] in ("/", "#", "@", "!"):
return
pipmodule = pip.pattern_match.group(1)
if pipmodule:
await pip.edit("`Searching . . .`")
pipc = await asyncrunapp(
"pip3",
"search",
pipmodule,
stdout=asyncPIPE,
stderr=asyncPIPE,
)
stdout, stderr = await pipc.communicate()
pipout = str(stdout.decode().strip()) + str(stderr.decode().strip())
if pipout:
if len(pipout) > 4096:
await pip.edit("`Output too large, sending as file`")
file = open("output.txt", "w+")
file.write(pipout)
file.close()
await pip.client.send_file(
pip.chat_id,
"output.txt",
reply_to=pip.id,
)
remove("output.txt")
return
await pip.edit(
"**Query: **\n`"
f"pip3 search {pipmodule}"
"`\n**Result: **\n`"
f"{pipout}"
"`"
)
else:
await pip.edit(
"**Query: **\n`"
f"pip3 search {pipmodule}"
"`\n**Result: **\n`No Result Returned/False`"
)
else:
await pip.edit("`Use .help pip to see an example`")
@register(outgoing=True, pattern=r"^\.(?:alive|on)\s?(.)?")
async def amireallyalive(alive):
user = await bot.get_me()
await get_readable_time((time.time() - StartTime))
output = (
f"**┏▼━━━━━━━━━━━━━━━━━▼┓**\n"
f"•➣ **Name** : `{DEFAULTUSER}` \n"
f"•➣ **UserName** : @{user.username} \n"
f"•➣ **Telethon** : `Versi {version.__version__}` \n"
f"•➣ **Python** : `Versi {python_version()}` \n"
f"•➣ **Exor Versi** : `{BOT_VER}` \n"
f"•➣ **Module** : `{len(modules)}` \n\n"
f"•➣ [Bot_Sinick](t.me/Bot_Sinick) \n"
f"┗▲━━━━━━━━━━━━━━━━━▲┛")
if ALIVE_LOGO:
try:
logo = ALIVE_LOGO
await alive.delete()
msg = await bot.send_file(alive.chat_id, logo, caption=output)
await asyncio.sleep(200)
await msg.delete()
except BaseException:
await alive.edit(
output + "\n\n *`The provided logo is invalid."
"\nMake sure the link is directed to the logo picture`"
)
await asyncio.sleep(100)
await alive.delete()
else:
await alive.edit(output)
await asyncio.sleep(100)
await alive.delete()
@register(outgoing=True, pattern=r"^\.aliveu")
async def amireallyaliveuser(username):
message = username.text
output = ".aliveu [new user without brackets] nor can it be empty"
if message != ".aliveu" and message[7:8] == " ":
newuser = message[8:]
global DEFAULTUSER
DEFAULTUSER = newuser
output = "Successfully changed user to " + newuser + "!"
await username.edit("`" f"{output}" "`")
@register(outgoing=True, pattern=r"^\.resetalive$")
async def amireallyalivereset(ureset):
global DEFAULTUSER
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else uname().node
await ureset.edit("`" "Successfully reset user for alive!" "`")
CMD_HELP.update({
"system":
"`.sysd`\
\nUsage: Shows system information using neofetch.\
\n\n`.botver`\
\nUsage: Shows the userbot version.\
\n\n`.pip` <module(s)>\
\nUsage: Does a search of pip modules(s).\
\n\n`.start`\
\nUsage: Type .start to see whether your bot is working or not.\
\n\n`.aliveu` <text>\
\nUsage: Changes the 'user' in alive to the text you want.\
\n\n`.resetalive`\
\nUsage: Resets the user to default.\
\n\n`.db`\
\nUsage:Shows database related info.\
\n\n.`.spc`\
\nUsage:Show system specification."
})
|
from typing import Optional
from primefac import primefac
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.execution_engine import PandasExecutionEngine
from great_expectations.expectations.expectation import ColumnMapExpectation
from great_expectations.expectations.metrics import (
ColumnMapMetricProvider,
column_condition_partial,
)
# This method compares a string to the valid semiprime number
# Reference: https://rosettacode.org/wiki/Semiprime#Python
def is_valid_semiprime(num: str) -> bool:
try:
n = int(num)
d = primefac(n)
try:
return next(d) * next(d) == n
except StopIteration:
return False
except ValueError:
return False
# This class defines a Metric to support your Expectation.
# For most ColumnMapExpectations, the main business logic for calculation will live in this class.
class ColumnValuesToBeValidSemiprime(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_semiprime"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_semiprime(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
class ExpectColumnValuesToBeValidSemiprime(ColumnMapExpectation):
"""This Expectation validates data as conforming to the valid semiprime code."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_semiprime": [
"4",
"6",
"95",
"1679",
"297159",
],
"malformed_semiprime": [
"1",
"5",
"100",
"297160",
"This is not a valid semiprime number",
],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "well_formed_semiprime"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "malformed_semiprime"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_semiprime"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration]
) -> None:
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
None. Raises InvalidExpectationConfigurationError if the config is not validated successfully
"""
super().validate_configuration(configuration)
if configuration is None:
configuration = self.configuration
# # Check other things in configuration.kwargs and raise Exceptions if needed
# try:
# assert (
# ...
# ), "message"
# assert (
# ...
# ), "message"
# except AssertionError as e:
# raise InvalidExpectationConfigurationError(str(e))
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental",
"tags": ["experimental", "hackathon", "typed-entities"],
"contributors": [
"@voidforall",
],
"requirements": ["primefac"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidSemiprime().print_diagnostic_checklist()
|
from tqdm import tqdm
import pickle
import os
import multiprocessing
from HMMs import *
from ._collect import collect_tag_stats, collect_word_freq, collect_possible_values
from utils import *
from framework import Sentence
class Estimator(object):
def __init__(self, sentences, tag_meta_info, n1, n, copy_indices, cfg):
"""
Given training data, consisting of anonymized sentences and output of
executable tags, Estimator will apply EM algorithm along with a simple HMMs
to optimize the joint probabilities.
:param list[Sentence] sentences: Corpus.
where 3 represents STR (a special token that represents proper nouns),
and 0 represents (another special token that represents numbers)
:param dict tag_meta_info: The output type of every tags
:param int n1: The size of unigram
:param int n: The size of vocabulary
:param list copy_indices: Special tokens. In the above example, 3 and 0.
:param str null_mode: Whether to add a special NULL tag. Used in HMMs class.
"""
null_mode = cfg.null_mode
self.cfg = cfg
# Convention: d is the # of examples
self.d = len(sentences)
# Convention: k is the maximum of word spans
self.k = cfg.k
self.copy_indices = copy_indices.copy()
# Convention: m is the number of states
self.m = len(tag_meta_info['all'])
# Training data
self.tag_meta_info = tag_meta_info.copy()
self.null_mode = null_mode
self.stats = collect_tag_stats(sentences, tag_meta_info, self.cfg)
self.possible_values = dict()
self.freq = collect_word_freq(sentences, n)
# Convention: n is the vocabulary size
self.n = n
self.n1 = n1
if cfg.null_ratio > 0:
pr = PosteriorRegularization(self.m, self.null_mode, self.k, cfg)
else:
pr = None
self.param = dict()
self.loaded = True
if not self.load():
self.loaded = False
self.HMMs = HMMs(self.m, null_mode=null_mode, semi=self.k, pr=pr,
use_pr_in_decode=cfg.null_ratio > 0)
self._init_params()
self.emit_probability = list()
self.update_HMM = True
def _init_params(self):
"""
Initialize parameters for EM before the first epoch.
:return None: Nothing to return.
"""
self.param = [None for _ in range(self.m+1)]
if self.cfg.init == 'uniform':
word_density = np.ones(shape=(self.n, ), dtype=np.float64) / self.n
elif self.cfg.init == 'freq':
word_density = self.freq.copy()
else:
raise NotImplemented
# For continuous values.
for cont_idx in self.tag_meta_info['cont']:
self.param[cont_idx] = param_ = dict()
param_['mean'] = self.stats[cont_idx][0].repeat(self.n)
param_['variance'] = self.stats[cont_idx][1].repeat(self.n)
param_['category'] = word_density.copy()
param_['gross'] = self.stats[cont_idx].copy()
if self.cfg.cont_feature:
param_['pre'] = word_density.copy()
param_['nxt'] = word_density.copy()
# For discrete values
for disc_idx in self.tag_meta_info['disc']:
self.param[disc_idx] = np.outer(self.stats[disc_idx], word_density)
# For NULL tag
self.param[-1] = np.zeros(shape=(self.n, ), dtype=np.float64)
self.param[-1][:] = 1/self.n1
def _probability(self, sentences):
"""
Pre-calculate probabilities for training.
:param list[Sentence] sentences:
:return list: Probabilities.
"""
self.possible_values = collect_possible_values(sentences, self.tag_meta_info)
probability = [None for _ in range(self.m+1)]
# For continuous values
for cont_idx in self.tag_meta_info['cont']:
candidate = dict()
values = self.possible_values[cont_idx]
mu, sigma = self.param[cont_idx]['gross']
# Variables with affix _w belong to individual words
mu_w = self.param[cont_idx]['mean']
sigma_w = self.param[cont_idx]['variance']
nu_w = self.param[cont_idx]['category']
# Precalculate the emission scores for all possible values
for value in values:
# pr: shape [n]
pr = Gaussian(mu_w, sigma_w, value)
pr = pr * nu_w
# pr = pr / Gaussian(mu, sigma, value)
if self.cfg.normalized:
pr = normalize(pr)
if self.cfg.no_num:
pr[:] = 0.
candidate[value] = pr
pr[-1] = 0.0
probability[cont_idx] = candidate
# For discrete values
for disc_idx in self.tag_meta_info['disc']:
probability[disc_idx] = self.param[disc_idx].copy()
probability[disc_idx][:, -1] = 0
# For NULL tag
probability[-1] = self.param[-1].copy()
# Store it into emit_probability
self.emit_probability = probability
return probability
def _emission(self, sentence, method):
"""
Calculate the emission score of sentence.
:param Sentence sentence: Explained above.
:param str method: How to deal with multiple records?
:return np.ndarray: Emission scores.
Shape [s, k, m+1] (including NULL tag)
"""
# Convention: s is the length of the sentence
m, n, k, s = self.m, self.n, self.k, sentence.s
pr = self.emit_probability
if method == 'ave':
multiple = np.average
elif method == 'max':
multiple = np.max
elif method == 'sum':
multiple = np.sum
else:
raise Exception
emit = np.zeros(shape=(s, k, self.m+1), dtype=np.float64)
for word_idx in range(s):
single_word = sentence.mat[word_idx, 0]
if single_word in self.copy_indices:
emit[word_idx, 0, sentence.matches[word_idx]] = 1.0
if self.cfg.cont_feature and isinstance(sentence.slot[word_idx], int):
pre_word = nxt_word = -1
if word_idx > 0:
pre_word = sentence.mat[word_idx-1, 0]
if word_idx < s-1:
nxt_word = sentence.mat[word_idx+1, 0]
for m_idx in self.tag_meta_info['cont']:
additional = self.param[m_idx]['pre'][pre_word] \
* self.param[m_idx]['nxt'][nxt_word]
emit[word_idx, 0, m_idx] *= additional
else:
token_indices = sentence.mat[word_idx]
for tag_idx in self.tag_meta_info['emit']:
values = sentence.tag[tag_idx]
values = [pr[tag_idx][value][token_indices] for value in values]
if len(values) == 0:
continue
probabilities = multiple(values, axis=0)
emit[word_idx, :, tag_idx] = probabilities
if single_word not in special_indices:
emit[word_idx, 0, -1] = pr[-1][single_word]
else:
any_matched = emit[word_idx, 0, :].sum()
if any_matched == 0:
emit[word_idx, 0, -1] = 1e-4
return emit
def _blank_counter(self):
"""
Initialize a blank counter for every epoch.
:return list: Counter.
"""
m = self.m
counter = [np.zeros(0) for _ in range(m)]
for cont_idx in self.tag_meta_info['cont']:
counter[cont_idx] = curr_counter = dict()
curr_counter['center'] = dict()
for value in self.possible_values[cont_idx]:
curr_counter['center'][value] = np.zeros(shape=(self.n,), dtype=np.float64)
if self.cfg.cont_feature:
curr_counter['pre'] = np.zeros(shape=(self.n,), dtype=np.float64)
curr_counter['nxt'] = np.zeros(shape=(self.n,), dtype=np.float64)
for disc_idx in self.tag_meta_info['disc']:
counter[disc_idx] = dict()
counter[disc_idx]['center'] = np.zeros_like(self.param[disc_idx], dtype=np.float64)
# For NULL tag
null_counter = np.zeros(shape=(self.n,), dtype=np.float64)
counter.append(null_counter)
return counter
def _merge_counter(self, counters):
big_counter = self._blank_counter()
for counter in counters:
for cont_idx in self.tag_meta_info['cont']:
for value in self.possible_values[cont_idx]:
big_counter[cont_idx]['center'][value] += counter[cont_idx]['center'][value]
if self.cfg.cont_feature:
big_counter[cont_idx]['pre'] += counter[cont_idx]['pre']
big_counter[cont_idx]['nxt'] += counter[cont_idx]['nxt']
for disc_idx in self.tag_meta_info['disc']:
big_counter[disc_idx]['center'] += counter[disc_idx]['center']
big_counter[self.m] += counter[self.m]
return big_counter
def _update_param(self, counter):
"""
Update emission parameters according to soft counts.
:param list counter: Soft counter.
:return None: Nothing to return.
"""
for cont_idx in self.tag_meta_info['cont']:
param_ = self.param[cont_idx]
counter_ = counter[cont_idx]['center']
if len(counter_) == 0:
continue
param_['mean'], param_['variance'] = weighted_mean_std(counter_)
word_cnt = np.sum(list(counter_.values()), axis=0)
param_['category'] = normalize(word_cnt)
for value in counter_:
counter_[value] = counter_[value].sum()
if self.cfg.cont_feature:
counter[cont_idx]['pre'][-1] = 0
counter[cont_idx]['nxt'][-1] = 0
param_['pre'] = normalize(counter[cont_idx]['pre'])
param_['nxt'] = normalize(counter[cont_idx]['nxt'])
param_['pre'][-1] = 1/self.n
param_['nxt'][-1] = 1/self.n
# param_['gross'] = weighted_mean_variance(counter_)
self._adjust_variance()
for disc_idx in self.tag_meta_info['disc']:
if counter[disc_idx]['center'].sum() == 0:
continue
self.param[disc_idx] = normalize(counter[disc_idx]['center'])
# For NULL tag
m = self.m
self.param[m] = counter[m] / counter[m].sum()
def _adjust_variance(self):
"""
Set a lower bound on variance.
:rtype: None
"""
for m_idx in self.tag_meta_info['cont']:
param_ = self.param[m_idx]
variance_lower = param_['gross'][1] * self.cfg.lower_ratio
variances = param_['variance']
variances[variances < 1.0] = 1.0
@staticmethod
def _related_factors():
return [
'k',
'emit_epoch',
'trans_epoch',
'null_mode',
'word_freq',
'lower_ratio',
'null_ratio',
'optim_iter',
'no_num',
'debug',
'normalized',
'filter',
'no_delta_match',
'init',
'double_direction',
'cont_feature',
]
def _job(self, arg):
t_idx, sentences_, config_ = arg
self.cfg.copy_from(config_)
m, k = self.m, self.k
bar = None
if t_idx == 0:
bar = tqdm(total=len(sentences_))
emit_counter_ = self._blank_counter()
if self.update_HMM:
hmm_counter_ = self.HMMs.blank_counter()
else:
hmm_counter_ = None
for sentence_ in sentences_:
if t_idx == 0:
bar.update()
emit = self._emission(sentence_, self.cfg.train_method)
# soft_count: shape [s, k, m+1]
soft_count = \
self.HMMs.forward_backward(emit,
cnt=hmm_counter_,
sentence=sentence_,
)
for s_idx in range(sentence_.s):
for k_idx in range(k):
word_token = sentence_.mat[s_idx, k_idx]
# For ground tags
for m_idx in self.tag_meta_info['emit']:
values = sentence_.tag[m_idx]
n_value = len(values)
curr_cnt = soft_count[s_idx, k_idx, m_idx]
for value in values:
emit_counter_[m_idx]['center'][value][word_token] += curr_cnt / n_value
if m_idx in self.tag_meta_info['cont']\
and self.cfg.cont_feature\
and word_token == special_indices[0]\
and n_value > 0:
pre_word = nxt_word = -1
if s_idx > 0:
pre_word = sentence_.mat[s_idx-1, 0]
if s_idx < sentence_.s-1:
nxt_word = sentence_.mat[s_idx+1, 0]
emit_counter_[m_idx]['pre'][pre_word] += curr_cnt/n_value
emit_counter_[m_idx]['nxt'][nxt_word] += curr_cnt/n_value
# For NULL tag
emit_counter_[m][word_token] += soft_count[s_idx, k_idx, m]
if t_idx == 0:
bar.close()
return emit_counter_, hmm_counter_
def epoch(self, sentences, with_transition):
"""
An EM training epoch.
:param list[Sentence] sentences:
:param bool with_transition: Whether to train transition parameters.
:rtype: None
"""
self._probability(sentences)
self.update_HMM = with_transition
sentences = split_list(sentences, self.cfg.jobs)
args = list()
for t_idx, sentences_ in enumerate(sentences):
args.append([t_idx, sentences_, self.cfg])
with multiprocessing.Pool(processes=self.cfg.jobs) as pool:
cnt_ = pool.map(self._job, args)
emit_cnt = list()
hmms_cnt = list()
for emit_cnt_, hmms_cnt_ in cnt_:
emit_cnt.append(emit_cnt_)
hmms_cnt.append(hmms_cnt_)
emit_counter = self._merge_counter(emit_cnt)
self._update_param(emit_counter)
if with_transition:
self.HMMs.update_transition(hmms_cnt)
measure('An Epoch Is Finished!')
def decode(self, sentences):
"""
:param list[Sentence] sentences:
:rtype: None
"""
self._probability(sentences)
for sentence in sentences:
emit = self._emission(sentence, self.cfg.inference_method)
trace, max_score = self.HMMs.decode(emit, sentence)
sentence.pred = trace
def save(self):
file_name = self.cfg.file_name(*self._related_factors(), 'param')
file_name = self.cfg.cache(file_name)
with open(file_name, 'wb') as fp:
pickle.dump([self.param, self.HMMs], fp)
def load(self):
file_name = self.cfg.file_name(*self._related_factors(), 'param')
print(file_name)
file_name = self.cfg.cache(file_name)
if os.path.exists(file_name):
print('load param')
with open(file_name, 'rb') as fp:
self.param, self.HMMs = pickle.load(fp)
return True
else:
print('init param from scratch')
return False
def correlated(self, m_idx):
"""
:param int m_idx:
:rtype: list[int]
"""
if m_idx in self.tag_meta_info['cont']:
words = self.freq.copy()
for n_idx in range(self.n):
words[n_idx] = self.param[m_idx]['category'][n_idx]
ordered = np.argsort(words)
return ordered[::-1].tolist()
elif m_idx in self.tag_meta_info['disc']:
c = self.param[m_idx].shape[0]
words = np.outer(np.ones(shape=(c,)), self.freq)
words = self.param[m_idx] / words
ordered = np.argsort(words)[:, ::-1].tolist()
return ordered
|
import bs4
from bs4 import NavigableString
from selenium import webdriver
import sys
import time
import os
import traceback
import logging
import tempfile
import re
from selenium.common.exceptions import NoSuchElementException
import pr_settings
import gmail
logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO)
slot_container_with_date_regex = re.compile('^slot-container-(\d{4}-\d{2}-\d{2})$')
not_available_text = "No doorstep delivery windows are available".lower()
class HeartBeat:
def __init__(self, freq_in_secs):
self.freq_in_sec = freq_in_secs
self.starting = time.time()
def check(self):
elapsed = time.time() - self.starting
logging.info('elapsed sec : ' + str(elapsed))
if elapsed > self.freq_in_sec:
os.system('say "Program still alive"')
self.starting = time.time()
class Slot:
def __init__(self, dateStr, slots_open):
self.dateStr = dateStr
self.slotsOpen = slots_open
def __str__(self):
return "Slot[" + self.dateStr + (" HAS" if self.slotsOpen else " has NO") \
+ " open slots]"
def find_slot_from_slot_container_base(soup):
"""
:param bs: beautifulsoup object
:return:
"""
slot_container_root = soup.find(id="slot-container-root")
slots = []
for slot in slot_container_root.findAll('div', id=slot_container_with_date_regex):
dateStr = slot_container_with_date_regex.match(slot['id']).group(1)
unattended_container = slot.find('div', id="slot-container-UNATTENDED")
text = unattended_container.findAll(end_node)[0].text
logging.debug("Found text : " + text)
slotsOpen = False
if (text is not None and text.lower().find(not_available_text) >= 0):
slotsOpen = False
else:
slotsOpen = True
slots.append(Slot(dateStr, slotsOpen))
return slots
def alert(open_slots):
slots_str = "slots : " + str([str(s) for s in open_slots])
logging.info('SLOTS OPEN!')
os.system('say "Slots for delivery opened!"')
send_gmail(slots_str)
logging.info('email sent')
time.sleep(1400)
def saveToFile(folder, text):
f = open(folder + next(tempfile._get_candidate_names())+'.html', "a")
f.write(text)
f.close()
def send_gmail(body_text):
service = gmail.build_service()
# Call the Gmail API
msg = gmail.create_message(pr_settings.gmail_from, pr_settings.gmail_to, pr_settings.gmail_subject,
pr_settings.gmail_body+" "+body_text)
gmail.send_message(service, 'me', msg)
def check_slots_algo1(soup):
"""
:param soup: beautiful soup object representing the whole html
:return: True if has open slots. False otherwise.
"""
no_open_slots = True
try:
slots = find_slot_from_slot_container_base(soup)
logging.info("slots : " + str([str(s) for s in slots]))
open_slots = [sl for sl in slots if sl.slotsOpen]
if len(open_slots) == 0:
return False
else:
saveToFile(pr_settings.html_file_temp_folder, str(soup))
alert(open_slots)
return True
except NoSuchElementException as e:
traceback.print_exc(file=sys.stdout)
def end_node(tag):
"""
Args:
tag: html element.
Returns: True if tag is a span and contains text and no other tags inside.
"""
if tag.name not in ["span"]:
return False
if isinstance(tag, NavigableString): # if str return
return False
if not tag.text: # if no text return false
return False
elif len(tag.find_all(text=False)) > 0: # no other tags inside other than text
return False
return True # if valid it reaches here
def getWFSlot(productUrl):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
}
driver = webdriver.Chrome(executable_path=pr_settings.chrome_webdriver_executable_path)
driver.get(productUrl)
html = driver.page_source
soup = bs4.BeautifulSoup(html, features="html.parser")
time.sleep(60)
has_open_slots = False
heart_beat = HeartBeat(600)
while not has_open_slots:
heart_beat.check()
driver.refresh()
logging.info("refreshed")
html = driver.page_source
# saveToFile(pr_settings.html_file_temp_folder,
# html)
soup = bs4.BeautifulSoup(html, features="html.parser")
has_open_slots = check_slots_algo1(soup)
if has_open_slots:
time.sleep(1400)
else :
time.sleep(3)
#
# try:
# open_slots = soup.find('div', class_='orderSlotExists');
# if open_slots is not None and open_slots.text() != "false":
# no_open_slots = False
# alert()
# else:
# logging.info('Ah! No open slots yet.')
# except AttributeError as e:
# traceback.print_exc(file=sys.stdout)
def main():
getWFSlot('https://www.amazon.com/gp/buy/shipoptionselect/handlers/display.html?hasWorkingJavascript=1')
if __name__ == '__main__':
main()
|
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
/** \file services/serialization/code/sd__resultCodesXMLMetadata.h
* \brief Macro definitions for XML deserialization validation error codes
*/
#ifndef SD__RESULTCODESXMLMETADATA_H
#define SD__RESULTCODESXMLMETADATA_H
#include "sd__resultCodesXML.h"
/* Internal error numbers which might occur for the XMLMetadata serializer */
#define SD_ERRNO_UNMATCHING_TYPE 200U
#define SD_MESSAGE_UNMATCHING_TYPE "Types do not match"
#endif /* SD__RESULTCODESXMLMETADATA_H */
|
import React from "react";
function DropdownHover() {
return (
<div className="dropdown dropdown-hover">
<div tabindex="0" className="m-1 btn">open on hover</div>
<ul className="shadow menu dropdown-content bg-base-100 rounded-box w-52">
<li>
<a>Item 1</a>
</li>
<li>
<a>Item 2</a>
</li>
<li>
<a>Item 3</a>
</li>
</ul>
</div>
);
}
export default DropdownHover; |
"""
Implementation of Spearman's Rho squared as a pairwise distance metric
Base on
http://www.plhyu.com/administrator/components/com_jresearch/files/publications/Mixtures_of_weighted_distance-based_models_for_ranking_data_with_applications_in_political_studies.pdf
TODO:
- add tests
"""
from sklearn.metrics import pairwise_distances as sklearn_pairwise_distances
import dask.array as da
from dask_ml.metrics.pairwise import pairwise_distances as dask_pairwise_distances
import numpy as np
from numba import jit
@jit
def spearman_squared_distance(a, b):
"""
Computes weighted Spearmans's Rho squared distance. Runs in O(n).
Numpy for efficiency.
Args:
a, b: 1D numpy arrays of normalized local attributions - e.g. np.sum(a) =1
Returns:
distance: float >= 0 - the distance between the two attributions
"""
order_penalty = (a - b) ** 2
weight = np.multiply(a, b)
distance = 1e4 * abs(np.sum(np.multiply(order_penalty, weight)))
return distance
def spearman_squared_distance_legacy(r_1, r_2):
"""
Computes a weighted Spearman's Rho squared distance. Runs in O(n)
Args:
r_1, r_2 (list): list of weighted rankings.
Index corresponds to an item and the value is the weight
Entries should be positive and sum to 1
Example: r_1 = [0.1, 0.2, 0.7]
Returns: float >= representing the distance between the rankings
"""
# confirm r_1 and r_2 have same lengths
if len(r_1) != len(r_2):
raise ValueError("rankings must contain the same number of elements")
distance = 0
for r_1_value, r_2_value in zip(r_1, r_2):
order_penalty = (r_1_value - r_2_value) ** 2
weight = r_1_value * r_2_value * 100 * 100
distance += weight * order_penalty
return distance
def pairwise_spearman_distance_matrix(rankings):
"""Returns Spearman Distances for the provided rankings
Args:
rankings (numpy.array, dask.array): Normalized Attributions
dask (boolean): whether or not to use dask's implementation
Returns:
[array[array]]: Spearman Distance Matrix
"""
if isinstance(rankings, da.Array):
D = dask_pairwise_distances(rankings, np.asarray(rankings), metric=spearman_squared_distance)
elif isinstance(rankings, np.ndarray):
D = sklearn_pairwise_distances(rankings, rankings, metric=spearman_squared_distance)
return D
def pairwise_spearman_distance_matrix_legacy(rankings):
"""
Computes a matrix of pairwise distance
Args:
rankings (list): each element is a list of weighted rankings (see ktau_weighted_distance)
Returns: matrix (list of lists) containing pairwise distances
"""
D = []
for r_1 in rankings:
row = []
for r_2 in rankings:
distance = spearman_squared_distance(r_1, r_2)
row.append(distance)
D.append(row)
return D
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = InitialValueTemplateError;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _fullscreen = _interopRequireDefault(require("part:@sanity/components/dialogs/fullscreen"));
var _content = _interopRequireDefault(require("part:@sanity/components/dialogs/content"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function InitialValueTemplateError(_ref) {
var errors = _ref.errors;
return /*#__PURE__*/_react.default.createElement(_fullscreen.default, {
color: "danger",
title: "Initial value template error",
isOpen: true,
centered: true
}, /*#__PURE__*/_react.default.createElement(_content.default, {
size: "medium",
padding: "none"
}, /*#__PURE__*/_react.default.createElement("p", null, "Failed to load initial value templates:"), errors.map((error, i) => /*#__PURE__*/_react.default.createElement("p", {
key: error.message
}, /*#__PURE__*/_react.default.createElement("code", null, error.message)))));
}
InitialValueTemplateError.propTypes = {
errors: _propTypes.default.arrayOf(_propTypes.default.shape({
message: _propTypes.default.string.isRequired
})).isRequired
}; |
from .sentence_pair_classifier import SentencePairClassifier |
# ---------------------------------------------------------------------------
# Pelion Device Management SDK
# (C) COPYRIGHT 2017 Arm Limited
#
# 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.
# --------------------------------------------------------------------------
"""Example: listing endpoints and filter them by type using Connect API."""
import datetime
from mbed_cloud import ConnectAPI
def _main():
api = ConnectAPI()
# Print devices that matches filter
filters = {
'created_at': {'$gte': datetime.datetime(2017, 1, 1),
'$lte': datetime.datetime(2017, 12, 31)
}
}
devices = api.list_connected_devices(order='asc', filters=filters)
for idx, device in enumerate(devices):
print(device)
if __name__ == "__main__":
_main()
|
jQuery(function ($) {
/*global Stripe*/
'use strict';
if (![].map) {
Array.prototype.map = function (fn) {
return $.map(this, fn);
};
}
/**
* Make the form friendly for credit card input
*/
var cardnumber = $('#cardnumber').payment('formatCardNumber').on('blur input', function () {
$(this).closest('span').toggleClass('valid', $.payment.validateCardNumber(this.value));
});
// Expiry is a single field, so we need to split it up to validate
var expiry = $('#expiry').payment('formatCardExpiry').on('blur input', function () {
var data = this.value.split('/').map(function (s) {
return s.trim();
});
$(this).closest('span').toggleClass('valid', $.payment.validateCardExpiry(data[0], data[1]));
});
// CVC
var cvc = $('#cvc').payment('formatCardCVC').on('blur input', function () {
var card = $.payment.cardType(cardnumber.val());
$(this).closest('span').toggleClass('valid', $.payment.validateCardCVC(this.value, card));
});
var email = $('#email').on('blur input', function () {
$(this).closest('span').toggleClass('valid', this.validity && this.validity.valid);
});
email.closest('span').toggleClass('valid', this.validity && this.validity.valid);
$('input[name=buyer_type]').on('change', function () {
var disabled = !(this.value === 'business' && this.checked);
$('.business').toggleClass('disabled', disabled).find(':input').prop('disabled', disabled);
}).trigger('change');
/**
* Automatically select the country based on the visitor's IP, and if they change
* the country and the country they select is in the EU, update the VAT prefix
*/
var eu = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI',
'FR', 'GB', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL',
'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
var countryEl = $('#country');
var vatEl = $('#vat');
var vatISOEl = $('#vatiso');
$.getJSON('https://country-finder.herokuapp.com/?callback=?', function (data) {
if (data.geo) {
countryEl.val(data.geo.country.toLowerCase()).trigger('change');
}
});
countryEl.on('change', function () {
var code = countryEl.val().toUpperCase();
vatEl.closest('div').toggleClass('disabled', eu.indexOf(code) === -1);
if (eu.indexOf(code) !== -1) {
vatISOEl.html(code);
} else {
vatISOEl.html('');
}
});
var price = { yearly: {}, monthly: {}, discount: {} };
price.yearly.el = $('#price-yearly');
price.yearly.value = price.yearly.el.data('price') * 1;
price.monthly.el = $('#price-monthly');
price.monthly.value = price.monthly.el.data('price') * 1;
price.discount.el = $('#discount');
price.discount.value = price.discount.el.data('price') * 1;
var fx = {
USD: { rate: 0, symbol: '$' },
EUR: { rate: 0, symbol: '€' },
GBP: { rate: 1, symbol: '£' }
};
function updatePricesTo(ccy) {
var yearly = price.yearly.value * fx[ccy].rate;
var monthly = price.monthly.value * fx[ccy].rate;
if (ccy !== 'GBP') {
yearly = yearly | 0;
monthly = monthly | 0;
}
var discount = price.discount.value * fx[ccy].rate | 0;
price.yearly.el.html(fx[ccy].symbol + yearly);
price.monthly.el.html(fx[ccy].symbol + monthly);
price.discount.el.html(fx[ccy].symbol + discount);
}
var $ccynote = $('.ccy-note');
$.ajax({
url: 'https://api.fixer.io/latest?symbols=GBP,USD',
dataType: 'jsonp',
success: function (data) {
var rates = data.rates;
fx.EUR.rate = 1 / rates.GBP;
fx.USD.rate = fx.EUR.rate / (1 / rates.USD);
// every other day chose USD for pricing
var useUSD = (new Date()).getDay() % 2;
if (useUSD === 0) {
analytics.experiment('usd-pricing');
$('.ccy input[value=USD]').click();
}
},
});
$('.ccy input').change(function () {
var ccy = this.value;
if (ccy === 'GBP') {
$ccynote.prop('hidden', true);
} else {
$ccynote.prop('hidden', false);
}
updatePricesTo(ccy);
})
/**
* Validate the VAT registration number (which we'll also do on the server
* side) using a simple heroku app.
*/
$('#validateVat').on('click', function (event) {
event.preventDefault();
var vatNum = vatEl[0].value.replace(/\s/g, '');
var vat = countryEl.val().toLowerCase() + vatNum;
if (vatNum) {
vatEl.addClass('validating');
$.getJSON('https://taxtools.io/api/validate/' + vat, function (data) {
if (!data.verified) {
return setTimeout(function () {
console.log('API request failed, trying again');
$('#validateVat').click();
}, 3000);
}
if (data) {
if (data.valid) {
vatEl[0].className = 'valid';
} else {
vatEl[0].className = 'invalid';
}
} else {
console.log('cannot validate VAT');
vatEl[0].className = '';
}
vatEl.removeClass('validating');
});
} else {
vatEl[0].className = '';
}
});
/**
* Do the Stripe dance.
*/
$('#payment-form').submit(function () {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button#pay').prop('disabled', true);
var expiryData = expiry.val().split('/').map(function (s) {
return s.trim();
});
Stripe.card.createToken({
number: $('#cardnumber').val(),
cvc: $('#cvc').val(),
'exp_month': expiryData[0],
'exp_year': expiryData[1]
}, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').html('<b class="icon-info-circle"></b> ' + response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
}
});
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-02 19:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('copyandpay', '0014_auto_20171101_1921'),
]
operations = [
migrations.AddField(
model_name='transaction',
name='customer',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='customer_transaction', to='copyandpay.Customer'),
),
migrations.AlterField(
model_name='scheduledpayment',
name='status',
field=models.CharField(choices=[('new', 'new'), ('processing', 'processing'), ('success', 'success'), ('failed', 'failed'), ('pending', 'pending')], default='new', max_length=10),
),
]
|
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": {
"0": "AM",
"1": "PM"
},
"DAY": {
"0": "Sunday",
"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday"
},
"MONTH": {
"0": "January",
"1": "February",
"2": "March",
"3": "April",
"4": "May",
"5": "June",
"6": "July",
"7": "August",
"8": "September",
"9": "October",
"10": "November",
"11": "December"
},
"SHORTDAY": {
"0": "Sun",
"1": "Mon",
"2": "Tue",
"3": "Wed",
"4": "Thu",
"5": "Fri",
"6": "Sat"
},
"SHORTMONTH": {
"0": "Jan",
"1": "Feb",
"2": "Mar",
"3": "Apr",
"4": "May",
"5": "Jun",
"6": "Jul",
"7": "Aug",
"8": "Sep",
"9": "Oct",
"10": "Nov",
"11": "Dec"
},
"fullDate": "dd MMMM y",
"longDate": "dd MMMM y",
"medium": "dd-MMM-y HH:mm:ss",
"mediumDate": "dd-MMM-y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": {
"0": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
"1": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
}
},
"id": "en-bz",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : doio_test.py
@Time : 2020/11/3 11:37
@Author: Tao.Xu
@Email : [email protected]
"""
import os
import unittest
from storagetest.libs.log import log
from storagetest.pkgs.base import PkgBase, TestProfile
logger = log.get_logger()
cur_dir = os.path.dirname(os.path.realpath(__file__))
bin_path = os.path.join(cur_dir, 'bin')
class DoIO(PkgBase):
"""
Run Test with LTP tools:
1. iogen & doio
2. growfiles
IOGEN & DOIO
=============
This is a pair of programs that does basic I/O operations on a set of files.
The file offset, I/O length, I/O operation, and what open(2) flags are
selected randomly from a pre-defined or commandline given set. All data
written can be verified (this is the usual method).
rwtest is a shell script that is a wrapper of iogen and doio.
GROWFILES
=============
Growfiles will create and truncate files in gradual steps using write, and
lseek. All system calls are checked for proper returns. The writes or the
whole file content can be verified. It can cause disk fragmentation.
"""
def __init__(self, top_path):
super(DoIO, self).__init__(top_path)
self.test_path = os.path.join(top_path, "doio")
def iogen_doio_test_profile(self):
"""
Examples:
---------
# run forever: 8 process - using record locks
iogen -i 0 100000b:doio_1 | doio -av -n 8 -m 1000
# run forever: 8 process - using record locks
iogen -i 0 100000b:doio_2 | doio -akv -n 8 -m 1000
"""
iogen_bin = os.path.join(bin_path, 'iogen')
doio_bin = os.path.join(bin_path, 'doio')
test = TestProfile(
name="iogen01",
test_path=self.test_path,
bin_path=bin_path,
command="{0} -i 120s -s read,write 500b:{1}doio.f1.$$ 1000b:{1}doio.f2.$$ | {2} -akv -n 2".format(
iogen_bin, self.test_path, doio_bin),
fail_flag="Test failed",
)
return test
def rwtest_profiles(self):
"""
Return rwtest case list FYI:
https://github.com/linux-test-project/ltp/blob/master/runtest/fs
"""
rwtest_bin = os.path.join(bin_path, 'rwtest')
cmd_list = [
"{0} -N rwtest01 -c -q -i 60s -f sync 10%25000:{1}/rw-sync-$$",
"{0} -N rwtest02 -c -q -i 60s -f buffered 10%25000:{1}/rw-buffered-$$",
"{0} -N rwtest03 -c -q -i 60s -n 2 -f buffered -s mmread,mmwrite -m random -Dv 10%25000:{1}/mm-buff-$$",
"{0} -N rwtest04 -c -q -i 60s -n 2 -f sync -s mmread,mmwrite -m random -Dv 10%25000:{1}/mm-sync-$$",
"{0} -N rwtest05 -c -q -i 50 -T 64b 500b:{1}/rwtest01%f",
"{0} -N iogen01 -i 120s -s read,write -Da -Dv -n 2 500b:{1}/doio.f1.$$ 1000b:{1}/doio.f2.$$",
]
tests = []
for idx, cmd in enumerate(cmd_list):
test = TestProfile(
name="rwtest-"+str(idx+1),
test_path=self.test_path,
bin_path=bin_path,
command=cmd.format(rwtest_bin, self.test_path),
fail_flag="Test failed",
)
tests.append(test)
return tests
def growfiles_test_profiles(self):
"""
Return growfiles case list FYI:
https://github.com/linux-test-project/ltp/blob/master/runtest/fs
"""
growfiles_bin = os.path.join(bin_path, 'growfiles')
cmd_list = [
"{0} -W gf01 -b -e 1 -u -i 0 -L 20 -w -C 1 -l -I r -T 10 -f glseek20 -S 2 -d {1}"
"{0} -W gf02 -b -e 1 -L 10 -i 100 -I p -S 2 -u -f gf03_ -d {1}"
"{0} -W gf03 -b -e 1 -g 1 -i 1 -S 150 -u -f gf05_ -d {1}"
"{0} -W gf04 -b -e 1 -g 4090 -i 500 -t 39000 -u -f gf06_ -d {1}"
"{0} -W gf05 -b -e 1 -g 5000 -i 500 -t 49900 -T10 -c9 -I p -u -f gf07_ -d {1}"
"{0} -W gf06 -b -e 1 -u -r 1-5000 -R 0--1 -i 0 -L 30 -C 1 -f g_rand10 -S 2 -d {1}"
"{0} -W gf07 -b -e 1 -u -r 1-5000 -R 0--2 -i 0 -L 30 -C 1 -I p -f g_rand13 -S 2 -d {1}"
"{0} -W gf08 -b -e 1 -u -r 1-5000 -R 0--2 -i 0 -L 30 -C 1 -f g_rand11 -S 2 -d {1}"
"{0} -W gf09 -b -e 1 -u -r 1-5000 -R 0--1 -i 0 -L 30 -C 1 -I p -f g_rand12 -S 2 -d {1}"
"{0} -W gf10 -b -e 1 -u -r 1-5000 -i 0 -L 30 -C 1 -I l -f g_lio14 -S 2 -d {1}"
"{0} -W gf11 -b -e 1 -u -r 1-5000 -i 0 -L 30 -C 1 -I L -f g_lio15 -S 2 -d {1}"
"{0} -W gf12 -b -e 1 -u -i 0 -L 30 {1}"
"{0} -W gf13 -b -e 1 -u -i 0 -L 30 -I r -r 1-4096 {1}"
"{0} -W gf14 -b -e 1 -u -i 0 -L 20 -w -l -C 1 -T 10 -f glseek19 -S 2 -d {1}"
"{0} -W gf15 -b -e 1 -u -r 1-49600 -I r -u -i 0 -L 120 -f Lgfile1 -d {1}"
"{0} -W gf16 -b -e 1 -i 0 -L 120 -u -g 4090 -T 101 -t 408990 -l -C 10 -c 1000 -S 10 -f Lgf02_ -d {1}"
"{0} -W gf17 -b -e 1 -i 0 -L 120 -u -g 5000 -T 101 -t 499990 -l -C 10 -c 1000 -S 10 -f Lgf03_ -d {1}"
"{0} -W gf18 -b -e 1 -i 0 -L 120 -w -u -r 10-5000 -I r -l -S 2 -f Lgf04_ -d {1}"
"{0} -W gf19 -b -e 1 -g 5000 -i 500 -t 49900 -T10 -c9 -I p -o O_RDWR,O_CREAT,O_TRUNC -u -f gf08i_ -d {1}"
"{0} -W gf20 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -r 1-256000:512 -R 512-256000 -T 4 -f gfbigio-$$ -d {1}"
"{0} -W gf21 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -g 20480 -T 10 -t 20480 -f gf-bld-$$ -d {1}"
"{0} -W gf22 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -g 20480 -T 10 -t 20480 -f gf-bldf-$$ -d {1}"
"{0} -W gf23 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -r 512-64000:1024 -R 1-384000 -T 4 -f gf-inf-$$ -d {1}"
"{0} -W gf24 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -g 20480 -f gf-jbld-$$ -d {1}"
"{0} -W gf25 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -r 1024000-2048000:2048 -R 4095-2048000 -T 1 -f gf-large-gs-$$ -d {1}"
"{0} -W gf26 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -r 128-32768:128 -R 512-64000 -T 4 -f gfsmallio-$$ -d {1}"
"{0} -W gf27 -b -D 0 -w -g 8b -C 1 -b -i 1000 -u -f gfsparse-1-$$ -d {1}"
"{0} -W gf28 -b -D 0 -w -g 16b -C 1 -b -i 1000 -u -f gfsparse-2-$$ -d {1}"
"{0} -W gf29 -b -D 0 -r 1-4096 -R 0-33554432 -i 0 -L 60 -C 1 -u -f gfsparse-3-$$ -d {1}"
"{0} -W gf30 -D 0 -b -i 0 -L 60 -u -B 1000b -e 1 -o O_RDWR,O_CREAT,O_SYNC -g 20480 -T 10 -t 20480 -f gf-sync-$$ -d {1}"
]
tests = []
for idx, cmd in enumerate(cmd_list):
test = TestProfile(
name="gf_" + str(idx + 1),
desc="growfiles test-" + str(idx + 1),
test_path=self.test_path,
bin_path=bin_path,
command=cmd.format(growfiles_bin, self.test_path),
fail_flag="Test failed",
)
tests.append(test)
return tests
def rwtest(self):
self.test_path = os.path.join(self.top_path, "rwtest")
return self.run_tests(self.rwtest_profiles())
def growfiles(self):
self.test_path = os.path.join(self.top_path, "growfiles")
return self.run_tests(self.growfiles_test_profiles())
def iogen_doio(self):
self.test_path = os.path.join(self.top_path, "iogen_doio")
return self.run(self.iogen_doio_test_profile())
class UnitTestCase(unittest.TestCase):
def setUp(self) -> None:
self.doio = DoIO("/mnt/test")
def test_01(self):
self.doio.rwtest()
def test_02(self):
self.doio.growfiles()
def test_03(self):
self.doio.iogen_doio()
if __name__ == '__main__':
# unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(UnitTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
|
var globals_func =
[
[ "_", "globals_func.html", null ],
[ "a", "globals_func_a.html", null ],
[ "b", "globals_func_b.html", null ],
[ "c", "globals_func_c.html", null ],
[ "e", "globals_func_e.html", null ],
[ "f", "globals_func_f.html", null ],
[ "g", "globals_func_g.html", null ],
[ "i", "globals_func_i.html", null ],
[ "l", "globals_func_l.html", null ],
[ "r", "globals_func_r.html", null ],
[ "s", "globals_func_s.html", null ],
[ "t", "globals_func_t.html", null ],
[ "u", "globals_func_u.html", null ],
[ "w", "globals_func_w.html", null ]
]; |
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
$(() => {
if($('.scroll-to-top').length) {
window.addEventListener('scroll', function () {
if(document.getElementsByTagName('html')[0].scrollTop > 1000) {
document.querySelector('.scroll-to-top').style.display = 'flex';
} else {
document.querySelector('.scroll-to-top').style.display = 'none';
}
})
}
});
const swiper = new Swiper('.swiper-container', {
effect: 'coverflow',
loop: true,
grabCursor: true,
centeredSlides: true,
autoplay: {
delay: 5000,
disableOnInteraction: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
pagination: {
el: '.swiper-pagination',
dynamicBullets: true,
},
coverflowEffect: {
rotate: 50,
stretch: 0,
depth: 100,
modifier: 1,
slideShadows: true,
},
breakpoints: {
576: {
slidesPerView: 1,
spaceBetween: 20,
},
768: {
slidesPerView: 2,
spaceBetween: 40,
},
1024: {
slidesPerView: 2,
spaceBetween: 50,
},
}
});
|
// Rollup plugins.
import babel from 'rollup-plugin-babel'
import cjs from 'rollup-plugin-commonjs'
import globals from 'rollup-plugin-node-globals'
import replace from 'rollup-plugin-replace'
import resolve from 'rollup-plugin-node-resolve'
export default {
input: 'src/index.js',
output: {
file: 'build/app.js',
format: 'iife',
moduleName: 'foo'
},
plugins: [
babel({
babelrc: false,
exclude: 'node_modules/**',
presets: [ [ 'es2015', { modules: false } ], 'stage-0', 'react' ],
plugins: [ 'external-helpers' ]
}),
cjs({
exclude: 'node_modules/process-es6/**',
include: [
'node_modules/create-react-class/**',
'node_modules/fbjs/**',
'node_modules/object-assign/**',
'node_modules/react/**',
'node_modules/react-dom/**',
'node_modules/prop-types/**'
]
}),
globals(),
replace({ 'process.env.NODE_ENV': JSON.stringify('development') }),
resolve({
browser: true,
main: true
})
],
sourcemap: true
}
|
from cogent3.draw.drawable import Drawable
from cogent3.draw.letter import letter_stack
from cogent3.util.dict_array import DictArray
from cogent3.util.union_dict import UnionDict
__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2007-2021, The Cogent Project"
__credits__ = ["Gavin Huttley"]
__license__ = "BSD-3"
__version__ = "2021.5.7a"
__maintainer__ = "Gavin Huttley"
__email__ = "[email protected]"
__status__ = "Alpha"
def get_mi_char_heights(fa):
"""computes character heights from MI terms
Parameters
----------
counts : MotifCountsArray
Returns
-------
DictArray
"""
I = fa.information()
mit = I * fa.array.T
return fa.template.wrap(mit.T)
def get_base_logo_layout(axnum, xtick_fontsize, ytick_fontsize):
"""creates default plotly layout for drawing a sequence logo
Parameters
----------
axnum : int
axis number for plotly
xtick_fontsize, ytick_fontsize : int
font size for tick values
Returns
-------
UnionDict
"""
layout = UnionDict()
# set x and y range, set y ticks
axis_lines = dict(
mirror=True,
linewidth=1,
showgrid=False,
linecolor="black",
showline=True,
visible=True,
zeroline=False,
)
axis = "axis" if axnum == 1 else f"axis{axnum}"
xanchor = "x" if axnum == 1 else f"x{axnum}"
yanchor = "y" if axnum == 1 else f"y{axnum}"
layout[f"x{axis}"] = dict(
anchor=yanchor,
tickfont=dict(size=xtick_fontsize),
ticks="inside",
)
layout[f"y{axis}"] = dict(
tickfont=dict(size=ytick_fontsize),
title="Bits",
anchor=xanchor,
ticks="inside",
)
layout[f"x{axis}"] |= axis_lines
layout[f"y{axis}"] |= axis_lines
layout.template = "plotly_white"
return layout
def _char_hts_as_lists(data):
"""returns a [[(base, height), ..], ..]"""
# data is assumed row-oriented
result = []
for d in data:
try:
d = d.to_dict()
except AttributeError:
# assume it's just a dict
pass
if d:
d = list(d.items())
else:
d = None
result.append(d)
return result
_dna_colours = dict(A="green", T="red", C="blue", G="orange")
def get_logo(
char_heights,
axnum=1,
height=400,
width=800,
ylim=None,
ydomain=None,
colours=None,
layout=None,
):
"""
Parameters
----------
char_heights
a seris of [[(base, value), ..], ..] or series of dicts with [{letter1: value, letter2: value}, ...]
Dicts are coerced to list of lists. If values are < 0, the letter is inverted. Empty elements are ignored.
axnum : int
plotly axis number
height, width: int
figure dimensions in pixels
ylim : float
maximum y-value
ydomain
[start, end], specifies vertical positioning for this logo
colours : dict
dict mapping characters to colours. Defaults to custom 'dna' colours
typically used for DNA
layout : UnionDict
Customised base layout
Returns
-------
Drawable
"""
if isinstance(char_heights, DictArray) or isinstance(char_heights[0], dict):
char_heights = _char_hts_as_lists(char_heights)
colours = colours or _dna_colours
if layout is None:
layout = get_base_logo_layout(axnum, 12, 12)
stack_data = []
est_ylim = 0
for d in char_heights:
if not d:
stack_data.append(None)
continue
d = sorted(d, key=lambda x: x[1])
if ylim is None:
est_ylim = max(est_ylim, max([e[-1] for e in d]))
stack_data.append(d)
stacks = []
for index, stack in enumerate(stack_data):
if stack is None:
continue
middle, stack_shapes = letter_stack(stack, index - 0.5, 1, colours, axnum)
stacks += stack_shapes
layout["shapes"] = stacks
if ylim is None:
ylim = est_ylim * 1.05
yaxis = "yaxis" if axnum == 1 else f"yaxis{axnum}"
layout[yaxis]["range"] = [0, ylim]
if ydomain:
layout[yaxis]["domain"] = ydomain
return Drawable(layout=layout, height=height, width=width)
|
var Layout=function(){var o="layouts/layout5/img/",n="layouts/layout5/css/",e=App.getResponsiveBreakpoint("md"),a=function(){$(window).scrollTop()>60?$("body").addClass("page-on-scroll"):$("body").removeClass("page-on-scroll")},t=function(){var o=function(){var o=$(window).scrollTop();o>100?$(".go2top").show():$(".go2top").hide()};o(),navigator.userAgent.match(/iPhone|iPad|iPod/i)?$(window).bind("touchend touchcancel touchleave",function(n){o()}):$(window).scroll(function(){o()}),$(".go2top").click(function(o){o.preventDefault(),$("html, body").animate({scrollTop:0},600)})},i=function(){$(".page-header .navbar-nav > .dropdown-fw, .page-header .navbar-nav > .more-dropdown, .page-header .navbar-nav > .dropdown > .dropdown-menu > .dropdown").click(function(o){if(App.getViewPort().width>e){if($(this).hasClass("more-dropdown")||$(this).hasClass("more-dropdown-sub"))return;o.stopPropagation()}else o.stopPropagation();var n=$(this).parent().find("> .dropdown");if(App.getViewPort().width<e)$(this).hasClass("open")?n.removeClass("open"):(n.removeClass("open"),$(this).addClass("open"),App.scrollTo($(this)));else{if($(this).hasClass("more-dropdown"))return;n.removeClass("open"),$(this).addClass("open"),App.scrollTo($(this))}}),$(".page-header .navbar-nav .more-dropdown-sub .dropdown-menu, .page-header .navbar-nav .dropdown-sub .dropdown-menu").click(function(){})},r=function(){var o=App.getViewPort().width,n=$(".page-header .navbar-nav");o>=e&&"desktop"!==n.data("breakpoint")?(n.data("breakpoint","desktop"),$('[data-hover="extended-dropdown"]',n).not(".hover-initialized").each(function(){$(this).dropdownHover(),$(this).addClass("hover-initialized")})):e>o&&"mobile"!==n.data("breakpoint")&&(n.data("breakpoint","mobile"),$('[data-hover="extended-dropdown"].hover-initialized',n).each(function(){$(this).unbind("hover"),$(this).parent().unbind("hover").find(".dropdown-submenu").each(function(){$(this).unbind("hover")}),$(this).removeClass("hover-initialized")}))};return{init:function(){t(),a(),i(),r(),App.addResizeHandler(r),$(window).scroll(function(){a()})},getLayoutImgPath:function(){return App.getAssetsPath()+o},getLayoutCssPath:function(){return App.getAssetsPath()+n}}}();jQuery(document).ready(function(){Layout.init()}); |
//Back End
// TILE OBJECT
function Tile() {
this.piece = "";
}
// GAME BOARD OBJECT
function Board() {
this.tilesArr = [];
this.playerTurn = -1;
}
// Master WINNER checking function
Board.prototype.winnerChickenDinner = function(tileIndex) {
var winningPlayer = "";
winningPlayer = this.checkHoriz(tileIndex, winningPlayer);
winningPlayer = this.checkVert(tileIndex, winningPlayer);
winningPlayer = this.checkDiagonAlley(tileIndex, winningPlayer);
return winningPlayer;
}
// check HORIZONTALLY for winner
Board.prototype.checkHoriz = function(tmpIndex, winningPlayerH) {
var tmpPiece = this.tilesArr[tmpIndex].piece;
if ((this.tilesArr[0].piece === tmpPiece) && (this.tilesArr[1].piece === tmpPiece) && (this.tilesArr[2].piece === tmpPiece)) {
winningPlayerH = this.tilesArr[tmpIndex].piece;
} else if ((this.tilesArr[3].piece === tmpPiece) && (this.tilesArr[4].piece === tmpPiece) && (this.tilesArr[5].piece === tmpPiece)) {
winningPlayerH = this.tilesArr[tmpIndex].piece;
} else if ((this.tilesArr[6].piece === tmpPiece) && (this.tilesArr[7].piece === tmpPiece) && (this.tilesArr[8].piece === tmpPiece)) {
winningPlayerH = this.tilesArr[tmpIndex].piece;
} else {
console.log("soy un perdedor");
}
return winningPlayerH;
}
// check VERTICALLY for winner
Board.prototype.checkVert = function (tmpIndex, winningPlayerV) {
var tmpPiece = this.tilesArr[tmpIndex].piece;
if ((this.tilesArr[0].piece === tmpPiece) && (this.tilesArr[3].piece === tmpPiece) && (this.tilesArr[6].piece === tmpPiece)) {
winningPlayerV = this.tilesArr[tmpIndex].piece;
} else if ((this.tilesArr[1].piece === tmpPiece) && (this.tilesArr[4].piece === tmpPiece) && (this.tilesArr[7].piece === tmpPiece)) {
winningPlayerV = this.tilesArr[tmpIndex].piece;
} else if ((this.tilesArr[2].piece === tmpPiece) && (this.tilesArr[5].piece === tmpPiece) && (this.tilesArr[8].piece === tmpPiece)) {
winningPlayerV = this.tilesArr[tmpIndex].piece;
} else {
console.log("soy un perdedor");
}
return winningPlayerV;
}
// check DIAGON_ALLEY for winner
Board.prototype.checkDiagonAlley = function (tmpIndex, winningPlayerD) {
var tmpPiece = this.tilesArr[tmpIndex].piece;
if ((this.tilesArr[0].piece === tmpPiece) && (this.tilesArr[4].piece === tmpPiece) && (this.tilesArr[8].piece === tmpPiece)) {
winningPlayerD = this.tilesArr[tmpIndex].piece;
} else if ((this.tilesArr[6].piece === tmpPiece) && (this.tilesArr[4].piece === tmpPiece) && (this.tilesArr[2].piece === tmpPiece)) {
winningPlayerD = this.tilesArr[tmpIndex].piece;
} else {
console.log("soy un perdedor");
}
return winningPlayerD;
}
// create board object and fill it with tile objects
var createBoard = function() {
var newBoard = new Board();
for (i = 0 ; i < 9 ; i++) {
let tmpTile = new Tile();
newBoard.tilesArr.push(tmpTile);
}
console.log(newBoard);
return newBoard;
}
// isMoveLegal? place piece on board, and store piece in tile object
var placePiece = function(tmpBoard , clickedIndex) {
let playerPiece = "";
if (isMoveLegal(tmpBoard.tilesArr[clickedIndex]) === true) {
tmpBoard.playerTurn *= -1;
if (tmpBoard.playerTurn === 1) {
playerPiece = "X"
tmpBoard.tilesArr[clickedIndex].piece = "X";
} else if (tmpBoard.playerTurn === -1) {
playerPiece = "O";
tmpBoard.tilesArr[clickedIndex].piece = "O";
} else {
console.log("W T H?!");
}
} else {
playerPiece = tmpBoard.tilesArr[clickedIndex].piece;
}
return playerPiece;
} // END placePiece function
// check if a move is legal
var isMoveLegal = function(tmpTile) {
var tmpBool;
if (tmpTile.piece === "") {
tmpBool = true;
} else {
tmpBool = false;
}
return tmpBool;
} // END isMoveLegal function
// tie checker
var isTie = function(tmpBoard1) {
var isNine = false;
var tmpCount = 0;
tmpBoard1.tilesArr.forEach(function(tmpTile) {
// console.log("tmpTile: " , tmpTile);
if (tmpTile.piece === "") {
tmpCount += 1;
};
});
if (tmpCount === 0) {
isNine = true;
} else {
isNine = false;
}
return isNine;
} // end tie checker
//Front End//
$(document).ready(function() {
// global
var myBoard = createBoard();
var firstPlayer;
var secondPlayer;
var counterMain;
// CLICK LETS PLAY
$("#btnPlay").click(function(){
firstPlayer = $("#player-one-name").val();
secondPlayer = $("#player-two-name").val();
$("#player-x").text(firstPlayer.toUpperCase());
$("#player-o").text(secondPlayer.toUpperCase());
$(".user-input").hide();
$(".players-labels").fadeIn(2000);
$(".center-board").fadeIn(1000);
$(".players-labels img").addClass("imgFlip");
});
// CLICK TILE
$("div .tile").click(function() {
let thisTileIndex = $(this).attr("value");
$(this).find("span").text(placePiece(myBoard , thisTileIndex));
// check for winner char
let finalWinner = myBoard.winnerChickenDinner(thisTileIndex);
// check for winner or tie
if ((isTie(myBoard) === true) && (finalWinner === "")) {
console.log("the game is a tie");
$(".players-labels").hide();
$(".center-board").hide();
$(".winner-area").show();
$(".winner-area h3").hide();
$("#player-winner").text("Game is a tie");
} else if ((finalWinner !== "") && (counterMain !== 9)) {
if (finalWinner === "X") {
finalWinner = firstPlayer;
} else if (finalWinner === "O") {
finalWinner = secondPlayer;
} else {
console.log("W T H?!");
}
$("#player-winner").text(finalWinner.toUpperCase());
$(".players-labels").hide();
$(".center-board").hide();
$(".winner-area").show();
}
// Update flipper
if (myBoard.playerTurn === -1) {
$(".players-labels img").addClass("imgFlip");
} else if (myBoard.playerTurn === 1) {
$(".players-labels img").removeClass("imgFlip");
} else {
console.log("W T H?!");
}
// Hilight selected tile
$(".tileCol .tile").removeClass("green-back");
$(".tileCol .tile").removeClass("white-back");
$(this).addClass("green-back");
});
$("#btnReset").click(function() {
location.reload();
});
});
|
import React, {Component} from 'react';
import {SectionList, View} from 'react-native';
import PropTypes from 'prop-types';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import styles from '../../styles/styles';
import * as PersonalDetails from '../../libs/actions/PersonalDetails';
import ONYXKEYS from '../../ONYXKEYS';
import * as OptionsListUtils from '../../libs/OptionsListUtils';
import Text from '../../components/Text';
import OptionRow from '../../components/OptionRow';
import TextInput from '../../components/TextInput';
import Navigation from '../../libs/Navigation/Navigation';
import ScreenWrapper from '../../components/ScreenWrapper';
import HeaderWithCloseButton from '../../components/HeaderWithCloseButton';
import compose from '../../libs/compose';
import withLocalize, {withLocalizePropTypes} from '../../components/withLocalize';
import CONST from '../../CONST';
import KeyboardAvoidingView from '../../components/KeyboardAvoidingView';
import Button from '../../components/Button';
import FixedFooter from '../../components/FixedFooter';
import * as IOU from '../../libs/actions/IOU';
/**
* IOU Currency selection for selecting currency
*/
const propTypes = {
// The personal details of the person who is logged in
myPersonalDetails: PropTypes.shape({
// Local Currency Code of the current user
localCurrencyCode: PropTypes.string,
}),
/** Holds data related to IOU */
iou: PropTypes.shape({
// Selected Currency Code of the current IOU
selectedCurrencyCode: PropTypes.string,
}),
// The currency list constant object from Onyx
currencyList: PropTypes.objectOf(PropTypes.shape({
// Symbol for the currency
symbol: PropTypes.string,
// Name of the currency
name: PropTypes.string,
// ISO4217 Code for the currency
ISO4217: PropTypes.string,
})),
...withLocalizePropTypes,
};
const defaultProps = {
myPersonalDetails: {
localCurrencyCode: CONST.CURRENCY.USD,
},
iou: {
selectedCurrencyCode: CONST.CURRENCY.USD,
},
currencyList: {},
};
class IOUCurrencySelection extends Component {
constructor(props) {
super(props);
const {currencyOptions} = OptionsListUtils.getCurrencyListForSections(this.getCurrencyOptions(this.props.currencyList),
'');
this.state = {
searchValue: '',
currencyData: currencyOptions,
toggledCurrencyCode: this.props.iou.selectedCurrencyCode || this.props.myPersonalDetails.localCurrencyCode,
};
this.getCurrencyOptions = this.getCurrencyOptions.bind(this);
this.toggleOption = this.toggleOption.bind(this);
this.getSections = this.getSections.bind(this);
this.confirmCurrencySelection = this.confirmCurrencySelection.bind(this);
this.changeSearchValue = this.changeSearchValue.bind(this);
}
componentDidMount() {
PersonalDetails.getCurrencyList();
}
/**
* Returns the sections needed for the OptionsSelector
*
* @param {Boolean} maxParticipantsReached
* @returns {Array}
*/
getSections() {
const sections = [];
sections.push({
title: this.props.translate('iOUCurrencySelection.allCurrencies'),
data: this.state.currencyData,
shouldShow: true,
indexOffset: 0,
});
return sections;
}
/**
*
* @returns {Object}
*/
getCurrencyOptions() {
const currencyListKeys = _.keys(this.props.currencyList);
const currencyOptions = _.map(currencyListKeys, currencyCode => ({
text: `${currencyCode} - ${this.props.currencyList[currencyCode].symbol}`,
searchText: `${currencyCode} ${this.props.currencyList[currencyCode].symbol}`,
currencyCode,
}));
return currencyOptions;
}
/**
* Function which toggles a currency in the list
*
* @param {String} toggledCurrencyCode
*
*/
toggleOption(toggledCurrencyCode) {
this.setState({toggledCurrencyCode});
}
/**
* Sets new search value
* @param {String} searchValue
* @return {void}
*/
changeSearchValue(searchValue) {
const {currencyOptions} = OptionsListUtils.getCurrencyListForSections(
this.getCurrencyOptions(this.props.currencyList),
searchValue,
);
this.setState({
searchValue,
currencyData: currencyOptions,
});
}
/**
* Confirms the selection of currency and sets values in Onyx
* @return {void}
*/
confirmCurrencySelection() {
IOU.setIOUSelectedCurrency(this.state.toggledCurrencyCode);
Navigation.goBack();
}
render() {
return (
<ScreenWrapper onTransitionEnd={() => {
if (!this.textInput) {
return;
}
this.textInput.focus();
}}
>
<KeyboardAvoidingView>
<HeaderWithCloseButton
title={this.props.translate('iOUCurrencySelection.selectCurrency')}
onCloseButtonPress={() => Navigation.goBack()}
/>
<View style={[styles.flex1, styles.w100]}>
<View style={[styles.flex1]}>
<View style={[styles.ph5, styles.pv3]}>
<TextInput
ref={el => this.textInput = el}
value={this.state.searchValue}
onChangeText={this.changeSearchValue}
placeholder={this.props.translate('common.search')}
/>
</View>
<View style={[styles.flex1]}>
<SectionList
indicatorStyle="white"
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
sections={this.getSections()}
keyExtractor={option => option.currencyCode}
stickySectionHeadersEnabled={false}
renderItem={({item, key}) => (
<OptionRow
key={key}
mode="compact"
hoverStyle={styles.hoveredComponentBG}
option={item}
onSelectRow={() => this.toggleOption(item.currencyCode)}
isSelected={
item.currencyCode === this.state.toggledCurrencyCode
}
showSelectedState
hideAdditionalOptionStates
/>
)}
renderSectionHeader={({section: {title}}) => (
<View>
{this.state.currencyData.length === 0 ? (
<Text style={[styles.ph5, styles.textLabel, styles.colorMuted]}>
{this.props.translate('common.noResultsFound')}
</Text>
) : (
<Text style={[styles.p5, styles.textMicroBold, styles.colorHeading]}>
{title}
</Text>
)}
</View>
)}
/>
</View>
</View>
</View>
<FixedFooter>
<Button
success
isDisabled={!this.props.iou.selectedCurrencyCode}
style={[styles.w100]}
text={this.props.translate('iou.confirm')}
onPress={this.confirmCurrencySelection}
/>
</FixedFooter>
</KeyboardAvoidingView>
</ScreenWrapper>
);
}
}
IOUCurrencySelection.propTypes = propTypes;
IOUCurrencySelection.defaultProps = defaultProps;
export default compose(
withLocalize,
withOnyx({
currencyList: {key: ONYXKEYS.CURRENCY_LIST},
myPersonalDetails: {key: ONYXKEYS.MY_PERSONAL_DETAILS},
iou: {key: ONYXKEYS.IOU},
}),
)(IOUCurrencySelection);
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
import os
import sys
sys.path.insert(0, os.getcwd() + "/..")
import numpy as np
from scipy import cluster
from easyai.data_loader.det.detection_dataset_process import DetectionDataSetProcess
from easyai.data_loader.det.detection_sample import DetectionSample
from easyai.helper import XMLProcess
from easyai.helper import ImageProcess
from easyai.config.task import detect2d_config
class CreateDetectionAnchors():
def __init__(self, train_path):
self.xmlProcess = XMLProcess()
self.image_process = ImageProcess()
self.detection_sample = DetectionSample(train_path,
detect2d_config.className)
self.detection_sample.read_sample()
self.dataset_process = DetectionDataSetProcess()
def get_anchors(self, number):
wh_numpy = self.get_width_height()
# Kmeans calculation
k = cluster.vq.kmeans(wh_numpy, number)[0]
k = k[np.argsort(k.prod(1))] # sort small to large
# Measure IoUs
iou = np.stack([self.compute_iou(wh_numpy, x) for x in k], 0)
biou = iou.max(0)[0] # closest anchor IoU
print('Best possible recall: %.3f' % (biou > 0.2635).float().mean()) # BPR (best possible recall)
# Print
print('kmeans anchors (n=%g, img_size=%g, IoU=%.2f/%.2f/%.2f-min/mean/best): ' %
(number, detect2d_config.imgSize, biou.min(), iou.mean(), biou.mean()), end='')
for i, x in enumerate(k):
print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n')
def get_width_height(self):
count = self.detection_sample.get_sample_count()
result = []
for index in range(count):
img_path, label_path = self.detection_sample.get_sample_path(index)
src_image, rgb_image = self.image_process.readRgbImage(img_path)
_, _, boxes = self.xmlProcess.parseRectData(label_path)
rgb_image, labels = self.dataset_process.resize_dataset(rgb_image,
detect2d_config.imgSize,
boxes,
detect2d_config.className)
temp = np.zeros((len(labels), 2), dtype=np.float32)
for index, object in enumerate(labels):
temp[index, :] = np.array([object.width(), object.height()])
result.append(temp)
return np.concatenate(result, axis=0)
def compute_iou(self, list_x, x2):
result = np.zeros((len(list_x), 1), dtype=np.float32)
for index, x1 in enumerate(list_x):
min_w = min(x1[0], x2[0])
min_h = min(x1[0], x2[1])
iou = (min_w * min_h) / (x1[0] * x1[1] + x2[0] * x2[1] - min_w * min_h)
result[index] = iou
return result
def test():
print("start...")
test = CreateDetectionAnchors("/home/lpj/github/data/Berkeley/ImageSets/train.txt")
test.get_anchors(9)
print("End of game, have a nice day!")
if __name__ == "__main__":
test()
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details.
//>>built
define({"themes/DashboardTheme/widgets/Header/nls/strings":{_widgetLabel:"Hlavi\u010dka",signin:"Prihl\u00e1si\u0165 sa",signout:"Odhl\u00e1si\u0165 sa",about:"Inform\u00e1cie",signInTo:"Prihl\u00e1si\u0165 sa do",cantSignOutTip:"T\u00e1to funkcia nie je k dispoz\u00edcii v re\u017eime n\u00e1h\u013eadu.",_localized:{}}}); |
import React from 'react';
import { StylesProvider, jssPreset } from '@material-ui/styles';
import { create } from 'jss';
import rtl from 'jss-rtl';
import { MainStyle } from '../css';
import PropTypes from 'prop-types';
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
function Main ({ open, children, flat }) {
const classes = MainStyle();
return (
<React.Fragment>
{
!flat
? (
<StylesProvider jss={jss}>
<main className={classes.content}>
<div className={classes.drawerHeader} />
{children}
</main>
</StylesProvider>
)
: (
<StylesProvider jss={jss}>
{children}
</StylesProvider>
)
}
</React.Fragment>
);
}
Main.propTypes = {
open: PropTypes.bool,
children: PropTypes.any,
flat: PropTypes.bool
}
export default Main;
|
// Modules
import { createContext } from 'react'
import PropTypes from 'prop-types'
// Data
import themeColorGroups from 'data/themeColorGroups'
// Hooks
import useBrowserStorage from 'hooks/useBrowserStorage'
// Variables
const currentThemeDefaultValue = {}
const CurrentThemeContext = createContext(currentThemeDefaultValue)
// PropTypes
const propTypes = { children: PropTypes.node }
const CurrentThemeProvider = ({ children }) => {
const [themeName, setThemeName] = useBrowserStorage('smwdColorThemeName', 'monochrome')
const [customTheme, setCustomTheme] = useBrowserStorage('smwdCustomTheme', { ...themeColorGroups.monochrome })
const [hasCustomTheme, setHasCustomTheme] = useBrowserStorage('smwdHasCustomTheme', false)
let theme
if (themeName === 'custom')
theme = customTheme
else
theme = themeColorGroups[themeName]
return (
<CurrentThemeContext.Provider
value={{
customTheme,
hasCustomTheme,
setCustomTheme,
setHasCustomTheme,
setThemeName,
theme,
themeName,
}}
>
{children}
</CurrentThemeContext.Provider>
)
}
CurrentThemeProvider.propTypes = propTypes
export {
CurrentThemeContext,
CurrentThemeProvider,
}
|
#!/usr/bin/python
#
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
from cfgm_common.vnc_cassandra import VncCassandraClient
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
class ICCassandraInfo():
def __init__(self, addr_info, user, password, use_ssl, ca_certs,
db_prefix, issu_info, keyspace_info, logger):
self.addr_info = addr_info
self.user = user
self.password = password
self.use_ssl = use_ssl
self.ca_certs = ca_certs
self.db_prefix = db_prefix
self.issu_info = issu_info
self.keyspace_info = keyspace_info
self.logger = logger
# end
class ICCassandraClient():
def _issu_basic_function(self, kspace, cfam, cols):
return dict(cols)
def __init__(self, oldversion_server_list, newversion_server_list,
old_user, old_password, new_user, new_password,
odb_use_ssl, odb_ca_certs, ndb_use_ssl, ndb_ca_certs,
odb_prefix, ndb_prefix,
issu_info, logger):
self._oldversion_server_list = oldversion_server_list
self._newversion_server_list = newversion_server_list
self._odb_prefix = odb_prefix
self._ndb_prefix = ndb_prefix
self._odb_use_ssl = odb_use_ssl
self._odb_ca_certs = odb_ca_certs
self._ndb_use_ssl = ndb_use_ssl
self._ndb_ca_certs = ndb_ca_certs
self._issu_info = issu_info
self._logger = logger
self._ks_issu_func_info = {}
self._nkeyspaces = {}
self._okeyspaces = {}
self._old_creds = None
if old_user and old_password:
self._old_creds = {
'username': old_user,
'password': old_password,
}
self._new_creds = None
if new_user and new_password:
self._new_creds = {
'username': new_user,
'password': new_password,
}
self._logger(
"Issu contrail cassandra initialized...",
level=SandeshLevel.SYS_INFO,
)
self.issu_prepare()
def issu_prepare(self):
self._logger(
"Issu contrail cassandra prepare...",
level=SandeshLevel.SYS_INFO,
)
for issu_func, ks, cflist in self._issu_info:
if issu_func is None:
issu_func = self._issu_basic_function
ks_issu_func_info = {ks: issu_func}
nks = {ks: cflist}
oks = {ks: cflist}
self._nkeyspaces.update(nks)
self._okeyspaces.update(oks)
self._ks_issu_func_info.update(ks_issu_func_info)
self._oldversion_handle = VncCassandraClient(
self._oldversion_server_list, db_prefix=self._odb_prefix,
ro_keyspaces=self._okeyspaces, logger=self._logger,
credential=self._old_creds,
ssl_enabled=self._odb_use_ssl,
ca_certs=self._odb_ca_certs)
self._newversion_handle = VncCassandraClient(
self._newversion_server_list, db_prefix=self._ndb_prefix,
rw_keyspaces=self._nkeyspaces, logger=self._logger,
credential=self._new_creds,
ssl_enabled=self._ndb_use_ssl,
ca_certs=self._ndb_ca_certs)
def _fetch_issu_func(self, ks):
return self._ks_issu_func_info[ks]
# Overwrite what is seen in the newer with the old version.
def _merge_overwrite(self, new, current):
updated = current
updated.update(new)
return updated
# For now this function should be called for only config_db_uuid.
# If we separate out config_db_uuid keyspace from VncCassandraClient,
# then we don't need to pass keyspaces here.
def issu_merge_copy(self, keyspaces):
for ks, cflist in keyspaces.items():
self._logger(
"Issu contrail cassandra merge copy, keyspace: " +
str(ks), level=SandeshLevel.SYS_INFO)
issu_funct = self._fetch_issu_func(ks)
for cf in cflist:
newversion_result = self._newversion_handle._cassandra_driver.get_range(cf) or {}
self._logger(
"Building New DB memory for columnfamily: " + str(cf),
level=SandeshLevel.SYS_INFO)
new_db = dict(newversion_result)
oldversion_result = self._oldversion_handle._cassandra_driver.get_range(cf) or {}
self._logger(
"Doing ISSU copy for columnfamily: " + str(cf),
level=SandeshLevel.SYS_INFO)
for rows, columns in oldversion_result:
out = issu_funct(ks, cf, columns)
current = new_db.pop(rows, None)
if current is not None:
updated = self._merge_overwrite(out, dict(current))
_ = self._newversion_handle.add(cf, rows, updated)
else:
updated = []
_ = self._newversion_handle.add(cf, rows, out)
diff = set(updated) - set(out)
_ = self._newversion_handle._cassandra_driver.get_cf(cf).remove(rows, diff)
self._logger(
"Pruning New DB if entires don't exist in old DB column "
"family: " + str(cf), level=SandeshLevel.SYS_INFO)
for item in new_db:
# TBD should be catch exception and fail ISSU
self._newversion_handle.delete(cf, item)
def issu_copy(self, keyspaces):
for ks, cflist in keyspaces.items():
issu_funct = self._fetch_issu_func(ks)
for cf in cflist:
self._logger(
"Issu Copy KeySpace: " + str(ks) +
" Column Family: " + str(cf), level=SandeshLevel.SYS_INFO)
oldversion_result = self._oldversion_handle._cassandra_driver.get_range(cf) or {}
for rows, columns in oldversion_result:
out = issu_funct(ks, cf, columns)
_ = self._newversion_handle.add(cf, rows, out)
# TBD If failure to add, fail ISSU
def issu_read_row(self, msg):
try:
(ok, result) = self._newversion_handle.object_read(
msg['type'], [msg['uuid']], field_names=['fq_name'])
except Exception as e:
self._logger(str(e), level=SandeshLevel.SYS_ERR)
return {}
return result[0]
def issu_sync_row(self, msg, cf):
if msg['oper'] == "CREATE":
self._logger(msg, level=SandeshLevel.SYS_INFO)
try:
self._newversion_handle.object_create(
msg['type'], msg['uuid'], msg['obj_dict'])
except Exception as e:
self._logger(str(e), level=SandeshLevel.SYS_ERR)
elif msg['oper'] == "UPDATE":
self._logger(msg, level=SandeshLevel.SYS_INFO)
uuid_list = []
uuid_list.append(msg['uuid'])
try:
bool1, current = self._newversion_handle.object_read(
msg['type'], uuid_list)
bool2, new = self._oldversion_handle.object_read(
msg['type'], uuid_list)
except Exception as e:
self._logger(str(e), level=SandeshLevel.SYS_ERR)
return
updated = self._merge_overwrite(
dict(new.pop()), dict(current.pop()))
# New object dictionary should be created, for now passing as is
try:
self._newversion_handle.object_update(
msg['type'], msg['uuid'], updated)
except Exception as e:
self._logger(str(e), level=SandeshLevel.SYS_ERR)
elif msg['oper'] == "DELETE":
self._logger(msg, level=SandeshLevel.SYS_INFO)
try:
self._newversion_handle.object_delete(
msg['type'], msg['uuid'])
except Exception as e:
self._logger(str(e), level=SandeshLevel.SYS_ERR)
return
# end
|
/*
* 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.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: [email protected]
*/
#ifndef __RESHAPE_PARAM_H__
#define __RESHAPE_PARAM_H__
typedef struct reshape_param
{
/*
int dim_0;
int dim_1;
int dim_2;
int dim_3;
int dim_size;
int axis;
*/
int* re_shape;
int reverse;
int is_mxnet;
int is_onnx;
int dim_size;
} reshape_param_t;
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Copyright (c) 2021 The VOLTNOTE developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_COMPRESSOR_H
#define BITCOIN_COMPRESSOR_H
#include "primitives/transaction.h"
#include "script/script.h"
#include "serialize.h"
class CKeyID;
class CPubKey;
class CScriptID;
/** Compact serializer for scripts.
*
* It detects common cases and encodes them much more efficiently.
* 3 special cases are defined:
* * Pay to pubkey hash (encoded as 21 bytes)
* * Pay to script hash (encoded as 21 bytes)
* * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
*
* Other scripts up to 121 bytes require 1 byte + script length. Above
* that, scripts up to 16505 bytes require 2 bytes + script length.
*/
class CScriptCompressor
{
private:
/**
* make this static for now (there are only 6 special scripts defined)
* this can potentially be extended together with a new nVersion for
* transactions, in which case this value becomes dependent on nVersion
* and nHeight of the enclosing transaction.
*/
static const unsigned int nSpecialScripts = 6;
CScript& script;
protected:
/**
* These check for scripts for which a special case with a shorter encoding is defined.
* They are implemented separately from the CScript test, as these test for exact byte
* sequence correspondences, and are more strict. For example, IsToPubKey also verifies
* whether the public key is valid (as invalid ones cannot be represented in compressed
* form).
*/
bool IsToKeyID(CKeyID& hash) const;
bool IsToScriptID(CScriptID& hash) const;
bool IsToPubKey(CPubKey& pubkey) const;
bool Compress(std::vector<unsigned char>& out) const;
unsigned int GetSpecialSize(unsigned int nSize) const;
bool Decompress(unsigned int nSize, const std::vector<unsigned char>& out);
public:
CScriptCompressor(CScript& scriptIn) : script(scriptIn) {}
template <typename Stream>
void Serialize(Stream& s) const
{
std::vector<unsigned char> compr;
if (Compress(compr)) {
s << CFlatData(compr);
return;
}
unsigned int nSize = script.size() + nSpecialScripts;
s << VARINT(nSize);
s << CFlatData(script);
}
template <typename Stream>
void Unserialize(Stream& s)
{
unsigned int nSize = 0;
s >> VARINT(nSize);
if (nSize < nSpecialScripts) {
std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
s >> REF(CFlatData(vch));
Decompress(nSize, vch);
return;
}
nSize -= nSpecialScripts;
if (nSize > MAX_SCRIPT_SIZE) {
// Overly long script, replace with a short invalid one
script << OP_RETURN;
s.ignore(nSize);
} else {
script.resize(nSize);
s >> REF(CFlatData(script));
}
}
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut& txout;
public:
static uint64_t CompressAmount(uint64_t nAmount);
static uint64_t DecompressAmount(uint64_t nAmount);
CTxOutCompressor(CTxOut& txoutIn) : txout(txoutIn) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
if (!ser_action.ForRead()) {
uint64_t nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));
} else {
uint64_t nVal = 0;
READWRITE(VARINT(nVal));
txout.nValue = DecompressAmount(nVal);
}
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
}
};
#endif // BITCOIN_COMPRESSOR_H
|
# coding=utf-8
# Copyright 2020 The Mesh TensorFlow 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.
# Lint as: python3
"""Tests for mesh_tensorflow.transformer.adaptive_softmax."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import mesh_tensorflow as mtf
from mesh_tensorflow.transformer import adaptive_softmax
import mock
import numpy as np
import scipy.special
import tensorflow.compat.v1 as tf
def initialize_by_shape(shape_to_value):
"""Create an initializer with values specified by tensor shape."""
def initialize(shape, dtype):
shape = tuple(shape)
if shape not in shape_to_value:
raise ValueError(
'Shape {} not found in shape to value map.'.format(shape))
return tf.reshape(
tf.constant(shape_to_value[tuple(shape)], dtype=dtype), shape)
return initialize
def _log_softmax(logits):
log_z = scipy.special.logsumexp(logits)
return logits - log_z
def _softmax_cross_entropy_with_logits(logits, target):
soft_target = np.zeros(len(logits))
soft_target[target] = 1
return -np.sum(_log_softmax(logits) * soft_target)
class AdaptiveSoftmaxTest(tf.test.TestCase):
def setUp(self):
super(AdaptiveSoftmaxTest, self).setUp()
self.graph = mtf.Graph()
self.mesh = mtf.Mesh(self.graph, 'mtf_mesh')
self.variable_dtype = mtf.VariableDType(activation_dtype=tf.float32)
self.addCleanup(mock.patch.stopall)
self.initializer_mock = mock.MagicMock()
random_normal_initializer_mock = mock.patch.object(
tf, 'random_normal_initializer').start()
random_normal_initializer_mock.return_value = self.initializer_mock
def _export_to_tf_tensor(self, mtf_tensor):
mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(
shape=[], layout={}, devices=[''])
lowering = mtf.Lowering(self.graph, {self.mesh: mesh_impl})
return lowering, lowering.export_to_tf_tensor(mtf_tensor)
def test_adaptive_softmax_loss_fn_tailClustersAllProject_correctlyComputesTheLoss(
self):
# Arrange.
seq_len = 16
vocab_size = 8
model_size = 2
vocab_dim = mtf.Dimension('vocab', vocab_size)
model_dim = mtf.Dimension('model', model_size)
length_dim = mtf.Dimension('length', seq_len)
decoder = mock.MagicMock()
decoder.z_loss = 0.0
decoder.loss_denominator = mock.MagicMock()
decoder.loss_denominator.return_value = 1.0
# 7 tokens in head cluster
# 5 tokens in tail cluster 1
# 4 tokens in tail cluster 2
targets_array = [2, 4, 4, 6, 2, 5, 7, 5, 2, 1, 6, 7, 0, 0, 3, 2]
targets = tf.constant(targets_array, dtype=tf.int32)
hidden = tf.constant(
[[0, -10], [1, -11], [2, -12], [3, -13], [4, -14], [5, -15], [6, -16],
[7, -17], [8, -18], [9, -19], [10, -20], [11, -21], [12, -22],
[13, -23], [14, -24], [15, -25]],
dtype=tf.float32)
mtf_targets = mtf.import_tf_tensor(
self.mesh, targets, shape=mtf.Shape([length_dim]))
mtf_hidden = mtf.import_tf_tensor(
self.mesh, hidden, shape=mtf.Shape([length_dim, model_dim]))
self.initializer_mock.side_effect = initialize_by_shape({
(5, 2): [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]],
(3, 2): [[11, 14], [12, 15], [13, 16]],
(2, 1): [[17, 18]],
(1, 2): [[19], [20]],
})
vocab_embedding = adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2
}, {
'token_count': 3,
'embedding_size': 2,
'length_projection_factor': 0.5,
}, {
'token_count': 2,
'embedding_size': 1,
'length_projection_factor': 0.125,
}])
context = mock.MagicMock()
context.activation_dtype = tf.float32
context.shared_params = {'embedding': vocab_embedding}
# Act.
mtf_loss = adaptive_softmax.adaptive_softmax_loss_fn(
decoder, context, mtf_hidden, mtf_targets, output_vocab_dim=None)
lowering, loss = self._export_to_tf_tensor(mtf_loss)
self.evaluate(tf.global_variables_initializer())
self.evaluate(lowering.copy_masters_to_slices())
actual_loss, = self.evaluate([loss])
# Assert.
def expected_head_loss(position, label):
factor = model_dim.size**-0.5
logits = [
factor * (1 * position - 6 * (10 + position)),
factor * (2 * position - 7 * (10 + position)),
factor * (3 * position - 8 * (10 + position)),
factor * (4 * position - 9 * (10 + position)),
factor * (5 * position - 10 * (10 + position)),
]
return _softmax_cross_entropy_with_logits(logits, label)
expected_head_labels = [2, 3, 3, 4, 2, 3, 4, 3, 2, 1, 4, 4, 0, 0, 3, 2]
expected_head_loss = sum(
expected_head_loss(position, expected_label)
for position, expected_label in enumerate(expected_head_labels)
if expected_label)
def expected_tail_cluster_1_loss(position):
factor = model_dim.size**-0.5
logits = [
factor * (11 * position - 14 * (10 + position)),
factor * (12 * position - 15 * (10 + position)),
factor * (13 * position - 16 * (10 + position)),
]
first_token_in_cluster_id = 3
return _softmax_cross_entropy_with_logits(
logits, targets_array[position] - first_token_in_cluster_id)
expected_tail_cluster_1_loss = sum([
expected_tail_cluster_1_loss(position=1),
expected_tail_cluster_1_loss(position=2),
expected_tail_cluster_1_loss(position=5),
expected_tail_cluster_1_loss(position=7),
expected_tail_cluster_1_loss(position=14),
])
def expected_tail_cluster_2_loss(position):
factor = model_dim.size**-0.5
logits = [
factor * (17 * 19 * position - 17 * 20 * (10 + position)),
factor * (18 * 19 * position - 18 * 20 * (10 + position)),
]
first_token_in_cluster_id = 6
return _softmax_cross_entropy_with_logits(
logits, targets_array[position] - first_token_in_cluster_id)
# Due to the length_projection_factor of 1/8, only 2 tokens will be counted
# despite there being 4 tokens in this cluster.
expected_tail_cluster_2_loss = sum([
expected_tail_cluster_2_loss(position=3),
expected_tail_cluster_2_loss(position=6),
])
expected_loss = (
expected_head_loss + expected_tail_cluster_1_loss +
expected_tail_cluster_2_loss)
self.assertAllClose(actual_loss, expected_loss)
def test_adaptive_softmax_loss_fn_tailClusterDoesNotProject_correctlyComputesTheLoss(
self):
# Arrange.
seq_len = 16
vocab_size = 8
model_size = 2
vocab_dim = mtf.Dimension('vocab', vocab_size)
model_dim = mtf.Dimension('model', model_size)
length_dim = mtf.Dimension('length', seq_len)
decoder = mock.MagicMock()
decoder.z_loss = 0.0
decoder.loss_denominator = mock.MagicMock()
decoder.loss_denominator.return_value = 1.0
# 7 tokens in head cluster
# 5 tokens in tail cluster 1
# 4 tokens in tail cluster 2
targets_array = [2, 4, 4, 6, 2, 5, 7, 5, 2, 1, 6, 7, 0, 0, 3, 2]
targets = tf.constant(targets_array, dtype=tf.int32)
hidden = tf.constant(
[[0, -10], [1, -11], [2, -12], [3, -13], [4, -14], [5, -15], [6, -16],
[7, -17], [8, -18], [9, -19], [10, -20], [11, -21], [12, -22],
[13, -23], [14, -24], [15, -25]],
dtype=tf.float32)
mtf_targets = mtf.import_tf_tensor(
self.mesh, targets, shape=mtf.Shape([length_dim]))
mtf_hidden = mtf.import_tf_tensor(
self.mesh, hidden, shape=mtf.Shape([length_dim, model_dim]))
self.initializer_mock.side_effect = initialize_by_shape({
(5, 2): [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]],
(3, 2): [[11, 14], [12, 15], [13, 16]],
(2, 1): [[17, 18]],
(1, 2): [[19], [20]],
})
vocab_embedding = adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2
}, {
'token_count': 3,
'embedding_size': 2,
'length_projection_factor': 0.5,
}, {
'token_count': 2,
'embedding_size': 1,
'length_projection_factor': 1,
}])
context = mock.MagicMock()
context.activation_dtype = tf.float32
context.shared_params = {'embedding': vocab_embedding}
# Act.
mtf_loss = adaptive_softmax.adaptive_softmax_loss_fn(
decoder, context, mtf_hidden, mtf_targets, output_vocab_dim=None)
lowering, loss = self._export_to_tf_tensor(mtf_loss)
self.evaluate(tf.global_variables_initializer())
self.evaluate(lowering.copy_masters_to_slices())
actual_loss, = self.evaluate([loss])
# Assert.
def expected_head_loss(position, label):
factor = model_dim.size**-0.5
logits = [
factor * (1 * position - 6 * (10 + position)),
factor * (2 * position - 7 * (10 + position)),
factor * (3 * position - 8 * (10 + position)),
factor * (4 * position - 9 * (10 + position)),
factor * (5 * position - 10 * (10 + position)),
]
return _softmax_cross_entropy_with_logits(logits, label)
expected_head_labels = [2, 3, 3, 4, 2, 3, 4, 3, 2, 1, 4, 4, 0, 0, 3, 2]
expected_head_loss = sum(
expected_head_loss(position, expected_label)
for position, expected_label in enumerate(expected_head_labels)
if expected_label)
def expected_tail_cluster_1_loss(position):
factor = model_dim.size**-0.5
logits = [
factor * (11 * position - 14 * (10 + position)),
factor * (12 * position - 15 * (10 + position)),
factor * (13 * position - 16 * (10 + position)),
]
first_token_in_cluster_id = 3
return _softmax_cross_entropy_with_logits(
logits, targets_array[position] - first_token_in_cluster_id)
expected_tail_cluster_1_loss = sum([
expected_tail_cluster_1_loss(position=1),
expected_tail_cluster_1_loss(position=2),
expected_tail_cluster_1_loss(position=5),
expected_tail_cluster_1_loss(position=7),
expected_tail_cluster_1_loss(position=14),
])
def expected_tail_cluster_2_loss(position):
factor = model_dim.size**-0.5
logits = [
factor * (17 * 19 * position - 17 * 20 * (10 + position)),
factor * (18 * 19 * position - 18 * 20 * (10 + position)),
]
first_token_in_cluster_id = 6
return _softmax_cross_entropy_with_logits(
logits, targets_array[position] - first_token_in_cluster_id)
expected_tail_cluster_2_loss = sum([
expected_tail_cluster_2_loss(position=3),
expected_tail_cluster_2_loss(position=6),
expected_tail_cluster_2_loss(position=10),
expected_tail_cluster_2_loss(position=11),
])
expected_loss = (
expected_head_loss + expected_tail_cluster_1_loss +
expected_tail_cluster_2_loss)
self.assertAllClose(actual_loss, expected_loss)
def test_hidden_to_logits_returnsHiddenDuringTraining(self):
# Arrange.
seq_len = 2
vocab_size = 3
model_size = 2
vocab_dim = mtf.Dimension('vocab', vocab_size)
model_dim = mtf.Dimension('model', model_size)
length_dim = mtf.Dimension('length', seq_len)
context = mock.MagicMock()
context.activation_dtype = tf.float32
context.mode = tf.estimator.ModeKeys.TRAIN
embeddings = tf.constant([[1, 0], [0, 2]], dtype=tf.float32)
mtf_embeddings = mtf.import_tf_tensor(
self.mesh, embeddings, shape=mtf.Shape([length_dim, model_dim]))
self.initializer_mock.side_effect = initialize_by_shape({
(3, 2): [[1, 6], [2, 7], [3, 8]],
})
vocab_embedding = adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2
}])
mtf_logits = vocab_embedding.hidden_to_logits(
mtf_embeddings, context=context)
self.assertEqual(mtf_logits, mtf_embeddings)
def test_hidden_to_logits_returnsCorrectLogitsDuringEval(self):
# Arrange.
seq_len = 2
vocab_size = 8
model_size = 2
vocab_dim = mtf.Dimension('vocab', vocab_size)
model_dim = mtf.Dimension('model', model_size)
length_dim = mtf.Dimension('length', seq_len)
context = mock.MagicMock()
context.activation_dtype = tf.float32
context.mode = tf.estimator.ModeKeys.EVAL
embeddings = tf.constant([[1, 0], [0, 2]], dtype=tf.float32)
mtf_embeddings = mtf.import_tf_tensor(
self.mesh, embeddings, shape=mtf.Shape([length_dim, model_dim]))
self.initializer_mock.side_effect = initialize_by_shape({
(5, 2): [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]],
(3, 2): [[11, 14], [12, 15], [13, 16]],
(2, 1): [[17, 18]],
(1, 2): [[19], [20]],
})
vocab_embedding = adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2
}, {
'token_count': 3,
'embedding_size': 2,
'length_projection_factor': 0.5,
}, {
'token_count': 2,
'embedding_size': 1,
'length_projection_factor': 0.125,
}])
# Act.
mtf_logits = vocab_embedding.hidden_to_logits(
mtf_embeddings, context=context)
lowering, logits = self._export_to_tf_tensor(mtf_logits)
self.evaluate(tf.global_variables_initializer())
self.evaluate(lowering.copy_masters_to_slices())
actual_logits, = self.evaluate([logits])
# Assert.
def scaled_log_softmax(a):
a = np.array(a, dtype=float) * model_dim.size**-0.5
return _log_softmax(a)
head_log_softmax1 = scaled_log_softmax([1, 2, 3, 4, 5])
head_log_softmax2 = scaled_log_softmax([2 * 6, 2 * 7, 2 * 8, 2 * 9, 2 * 10])
expected_logits = [
np.concatenate([
head_log_softmax1[:3],
head_log_softmax1[3] + scaled_log_softmax([11, 12, 13]),
head_log_softmax1[4] + scaled_log_softmax([17 * 19, 18 * 19]),
]),
np.concatenate([
head_log_softmax2[:3],
head_log_softmax2[3] + scaled_log_softmax([2 * 14, 2 * 15, 2 * 16]),
head_log_softmax2[4] +
scaled_log_softmax([2 * 17 * 20, 2 * 18 * 20]),
]),
]
self.assertAllClose(actual_logits, expected_logits, atol=5e-5)
def test_ids_to_embedding_correctlyEmbeds(self):
seq_len = 6
vocab_size = 5
model_size = 2
vocab_dim = mtf.Dimension('vocab', vocab_size)
model_dim = mtf.Dimension('model', model_size)
length_dim = mtf.Dimension('length', seq_len)
ids = tf.constant([0, 1, 2, 3, 4, 0], dtype=tf.int32)
mtf_ids = mtf.import_tf_tensor(
self.mesh, ids, shape=mtf.Shape([length_dim]))
self.initializer_mock.side_effect = initialize_by_shape({
(3, 2): [[0, 1], [2, 0], [-1000, -4000]],
(3, 1): [[1], [2], [3]],
(1, 2): [[1], [2]],
})
vocab_embedding = adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 2,
'embedding_size': 2
}, {
'token_count': 3,
'embedding_size': 1
}])
mtf_embedding = vocab_embedding.ids_to_embedding(mtf_ids, context=None)
mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(
shape=[], layout={}, devices=[''])
lowering = mtf.Lowering(self.graph, {self.mesh: mesh_impl})
actual_embedding = lowering.export_to_tf_tensor(mtf_embedding)
self.evaluate(tf.global_variables_initializer())
self.evaluate(lowering.copy_masters_to_slices())
actual, = self.evaluate([actual_embedding])
self.assertAllClose(actual,
[[0, 1], [2, 0], [1, 2], [2, 4], [3, 6], [0, 1]])
def test_constructor_tokenCountsDontSumToVocabSize_raisesValueError(self):
vocab_dim = mtf.Dimension('vocab', 5)
model_dim = mtf.Dimension('model', 2)
with self.assertRaises(ValueError):
adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2
}, {
'token_count': 3,
'embedding_size': 1
}])
def test_constructor_projectFactorNotWithinZeroAndOne_raisesValueError(self):
vocab_dim = mtf.Dimension('vocab', 3)
model_dim = mtf.Dimension('model', 2)
with self.assertRaises(ValueError):
adaptive_softmax.AdaptiveSoftmaxVocabEmbedding(
self.mesh,
vocab_dim,
output_dim=model_dim,
variable_dtype=self.variable_dtype,
name='embedding',
ensemble_dim=None,
clusters=[{
'token_count': 3,
'embedding_size': 2,
'length_projection_factor': 1.1,
}])
if __name__ == '__main__':
tf.test.main()
|
import { FacilityResource, FacilityDatasetResource } from 'kolibri.resources';
import { showFacilityConfigPage } from '../../src/modules/facilityConfig/handlers';
import { jestMockResource } from 'testUtils'; // eslint-disable-line
import makeStore from '../makeStore';
const FacilityStub = jestMockResource(FacilityResource);
const DatasetStub = jestMockResource(FacilityDatasetResource);
const fakeFacility = {
name: 'Nalanda Maths',
};
const fakeDatasets = [
{
id: 'dataset_2',
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: true,
},
// could return more than one dataset in theory
{ id: 'dataset_3' },
];
describe('facility config page actions', () => {
let store;
let commitStub;
beforeEach(() => {
store = makeStore();
commitStub = jest.spyOn(store, 'commit');
Object.assign(store.state.core, {
pageId: '123',
session: {
facility_id: 1,
},
});
FacilityResource.__resetMocks();
FacilityDatasetResource.__resetMocks();
});
describe('showFacilityConfigPage action', () => {
it('when resources load successfully', () => {
FacilityStub.__getModelFetchReturns(fakeFacility);
DatasetStub.__getCollectionFetchReturns(fakeDatasets);
const expectedState = {
facilityDatasetId: 'dataset_2',
facilityName: 'Nalanda Maths',
settings: expect.objectContaining({
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: true,
}),
settingsCopy: expect.objectContaining({
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: true,
}),
};
return showFacilityConfigPage(store).then(() => {
expect(DatasetStub.getCollection).toHaveBeenCalledWith({ facility_id: 1 });
expect(commitStub).toHaveBeenCalledWith(
'facilityConfig/SET_STATE',
expect.objectContaining(expectedState)
);
});
});
describe('error handling', () => {
const expectedState = {
facilityName: '',
settings: null,
notification: 'PAGELOAD_FAILURE',
};
it('when fetching Facility fails', () => {
FacilityStub.__getModelFetchReturns('incomprehensible error', true);
DatasetStub.__getCollectionFetchReturns(fakeDatasets);
return showFacilityConfigPage(store).then(() => {
expect(commitStub).toHaveBeenCalledWith(
'facilityConfig/SET_STATE',
expect.objectContaining(expectedState)
);
});
});
it('when fetching FacilityDataset fails', () => {
FacilityStub.__getModelFetchReturns(fakeFacility);
DatasetStub.__getCollectionFetchReturns('incomprehensible error', true);
return showFacilityConfigPage(store).then(() => {
expect(commitStub).toHaveBeenCalledWith(
'facilityConfig/SET_STATE',
expect.objectContaining(expectedState)
);
});
});
});
});
describe('saveFacilityConfig action', () => {
beforeEach(() => {
store.commit('facilityConfig/SET_STATE', {
facilityDatasetId: 1000,
settings: {
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: false,
},
});
});
it('when save is successful', () => {
const expectedRequest = {
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: false,
};
// IRL returns the updated Model
const saveStub = DatasetStub.__getModelSaveReturns('ok');
return store.dispatch('facilityConfig/saveFacilityConfig').then(() => {
expect(DatasetStub.getModel).toHaveBeenCalledWith(1000, {});
expect(saveStub).toHaveBeenCalledWith(expect.objectContaining(expectedRequest), false);
expect(store.state.facilityConfig.notification).toEqual('SAVE_SUCCESS');
});
});
it('when save fails', () => {
const saveStub = DatasetStub.__getModelSaveReturns('heck no', true);
return store.dispatch('facilityConfig/saveFacilityConfig').then(() => {
expect(saveStub).toHaveBeenCalled();
expect(store.state.facilityConfig.notification).toEqual('SAVE_FAILURE');
expect(store.state.facilityConfig.settings).toEqual({
learner_can_edit_name: true,
learner_can_edit_username: false,
learner_can_edit_password: true,
learner_can_delete_account: true,
learner_can_sign_up: false,
});
});
});
it('resetFacilityConfig action dispatches resets settings and makes a save request', () => {
const saveStub = DatasetStub.__getModelSaveReturns('ok default');
return store.dispatch('facilityConfig/resetFacilityConfig').then(() => {
expect(saveStub).toHaveBeenCalled();
expect(store.state.facilityConfig.settings).toEqual({
learner_can_edit_username: true,
learner_can_edit_name: true,
learner_can_edit_password: true,
learner_can_sign_up: true,
learner_can_delete_account: true,
learner_can_login_with_no_password: false,
show_download_button_in_learn: false,
});
});
});
});
});
|
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type : GUC
Case Name : 使用gs_guc set方法设置参数enable_sonic_hashagg为off,观察预期结果
Description :
1.查询enable_sonic_hashagg默认值
2.修改参数值为off并重启数据库
3.查询该参数修改后的值
4.恢复参数默认值
Expect :
1.显示默认值为on
2.修改成功
3.显示off
4.默认值恢复成功
History :
"""
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
LOG = Logger()
commonsh = CommonSH('dbuser')
class QueryPlan(unittest.TestCase):
def setUp(self):
self.constant = Constant()
LOG.info(
'------Opengauss_Function_Guc_Queryplan_Case0105start------')
def test_enable_sonic_hashagg(self):
LOG.info('--步骤1:查看默认值--')
sql_cmd = commonsh.execut_db_sql('show enable_sonic_hashagg;')
LOG.info(sql_cmd)
self.res = sql_cmd.splitlines()[-2].strip()
LOG.info('--步骤2:设置enable_sonic_hashagg为off并重启数据库--')
msg = commonsh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
'enable_sonic_hashagg =off')
LOG.info(msg)
self.assertTrue(msg)
msg = commonsh.restart_db_cluster()
LOG.info(msg)
status = commonsh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status)
LOG.info('--步骤3:查询该参数修改后的值--')
sql_cmd = commonsh.execut_db_sql('show enable_sonic_hashagg;')
LOG.info(sql_cmd)
self.assertIn(self.constant.BOOLEAN_VALUES[1], sql_cmd)
def tearDown(self):
LOG.info('--步骤4:清理环境--')
sql_cmd = commonsh.execut_db_sql('show enable_sonic_hashagg;')
LOG.info(sql_cmd)
if self.res != sql_cmd.split('\n')[-2].strip():
msg = commonsh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
f"enable_sonic_hashagg={self.res}")
LOG.info(msg)
msg = commonsh.restart_db_cluster()
LOG.info(msg)
status = commonsh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status)
sql_cmd = commonsh.execut_db_sql('show enable_sonic_hashagg;')
LOG.info(sql_cmd)
LOG.info(
'-----Opengauss_Function_Guc_Queryplan_Case0105执行完成------')
|
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
def to_bytes(s):
return s if isinstance(s, bytes) else s.encode("utf-8")
def to_str(b):
return b if isinstance(b, str) else b.decode("utf-8", "ignore")
else:
def to_bytes(s):
return bytes(s)
def to_str(b):
return str(b)
|
import React from 'react';
import { Card } from 'react-bootstrap';
function Reviews() {
return (
<div className="container-fluid" id="review-div">
<div className="row title-row col-lg-12 col-sm-12" >
<h2 className="serviceTitle col-sm-12">Service Reviews</h2>
</div>
<div className="row v-100 reviews-row col-sm-12">
<div className="col">
<Card className="reviewCard" border="primary" style={{ width: '18rem' }}>
<Card.Header><strong>Carl</strong> › Vernonia</Card.Header>
<Card.Body>
<Card.Title>Very Helpful</Card.Title>
<Card.Text>
I was having a hard time finding my internet icon and getting connected to my Wifi, but Cathy was able to help me out. I'm pretty sure it's working now.
</Card.Text>
<Card.Link href="/reviews">More Info</Card.Link>
</Card.Body>
</Card>
</div>
<div className="col">
<Card className="reviewCard" border="primary" style={{ width: '18rem' }}>
<Card.Header><strong>Chaz</strong> › Newberg</Card.Header>
<Card.Body>
<Card.Title>Got My Phone Back</Card.Title>
<Card.Text>
Ellen helped me get my apps on my phone fixed and now it's working just fine.
</Card.Text>
<Card.Link href="/reviews">More Info</Card.Link>
</Card.Body>
</Card>
</div>
<div className="col">
<Card className="reviewCard" border="primary" style={{ width: '18rem' }}>
<Card.Header><strong>Gwen</strong> › Vancouver</Card.Header>
<Card.Body>
<Card.Title>Bingo!</Card.Title>
<Card.Text>
It finally works! My grandson came over and fixed my printer, but screwed up my tablet. I reached out to Igor Johnson and now I'm back playing Words with Friends. Thank you so much!
</Card.Text>
<Card.Link href="/reviews">More Info</Card.Link>
</Card.Body>
</Card>
</div>
<div className="col">
<Card className="reviewCard" border="primary" style={{ width: '18rem' }}>
<Card.Header><strong>Brett</strong> › Woodstock</Card.Header>
<Card.Body>
<Card.Title>Upgraded and Smokin' Fast</Card.Title>
<Card.Text>
I was unsure about upgrading my PC so I used your services and found Estelle. Her certification gave me the peace of mind I needed to call her and get the support I needed.
</Card.Text>
<Card.Link href="/reviews">More Info</Card.Link>
</Card.Body>
</Card>
</div>
<div className="review-end"></div>
</div>
</div>
)
};
export default Reviews;
|
# -*- coding: utf-8 -*-
import time,base64,hashlib,json,signal,sys,argparse,websocket,asyncio,_thread
from urllib.parse import quote,unquote
log = print
global UserID,status,token,username
token = ''
username = ''
status = True
UserID = 0
def on_message(ws, message):
raw_data = json.loads(message)
global UserID
if(raw_data['info'] == 'startChat'):
UserID = int(raw_data['userid'])
info_fail = '[{0}] {1} Online:{2} '
info = 'info:{0} online:{1}'
msg = '[Recv] {0} \nUser ID: {1} Username:{2} >:{3}'
chatdata = unquote(unquote(raw_data['chatdata']))
if(len(raw_data['status']) > 0):
if(raw_data['status']!='normal'):
log(info_fail.format(raw_data['status'],raw_data['info'],raw_data['online']))
else:
log(info.format(raw_data['info'],raw_data['online']))
log(msg.format(raw_data['time'],raw_data['userid'],raw_data['username'],chatdata))
log('[Your ID:{0}] >:'.format(UserID))
def on_error(ws, error):
log(error)
def on_open(ws):
global token
ws.send(token)
def run():
Chat(ws)
_thread.start_new_thread(run, ())
log('[INFO] Client Running!')
def on_close(ws):
global status
status = False
ws.close()
log('[INFO] Client Exit Success!')
def Chat(client):
global username,token,status,UserID
message = {
"chatdata":'',
"time":'',
"username":username,
"token":token,
}
while status:
chatdata = input('')
message['chatdata'] = quote(chatdata)
message['time'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
client.send(json.dumps(message))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--port', default=9001, type=int,help="This is Chat Server Port.")
parser.add_argument('--server', default="127.0.0.1", type=str,help="This is Chat Server IP.")
parser.add_argument('--token', default="", type=str,help="This is Chat Server Login token.")
args = parser.parse_args()
#websocket.enableTrace(True)
if isinstance(args.port, int):
client = 0
token = args.token
if isinstance(args.server, str):
username = input('Username: > ')
while len(username)<3:
username = input('Username: > ')
client = websocket.WebSocketApp('ws://'+args.server+':'+str(args.port),on_message=on_message,on_error=on_error,on_close=on_close,on_open=on_open)
client.run_forever()
def signalHandler(s, frame):
if s == signal.SIGINT:
client.close()
signal.signal(signal.SIGINT, signalHandler) |
/*
* VulkanRenderer.h
*
* Created on: Sep 11, 2017
* Author: david
*/
#ifndef RENDERING_VULKAN_VULKANRENDERER_H_
#define RENDERING_VULKAN_VULKANRENDERER_H_
#include <Rendering/Renderer/Renderer.h>
#include <Rendering/Vulkan/vulkan_common.h>
#include <Rendering/Vulkan/VulkanObjects.h>
class VulkanSwapchain;
class VulkanPipelines;
class VulkanRenderer : public Renderer
{
public:
VkInstance instance;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkQueue graphicsQueue;
VkQueue computeQueue;
VkQueue transferQueue;
VkQueue presentQueue;
DeviceQueues deviceQueueInfo;
RendererAllocInfo onAllocInfo;
VkPhysicalDeviceFeatures deviceFeatures;
VkPhysicalDeviceProperties deviceProps;
VmaAllocator memAllocator;
#ifdef __linux__
shaderc::Compiler *defaultCompiler;
#endif
VulkanSwapchain *swapchains;
VulkanPipelines *pipelineHandler; // Does all the pipeline handling (creation, caching, etc)
VulkanRenderer (const RendererAllocInfo& allocInfo);
virtual ~VulkanRenderer ();
void initRenderer ();
CommandPool createCommandPool (QueueType queue, CommandPoolFlags flags);
void submitToQueue (QueueType queue, const std::vector<CommandBuffer> &cmdBuffers, const std::vector<Semaphore> &waitSemaphores, const std::vector<PipelineStageFlags> &waitSemaphoreStages, const std::vector<Semaphore> &signalSemaphores, Fence fence);
void waitForQueueIdle (QueueType queue);
void waitForDeviceIdle ();
bool getFenceStatus (Fence fence);
void resetFence (Fence fence);
void resetFences (const std::vector<Fence> &fences);
void waitForFence (Fence fence, double timeoutInSeconds);
void waitForFences (const std::vector<Fence> &fences, bool waitForAll, double timeoutInSeconds);
void writeDescriptorSets (const std::vector<DescriptorWriteInfo> &writes);
RenderPass createRenderPass(const std::vector<AttachmentDescription> &attachments, const std::vector<SubpassDescription> &subpasses, const std::vector<SubpassDependency> &dependencies);
Framebuffer createFramebuffer(RenderPass renderPass, const std::vector<TextureView> &attachments, uint32_t width, uint32_t height, uint32_t layers);
ShaderModule createShaderModule (const std::string &file, ShaderStageFlagBits stage, ShaderSourceLanguage sourceLang, const std::string &entryPoint);
ShaderModule createShaderModuleFromSource (const std::string &source, const std::string &referenceName, ShaderStageFlagBits stage, ShaderSourceLanguage sourceLang, const std::string &entryPoint);
Pipeline createGraphicsPipeline (const GraphicsPipelineInfo &pipelineInfo, RenderPass renderPass, uint32_t subpass);
Pipeline createComputePipeline(const ComputePipelineInfo &pipelineInfo);
DescriptorPool createDescriptorPool (const std::vector<DescriptorSetLayoutBinding> &layoutBindings, uint32_t poolBlockAllocSize);
Fence createFence (bool createAsSignaled);
Semaphore createSemaphore ();
std::vector<Semaphore> createSemaphores (uint32_t count);
Texture createTexture (suvec3 extent, ResourceFormat format, TextureUsageFlags usage, MemoryUsage memUsage, bool ownMemory, uint32_t mipLevelCount, uint32_t arrayLayerCount);
TextureView createTextureView (Texture texture, TextureViewType viewType, TextureSubresourceRange subresourceRange, ResourceFormat viewFormat);
Sampler createSampler (SamplerAddressMode addressMode, SamplerFilter minFilter, SamplerFilter magFilter, float anisotropy, svec3 min_max_biasLod, SamplerMipmapMode mipmapMode);
Buffer createBuffer (size_t size, BufferUsageType usage, bool canBeTransferDst, bool canBeTransferSrc, MemoryUsage memUsage, bool ownMemory);
void *mapBuffer (Buffer buffer);
void unmapBuffer (Buffer buffer);
StagingBuffer createStagingBuffer (size_t dataSize);
StagingBuffer createAndFillStagingBuffer (size_t dataSize, const void *data);
void fillStagingBuffer (StagingBuffer stagingBuffer, size_t dataSize, const void *data);
void *mapStagingBuffer(StagingBuffer stagingBuffer);
void unmapStagingBuffer(StagingBuffer stagingBuffer);
void destroyCommandPool (CommandPool pool);
void destroyRenderPass (RenderPass renderPass);
void destroyFramebuffer (Framebuffer framebuffer);
void destroyPipeline (Pipeline pipeline);
void destroyShaderModule (ShaderModule module);
void destroyDescriptorPool (DescriptorPool pool);
void destroyTexture (Texture texture);
void destroyTextureView (TextureView textureView);
void destroySampler (Sampler sampler);
void destroyBuffer (Buffer buffer);
void destroyStagingBuffer (StagingBuffer stagingBuffer);
void destroyFence (Fence fence);
void destroySemaphore (Semaphore sem);
void setObjectDebugName (void *obj, RendererObjectType objType, const std::string &name);
void initSwapchain (Window *wnd);
void presentToSwapchain (Window *wnd);
void recreateSwapchain (Window *wnd);
void setSwapchainTexture (Window *wnd, TextureView texView, Sampler sampler, TextureLayout layout);
bool areValidationLayersEnabled ();
bool checkExtraSurfacePresentSupport(VkSurfaceKHR surface);
VulkanDescriptorPoolObject createDescPoolObject (const std::vector<VkDescriptorPoolSize> &poolSizes, uint32_t maxSets);
private:
VkDebugReportCallbackEXT dbgCallback;
bool validationLayersEnabled;
void choosePhysicalDevice ();
void createLogicalDevice ();
void cleanupVulkan ();
DeviceQueues findQueueFamilies (VkPhysicalDevice physDevice);
std::vector<const char*> getInstanceExtensions ();
bool checkValidationLayerSupport (std::vector<const char*> layers);
bool checkDeviceExtensionSupport (VkPhysicalDevice physDevice, std::vector<const char*> extensions);
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback (VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char* layerPrefix, const char* msg, void* userData);
};
#endif /* RENDERING_VULKAN_VULKANRENDERER_H_ */
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pydisp documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import pydisp
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pydisp'
copyright = u'2016, Daniel Maturana'
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = pydisp.__version__
# The full version, including alpha/beta/rc tags.
release = pydisp.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pydispdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'pydisp.tex',
u'pydisp Documentation',
u'Daniel Maturana', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pydisp',
u'pydisp Documentation',
[u'Daniel Maturana'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pydisp',
u'pydisp Documentation',
u'Daniel Maturana',
'pydisp',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
|
/*
[sql_lite_db_crud_test.js]
encoding=utf-8
*/
// 未だ不要。後で実装。
|
function CardClass(num1)
{
this.cardID=num1;
this.controller=0;
this.hist=0;
this.used=false;
this.dropCode='<section id="space'+this.cardID+'"><canvas id="card' + this.cardID + '" class="boardcard"></canvas></section>';
this.backColor="rgb("+(Math.floor((Math.random()-.5)*60)+74)+", "+(Math.floor((Math.random()-.5)*60)+74)+", "+(Math.floor((Math.random()-.5)*100)+194)+")";
//place card on board
this.placeCard=function()
{
$('#board').append(this.dropCode);
$("#card"+this.cardID).css({"width":"190px","height":"90px","float":"left","border-style":"solid","border-width":"5px","background-color":"white","border-color":"rgb(194, 194, 208)"});
};
//handles highlighting of cards in UI
this.highlight=function()
{
$("#card"+this.cardID).css({"border-color":"black"});
};
this.unhighlight=function()
{
var borderColor="rgb(194, 194, 208)";
if(this.controller==1)
borderColor="darkGreen";
if(this.controller==-1)
borderColor="darkRed";
$("#card"+this.cardID).css({"border-color":borderColor});
};
//selecting of cards by user
this.p1select=function()
{
if(this.controller==0)
{
this.controller=1;
$("#card"+this.cardID).css({"border-color":"darkGreen"});
return fields()[0].value;
}
return 0;
};
//selecting of cards by AI
this.p2select=function()
{
if(this.controller==0)
{
this.controller=-1;
$("#card"+this.cardID).css({"border-color":"darkRed"});
return true;
}
return false
};
this.deselect=function()
{
if(!(this.used))
{
this.controller=0;
$("#card"+this.cardID).css({"border-color":"rgb(194, 194, 208)"});
}
}
//displays card histogram
this.setHist=function(num1,num2,num3, arr1)
{
this.hist=new histMaker(num1,num2,num3,arr1[num1-1]);
this.hist.initializeExperiment();
}
} |
"""Conversions between XRP drops and native number types."""
from decimal import Context, Decimal, InvalidOperation, setcontext
from re import fullmatch
from typing import Union
from typing_extensions import Final
from xrpl.constants import XRPLException
ONE_DROP: Final[Decimal] = Decimal("0.000001") #: Indivisible unit of XRP
MAX_XRP: Final[Decimal] = Decimal(10 ** 11) #: 100 billion decimal XRP
MAX_DROPS: Final[Decimal] = Decimal(10 ** 17) #: Maximum possible drops of XRP
# Drops should be an integer string. MAY have (positive) exponent.
# See also: https://xrpl.org/currency-formats.html#string-numbers
_DROPS_REGEX: Final[str] = r"[1-9][0-9Ee-]{0,17}|0"
_DROPS_CONTEXT: Final[Context] = Context(prec=18, Emin=0, Emax=18)
def xrp_to_drops(xrp: Union[int, float, Decimal]) -> str:
"""
Convert a numeric XRP amount to drops of XRP.
Args:
xrp: Numeric representation of whole XRP
Returns:
Equivalent amount in drops of XRP
Raises:
TypeError: if ``xrp`` is given as a string
XRPRangeException: if the given amount of XRP is invalid
"""
if type(xrp) == str: # type: ignore
# This protects people from passing drops to this function and getting
# a million times as many drops back.
raise TypeError(
"XRP provided as a string. Use a number format" "like Decimal or int."
)
setcontext(_DROPS_CONTEXT)
try:
xrp_d = Decimal(xrp)
except InvalidOperation:
raise XRPRangeException(f"Not a valid amount of XRP: '{xrp}'")
if not xrp_d.is_finite(): # NaN or an Infinity
raise XRPRangeException(f"Not a valid amount of XRP: '{xrp}'")
if xrp_d < ONE_DROP and xrp_d != 0:
raise XRPRangeException(f"XRP amount {xrp} is too small.")
if xrp_d > MAX_XRP:
raise XRPRangeException(f"XRP amount {xrp} is too large.")
drops_amount = (xrp_d / ONE_DROP).quantize(Decimal(1))
drops_str = str(drops_amount).strip()
# This should never happen, but is a precaution against Decimal doing
# something unexpected.
if not fullmatch(_DROPS_REGEX, drops_str):
raise XRPRangeException(
f"xrp_to_drops failed sanity check. Value "
f"'{drops_str}' does not match the drops regex"
)
return drops_str
def drops_to_xrp(drops: str) -> Decimal:
"""
Convert from drops to decimal XRP.
Args:
drops: String representing indivisible drops of XRP
Returns:
Decimal representation of the same amount of XRP
Raises:
TypeError: if ``drops`` not given as a string
XRPRangeException: if the given number of drops is invalid
"""
if type(drops) != str:
raise TypeError(f"Drops must be provided as string (got {type(drops)})")
drops = drops.strip()
setcontext(_DROPS_CONTEXT)
if not fullmatch(_DROPS_REGEX, drops):
raise XRPRangeException(f"Not a valid amount of drops: '{drops}'")
try:
drops_d = Decimal(drops)
except InvalidOperation:
raise XRPRangeException(f"Not a valid amount of drops: '{drops}'")
xrp_d = drops_d * ONE_DROP
if xrp_d > MAX_XRP:
raise XRPRangeException(f"Drops amount {drops} is too large.")
return xrp_d
class XRPRangeException(XRPLException):
"""Exception for invalid XRP amounts."""
pass
|
from zeit.cms.content.browser.form import CommonMetadataFormBase
from zeit.cms.i18n import MessageFactory as _
import gocept.form.grouped
import zeit.cms.related.interfaces
import zeit.cms.workflow.interfaces
import zeit.content.video.interfaces
import zeit.push.browser.form
import zope.dublincore.interfaces
import zope.formlib.form
class Base(zeit.push.browser.form.SocialBase,
zeit.push.browser.form.MobileBase):
form_fields = zope.formlib.form.FormFields(
zeit.content.video.interfaces.IVideo,
zeit.cms.related.interfaces.IRelatedContent,
zeit.cms.workflow.interfaces.IPublishInfo,
zope.dublincore.interfaces.IDCTimes,
render_context=zope.formlib.interfaces.DISPLAY_UNWRITEABLE
).select(
'supertitle', 'title', 'subtitle', 'teaserText',
'product', 'ressort', 'keywords', 'serie',
'banner', 'banner_id',
'has_recensions', 'commentsAllowed',
'commentsPremoderate', 'related', 'channels', 'lead_candidate',
'video_still_copyright', 'has_advertisement',
# remaining:
'__name__', 'cms_thumbnail', 'cms_video_still',
'created', 'date_first_released', 'modified', 'expires',
'thumbnail', 'video_still', 'authorships')
field_groups = (
gocept.form.grouped.Fields(
_("Texts"),
('supertitle', 'title', 'teaserText', 'video_still_copyright'),
css_class='wide-widgets column-left'),
gocept.form.grouped.Fields(
_("Navigation"),
('product', 'ressort', 'keywords', 'serie'),
css_class='column-right'),
gocept.form.grouped.Fields(
_("Options"),
('dailyNewsletter', 'banner', 'banner_id',
'breaking_news', 'has_recensions', 'commentsAllowed',
'commentsPremoderate', 'has_advertisement'),
css_class='column-right checkboxes'),
zeit.push.browser.form.SocialBase.social_fields,
zeit.push.browser.form.MobileBase.mobile_fields,
CommonMetadataFormBase.auto_cp_fields,
gocept.form.grouped.Fields(
_('Teaser elements'),
('related', 'cms_thumbnail', 'cms_video_still'),
css_class='wide-widgets column-left'),
gocept.form.grouped.RemainingFields(
'', css_class='column-left'),
)
class Edit(Base, zeit.cms.browser.form.EditForm):
title = _('Video')
class Display(Base, zeit.cms.browser.form.DisplayForm):
title = _('Video')
class Thumbnail(zeit.cms.browser.view.Base):
@property
def thumbnail_url(self):
return self.context.thumbnail
def __call__(self):
return self.redirect(self.thumbnail_url, trusted=True)
class ThumbnailURL(zope.traversing.browser.absoluteurl.AbsoluteURL):
def __str__(self):
if self.context.thumbnail_url:
return self.context.thumbnail_url
raise TypeError("No Thumbnail")
class Still(zeit.cms.browser.view.Base):
@property
def video_still_url(self):
return self.context.video_still
def __call__(self):
return self.redirect(self.video_still_url, trusted=True)
class StillURL(zope.traversing.browser.absoluteurl.AbsoluteURL):
def __str__(self):
if self.context.video_still_url:
return self.context.video_still_url
raise TypeError("No still url")
class PlaylistDisplayForm(zeit.cms.browser.form.DisplayForm):
title = _('View playlist')
form_fields = zope.formlib.form.FormFields(
zeit.content.video.interfaces.IPlaylist)
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "5a74");
/******/ })
/************************************************************************/
/******/ ({
/***/ "01f9":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__("2d00");
var $export = __webpack_require__("5ca1");
var redefine = __webpack_require__("2aba");
var hide = __webpack_require__("32e9");
var Iterators = __webpack_require__("84f2");
var $iterCreate = __webpack_require__("41a0");
var setToStringTag = __webpack_require__("7f20");
var getPrototypeOf = __webpack_require__("38fd");
var ITERATOR = __webpack_require__("2b4c")('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/***/ "0218":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("fa4d");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("a895b96a", content, shadowRoot)
};
/***/ }),
/***/ "02f4":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("4588");
var defined = __webpack_require__("be13");
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/***/ "0390":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var at = __webpack_require__("02f4")(true);
// `AdvanceStringIndex` abstract operation
// https://tc39.github.io/ecma262/#sec-advancestringindex
module.exports = function (S, index, unicode) {
return index + (unicode ? at(S, index).length : 1);
};
/***/ }),
/***/ "06db":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__("23c6");
var test = {};
test[__webpack_require__("2b4c")('toStringTag')] = 'z';
if (test + '' != '[object z]') {
__webpack_require__("2aba")(Object.prototype, 'toString', function toString() {
return '[object ' + classof(this) + ']';
}, true);
}
/***/ }),
/***/ "09fa":
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/ecma262/#sec-toindex
var toInteger = __webpack_require__("4588");
var toLength = __webpack_require__("9def");
module.exports = function (it) {
if (it === undefined) return 0;
var number = toInteger(it);
var length = toLength(number);
if (number !== length) throw RangeError('Wrong length!');
return length;
};
/***/ }),
/***/ "0a49":
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__("9b43");
var IObject = __webpack_require__("626a");
var toObject = __webpack_require__("4bf8");
var toLength = __webpack_require__("9def");
var asc = __webpack_require__("cd1c");
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ }),
/***/ "0b68":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("3339");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("795354eb", content, shadowRoot)
};
/***/ }),
/***/ "0bfb":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__("cb7c");
module.exports = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
/***/ }),
/***/ "0cd8":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $reduce = __webpack_require__("7b23");
$export($export.P + $export.F * !__webpack_require__("2f21")([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ }),
/***/ "0d58":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__("ce10");
var enumBugKeys = __webpack_require__("e11e");
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/***/ "0ed5":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomUsersTag_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("e787");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomUsersTag_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomUsersTag_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "0f88":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var hide = __webpack_require__("32e9");
var uid = __webpack_require__("ca5a");
var TYPED = uid('typed_array');
var VIEW = uid('view');
var ABV = !!(global.ArrayBuffer && global.DataView);
var CONSTR = ABV;
var i = 0;
var l = 9;
var Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while (i < l) {
if (Typed = global[TypedArrayConstructors[i++]]) {
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ }),
/***/ "1169":
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__("2d95");
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/***/ "11e9":
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__("52a7");
var createDesc = __webpack_require__("4630");
var toIObject = __webpack_require__("6821");
var toPrimitive = __webpack_require__("6a99");
var has = __webpack_require__("69a8");
var IE8_DOM_DEFINE = __webpack_require__("c69a");
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__("9e1e") ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/***/ "13fc":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, "#vac-icon-search{fill:var(--chat-icon-color-search)}#vac-icon-add{fill:var(--chat-icon-color-add)}#vac-icon-toggle{fill:var(--chat-icon-color-toggle)}#vac-icon-menu{fill:var(--chat-icon-color-menu)}#vac-icon-close{fill:var(--chat-icon-color-close)}#vac-icon-close-image{fill:var(--chat-icon-color-close-image)}#vac-icon-file{fill:var(--chat-icon-color-file)}#vac-icon-paperclip{fill:var(--chat-icon-color-paperclip)}#vac-icon-close-outline{fill:var(--chat-icon-color-close-outline)}#vac-icon-send{fill:var(--chat-icon-color-send)}#vac-icon-send-disabled{fill:var(--chat-icon-color-send-disabled)}#vac-icon-emoji{fill:var(--chat-icon-color-emoji)}#vac-icon-emoji-reaction{fill:var(--chat-icon-color-emoji-reaction)}#vac-icon-document{fill:var(--chat-icon-color-document)}#vac-icon-pencil{fill:var(--chat-icon-color-pencil)}#vac-icon-checkmark,#vac-icon-double-checkmark{fill:var(--chat-icon-color-checkmark)}#vac-icon-checkmark-seen,#vac-icon-double-checkmark-seen{fill:var(--chat-icon-color-checkmark-seen)}#vac-icon-eye{fill:var(--chat-icon-color-eye)}#vac-icon-dropdown-message{fill:var(--chat-icon-color-dropdown-message)}#vac-icon-dropdown-room{fill:var(--chat-icon-color-dropdown-room)}#vac-icon-dropdown-scroll{fill:var(--chat-icon-color-dropdown-scroll)}#vac-icon-audio-play{fill:var(--chat-icon-color-audio-play)}#vac-icon-audio-pause{fill:var(--chat-icon-color-audio-pause)}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "1448":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.12 String.prototype.strike()
__webpack_require__("386b")('strike', function (createHTML) {
return function strike() {
return createHTML(this, 'strike', '', '');
};
});
/***/ }),
/***/ "1495":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("86cc");
var anObject = __webpack_require__("cb7c");
var getKeys = __webpack_require__("0d58");
module.exports = __webpack_require__("9e1e") ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/***/ "15ac":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("ec30")('Int16', 2, function (init) {
return function Int16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/***/ "1652":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.stateify = exports.TokenState = exports.CharacterState = undefined;
var _class = __webpack_require__("254c");
function createStateClass() {
return function (tClass) {
this.j = [];
this.T = tClass || null;
};
}
/**
A simple state machine that can emit token classes
The `j` property in this class refers to state jumps. It's a
multidimensional array where for each element:
* index [0] is a symbol or class of symbols to transition to.
* index [1] is a State instance which matches
The type of symbol will depend on the target implementation for this class.
In Linkify, we have a two-stage scanner. Each stage uses this state machine
but with a slighly different (polymorphic) implementation.
The `T` property refers to the token class.
TODO: Can the `on` and `next` methods be combined?
@class BaseState
*/
var BaseState = createStateClass();
BaseState.prototype = {
defaultTransition: false,
/**
@method constructor
@param {Class} tClass Pass in the kind of token to emit if there are
no jumps after this state and the state is accepting.
*/
/**
On the given symbol(s), this machine should go to the given state
@method on
@param {Array|Mixed} symbol
@param {BaseState} state Note that the type of this state should be the
same as the current instance (i.e., don't pass in a different
subclass)
*/
on: function on(symbol, state) {
if (symbol instanceof Array) {
for (var i = 0; i < symbol.length; i++) {
this.j.push([symbol[i], state]);
}
return this;
}
this.j.push([symbol, state]);
return this;
},
/**
Given the next item, returns next state for that item
@method next
@param {Mixed} item Should be an instance of the symbols handled by
this particular machine.
@return {State} state Returns false if no jumps are available
*/
next: function next(item) {
for (var i = 0; i < this.j.length; i++) {
var jump = this.j[i];
var symbol = jump[0]; // Next item to check for
var state = jump[1]; // State to jump to if items match
// compare item with symbol
if (this.test(item, symbol)) {
return state;
}
}
// Nowhere left to jump!
return this.defaultTransition;
},
/**
Does this state accept?
`true` only of `this.T` exists
@method accepts
@return {Boolean}
*/
accepts: function accepts() {
return !!this.T;
},
/**
Determine whether a given item "symbolizes" the symbol, where symbol is
a class of items handled by this state machine.
This method should be overriden in extended classes.
@method test
@param {Mixed} item Does this item match the given symbol?
@param {Mixed} symbol
@return {Boolean}
*/
test: function test(item, symbol) {
return item === symbol;
},
/**
Emit the token for this State (just return it in this case)
If this emits a token, this instance is an accepting state
@method emit
@return {Class} T
*/
emit: function emit() {
return this.T;
}
};
/**
State machine for string-based input
@class CharacterState
@extends BaseState
*/
var CharacterState = (0, _class.inherits)(BaseState, createStateClass(), {
/**
Does the given character match the given character or regular
expression?
@method test
@param {String} char
@param {String|RegExp} charOrRegExp
@return {Boolean}
*/
test: function test(character, charOrRegExp) {
return character === charOrRegExp || charOrRegExp instanceof RegExp && charOrRegExp.test(character);
}
});
/**
State machine for input in the form of TextTokens
@class TokenState
@extends BaseState
*/
var TokenState = (0, _class.inherits)(BaseState, createStateClass(), {
/**
* Similar to `on`, but returns the state the results in the transition from
* the given item
* @method jump
* @param {Mixed} item
* @param {Token} [token]
* @return state
*/
jump: function jump(token) {
var tClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var state = this.next(new token('')); // dummy temp token
if (state === this.defaultTransition) {
// Make a new state!
state = new this.constructor(tClass);
this.on(token, state);
} else if (tClass) {
state.T = tClass;
}
return state;
},
/**
Is the given token an instance of the given token class?
@method test
@param {TextToken} token
@param {Class} tokenClass
@return {Boolean}
*/
test: function test(token, tokenClass) {
return token instanceof tokenClass;
}
});
/**
Given a non-empty target string, generates states (if required) for each
consecutive substring of characters in str starting from the beginning of
the string. The final state will have a special value, as specified in
options. All other "in between" substrings will have a default end state.
This turns the state machine into a Trie-like data structure (rather than a
intelligently-designed DFA).
Note that I haven't really tried these with any strings other than
DOMAIN.
@param {String} str
@param {CharacterState} start State to jump from the first character
@param {Class} endToken Token class to emit when the given string has been
matched and no more jumps exist.
@param {Class} defaultToken "Filler token", or which token type to emit when
we don't have a full match
@return {Array} list of newly-created states
*/
function stateify(str, start, endToken, defaultToken) {
var i = 0,
len = str.length,
state = start,
newStates = [],
nextState = void 0;
// Find the next state without a jump to the next character
while (i < len && (nextState = state.next(str[i]))) {
state = nextState;
i++;
}
if (i >= len) {
return [];
} // no new tokens were added
while (i < len - 1) {
nextState = new CharacterState(defaultToken);
newStates.push(nextState);
state.on(str[i], nextState);
state = nextState;
i++;
}
nextState = new CharacterState(endToken);
newStates.push(nextState);
state.on(str[len - 1], nextState);
return newStates;
}
exports.CharacterState = CharacterState;
exports.TokenState = TokenState;
exports.stateify = stateify;
/***/ }),
/***/ "172b":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-reply-container{position:absolute;display:flex;padding:10px 10px 0 10px;background:var(--chat-footer-bg-color);align-items:center;width:calc(100% - 20px)}.vac-reply-container .vac-reply-box{width:100%;overflow:hidden;background:var(--chat-footer-bg-color-reply);border-radius:4px;padding:8px 10px;display:flex}.vac-reply-container .vac-reply-info{overflow:hidden}.vac-reply-container .vac-reply-username{color:var(--chat-message-color-reply-username);font-size:12px;line-height:15px;margin-bottom:2px}.vac-reply-container .vac-reply-content{font-size:12px;color:var(--chat-message-color-reply-content);white-space:pre-line}.vac-reply-container .vac-icon-reply{margin-left:10px}.vac-reply-container .vac-icon-reply svg{height:20px;width:20px}.vac-reply-container .vac-image-reply{max-height:100px;margin-right:10px;border-radius:4px}@media only screen and (max-width:768px){.vac-reply-container{padding:5px 8px;width:calc(100% - 16px)}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "1991":
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__("9b43");
var invoke = __webpack_require__("31f4");
var html = __webpack_require__("fab2");
var cel = __webpack_require__("230e");
var global = __webpack_require__("7726");
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (__webpack_require__("2d95")(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/***/ "1a98":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "detectMobile", function() { return detectMobile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iOSDevice", function() { return iOSDevice; });
/* harmony import */ var core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("6762");
/* harmony import */ var core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("2fdb");
/* harmony import */ var core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1__);
function detectMobile() {
var userAgent = getUserAgent();
var userAgentPart = userAgent.substr(0, 4);
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw(n|u)|c55\/|capi|ccwa|cdm|cell|chtm|cldc|cmd|co(mp|nd)|craw|da(it|ll|ng)|dbte|dcs|devi|dica|dmob|do(c|p)o|ds(12|d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(|_)|g1 u|g560|gene|gf5|gmo|go(\.w|od)|gr(ad|un)|haie|hcit|hd(m|p|t)|hei|hi(pt|ta)|hp( i|ip)|hsc|ht(c(| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i(20|go|ma)|i230|iac( ||\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|[a-w])|libw|lynx|m1w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|mcr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|([1-8]|c))|phil|pire|pl(ay|uc)|pn2|po(ck|rt|se)|prox|psio|ptg|qaa|qc(07|12|21|32|60|[2-7]|i)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h|oo|p)|sdk\/|se(c(|0|1)|47|mc|nd|ri)|sgh|shar|sie(|m)|sk0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h|v|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl|tdg|tel(i|m)|tim|tmo|to(pl|sh)|ts(70|m|m3|m5)|tx9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas|your|zeto|zte/i.test(userAgentPart);
}
function getUserAgent() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera || null;
if (!userAgent) throw new Error('Failed to look for user agent information.');
return userAgent;
}
function iOSDevice() {
return ['iPad', 'iPhone', 'iPod'].includes(navigator.platform) || navigator.userAgent.includes('Mac') && 'ontouchend' in document;
}
/***/ }),
/***/ "1c01":
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__("5ca1");
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__("9e1e"), 'Object', { defineProperty: __webpack_require__("86cc").f });
/***/ }),
/***/ "1c4c":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ctx = __webpack_require__("9b43");
var $export = __webpack_require__("5ca1");
var toObject = __webpack_require__("4bf8");
var call = __webpack_require__("1fa8");
var isArrayIter = __webpack_require__("33a4");
var toLength = __webpack_require__("9def");
var createProperty = __webpack_require__("f1ae");
var getIterFn = __webpack_require__("27ee");
$export($export.S + $export.F * !__webpack_require__("5cc5")(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/***/ "1fa8":
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__("cb7c");
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/***/ "214f":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__("b0c5");
var redefine = __webpack_require__("2aba");
var hide = __webpack_require__("32e9");
var fails = __webpack_require__("79e5");
var defined = __webpack_require__("be13");
var wks = __webpack_require__("2b4c");
var regexpExec = __webpack_require__("520a");
var SPECIES = wks('species');
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
// #replace needs built-in support for named groups.
// #match works fine because it just return the exec results, even if it has
// a "grops" property.
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = (function () {
// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
var re = /(?:)/;
var originalExec = re.exec;
re.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re);
return result.length === 2 && result[0] === 'a' && result[1] === 'b';
})();
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var DELEGATES_TO_SYMBOL = !fails(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL ? !fails(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
re.exec = function () { execCalled = true; return null; };
if (KEY === 'split') {
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES] = function () { return re; };
}
re[SYMBOL]('');
return !execCalled;
}) : undefined;
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
(KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
(KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
) {
var nativeRegExpMethod = /./[SYMBOL];
var fns = exec(
defined,
SYMBOL,
''[KEY],
function maybeCallNative(nativeMethod, regexp, str, arg2, forceStringMethod) {
if (regexp.exec === regexpExec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
}
);
var strfn = fns[0];
var rxfn = fns[1];
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
/***/ }),
/***/ "22bf":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-format-message-wrapper .vac-icon-deleted{height:14px;width:14px;vertical-align:middle;margin:-3px 1px 0 0;fill:var(--chat-room-color-message)}.vac-format-message-wrapper .vac-image-link-container{background-color:var(--chat-message-bg-color-media);padding:8px;margin:2px auto;border-radius:4px}.vac-format-message-wrapper .vac-image-link{position:relative;background-color:var(--chat-message-bg-color-image)!important;background-size:contain;background-position:50%!important;background-repeat:no-repeat!important;height:150px;width:150px;max-width:100%;border-radius:4px;margin:0 auto}.vac-format-message-wrapper .vac-image-link-message{max-width:166px;font-size:12px}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "230e":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
var document = __webpack_require__("7726").document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/***/ "23bf":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var html = __webpack_require__("fab2");
var cof = __webpack_require__("2d95");
var toAbsoluteIndex = __webpack_require__("77f1");
var toLength = __webpack_require__("9def");
var arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__("79e5")(function () {
if (html) arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end) {
var len = toLength(this.length);
var klass = cof(this);
end = end === undefined ? len : end;
if (klass == 'Array') return arraySlice.call(this, begin, end);
var start = toAbsoluteIndex(begin, len);
var upTo = toAbsoluteIndex(end, len);
var size = toLength(upTo - start);
var cloned = new Array(size);
var i = 0;
for (; i < size; i++) cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ }),
/***/ "23c6":
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__("2d95");
var TAG = __webpack_require__("2b4c")('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/***/ "23e8":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("b467");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("3ad9df4b", content, shadowRoot)
};
/***/ }),
/***/ "24fb":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
/***/ }),
/***/ "254c":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.inherits = inherits;
function inherits(parent, child) {
var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var extended = Object.create(parent.prototype);
for (var p in props) {
extended[p] = props[p];
}
extended.constructor = child;
child.prototype = extended;
return child;
}
/***/ }),
/***/ "2621":
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/***/ "27ee":
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__("23c6");
var ITERATOR = __webpack_require__("2b4c")('iterator');
var Iterators = __webpack_require__("84f2");
module.exports = __webpack_require__("8378").getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/***/ "2a92":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Message_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("c1c7");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Message_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Message_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "2aba":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var hide = __webpack_require__("32e9");
var has = __webpack_require__("69a8");
var SRC = __webpack_require__("ca5a")('src');
var $toString = __webpack_require__("fa5b");
var TO_STRING = 'toString';
var TPL = ('' + $toString).split(TO_STRING);
__webpack_require__("8378").inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ }),
/***/ "2aeb":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__("cb7c");
var dPs = __webpack_require__("1495");
var enumBugKeys = __webpack_require__("e11e");
var IE_PROTO = __webpack_require__("613b")('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__("230e")('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__("fab2").appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/***/ "2b4c":
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__("5537")('wks');
var uid = __webpack_require__("ca5a");
var Symbol = __webpack_require__("7726").Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/***/ "2c2f":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-message-actions-wrapper .vac-options-container{position:absolute;top:2px;right:10px;height:40px;width:70px;overflow:hidden;border-top-right-radius:8px}.vac-message-actions-wrapper .vac-options-image .vac-blur-container{border-bottom-left-radius:15px}.vac-message-actions-wrapper .vac-blur-container{position:absolute;height:100%;width:100%;left:8px;bottom:10px;background:var(--chat-message-bg-color);filter:blur(3px);border-bottom-left-radius:8px}.vac-message-actions-wrapper .vac-options-me{background:var(--chat-message-bg-color-me)}.vac-message-actions-wrapper .vac-message-options{background:var(--chat-icon-bg-dropdown-message);border-radius:50%;position:absolute;top:7px;right:7px}.vac-message-actions-wrapper .vac-message-options svg{height:17px;width:17px;padding:5px;margin:-5px}.vac-message-actions-wrapper .vac-message-emojis{position:absolute;top:6px;right:30px}.vac-message-actions-wrapper .vac-menu-options{right:15px}.vac-message-actions-wrapper .vac-menu-left{right:-118px}@media only screen and (max-width:768px){.vac-message-actions-wrapper .vac-options-container{right:3px}.vac-message-actions-wrapper .vac-menu-left{right:-50px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "2caf":
/***/ (function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__("5ca1");
$export($export.S, 'Array', { isArray: __webpack_require__("1169") });
/***/ }),
/***/ "2d00":
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/***/ "2d78":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.tokenize = exports.test = exports.scanner = exports.parser = exports.options = exports.inherits = exports.find = undefined;
var _class = __webpack_require__("254c");
var _options = __webpack_require__("316e");
var options = _interopRequireWildcard(_options);
var _scanner = __webpack_require__("b7fe");
var scanner = _interopRequireWildcard(_scanner);
var _parser = __webpack_require__("4128");
var parser = _interopRequireWildcard(_parser);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
/**
Converts a string into tokens that represent linkable and non-linkable bits
@method tokenize
@param {String} str
@return {Array} tokens
*/
var tokenize = function tokenize(str) {
return parser.run(scanner.run(str));
};
/**
Returns a list of linkable items in the given string.
*/
var find = function find(str) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var tokens = tokenize(str);
var filtered = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.isLink && (!type || token.type === type)) {
filtered.push(token.toObject());
}
}
return filtered;
};
/**
Is the given string valid linkable text of some sort
Note that this does not trim the text for you.
Optionally pass in a second `type` param, which is the type of link to test
for.
For example,
test(str, 'email');
Will return `true` if str is a valid email.
*/
var test = function test(str) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var tokens = tokenize(str);
return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].type === type);
};
// Scanner and parser provide states and tokens for the lexicographic stage
// (will be used to add additional link types)
exports.find = find;
exports.inherits = _class.inherits;
exports.options = options;
exports.parser = parser;
exports.scanner = scanner;
exports.test = test;
exports.tokenize = tokenize;
/***/ }),
/***/ "2d95":
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/***/ "2f21":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var fails = __webpack_require__("79e5");
module.exports = function (method, arg) {
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call
arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);
});
};
/***/ }),
/***/ "2fdb":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
var $export = __webpack_require__("5ca1");
var context = __webpack_require__("d2c8");
var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__("5147")(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "3039":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-image-container{width:250px;max-width:100%}.vac-image-container .vac-image-loading{filter:blur(3px)}.vac-image-container .vac-image-buttons{position:absolute;width:100%;height:100%;border-radius:4px;background:linear-gradient(180deg,transparent 55%,rgba(0,0,0,.02) 60%,rgba(0,0,0,.05) 65%,rgba(0,0,0,.1) 70%,rgba(0,0,0,.2) 75%,rgba(0,0,0,.3) 80%,rgba(0,0,0,.5) 85%,rgba(0,0,0,.6) 90%,rgba(0,0,0,.7) 95%,rgba(0,0,0,.8))}.vac-image-container .vac-image-buttons svg{height:26px;width:26px}.vac-image-container .vac-image-buttons .vac-button-download,.vac-image-container .vac-image-buttons .vac-button-view{position:absolute;bottom:6px;left:7px}.vac-image-container .vac-image-buttons :first-child{left:40px}.vac-image-container .vac-image-buttons .vac-button-view{max-width:18px;bottom:8px}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "316e":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var defaults = {
defaultProtocol: 'http',
events: null,
format: noop,
formatHref: noop,
nl2br: false,
tagName: 'a',
target: typeToTarget,
validate: true,
ignoreTags: [],
attributes: null,
className: 'linkified' // Deprecated value - no default class will be provided in the future
};
exports.defaults = defaults;
exports.Options = Options;
exports.contains = contains;
function Options(opts) {
opts = opts || {};
this.defaultProtocol = opts.hasOwnProperty('defaultProtocol') ? opts.defaultProtocol : defaults.defaultProtocol;
this.events = opts.hasOwnProperty('events') ? opts.events : defaults.events;
this.format = opts.hasOwnProperty('format') ? opts.format : defaults.format;
this.formatHref = opts.hasOwnProperty('formatHref') ? opts.formatHref : defaults.formatHref;
this.nl2br = opts.hasOwnProperty('nl2br') ? opts.nl2br : defaults.nl2br;
this.tagName = opts.hasOwnProperty('tagName') ? opts.tagName : defaults.tagName;
this.target = opts.hasOwnProperty('target') ? opts.target : defaults.target;
this.validate = opts.hasOwnProperty('validate') ? opts.validate : defaults.validate;
this.ignoreTags = [];
// linkAttributes and linkClass is deprecated
this.attributes = opts.attributes || opts.linkAttributes || defaults.attributes;
this.className = opts.hasOwnProperty('className') ? opts.className : opts.linkClass || defaults.className;
// Make all tags names upper case
var ignoredTags = opts.hasOwnProperty('ignoreTags') ? opts.ignoreTags : defaults.ignoreTags;
for (var i = 0; i < ignoredTags.length; i++) {
this.ignoreTags.push(ignoredTags[i].toUpperCase());
}
}
Options.prototype = {
/**
* Given the token, return all options for how it should be displayed
*/
resolve: function resolve(token) {
var href = token.toHref(this.defaultProtocol);
return {
formatted: this.get('format', token.toString(), token),
formattedHref: this.get('formatHref', href, token),
tagName: this.get('tagName', href, token),
className: this.get('className', href, token),
target: this.get('target', href, token),
events: this.getObject('events', href, token),
attributes: this.getObject('attributes', href, token)
};
},
/**
* Returns true or false based on whether a token should be displayed as a
* link based on the user options. By default,
*/
check: function check(token) {
return this.get('validate', token.toString(), token);
},
// Private methods
/**
* Resolve an option's value based on the value of the option and the given
* params.
* @param {String} key Name of option to use
* @param operator will be passed to the target option if it's method
* @param {MultiToken} token The token from linkify.tokenize
*/
get: function get(key, operator, token) {
var optionValue = void 0,
option = this[key];
if (!option) {
return option;
}
switch (typeof option === 'undefined' ? 'undefined' : _typeof(option)) {
case 'function':
return option(operator, token.type);
case 'object':
optionValue = option.hasOwnProperty(token.type) ? option[token.type] : defaults[key];
return typeof optionValue === 'function' ? optionValue(operator, token.type) : optionValue;
}
return option;
},
getObject: function getObject(key, operator, token) {
var option = this[key];
return typeof option === 'function' ? option(operator, token.type) : option;
}
};
/**
* Quick indexOf replacement for checking the ignoreTags option
*/
function contains(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return true;
}
}
return false;
}
function noop(val) {
return val;
}
function typeToTarget(href, type) {
return type === 'url' ? '_blank' : null;
}
/***/ }),
/***/ "31f4":
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
var un = that === undefined;
switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ }),
/***/ "32e9":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("86cc");
var createDesc = __webpack_require__("4630");
module.exports = __webpack_require__("9e1e") ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/***/ "3339":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-col-messages{position:relative;height:100%;flex:1;overflow:hidden;display:flex;flex-flow:column}.vac-col-messages .vac-container-center{height:100%;width:100%;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}.vac-col-messages .vac-room-empty{font-size:14px;color:#9ca6af;font-style:italic;line-height:20px;white-space:pre-line}.vac-col-messages .vac-room-empty div{padding:0 10%}.vac-col-messages .vac-container-scroll{background:var(--chat-content-bg-color);flex:1;overflow-y:auto;margin-right:1px;margin-top:60px;-webkit-overflow-scrolling:touch}.vac-col-messages .vac-container-scroll.vac-scroll-smooth{scroll-behavior:smooth}.vac-col-messages .vac-messages-container{padding:0 5px 5px}.vac-col-messages .vac-text-started{font-size:14px;color:var(--chat-message-color-started);font-style:italic;text-align:center;margin-top:30px;margin-bottom:20px}.vac-col-messages .vac-infinite-loading{height:68px}.vac-col-messages .vac-icon-scroll{position:absolute;bottom:80px;right:20px;padding:8px;background:var(--chat-bg-scroll-icon);border-radius:50%;box-shadow:0 1px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 2px 0 rgba(0,0,0,.12);display:flex;cursor:pointer;z-index:10}.vac-col-messages .vac-icon-scroll svg{height:25px;width:25px}.vac-col-messages .vac-messages-count{position:absolute;top:-8px;left:11px;background-color:var(--chat-message-bg-color-scroll-counter);color:var(--chat-message-color-scroll-counter)}.vac-col-messages .vac-room-footer{width:100%;border-bottom-right-radius:4px;z-index:10}.vac-col-messages .vac-box-footer{display:flex;position:relative;background:var(--chat-footer-bg-color);padding:10px 8px 10px}.vac-col-messages .vac-textarea{height:20px;width:100%;line-height:20px;overflow:hidden;outline:0;resize:none;border-radius:20px;padding:12px 16px;box-sizing:content-box;font-size:16px;background:var(--chat-bg-color-input);color:var(--chat-color);caret-color:var(--chat-color-caret);border:var(--chat-border-style-input)}.vac-col-messages .vac-textarea::-moz-placeholder{color:var(--chat-color-placeholder);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vac-col-messages .vac-textarea:-ms-input-placeholder{color:var(--chat-color-placeholder);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vac-col-messages .vac-textarea::placeholder{color:var(--chat-color-placeholder);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vac-col-messages .vac-textarea-outline{border:1px solid var(--chat-border-color-input-selected);box-shadow:inset 0 0 0 1px var(--chat-border-color-input-selected)}.vac-col-messages .vac-icon-textarea,.vac-col-messages .vac-icon-textarea-left{display:flex;align-items:center}.vac-col-messages .vac-icon-textarea-left .vac-wrapper,.vac-col-messages .vac-icon-textarea-left svg,.vac-col-messages .vac-icon-textarea .vac-wrapper,.vac-col-messages .vac-icon-textarea svg{margin:0 7px}.vac-col-messages .vac-icon-textarea{margin-left:5px}.vac-col-messages .vac-icon-textarea-left{display:flex;align-items:center;margin-right:5px}.vac-col-messages .vac-icon-textarea-left .vac-wrapper,.vac-col-messages .vac-icon-textarea-left svg{margin:0 7px}.vac-col-messages .vac-icon-textarea-left .vac-icon-microphone{fill:var(--chat-icon-color-microphone);margin:0 7px}.vac-col-messages .vac-icon-textarea-left .vac-dot-audio-record{height:15px;width:15px;border-radius:50%;background-color:var(--chat-message-bg-color-audio-record);-webkit-animation:vac-scaling .8s ease-in-out infinite alternate;animation:vac-scaling .8s ease-in-out infinite alternate}@-webkit-keyframes vac-scaling{0%{transform:scale(1);opacity:.4}to{transform:scale(1.1);opacity:1}}@keyframes vac-scaling{0%{transform:scale(1);opacity:.4}to{transform:scale(1.1);opacity:1}}.vac-col-messages .vac-icon-textarea-left .vac-dot-audio-record-time{font-size:16px;color:var(--chat-color);margin-left:8px;width:45px}.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-confirm,.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-confirm svg,.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-stop,.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-stop svg{min-height:28px;min-width:28px}.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-stop{margin-right:20px}.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-stop #vac-icon-close-outline{fill:var(--chat-icon-color-audio-cancel)}.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-confirm{margin-right:3px;margin-left:12px}.vac-col-messages .vac-icon-textarea-left .vac-icon-audio-confirm #vac-icon-checkmark{fill:var(--chat-icon-color-audio-confirm)}.vac-col-messages .vac-media-container{position:absolute;max-width:25%;left:16px;top:18px}.vac-col-messages .vac-media-file{display:flex;justify-content:center;flex-direction:column;min-height:30px}.vac-col-messages .vac-media-file img{border-radius:15px;width:100%;max-width:150px;max-height:100%}.vac-col-messages .vac-media-file video{border-radius:15px;width:100%;max-width:250px;max-height:100%}.vac-col-messages .vac-icon-media{position:absolute;top:6px;left:6px;z-index:10}.vac-col-messages .vac-icon-media svg{height:20px;width:20px;border-radius:50%}.vac-col-messages .vac-icon-media:before{content:\" \";position:absolute;width:100%;height:100%;background:rgba(0,0,0,.5);border-radius:50%;z-index:-1}.vac-col-messages .vac-file-container{display:flex;align-items:center;width:calc(100% - 115px);height:20px;padding:12px 0;box-sizing:content-box;background:var(--chat-bg-color-input);border:var(--chat-border-style-input);border-radius:20px}.vac-col-messages .vac-file-container.vac-file-container-edit{width:calc(100% - 150px)}.vac-col-messages .vac-file-container .vac-icon-file{display:flex;margin:0 8px 0 15px}.vac-col-messages .vac-file-container .vac-file-message{max-width:calc(100% - 75px);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vac-col-messages .vac-file-container .vac-icon-remove{margin:0 8px}.vac-col-messages .vac-file-container .vac-icon-remove svg{height:18px;width:18px}.vac-col-messages .vac-send-disabled,.vac-col-messages .vac-send-disabled svg{cursor:none!important;pointer-events:none!important;transform:none!important}.vac-col-messages .vac-messages-hidden{opacity:0}@media only screen and (max-width:768px){.vac-col-messages .vac-container-scroll{margin-top:50px}.vac-col-messages .vac-infinite-loading{height:58px}.vac-col-messages .vac-box-footer{border-top:var(--chat-border-style-input);padding:7px 2px 7px 7px}.vac-col-messages .vac-text-started{margin-top:20px}.vac-col-messages .vac-textarea{padding:7px;line-height:18px}.vac-col-messages .vac-textarea::-moz-placeholder{color:transparent}.vac-col-messages .vac-textarea:-ms-input-placeholder{color:transparent}.vac-col-messages .vac-textarea::placeholder{color:transparent}.vac-col-messages .vac-icon-textarea-left .vac-wrapper,.vac-col-messages .vac-icon-textarea-left svg,.vac-col-messages .vac-icon-textarea .vac-wrapper,.vac-col-messages .vac-icon-textarea svg{margin:0 5px!important}.vac-col-messages .vac-media-container{top:10px;left:10px}.vac-col-messages .vac-media-file img,.vac-col-messages .vac-media-file video{transform:scale(.97)}.vac-col-messages .vac-room-footer{width:100%}.vac-col-messages .vac-file-container{padding:7px 0}.vac-col-messages .vac-file-container .icon-file{margin-left:10px}.vac-col-messages .vac-icon-scroll{bottom:70px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "33a4":
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__("84f2");
var ITERATOR = __webpack_require__("2b4c")('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/***/ "3545":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-reply-message{background:var(--chat-message-bg-color-reply);border-radius:4px;margin:-1px -5px 8px;padding:8px 10px}.vac-reply-message .vac-reply-username{color:var(--chat-message-color-reply-username);font-size:12px;line-height:15px;margin-bottom:2px}.vac-reply-message .vac-image-reply-container{width:70px}.vac-reply-message .vac-image-reply-container .vac-message-image-reply{height:70px;width:70px;margin:4px auto 3px}.vac-reply-message .vac-video-reply-container{width:200px;max-width:100%}.vac-reply-message .vac-video-reply-container video{border-radius:4px}.vac-reply-message .vac-reply-content{font-size:12px;color:var(--chat-message-color-reply-content)}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "35d6":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "default", function() { return /* binding */ addStylesToShadowDOM; });
// CONCATENATED MODULE: ./node_modules/vue-style-loader/lib/listToStyles.js
/**
* Translates the list format produced by css-loader into something
* easier to manipulate.
*/
function listToStyles (parentId, list) {
var styles = []
var newStyles = {}
for (var i = 0; i < list.length; i++) {
var item = list[i]
var id = item[0]
var css = item[1]
var media = item[2]
var sourceMap = item[3]
var part = {
id: parentId + ':' + i,
css: css,
media: media,
sourceMap: sourceMap
}
if (!newStyles[id]) {
styles.push(newStyles[id] = { id: id, parts: [part] })
} else {
newStyles[id].parts.push(part)
}
}
return styles
}
// CONCATENATED MODULE: ./node_modules/vue-style-loader/lib/addStylesShadow.js
function addStylesToShadowDOM (parentId, list, shadowRoot) {
var styles = listToStyles(parentId, list)
addStyles(styles, shadowRoot)
}
/*
type StyleObject = {
id: number;
parts: Array<StyleObjectPart>
}
type StyleObjectPart = {
css: string;
media: string;
sourceMap: ?string
}
*/
function addStyles (styles /* Array<StyleObject> */, shadowRoot) {
const injectedStyles =
shadowRoot._injectedStyles ||
(shadowRoot._injectedStyles = {})
for (var i = 0; i < styles.length; i++) {
var item = styles[i]
var style = injectedStyles[item.id]
if (!style) {
for (var j = 0; j < item.parts.length; j++) {
addStyle(item.parts[j], shadowRoot)
}
injectedStyles[item.id] = true
}
}
}
function createStyleElement (shadowRoot) {
var styleElement = document.createElement('style')
styleElement.type = 'text/css'
shadowRoot.appendChild(styleElement)
return styleElement
}
function addStyle (obj /* StyleObjectPart */, shadowRoot) {
var styleElement = createStyleElement(shadowRoot)
var css = obj.css
var media = obj.media
var sourceMap = obj.sourceMap
if (media) {
styleElement.setAttribute('media', media)
}
if (sourceMap) {
// https://developer.chrome.com/devtools/docs/javascript-debugging
// this makes source maps inside style tags work properly in Chrome
css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'
// http://stackoverflow.com/a/26603875
css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'
}
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = css
} else {
while (styleElement.firstChild) {
styleElement.removeChild(styleElement.firstChild)
}
styleElement.appendChild(document.createTextNode(css))
}
}
/***/ }),
/***/ "35f2":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_SvgIcon_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("7ebf");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_SvgIcon_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_SvgIcon_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "3662":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("88f6");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("14cf3ada", content, shadowRoot)
};
/***/ }),
/***/ "3687":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomContent_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("3662");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomContent_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomContent_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "36bd":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var toObject = __webpack_require__("4bf8");
var toAbsoluteIndex = __webpack_require__("77f1");
var toLength = __webpack_require__("9def");
module.exports = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = toLength(O.length);
var aLen = arguments.length;
var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
var end = aLen > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
/***/ }),
/***/ "37c8":
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__("2b4c");
/***/ }),
/***/ "384a":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("7154");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("2979e74c", content, shadowRoot)
};
/***/ }),
/***/ "386b":
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__("5ca1");
var fails = __webpack_require__("79e5");
var defined = __webpack_require__("be13");
var quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function (string, tag, attribute, value) {
var S = String(defined(string));
var p1 = '<' + tag;
if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function (NAME, exec) {
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function () {
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ }),
/***/ "386d":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__("cb7c");
var sameValue = __webpack_require__("83a1");
var regExpExec = __webpack_require__("5f1b");
// @@search logic
__webpack_require__("214f")('search', 1, function (defined, SEARCH, $search, maybeCallNative) {
return [
// `String.prototype.search` method
// https://tc39.github.io/ecma262/#sec-string.prototype.search
function search(regexp) {
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
},
// `RegExp.prototype[@@search]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
function (regexp) {
var res = maybeCallNative($search, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var previousLastIndex = rx.lastIndex;
if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
var result = regExpExec(rx, S);
if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
return result === null ? -1 : result.index;
}
];
});
/***/ }),
/***/ "38fd":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__("69a8");
var toObject = __webpack_require__("4bf8");
var IE_PROTO = __webpack_require__("613b")('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/***/ "3a72":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var core = __webpack_require__("8378");
var LIBRARY = __webpack_require__("2d00");
var wksExt = __webpack_require__("37c8");
var defineProperty = __webpack_require__("86cc").f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
/***/ }),
/***/ "3afd":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-button-reaction{display:inline-flex;align-items:center;border:var(--chat-message-border-style-reaction);outline:none;background:var(--chat-message-bg-color-reaction);border-radius:4px;margin:4px 2px 0;transition:.3s;padding:0 5px;font-size:18px;line-height:23px}.vac-button-reaction span{font-size:11px;font-weight:500;min-width:7px;color:var(--chat-message-color-reaction-counter)}.vac-button-reaction:hover{border:var(--chat-message-border-style-reaction-hover);background:var(--chat-message-bg-color-reaction-hover);cursor:pointer}.vac-button-reaction.vac-reaction-me{border:var(--chat-message-border-style-reaction-me);background:var(--chat-message-bg-color-reaction-me)}.vac-button-reaction.vac-reaction-me span{color:var(--chat-message-color-reaction-counter-me)}.vac-button-reaction.vac-reaction-me:hover{border:var(--chat-message-border-style-reaction-hover-me);background:var(--chat-message-bg-color-reaction-hover-me)}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "3b2b":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var inheritIfRequired = __webpack_require__("5dbc");
var dP = __webpack_require__("86cc").f;
var gOPN = __webpack_require__("9093").f;
var isRegExp = __webpack_require__("aae3");
var $flags = __webpack_require__("0bfb");
var $RegExp = global.RegExp;
var Base = $RegExp;
var proto = $RegExp.prototype;
var re1 = /a/g;
var re2 = /a/g;
// "new" creates a new object, old webkit buggy here
var CORRECT_NEW = new $RegExp(re1) !== re1;
if (__webpack_require__("9e1e") && (!CORRECT_NEW || __webpack_require__("79e5")(function () {
re2[__webpack_require__("2b4c")('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))) {
$RegExp = function RegExp(p, f) {
var tiRE = this instanceof $RegExp;
var piRE = isRegExp(p);
var fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function (key) {
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function () { return Base[key]; },
set: function (it) { Base[key] = it; }
});
};
for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__("2aba")(global, 'RegExp', $RegExp);
}
__webpack_require__("7a56")('RegExp');
/***/ }),
/***/ "3c0d":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_EmojiPicker_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("42d3");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_EmojiPicker_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_EmojiPicker_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "3cd7":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomMessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("d62c");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomMessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomMessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "3fee":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("c735");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("5a6fe0e4", content, shadowRoot)
};
/***/ }),
/***/ "4128":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.start = exports.run = exports.TOKENS = exports.State = undefined;
var _state = __webpack_require__("1652");
var _multi = __webpack_require__("bea1");
var MULTI_TOKENS = _interopRequireWildcard(_multi);
var _text = __webpack_require__("7656");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
Not exactly parser, more like the second-stage scanner (although we can
theoretically hotswap the code here with a real parser in the future... but
for a little URL-finding utility abstract syntax trees may be a little
overkill).
URL format: http://en.wikipedia.org/wiki/URI_scheme
Email format: http://en.wikipedia.org/wiki/Email_address (links to RFC in
reference)
@module linkify
@submodule parser
@main parser
*/
var makeState = function makeState(tokenClass) {
return new _state.TokenState(tokenClass);
};
// The universal starting state.
var S_START = makeState();
// Intermediate states for URLs. Note that domains that begin with a protocol
// are treated slighly differently from those that don't.
var S_PROTOCOL = makeState(); // e.g., 'http:'
var S_MAILTO = makeState(); // 'mailto:'
var S_PROTOCOL_SLASH = makeState(); // e.g., '/', 'http:/''
var S_PROTOCOL_SLASH_SLASH = makeState(); // e.g., '//', 'http://'
var S_DOMAIN = makeState(); // parsed string ends with a potential domain name (A)
var S_DOMAIN_DOT = makeState(); // (A) domain followed by DOT
var S_TLD = makeState(_multi.URL); // (A) Simplest possible URL with no query string
var S_TLD_COLON = makeState(); // (A) URL followed by colon (potential port number here)
var S_TLD_PORT = makeState(_multi.URL); // TLD followed by a port number
var S_URL = makeState(_multi.URL); // Long URL with optional port and maybe query string
var S_URL_NON_ACCEPTING = makeState(); // URL followed by some symbols (will not be part of the final URL)
var S_URL_OPENBRACE = makeState(); // URL followed by {
var S_URL_OPENBRACKET = makeState(); // URL followed by [
var S_URL_OPENANGLEBRACKET = makeState(); // URL followed by <
var S_URL_OPENPAREN = makeState(); // URL followed by (
var S_URL_OPENBRACE_Q = makeState(_multi.URL); // URL followed by { and some symbols that the URL can end it
var S_URL_OPENBRACKET_Q = makeState(_multi.URL); // URL followed by [ and some symbols that the URL can end it
var S_URL_OPENANGLEBRACKET_Q = makeState(_multi.URL); // URL followed by < and some symbols that the URL can end it
var S_URL_OPENPAREN_Q = makeState(_multi.URL); // URL followed by ( and some symbols that the URL can end it
var S_URL_OPENBRACE_SYMS = makeState(); // S_URL_OPENBRACE_Q followed by some symbols it cannot end it
var S_URL_OPENBRACKET_SYMS = makeState(); // S_URL_OPENBRACKET_Q followed by some symbols it cannot end it
var S_URL_OPENANGLEBRACKET_SYMS = makeState(); // S_URL_OPENANGLEBRACKET_Q followed by some symbols it cannot end it
var S_URL_OPENPAREN_SYMS = makeState(); // S_URL_OPENPAREN_Q followed by some symbols it cannot end it
var S_EMAIL_DOMAIN = makeState(); // parsed string starts with local email info + @ with a potential domain name (C)
var S_EMAIL_DOMAIN_DOT = makeState(); // (C) domain followed by DOT
var S_EMAIL = makeState(_multi.EMAIL); // (C) Possible email address (could have more tlds)
var S_EMAIL_COLON = makeState(); // (C) URL followed by colon (potential port number here)
var S_EMAIL_PORT = makeState(_multi.EMAIL); // (C) Email address with a port
var S_MAILTO_EMAIL = makeState(_multi.MAILTOEMAIL); // Email that begins with the mailto prefix (D)
var S_MAILTO_EMAIL_NON_ACCEPTING = makeState(); // (D) Followed by some non-query string chars
var S_LOCALPART = makeState(); // Local part of the email address
var S_LOCALPART_AT = makeState(); // Local part of the email address plus @
var S_LOCALPART_DOT = makeState(); // Local part of the email address plus '.' (localpart cannot end in .)
var S_NL = makeState(_multi.NL); // single new line
// Make path from start to protocol (with '//')
S_START.on(_text.NL, S_NL).on(_text.PROTOCOL, S_PROTOCOL).on(_text.MAILTO, S_MAILTO).on(_text.SLASH, S_PROTOCOL_SLASH);
S_PROTOCOL.on(_text.SLASH, S_PROTOCOL_SLASH);
S_PROTOCOL_SLASH.on(_text.SLASH, S_PROTOCOL_SLASH_SLASH);
// The very first potential domain name
S_START.on(_text.TLD, S_DOMAIN).on(_text.DOMAIN, S_DOMAIN).on(_text.LOCALHOST, S_TLD).on(_text.NUM, S_DOMAIN);
// Force URL for protocol followed by anything sane
S_PROTOCOL_SLASH_SLASH.on(_text.TLD, S_URL).on(_text.DOMAIN, S_URL).on(_text.NUM, S_URL).on(_text.LOCALHOST, S_URL);
// Account for dots and hyphens
// hyphens are usually parts of domain names
S_DOMAIN.on(_text.DOT, S_DOMAIN_DOT);
S_EMAIL_DOMAIN.on(_text.DOT, S_EMAIL_DOMAIN_DOT);
// Hyphen can jump back to a domain name
// After the first domain and a dot, we can find either a URL or another domain
S_DOMAIN_DOT.on(_text.TLD, S_TLD).on(_text.DOMAIN, S_DOMAIN).on(_text.NUM, S_DOMAIN).on(_text.LOCALHOST, S_DOMAIN);
S_EMAIL_DOMAIN_DOT.on(_text.TLD, S_EMAIL).on(_text.DOMAIN, S_EMAIL_DOMAIN).on(_text.NUM, S_EMAIL_DOMAIN).on(_text.LOCALHOST, S_EMAIL_DOMAIN);
// S_TLD accepts! But the URL could be longer, try to find a match greedily
// The `run` function should be able to "rollback" to the accepting state
S_TLD.on(_text.DOT, S_DOMAIN_DOT);
S_EMAIL.on(_text.DOT, S_EMAIL_DOMAIN_DOT);
// Become real URLs after `SLASH` or `COLON NUM SLASH`
// Here PSS and non-PSS converge
S_TLD.on(_text.COLON, S_TLD_COLON).on(_text.SLASH, S_URL);
S_TLD_COLON.on(_text.NUM, S_TLD_PORT);
S_TLD_PORT.on(_text.SLASH, S_URL);
S_EMAIL.on(_text.COLON, S_EMAIL_COLON);
S_EMAIL_COLON.on(_text.NUM, S_EMAIL_PORT);
// Types of characters the URL can definitely end in
var qsAccepting = [_text.DOMAIN, _text.AT, _text.LOCALHOST, _text.NUM, _text.PLUS, _text.POUND, _text.PROTOCOL, _text.SLASH, _text.TLD, _text.UNDERSCORE, _text.SYM, _text.AMPERSAND];
// Types of tokens that can follow a URL and be part of the query string
// but cannot be the very last characters
// Characters that cannot appear in the URL at all should be excluded
var qsNonAccepting = [_text.COLON, _text.DOT, _text.QUERY, _text.PUNCTUATION, _text.CLOSEBRACE, _text.CLOSEBRACKET, _text.CLOSEANGLEBRACKET, _text.CLOSEPAREN, _text.OPENBRACE, _text.OPENBRACKET, _text.OPENANGLEBRACKET, _text.OPENPAREN];
// These states are responsible primarily for determining whether or not to
// include the final round bracket.
// URL, followed by an opening bracket
S_URL.on(_text.OPENBRACE, S_URL_OPENBRACE).on(_text.OPENBRACKET, S_URL_OPENBRACKET).on(_text.OPENANGLEBRACKET, S_URL_OPENANGLEBRACKET).on(_text.OPENPAREN, S_URL_OPENPAREN);
// URL with extra symbols at the end, followed by an opening bracket
S_URL_NON_ACCEPTING.on(_text.OPENBRACE, S_URL_OPENBRACE).on(_text.OPENBRACKET, S_URL_OPENBRACKET).on(_text.OPENANGLEBRACKET, S_URL_OPENANGLEBRACKET).on(_text.OPENPAREN, S_URL_OPENPAREN);
// Closing bracket component. This character WILL be included in the URL
S_URL_OPENBRACE.on(_text.CLOSEBRACE, S_URL);
S_URL_OPENBRACKET.on(_text.CLOSEBRACKET, S_URL);
S_URL_OPENANGLEBRACKET.on(_text.CLOSEANGLEBRACKET, S_URL);
S_URL_OPENPAREN.on(_text.CLOSEPAREN, S_URL);
S_URL_OPENBRACE_Q.on(_text.CLOSEBRACE, S_URL);
S_URL_OPENBRACKET_Q.on(_text.CLOSEBRACKET, S_URL);
S_URL_OPENANGLEBRACKET_Q.on(_text.CLOSEANGLEBRACKET, S_URL);
S_URL_OPENPAREN_Q.on(_text.CLOSEPAREN, S_URL);
S_URL_OPENBRACE_SYMS.on(_text.CLOSEBRACE, S_URL);
S_URL_OPENBRACKET_SYMS.on(_text.CLOSEBRACKET, S_URL);
S_URL_OPENANGLEBRACKET_SYMS.on(_text.CLOSEANGLEBRACKET, S_URL);
S_URL_OPENPAREN_SYMS.on(_text.CLOSEPAREN, S_URL);
// URL that beings with an opening bracket, followed by a symbols.
// Note that the final state can still be `S_URL_OPENBRACE_Q` (if the URL only
// has a single opening bracket for some reason).
S_URL_OPENBRACE.on(qsAccepting, S_URL_OPENBRACE_Q);
S_URL_OPENBRACKET.on(qsAccepting, S_URL_OPENBRACKET_Q);
S_URL_OPENANGLEBRACKET.on(qsAccepting, S_URL_OPENANGLEBRACKET_Q);
S_URL_OPENPAREN.on(qsAccepting, S_URL_OPENPAREN_Q);
S_URL_OPENBRACE.on(qsNonAccepting, S_URL_OPENBRACE_SYMS);
S_URL_OPENBRACKET.on(qsNonAccepting, S_URL_OPENBRACKET_SYMS);
S_URL_OPENANGLEBRACKET.on(qsNonAccepting, S_URL_OPENANGLEBRACKET_SYMS);
S_URL_OPENPAREN.on(qsNonAccepting, S_URL_OPENPAREN_SYMS);
// URL that begins with an opening bracket, followed by some symbols
S_URL_OPENBRACE_Q.on(qsAccepting, S_URL_OPENBRACE_Q);
S_URL_OPENBRACKET_Q.on(qsAccepting, S_URL_OPENBRACKET_Q);
S_URL_OPENANGLEBRACKET_Q.on(qsAccepting, S_URL_OPENANGLEBRACKET_Q);
S_URL_OPENPAREN_Q.on(qsAccepting, S_URL_OPENPAREN_Q);
S_URL_OPENBRACE_Q.on(qsNonAccepting, S_URL_OPENBRACE_Q);
S_URL_OPENBRACKET_Q.on(qsNonAccepting, S_URL_OPENBRACKET_Q);
S_URL_OPENANGLEBRACKET_Q.on(qsNonAccepting, S_URL_OPENANGLEBRACKET_Q);
S_URL_OPENPAREN_Q.on(qsNonAccepting, S_URL_OPENPAREN_Q);
S_URL_OPENBRACE_SYMS.on(qsAccepting, S_URL_OPENBRACE_Q);
S_URL_OPENBRACKET_SYMS.on(qsAccepting, S_URL_OPENBRACKET_Q);
S_URL_OPENANGLEBRACKET_SYMS.on(qsAccepting, S_URL_OPENANGLEBRACKET_Q);
S_URL_OPENPAREN_SYMS.on(qsAccepting, S_URL_OPENPAREN_Q);
S_URL_OPENBRACE_SYMS.on(qsNonAccepting, S_URL_OPENBRACE_SYMS);
S_URL_OPENBRACKET_SYMS.on(qsNonAccepting, S_URL_OPENBRACKET_SYMS);
S_URL_OPENANGLEBRACKET_SYMS.on(qsNonAccepting, S_URL_OPENANGLEBRACKET_SYMS);
S_URL_OPENPAREN_SYMS.on(qsNonAccepting, S_URL_OPENPAREN_SYMS);
// Account for the query string
S_URL.on(qsAccepting, S_URL);
S_URL_NON_ACCEPTING.on(qsAccepting, S_URL);
S_URL.on(qsNonAccepting, S_URL_NON_ACCEPTING);
S_URL_NON_ACCEPTING.on(qsNonAccepting, S_URL_NON_ACCEPTING);
// Email address-specific state definitions
// Note: We are not allowing '/' in email addresses since this would interfere
// with real URLs
// For addresses with the mailto prefix
// 'mailto:' followed by anything sane is a valid email
S_MAILTO.on(_text.TLD, S_MAILTO_EMAIL).on(_text.DOMAIN, S_MAILTO_EMAIL).on(_text.NUM, S_MAILTO_EMAIL).on(_text.LOCALHOST, S_MAILTO_EMAIL);
// Greedily get more potential valid email values
S_MAILTO_EMAIL.on(qsAccepting, S_MAILTO_EMAIL).on(qsNonAccepting, S_MAILTO_EMAIL_NON_ACCEPTING);
S_MAILTO_EMAIL_NON_ACCEPTING.on(qsAccepting, S_MAILTO_EMAIL).on(qsNonAccepting, S_MAILTO_EMAIL_NON_ACCEPTING);
// For addresses without the mailto prefix
// Tokens allowed in the localpart of the email
var localpartAccepting = [_text.DOMAIN, _text.NUM, _text.PLUS, _text.POUND, _text.QUERY, _text.UNDERSCORE, _text.SYM, _text.AMPERSAND, _text.TLD];
// Some of the tokens in `localpartAccepting` are already accounted for here and
// will not be overwritten (don't worry)
S_DOMAIN.on(localpartAccepting, S_LOCALPART).on(_text.AT, S_LOCALPART_AT);
S_TLD.on(localpartAccepting, S_LOCALPART).on(_text.AT, S_LOCALPART_AT);
S_DOMAIN_DOT.on(localpartAccepting, S_LOCALPART);
// Okay we're on a localpart. Now what?
// TODO: IP addresses and what if the email starts with numbers?
S_LOCALPART.on(localpartAccepting, S_LOCALPART).on(_text.AT, S_LOCALPART_AT) // close to an email address now
.on(_text.DOT, S_LOCALPART_DOT);
S_LOCALPART_DOT.on(localpartAccepting, S_LOCALPART);
S_LOCALPART_AT.on(_text.TLD, S_EMAIL_DOMAIN).on(_text.DOMAIN, S_EMAIL_DOMAIN).on(_text.LOCALHOST, S_EMAIL);
// States following `@` defined above
var run = function run(tokens) {
var len = tokens.length;
var cursor = 0;
var multis = [];
var textTokens = [];
while (cursor < len) {
var state = S_START;
var secondState = null;
var nextState = null;
var multiLength = 0;
var latestAccepting = null;
var sinceAccepts = -1;
while (cursor < len && !(secondState = state.next(tokens[cursor]))) {
// Starting tokens with nowhere to jump to.
// Consider these to be just plain text
textTokens.push(tokens[cursor++]);
}
while (cursor < len && (nextState = secondState || state.next(tokens[cursor]))) {
// Get the next state
secondState = null;
state = nextState;
// Keep track of the latest accepting state
if (state.accepts()) {
sinceAccepts = 0;
latestAccepting = state;
} else if (sinceAccepts >= 0) {
sinceAccepts++;
}
cursor++;
multiLength++;
}
if (sinceAccepts < 0) {
// No accepting state was found, part of a regular text token
// Add all the tokens we looked at to the text tokens array
for (var i = cursor - multiLength; i < cursor; i++) {
textTokens.push(tokens[i]);
}
} else {
// Accepting state!
// First close off the textTokens (if available)
if (textTokens.length > 0) {
multis.push(new _multi.TEXT(textTokens));
textTokens = [];
}
// Roll back to the latest accepting state
cursor -= sinceAccepts;
multiLength -= sinceAccepts;
// Create a new multitoken
var MULTI = latestAccepting.emit();
multis.push(new MULTI(tokens.slice(cursor - multiLength, cursor)));
}
}
// Finally close off the textTokens (if available)
if (textTokens.length > 0) {
multis.push(new _multi.TEXT(textTokens));
}
return multis;
};
exports.State = _state.TokenState;
exports.TOKENS = MULTI_TOKENS;
exports.run = run;
exports.start = S_START;
/***/ }),
/***/ "41a0":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__("2aeb");
var descriptor = __webpack_require__("4630");
var setToStringTag = __webpack_require__("7f20");
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__("32e9")(IteratorPrototype, __webpack_require__("2b4c")('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/***/ "42d3":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("d48d");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("a4c65684", content, shadowRoot)
};
/***/ }),
/***/ "456d":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__("4bf8");
var $keys = __webpack_require__("0d58");
__webpack_require__("5eda")('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/***/ "4588":
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/***/ "4630":
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/***/ "46f3":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
function createTokenClass() {
return function (value) {
if (value) {
this.v = value;
}
};
}
exports.createTokenClass = createTokenClass;
/***/ }),
/***/ "48c0":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.5 String.prototype.bold()
__webpack_require__("386b")('bold', function (createHTML) {
return function bold() {
return createHTML(this, 'b', '', '');
};
});
/***/ }),
/***/ "4917":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__("cb7c");
var toLength = __webpack_require__("9def");
var advanceStringIndex = __webpack_require__("0390");
var regExpExec = __webpack_require__("5f1b");
// @@match logic
__webpack_require__("214f")('match', 1, function (defined, MATCH, $match, maybeCallNative) {
return [
// `String.prototype.match` method
// https://tc39.github.io/ecma262/#sec-string.prototype.match
function match(regexp) {
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
},
// `RegExp.prototype[@@match]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
function (regexp) {
var res = maybeCallNative($match, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
if (!rx.global) return regExpExec(rx, S);
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
var A = [];
var n = 0;
var result;
while ((result = regExpExec(rx, S)) !== null) {
var matchStr = String(result[0]);
A[n] = matchStr;
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
n++;
}
return n === 0 ? null : A;
}
];
});
/***/ }),
/***/ "4a59":
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__("9b43");
var call = __webpack_require__("1fa8");
var isArrayIter = __webpack_require__("33a4");
var anObject = __webpack_require__("cb7c");
var toLength = __webpack_require__("9def");
var getIterFn = __webpack_require__("27ee");
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/***/ "4bf8":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__("be13");
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/***/ "4c1d":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "roomsValidation", function() { return /* binding */ roomsValidation; });
__webpack_require__.d(__webpack_exports__, "partcipantsValidation", function() { return /* binding */ partcipantsValidation; });
__webpack_require__.d(__webpack_exports__, "messagesValidation", function() { return /* binding */ messagesValidation; });
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.symbol.js
var es6_symbol = __webpack_require__("8a81");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.iterator.js
var es6_string_iterator = __webpack_require__("5df3");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.to-string.js
var es6_object_to_string = __webpack_require__("06db");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.iterator.js
var es6_array_iterator = __webpack_require__("cadf");
// EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom.iterable.js
var web_dom_iterable = __webpack_require__("ac6a");
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.every.js
var es6_array_every = __webpack_require__("6095");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.is-array.js
var es6_array_is_array = __webpack_require__("2caf");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.find.js
var es6_array_find = __webpack_require__("7514");
// CONCATENATED MODULE: ./src/utils/data-validation.js
function roomsValidation(obj) {
var roomsValidate = [{
key: 'roomId',
type: ['string', 'number']
}, {
key: 'roomName',
type: ['string']
}, {
key: 'users',
type: ['array']
}];
var validate = function validate(obj, props) {
return props.every(function (prop) {
var validType = false;
if (prop.type[0] === 'array' && Array.isArray(obj[prop.key])) {
validType = true;
} else if (prop.type.find(function (t) {
return t === _typeof(obj[prop.key]);
})) {
validType = true;
}
return validType && checkObjectValid(obj, prop.key);
});
};
if (!validate(obj, roomsValidate)) {
throw new Error('Rooms object is not valid! Must contain roomId[String, Number], roomName[String] and users[Array]');
}
}
function partcipantsValidation(obj) {
var participantsValidate = [{
key: '_id',
type: ['string', 'number']
}, {
key: 'username',
type: ['string']
}];
var validate = function validate(obj, props) {
return props.every(function (prop) {
var validType = prop.type.find(function (t) {
return t === _typeof(obj[prop.key]);
});
return validType && checkObjectValid(obj, prop.key);
});
};
if (!validate(obj, participantsValidate)) {
throw new Error('Participants object is not valid! Must contain _id[String, Number] and username[String]');
}
}
function messagesValidation(obj) {
var messagesValidate = [{
key: '_id',
type: ['string', 'number']
}, {
key: 'content',
type: ['string', 'number']
}, {
key: 'senderId',
type: ['string', 'number']
}];
var validate = function validate(obj, props) {
return props.every(function (prop) {
var validType = prop.type.find(function (t) {
return t === _typeof(obj[prop.key]);
});
return validType && checkObjectValid(obj, prop.key);
});
};
if (!validate(obj, messagesValidate)) {
throw new Error('Messages object is not valid! Must contain _id[String, Number], content[String, Number] and senderId[String, Number]');
}
}
function checkObjectValid(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== null && obj[key] !== undefined;
}
/***/ }),
/***/ "4f37":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.25 String.prototype.trim()
__webpack_require__("aa77")('trim', function ($trim) {
return function trim() {
return $trim(this, 3);
};
});
/***/ }),
/***/ "504c":
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__("9e1e");
var getKeys = __webpack_require__("0d58");
var toIObject = __webpack_require__("6821");
var isEnum = __webpack_require__("52a7").f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS || isEnum.call(O, key)) {
result.push(isEntries ? [key, O[key]] : O[key]);
}
}
return result;
};
};
/***/ }),
/***/ "5147":
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__("2b4c")('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
/***/ }),
/***/ "520a":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpFlags = __webpack_require__("0bfb");
var nativeExec = RegExp.prototype.exec;
// This always refers to the native implementation, because the
// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
// which loads this file before patching the method.
var nativeReplace = String.prototype.replace;
var patchedExec = nativeExec;
var LAST_INDEX = 'lastIndex';
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/,
re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1[LAST_INDEX] !== 0 || re2[LAST_INDEX] !== 0;
})();
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
if (PATCH) {
patchedExec = function exec(str) {
var re = this;
var lastIndex, reCopy, match, i;
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re[LAST_INDEX];
match = nativeExec.call(re, str);
if (UPDATES_LAST_INDEX_WRONG && match) {
re[LAST_INDEX] = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
// eslint-disable-next-line no-loop-func
nativeReplace.call(match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
return match;
};
}
module.exports = patchedExec;
/***/ }),
/***/ "52a7":
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/***/ "551c":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__("2d00");
var global = __webpack_require__("7726");
var ctx = __webpack_require__("9b43");
var classof = __webpack_require__("23c6");
var $export = __webpack_require__("5ca1");
var isObject = __webpack_require__("d3f4");
var aFunction = __webpack_require__("d8e8");
var anInstance = __webpack_require__("f605");
var forOf = __webpack_require__("4a59");
var speciesConstructor = __webpack_require__("ebd6");
var task = __webpack_require__("1991").set;
var microtask = __webpack_require__("8079")();
var newPromiseCapabilityModule = __webpack_require__("a5b8");
var perform = __webpack_require__("9c80");
var userAgent = __webpack_require__("a25f");
var promiseResolve = __webpack_require__("bcaa");
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[__webpack_require__("2b4c")('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function')
&& promise.then(empty) instanceof FakePromise
// v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// we can't detect it synchronously, so just check versions
&& v8.indexOf('6.6') !== 0
&& userAgent.indexOf('Chrome/66') === -1;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // may throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
if (domain && !exited) domain.exit();
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__("dcbc")($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__("7f20")($Promise, PROMISE);
__webpack_require__("7a56")(PROMISE);
Wrapper = __webpack_require__("8378")[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__("5cc5")(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
/***/ }),
/***/ "5537":
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__("8378");
var global = __webpack_require__("7726");
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__("2d00") ? 'pure' : 'global',
copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/***/ "55dd":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var aFunction = __webpack_require__("d8e8");
var toObject = __webpack_require__("4bf8");
var fails = __webpack_require__("79e5");
var $sort = [].sort;
var test = [1, 2, 3];
$export($export.P + $export.F * (fails(function () {
// IE8-
test.sort(undefined);
}) || !fails(function () {
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__("2f21")($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn) {
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ }),
/***/ "57e7":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $indexOf = __webpack_require__("c366")(false);
var $native = [].indexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__("2f21")($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ }),
/***/ "589c":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioControl_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("98c5");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioControl_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioControl_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "58b2":
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__("5ca1");
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__("9e1e"), 'Object', { defineProperties: __webpack_require__("1495") });
/***/ }),
/***/ "5a74":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
// This file is imported into lib/wc client bundles.
if (typeof window !== 'undefined') {
var currentScript = window.document.currentScript
if (Object({"NODE_ENV":"production","BASE_URL":"/"}).NEED_CURRENTSCRIPT_POLYFILL) {
var getCurrentScript = __webpack_require__("8875")
currentScript = getCurrentScript()
// for backward compatibility, because previously we directly included the polyfill
if (!('currentScript' in document)) {
Object.defineProperty(document, 'currentScript', { get: getCurrentScript })
}
}
var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
if (src) {
__webpack_require__.p = src[1] // eslint-disable-line
}
}
// Indicate to webpack that this file can be concatenated
/* harmony default export */ var setPublicPath = (null);
// EXTERNAL MODULE: external "Vue"
var external_Vue_ = __webpack_require__("8bbf");
var external_Vue_default = /*#__PURE__*/__webpack_require__.n(external_Vue_);
// CONCATENATED MODULE: ./node_modules/@vue/web-component-wrapper/dist/vue-wc-wrapper.js
const camelizeRE = /-(\w)/g;
const camelize = str => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
};
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = str => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
};
function getInitialProps (propsList) {
const res = {};
propsList.forEach(key => {
res[key] = undefined;
});
return res
}
function injectHook (options, key, hook) {
options[key] = [].concat(options[key] || []);
options[key].unshift(hook);
}
function callHooks (vm, hook) {
if (vm) {
const hooks = vm.$options[hook] || [];
hooks.forEach(hook => {
hook.call(vm);
});
}
}
function createCustomEvent (name, args) {
return new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: args
})
}
const isBoolean = val => /function Boolean/.test(String(val));
const isNumber = val => /function Number/.test(String(val));
function convertAttributeValue (value, name, { type } = {}) {
if (isBoolean(type)) {
if (value === 'true' || value === 'false') {
return value === 'true'
}
if (value === '' || value === name || value != null) {
return true
}
return value
} else if (isNumber(type)) {
const parsed = parseFloat(value, 10);
return isNaN(parsed) ? value : parsed
} else {
return value
}
}
function toVNodes (h, children) {
const res = [];
for (let i = 0, l = children.length; i < l; i++) {
res.push(toVNode(h, children[i]));
}
return res
}
function toVNode (h, node) {
if (node.nodeType === 3) {
return node.data.trim() ? node.data : null
} else if (node.nodeType === 1) {
const data = {
attrs: getAttributes(node),
domProps: {
innerHTML: node.innerHTML
}
};
if (data.attrs.slot) {
data.slot = data.attrs.slot;
delete data.attrs.slot;
}
return h(node.tagName, data)
} else {
return null
}
}
function getAttributes (node) {
const res = {};
for (let i = 0, l = node.attributes.length; i < l; i++) {
const attr = node.attributes[i];
res[attr.nodeName] = attr.nodeValue;
}
return res
}
function wrap (Vue, Component) {
const isAsync = typeof Component === 'function' && !Component.cid;
let isInitialized = false;
let hyphenatedPropsList;
let camelizedPropsList;
let camelizedPropsMap;
function initialize (Component) {
if (isInitialized) return
const options = typeof Component === 'function'
? Component.options
: Component;
// extract props info
const propsList = Array.isArray(options.props)
? options.props
: Object.keys(options.props || {});
hyphenatedPropsList = propsList.map(hyphenate);
camelizedPropsList = propsList.map(camelize);
const originalPropsAsObject = Array.isArray(options.props) ? {} : options.props || {};
camelizedPropsMap = camelizedPropsList.reduce((map, key, i) => {
map[key] = originalPropsAsObject[propsList[i]];
return map
}, {});
// proxy $emit to native DOM events
injectHook(options, 'beforeCreate', function () {
const emit = this.$emit;
this.$emit = (name, ...args) => {
this.$root.$options.customElement.dispatchEvent(createCustomEvent(name, args));
return emit.call(this, name, ...args)
};
});
injectHook(options, 'created', function () {
// sync default props values to wrapper on created
camelizedPropsList.forEach(key => {
this.$root.props[key] = this[key];
});
});
// proxy props as Element properties
camelizedPropsList.forEach(key => {
Object.defineProperty(CustomElement.prototype, key, {
get () {
return this._wrapper.props[key]
},
set (newVal) {
this._wrapper.props[key] = newVal;
},
enumerable: false,
configurable: true
});
});
isInitialized = true;
}
function syncAttribute (el, key) {
const camelized = camelize(key);
const value = el.hasAttribute(key) ? el.getAttribute(key) : undefined;
el._wrapper.props[camelized] = convertAttributeValue(
value,
key,
camelizedPropsMap[camelized]
);
}
class CustomElement extends HTMLElement {
constructor () {
const self = super();
self.attachShadow({ mode: 'open' });
const wrapper = self._wrapper = new Vue({
name: 'shadow-root',
customElement: self,
shadowRoot: self.shadowRoot,
data () {
return {
props: {},
slotChildren: []
}
},
render (h) {
return h(Component, {
ref: 'inner',
props: this.props
}, this.slotChildren)
}
});
// Use MutationObserver to react to future attribute & slot content change
const observer = new MutationObserver(mutations => {
let hasChildrenChange = false;
for (let i = 0; i < mutations.length; i++) {
const m = mutations[i];
if (isInitialized && m.type === 'attributes' && m.target === self) {
syncAttribute(self, m.attributeName);
} else {
hasChildrenChange = true;
}
}
if (hasChildrenChange) {
wrapper.slotChildren = Object.freeze(toVNodes(
wrapper.$createElement,
self.childNodes
));
}
});
observer.observe(self, {
childList: true,
subtree: true,
characterData: true,
attributes: true
});
}
get vueComponent () {
return this._wrapper.$refs.inner
}
connectedCallback () {
const wrapper = this._wrapper;
if (!wrapper._isMounted) {
// initialize attributes
const syncInitialAttributes = () => {
wrapper.props = getInitialProps(camelizedPropsList);
hyphenatedPropsList.forEach(key => {
syncAttribute(this, key);
});
};
if (isInitialized) {
syncInitialAttributes();
} else {
// async & unresolved
Component().then(resolved => {
if (resolved.__esModule || resolved[Symbol.toStringTag] === 'Module') {
resolved = resolved.default;
}
initialize(resolved);
syncInitialAttributes();
});
}
// initialize children
wrapper.slotChildren = Object.freeze(toVNodes(
wrapper.$createElement,
this.childNodes
));
wrapper.$mount();
this.shadowRoot.appendChild(wrapper.$el);
} else {
callHooks(this.vueComponent, 'activated');
}
}
disconnectedCallback () {
callHooks(this.vueComponent, 'deactivated');
}
}
if (!isAsync) {
initialize(Component);
}
return CustomElement
}
/* harmony default export */ var vue_wc_wrapper = (wrap);
// EXTERNAL MODULE: ./node_modules/css-loader/dist/runtime/api.js
var api = __webpack_require__("24fb");
// EXTERNAL MODULE: ./node_modules/vue-style-loader/lib/addStylesShadow.js + 1 modules
var addStylesShadow = __webpack_require__("35d6");
// CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () {
injectStyles.call(
this,
(options.functional ? this.parent : this).$root.$options.shadowRoot
)
}
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functional component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/ChatWindow.vue?vue&type=template&id=0d9fd614&shadow
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-card-window",style:([{ height: _vm.height }, _vm.cssVars])},[_c('div',{staticClass:"vac-chat-container"},[(!_vm.singleRoom)?_c('rooms-list',{attrs:{"current-user-id":_vm.currentUserId,"rooms":_vm.orderedRooms,"loading-rooms":_vm.loadingRooms,"rooms-loaded":_vm.roomsLoaded,"room":_vm.room,"room-actions":_vm.roomActions,"text-messages":_vm.t,"show-add-room":_vm.showAddRoom,"show-rooms-list":_vm.showRoomsList,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"is-mobile":_vm.isMobile},on:{"fetch-room":_vm.fetchRoom,"fetch-more-rooms":_vm.fetchMoreRooms,"loading-more-rooms":function($event){_vm.loadingMoreRooms = $event},"add-room":_vm.addRoom,"room-action-handler":_vm.roomActionHandler},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):_vm._e(),_c('room',{attrs:{"current-user-id":_vm.currentUserId,"rooms":_vm.rooms,"room-id":_vm.room.roomId || '',"load-first-room":_vm.loadFirstRoom,"messages":_vm.messages,"room-message":_vm.roomMessage,"messages-loaded":_vm.messagesLoaded,"menu-actions":_vm.menuActions,"message-actions":_vm.messageActions,"show-send-icon":_vm.showSendIcon,"show-files":_vm.showFiles,"show-audio":_vm.showAudio,"show-emojis":_vm.showEmojis,"show-reaction-emojis":_vm.showReactionEmojis,"show-new-messages-divider":_vm.showNewMessagesDivider,"show-footer":_vm.showFooter,"text-messages":_vm.t,"single-room":_vm.singleRoom,"show-rooms-list":_vm.showRoomsList,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"is-mobile":_vm.isMobile,"loading-rooms":_vm.loadingRooms,"room-info":_vm.$listeners['room-info'],"textarea-action":_vm.$listeners['textarea-action-handler'],"accepted-files":_vm.acceptedFiles},on:{"toggle-rooms-list":_vm.toggleRoomsList,"room-info":_vm.roomInfo,"fetch-messages":_vm.fetchMessages,"send-message":_vm.sendMessage,"edit-message":_vm.editMessage,"delete-message":_vm.deleteMessage,"open-file":_vm.openFile,"open-user-tag":_vm.openUserTag,"menu-action-handler":_vm.menuActionHandler,"message-action-handler":_vm.messageActionHandler,"send-message-reaction":_vm.sendMessageReaction,"typing-message":_vm.typingMessage,"textarea-action-handler":_vm.textareaActionHandler},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)])}
var staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/ChatWindow.vue?vue&type=template&id=0d9fd614&shadow
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.keys.js
var es6_object_keys = __webpack_require__("456d");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.symbol.js
var es6_symbol = __webpack_require__("8a81");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.filter.js
var es6_array_filter = __webpack_require__("d25f");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.get-own-property-descriptor.js
var es6_object_get_own_property_descriptor = __webpack_require__("9986");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.for-each.js
var es6_array_for_each = __webpack_require__("f3e2");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es7.object.get-own-property-descriptors.js
var es7_object_get_own_property_descriptors = __webpack_require__("8e6e");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.define-properties.js
var es6_object_define_properties = __webpack_require__("58b2");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.define-property.js
var es6_object_define_property = __webpack_require__("1c01");
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.number.constructor.js
var es6_number_constructor = __webpack_require__("c5f6");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.map.js
var es6_array_map = __webpack_require__("6d67");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.sort.js
var es6_array_sort = __webpack_require__("55dd");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.slice.js
var es6_array_slice = __webpack_require__("23bf");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.find.js
var es6_array_find = __webpack_require__("7514");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es7.object.entries.js
var es7_object_entries = __webpack_require__("ffc1");
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomsList.vue?vue&type=template&id=3c4495e5&
var RoomsListvue_type_template_id_3c4495e5_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.showRoomsList),expression:"showRoomsList"}],staticClass:"vac-rooms-container vac-app-border-r",class:{ 'vac-rooms-container-full': _vm.isMobile }},[_vm._t("rooms-header"),_c('rooms-search',{attrs:{"rooms":_vm.rooms,"loading-rooms":_vm.loadingRooms,"text-messages":_vm.textMessages,"show-add-room":_vm.showAddRoom},on:{"search-room":_vm.searchRoom,"add-room":function($event){return _vm.$emit('add-room')}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}),_c('loader',{attrs:{"show":_vm.loadingRooms}}),(!_vm.loadingRooms && !_vm.rooms.length)?_c('div',{staticClass:"vac-rooms-empty"},[_vm._t("rooms-empty",[_vm._v(" "+_vm._s(_vm.textMessages.ROOMS_EMPTY)+" ")])],2):_vm._e(),(!_vm.loadingRooms)?_c('div',{staticClass:"vac-room-list"},[_vm._l((_vm.filteredRooms),function(fRoom){return _c('div',{key:fRoom.roomId,staticClass:"vac-room-item",class:{ 'vac-room-selected': _vm.selectedRoomId === fRoom.roomId },attrs:{"id":fRoom.roomId},on:{"click":function($event){return _vm.openRoom(fRoom)}}},[_c('room-content',{attrs:{"current-user-id":_vm.currentUserId,"room":fRoom,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"text-messages":_vm.textMessages,"room-actions":_vm.roomActions},on:{"room-action-handler":function($event){return _vm.$emit('room-action-handler', $event)}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)}),_c('transition',{attrs:{"name":"vac-fade-message"}},[(_vm.rooms.length && !_vm.loadingRooms)?_c('infinite-loading',{attrs:{"force-use-infinite-wrapper":".vac-room-list","web-component-name":"vue-advanced-chat","spinner":"spiral"},on:{"infinite":_vm.loadMoreRooms}},[_c('div',{attrs:{"slot":"spinner"},slot:"spinner"},[_c('loader',{attrs:{"show":true,"infinite":true}})],1),_c('div',{attrs:{"slot":"no-results"},slot:"no-results"}),_c('div',{attrs:{"slot":"no-more"},slot:"no-more"})]):_vm._e()],1)],2):_vm._e()],2)}
var RoomsListvue_type_template_id_3c4495e5_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsList.vue?vue&type=template&id=3c4495e5&
// EXTERNAL MODULE: ./node_modules/vue-infinite-loading/dist/vue-infinite-loading.js
var vue_infinite_loading = __webpack_require__("e166");
var vue_infinite_loading_default = /*#__PURE__*/__webpack_require__.n(vue_infinite_loading);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Loader.vue?vue&type=template&id=115a59fa&
var Loadervue_type_template_id_115a59fa_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"vac-fade-spinner","appear":""}},[(_vm.show)?_c('div',{staticClass:"vac-loader-wrapper",class:{
'vac-container-center': !_vm.infinite,
'vac-container-top': _vm.infinite
}},[_c('div',{attrs:{"id":"vac-circle"}})]):_vm._e()])}
var Loadervue_type_template_id_115a59fa_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/Loader.vue?vue&type=template&id=115a59fa&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Loader.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var Loadervue_type_script_lang_js_ = ({
name: 'Loader',
props: {
show: {
type: Boolean,
"default": false
},
infinite: {
type: Boolean,
"default": false
}
}
});
// CONCATENATED MODULE: ./src/components/Loader.vue?vue&type=script&lang=js&
/* harmony default export */ var components_Loadervue_type_script_lang_js_ = (Loadervue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/components/Loader.vue?vue&type=style&index=0&lang=scss&
var Loadervue_type_style_index_0_lang_scss_ = __webpack_require__("a071");
// CONCATENATED MODULE: ./src/components/Loader.vue
/* normalize component */
var component = normalizeComponent(
components_Loadervue_type_script_lang_js_,
Loadervue_type_template_id_115a59fa_render,
Loadervue_type_template_id_115a59fa_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var Loader = (component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomsSearch.vue?vue&type=template&id=079ff11e&
var RoomsSearchvue_type_template_id_079ff11e_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-box-search"},[(!_vm.loadingRooms && _vm.rooms.length)?_c('div',{staticClass:"vac-icon-search"},[_vm._t("search-icon",[_c('svg-icon',{attrs:{"name":"search"}})])],2):_vm._e(),(!_vm.loadingRooms && _vm.rooms.length)?_c('input',{staticClass:"vac-input",attrs:{"type":"search","placeholder":_vm.textMessages.SEARCH,"autocomplete":"off"},on:{"input":function($event){return _vm.$emit('search-room', $event)}}}):_vm._e(),(_vm.showAddRoom)?_c('div',{staticClass:"vac-svg-button vac-add-icon",on:{"click":function($event){return _vm.$emit('add-room')}}},[_vm._t("add-icon",[_c('svg-icon',{attrs:{"name":"add"}})])],2):_vm._e()])}
var RoomsSearchvue_type_template_id_079ff11e_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsSearch.vue?vue&type=template&id=079ff11e&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/SvgIcon.vue?vue&type=template&id=34aa1382&
var SvgIconvue_type_template_id_34aa1382_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{attrs:{"xmlns":"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink","version":"1.1","width":"24","height":"24","viewBox":("0 0 " + _vm.size + " " + _vm.size)}},[_c('path',{attrs:{"id":_vm.svgId,"d":_vm.svgItem[_vm.name].path}}),(_vm.svgItem[_vm.name].path2)?_c('path',{attrs:{"id":_vm.svgId,"d":_vm.svgItem[_vm.name].path2}}):_vm._e()])}
var SvgIconvue_type_template_id_34aa1382_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/SvgIcon.vue?vue&type=template&id=34aa1382&
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.function.name.js
var es6_function_name = __webpack_require__("7f7f");
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/SvgIcon.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var SvgIconvue_type_script_lang_js_ = ({
name: 'SvgIcon',
props: {
name: {
type: String,
"default": null
},
param: {
type: String,
"default": null
}
},
data: function data() {
return {
svgItem: {
search: {
path: 'M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z'
},
add: {
path: 'M17,13H13V17H11V13H7V11H11V7H13V11H17M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z'
},
toggle: {
path: 'M5,13L9,17L7.6,18.42L1.18,12L7.6,5.58L9,7L5,11H21V13H5M21,6V8H11V6H21M21,16V18H11V16H21Z'
},
menu: {
path: 'M12,16A2,2 0 0,1 14,18A2,2 0 0,1 12,20A2,2 0 0,1 10,18A2,2 0 0,1 12,16M12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12A2,2 0 0,1 12,10M12,4A2,2 0 0,1 14,6A2,2 0 0,1 12,8A2,2 0 0,1 10,6A2,2 0 0,1 12,4Z'
},
close: {
path: 'M12,2C17.53,2 22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53 2,12C2,6.47 6.47,2 12,2M15.59,7L12,10.59L8.41,7L7,8.41L10.59,12L7,15.59L8.41,17L12,13.41L15.59,17L17,15.59L13.41,12L17,8.41L15.59,7Z'
},
file: {
path: 'M14,17H7V15H14M17,13H7V11H17M17,9H7V7H17M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z'
},
paperclip: {
path: 'M16.5,6V17.5A4,4 0 0,1 12.5,21.5A4,4 0 0,1 8.5,17.5V5A2.5,2.5 0 0,1 11,2.5A2.5,2.5 0 0,1 13.5,5V15.5A1,1 0 0,1 12.5,16.5A1,1 0 0,1 11.5,15.5V6H10V15.5A2.5,2.5 0 0,0 12.5,18A2.5,2.5 0 0,0 15,15.5V5A4,4 0 0,0 11,1A4,4 0 0,0 7,5V17.5A5.5,5.5 0 0,0 12.5,23A5.5,5.5 0 0,0 18,17.5V6H16.5Z'
},
'close-outline': {
path: 'M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z'
},
send: {
path: 'M2,21L23,12L2,3V10L17,12L2,14V21Z'
},
emoji: {
path: 'M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z'
},
document: {
path: 'M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z'
},
pencil: {
path: 'M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z'
},
checkmark: {
path: 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z'
},
'double-checkmark': {
path: 'M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z'
},
eye: {
path: 'M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z'
},
dropdown: {
path: 'M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z'
},
deleted: {
path: 'M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,4A8,8 0 0,0 4,12C4,13.85 4.63,15.55 5.68,16.91L16.91,5.68C15.55,4.63 13.85,4 12,4M12,20A8,8 0 0,0 20,12C20,10.15 19.37,8.45 18.32,7.09L7.09,18.32C8.45,19.37 10.15,20 12,20Z'
},
microphone: {
size: 'large',
path: 'M432.8,216.4v39.2c0,45.2-15.3,84.3-45.2,118.4c-29.8,33.2-67.3,52.8-111.6,57.9v40.9h78.4c5.1,0,10.2,1.7,13.6,6c4.3,4.3,6,8.5,6,13.6c0,5.1-1.7,10.2-6,13.6c-4.3,4.3-8.5,6-13.6,6H157.6c-5.1,0-10.2-1.7-13.6-6c-4.3-4.3-6-8.5-6-13.6c0-5.1,1.7-10.2,6-13.6c4.3-4.3,8.5-6,13.6-6H236v-40.9c-44.3-5.1-81.8-23.9-111.6-57.9s-45.2-73.3-45.2-118.4v-39.2c0-5.1,1.7-10.2,6-13.6c4.3-4.3,8.5-6,13.6-6s10.2,1.7,13.6,6c4.3,4.3,6,8.5,6,13.6v39.2c0,37.5,13.6,70.7,40,97.1s59.6,40,97.1,40s70.7-13.6,97.1-40c26.4-26.4,40-59.6,40-97.1v-39.2c0-5.1,1.7-10.2,6-13.6c4.3-4.3,8.5-6,13.6-6c5.1,0,10.2,1.7,13.6,6C430.2,206.2,432.8,211.3,432.8,216.4z M353.5,98v157.6c0,27.3-9.4,50.3-29,69c-19.6,19.6-42.6,29-69,29s-50.3-9.4-69-29c-19.6-19.6-29-42.6-29-69V98c0-27.3,9.4-50.3,29-69c19.6-19.6,42.6-29,69-29s50.3,9.4,69,29C344.2,47.7,353.5,71.6,353.5,98z'
},
'audio-play': {
size: 'medium',
path: 'M43.331,21.237L7.233,0.397c-0.917-0.529-2.044-0.529-2.96,0c-0.916,0.528-1.48,1.505-1.48,2.563v41.684 c0,1.058,0.564,2.035,1.48,2.563c0.458,0.268,0.969,0.397,1.48,0.397c0.511,0,1.022-0.133,1.48-0.397l36.098-20.84 c0.918-0.529,1.479-1.506,1.479-2.564S44.247,21.767,43.331,21.237z'
},
'audio-pause': {
size: 'medium',
path: 'M17.991,40.976c0,3.662-2.969,6.631-6.631,6.631l0,0c-3.662,0-6.631-2.969-6.631-6.631V6.631C4.729,2.969,7.698,0,11.36,0l0,0c3.662,0,6.631,2.969,6.631,6.631V40.976z',
path2: 'M42.877,40.976c0,3.662-2.969,6.631-6.631,6.631l0,0c-3.662,0-6.631-2.969-6.631-6.631V6.631C29.616,2.969,32.585,0,36.246,0l0,0c3.662,0,6.631,2.969,6.631,6.631V40.976z'
}
}
};
},
computed: {
svgId: function svgId() {
var param = this.param ? '-' + this.param : '';
return "vac-icon-".concat(this.name).concat(param);
},
size: function size() {
var item = this.svgItem[this.name];
if (item.size === 'large') return 512;else if (item.size === 'medium') return 48;else return 24;
}
}
});
// CONCATENATED MODULE: ./src/components/SvgIcon.vue?vue&type=script&lang=js&
/* harmony default export */ var components_SvgIconvue_type_script_lang_js_ = (SvgIconvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/components/SvgIcon.vue?vue&type=style&index=0&lang=scss&
var SvgIconvue_type_style_index_0_lang_scss_ = __webpack_require__("35f2");
// CONCATENATED MODULE: ./src/components/SvgIcon.vue
/* normalize component */
var SvgIcon_component = normalizeComponent(
components_SvgIconvue_type_script_lang_js_,
SvgIconvue_type_template_id_34aa1382_render,
SvgIconvue_type_template_id_34aa1382_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var SvgIcon = (SvgIcon_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomsSearch.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var RoomsSearchvue_type_script_lang_js_ = ({
name: 'RoomsSearch',
components: {
SvgIcon: SvgIcon
},
props: {
textMessages: {
type: Object,
required: true
},
showAddRoom: {
type: Boolean,
required: true
},
rooms: {
type: Array,
required: true
},
loadingRooms: {
type: Boolean,
required: true
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsSearch.vue?vue&type=script&lang=js&
/* harmony default export */ var RoomsList_RoomsSearchvue_type_script_lang_js_ = (RoomsSearchvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/RoomsList/RoomsSearch.vue?vue&type=style&index=0&lang=scss&
var RoomsSearchvue_type_style_index_0_lang_scss_ = __webpack_require__("798f");
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsSearch.vue
/* normalize component */
var RoomsSearch_component = normalizeComponent(
RoomsList_RoomsSearchvue_type_script_lang_js_,
RoomsSearchvue_type_template_id_079ff11e_render,
RoomsSearchvue_type_template_id_079ff11e_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomsSearch = (RoomsSearch_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomContent.vue?vue&type=template&id=2d7743ae&
var RoomContentvue_type_template_id_2d7743ae_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-room-container"},[_vm._t("room-list-item",[(_vm.room.avatar)?_c('div',{staticClass:"vac-avatar",style:({ 'background-image': ("url('" + (_vm.room.avatar) + "')") })}):_vm._e(),_c('div',{staticClass:"vac-name-container vac-text-ellipsis"},[_c('div',{staticClass:"vac-title-container"},[(_vm.userStatus)?_c('div',{staticClass:"vac-state-circle",class:{ 'vac-state-online': _vm.userStatus === 'online' }}):_vm._e(),_c('div',{staticClass:"vac-room-name vac-text-ellipsis"},[_vm._v(" "+_vm._s(_vm.room.roomName)+" ")]),(_vm.room.lastMessage)?_c('div',{staticClass:"vac-text-date"},[_vm._v(" "+_vm._s(_vm.room.lastMessage.timestamp)+" ")]):_vm._e()]),_c('div',{staticClass:"vac-text-last",class:{
'vac-message-new':
_vm.room.lastMessage && _vm.room.lastMessage.new && !_vm.typingUsers
}},[(_vm.isMessageCheckmarkVisible)?_c('span',[_vm._t("checkmark-icon",[_c('svg-icon',{staticClass:"vac-icon-check",attrs:{"name":_vm.room.lastMessage.distributed
? 'double-checkmark'
: 'checkmark',"param":_vm.room.lastMessage.seen ? 'seen' : ''}})],null,_vm.room.lastMessage)],2):_vm._e(),(_vm.room.lastMessage && !_vm.room.lastMessage.deleted && _vm.isAudio)?_c('div',{staticClass:"vac-text-ellipsis"},[_vm._t("microphone-icon",[_c('svg-icon',{staticClass:"vac-icon-microphone",attrs:{"name":"microphone"}})]),_vm._v(" "+_vm._s(_vm.formattedDuration)+" ")],2):(_vm.room.lastMessage)?_c('format-message',{attrs:{"content":_vm.getLastMessage,"deleted":!!_vm.room.lastMessage.deleted && !_vm.typingUsers,"users":_vm.room.users,"linkify":false,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"single-line":true},scopedSlots:_vm._u([{key:"deleted-icon",fn:function(data){return [_vm._t("deleted-icon",null,null,data)]}}],null,true)}):_vm._e(),(!_vm.room.lastMessage && _vm.typingUsers)?_c('div',{staticClass:"vac-text-ellipsis"},[_vm._v(" "+_vm._s(_vm.typingUsers)+" ")]):_vm._e(),_c('div',{staticClass:"vac-room-options-container"},[(_vm.room.unreadCount)?_c('div',{staticClass:"vac-badge-counter vac-room-badge"},[_vm._v(" "+_vm._s(_vm.room.unreadCount)+" ")]):_vm._e(),_vm._t("room-list-options",[(_vm.roomActions.length)?_c('div',{staticClass:"vac-svg-button vac-list-room-options",on:{"click":function($event){$event.stopPropagation();_vm.roomMenuOpened = _vm.room.roomId}}},[_vm._t("room-list-options-icon",[_c('svg-icon',{attrs:{"name":"dropdown","param":"room"}})])],2):_vm._e(),(_vm.roomActions.length)?_c('transition',{attrs:{"name":"vac-slide-left"}},[(_vm.roomMenuOpened === _vm.room.roomId)?_c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeRoomMenu),expression:"closeRoomMenu"}],staticClass:"vac-menu-options"},[_c('div',{staticClass:"vac-menu-list"},_vm._l((_vm.roomActions),function(action){return _c('div',{key:action.name},[_c('div',{staticClass:"vac-menu-item",on:{"click":function($event){$event.stopPropagation();return _vm.roomActionHandler(action)}}},[_vm._v(" "+_vm._s(action.title)+" ")])])}),0)]):_vm._e()]):_vm._e()],null,{ room: _vm.room })],2)],1)])],null,{ room: _vm.room })],2)}
var RoomContentvue_type_template_id_2d7743ae_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomContent.vue?vue&type=template&id=2d7743ae&
// EXTERNAL MODULE: ./node_modules/v-click-outside/dist/v-click-outside.umd.js
var v_click_outside_umd = __webpack_require__("c28b");
var v_click_outside_umd_default = /*#__PURE__*/__webpack_require__.n(v_click_outside_umd);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/FormatMessage.vue?vue&type=template&id=0ef5045f&
var FormatMessagevue_type_template_id_0ef5045f_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-format-message-wrapper",class:{ 'vac-text-ellipsis': _vm.singleLine }},[(_vm.textFormatting)?_c('div',{class:{ 'vac-text-ellipsis': _vm.singleLine }},[_vm._l((_vm.linkifiedMessage),function(message,i){return [_c(message.url ? 'a' : 'span',{key:i,tag:"component",class:{
'vac-text-ellipsis': _vm.singleLine,
'vac-text-bold': message.bold,
'vac-text-italic': _vm.deleted || message.italic,
'vac-text-strike': message.strike,
'vac-text-underline': message.underline,
'vac-text-inline-code': !_vm.singleLine && message.inline,
'vac-text-multiline-code': !_vm.singleLine && message.multiline,
'vac-text-tag': !_vm.singleLine && !_vm.reply && message.tag
},attrs:{"href":message.href,"target":message.href ? _vm.linkOptions.target : null},on:{"click":function($event){return _vm.openTag(message)}}},[_vm._t("deleted-icon",[(_vm.deleted)?_c('svg-icon',{staticClass:"vac-icon-deleted",attrs:{"name":"deleted"}}):_vm._e()],null,{ deleted: _vm.deleted }),(message.url && message.image)?[_c('div',{staticClass:"vac-image-link-container"},[_c('div',{staticClass:"vac-image-link",style:({
'background-image': ("url('" + (message.value) + "')"),
height: message.height
})})]),_c('div',{staticClass:"vac-image-link-message"},[_c('span',[_vm._v(_vm._s(message.value))])])]:[_c('span',[_vm._v(_vm._s(message.value))])]],2)]})],2):_c('div',[_vm._v(" "+_vm._s(_vm.formattedContent)+" ")])])}
var FormatMessagevue_type_template_id_0ef5045f_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/FormatMessage.vue?vue&type=template&id=0ef5045f&
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.bold.js
var es6_string_bold = __webpack_require__("48c0");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.strike.js
var es6_string_strike = __webpack_require__("1448");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.index-of.js
var es6_array_index_of = __webpack_require__("57e7");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.last-index-of.js
var es6_array_last_index_of = __webpack_require__("9865");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.some.js
var es6_array_some = __webpack_require__("759f");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.includes.js
var es6_string_includes = __webpack_require__("2fdb");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es7.array.includes.js
var es7_array_includes = __webpack_require__("6762");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.regexp.replace.js
var es6_regexp_replace = __webpack_require__("a481");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.regexp.match.js
var es6_regexp_match = __webpack_require__("4917");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.regexp.constructor.js
var es6_regexp_constructor = __webpack_require__("3b2b");
// CONCATENATED MODULE: ./src/utils/format-string.js
var _pseudoMarkdown;
var linkify = __webpack_require__("74fe"); // require('linkifyjs/plugins/hashtag')(linkify)
/* harmony default export */ var format_string = (function (text, doLinkify) {
var json = compileToJSON(text);
var html = compileToHTML(json);
var result = [].concat.apply([], html);
if (doLinkify) linkifyResult(result);
return result;
});
var typeMarkdown = {
bold: '*',
italic: '_',
strike: '~',
underline: '°'
};
var pseudoMarkdown = (_pseudoMarkdown = {}, _defineProperty(_pseudoMarkdown, typeMarkdown.bold, {
end: '\\' + [typeMarkdown.bold],
allowed_chars: '.',
type: 'bold'
}), _defineProperty(_pseudoMarkdown, typeMarkdown.italic, {
end: [typeMarkdown.italic],
allowed_chars: '.',
type: 'italic'
}), _defineProperty(_pseudoMarkdown, typeMarkdown.strike, {
end: [typeMarkdown.strike],
allowed_chars: '.',
type: 'strike'
}), _defineProperty(_pseudoMarkdown, typeMarkdown.underline, {
end: [typeMarkdown.underline],
allowed_chars: '.',
type: 'underline'
}), _defineProperty(_pseudoMarkdown, '```', {
end: '```',
allowed_chars: '(.|\n)',
type: 'multiline-code'
}), _defineProperty(_pseudoMarkdown, '`', {
end: '`',
allowed_chars: '.',
type: 'inline-code'
}), _defineProperty(_pseudoMarkdown, '<usertag>', {
allowed_chars: '.',
end: '</usertag>',
type: 'tag'
}), _pseudoMarkdown);
function compileToJSON(str) {
var result = [];
var minIndexOf = -1;
var minIndexOfKey = null;
var links = linkify.find(str);
var minIndexFromLink = false;
if (links.length > 0) {
minIndexOf = str.indexOf(links[0].value);
minIndexFromLink = true;
}
Object.keys(pseudoMarkdown).forEach(function (startingValue) {
var io = str.indexOf(startingValue);
if (io >= 0 && (minIndexOf < 0 || io < minIndexOf)) {
minIndexOf = io;
minIndexOfKey = startingValue;
minIndexFromLink = false;
}
});
if (minIndexFromLink && minIndexOfKey !== -1) {
var strLeft = str.substr(0, minIndexOf);
var strLink = str.substr(minIndexOf, links[0].value.length);
var strRight = str.substr(minIndexOf + links[0].value.length);
result.push(strLeft);
result.push(strLink);
result = result.concat(compileToJSON(strRight));
return result;
}
if (minIndexOfKey) {
var _strLeft = str.substr(0, minIndexOf);
var _char = minIndexOfKey;
var _strRight = str.substr(minIndexOf + _char.length);
if (str.replace(/\s/g, '').length === _char.length * 2) {
return [str];
}
var match = _strRight.match(new RegExp('^(' + (pseudoMarkdown[_char].allowed_chars || '.') + '*' + (pseudoMarkdown[_char].end ? '?' : '') + ')' + (pseudoMarkdown[_char].end ? '(' + pseudoMarkdown[_char].end + ')' : ''), 'm'));
if (!match || !match[1]) {
_strLeft = _strLeft + _char;
result.push(_strLeft);
} else {
if (_strLeft) {
result.push(_strLeft);
}
var object = {
start: _char,
content: compileToJSON(match[1]),
end: match[2],
type: pseudoMarkdown[_char].type
};
result.push(object);
_strRight = _strRight.substr(match[0].length);
}
result = result.concat(compileToJSON(_strRight));
return result;
} else {
if (str) {
return [str];
} else {
return [];
}
}
}
function compileToHTML(json) {
var result = [];
json.forEach(function (item) {
if (typeof item === 'string') {
result.push({
types: [],
value: item
});
} else {
if (pseudoMarkdown[item.start]) {
result.push(parseContent(item));
}
}
});
return result;
}
function parseContent(item) {
var result = [];
item.content.forEach(function (it) {
if (typeof it === 'string') {
result.push({
types: [item.type],
value: it
});
} else {
it.content.forEach(function (i) {
if (typeof i === 'string') {
result.push({
types: [it.type].concat([item.type]),
value: i
});
} else {
result.push({
types: [i.type].concat([it.type]).concat([item.type]),
value: parseContent(i)
});
}
});
}
});
return result;
}
function linkifyResult(array) {
var result = [];
array.forEach(function (arr) {
var links = linkify.find(arr.value);
if (links.length) {
var spaces = arr.value.replace(links[0].value, '');
result.push({
types: arr.types,
value: spaces
});
arr.types = ['url'].concat(arr.types);
arr.href = links[0].href;
arr.value = links[0].value;
}
result.push(arr);
});
return result;
}
// EXTERNAL MODULE: ./src/utils/constants.js
var constants = __webpack_require__("c9d9");
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/FormatMessage.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var FormatMessagevue_type_script_lang_js_ = ({
name: 'FormatMessage',
components: {
SvgIcon: SvgIcon
},
props: {
content: {
type: [String, Number],
required: true
},
deleted: {
type: Boolean,
"default": false
},
users: {
type: Array,
"default": function _default() {
return [];
}
},
linkify: {
type: Boolean,
"default": true
},
singleLine: {
type: Boolean,
"default": false
},
reply: {
type: Boolean,
"default": false
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
}
},
computed: {
linkifiedMessage: function linkifiedMessage() {
var _this = this;
var message = format_string(this.formatTags(this.content), this.linkify && !this.linkOptions.disabled, this.linkOptions);
message.forEach(function (m) {
m.url = _this.checkType(m, 'url');
m.bold = _this.checkType(m, 'bold');
m.italic = _this.checkType(m, 'italic');
m.strike = _this.checkType(m, 'strike');
m.underline = _this.checkType(m, 'underline');
m.inline = _this.checkType(m, 'inline-code');
m.multiline = _this.checkType(m, 'multiline-code');
m.tag = _this.checkType(m, 'tag');
m.image = _this.checkImageType(m);
});
return message;
},
formattedContent: function formattedContent() {
return this.formatTags(this.content);
}
},
methods: {
checkType: function checkType(message, type) {
return message.types.indexOf(type) !== -1;
},
checkImageType: function checkImageType(message) {
var index = message.value.lastIndexOf('.');
var slashIndex = message.value.lastIndexOf('/');
if (slashIndex > index) index = -1;
var type = message.value.substring(index + 1, message.value.length);
var isMedia = index > 0 && constants["b" /* IMAGE_TYPES */].some(function (t) {
return type.toLowerCase().includes(t);
});
if (isMedia) this.setImageSize(message);
return isMedia;
},
setImageSize: function setImageSize(message) {
var image = new Image();
image.src = message.value;
image.addEventListener('load', onLoad);
function onLoad(img) {
var ratio = img.path[0].width / 150;
message.height = Math.round(img.path[0].height / ratio) + 'px';
image.removeEventListener('load', onLoad);
}
},
formatTags: function formatTags(content) {
this.users.forEach(function (user) {
var index = content.indexOf(user._id);
var isTag = content.substring(index - 9, index) === '<usertag>';
if (isTag) content = content.replace(user._id, "@".concat(user.username));
});
return content;
},
openTag: function openTag(message) {
if (!this.singleLine && this.checkType(message, 'tag')) {
var user = this.users.find(function (u) {
return message.value.indexOf(u.username) !== -1;
});
this.$emit('open-user-tag', user);
}
}
}
});
// CONCATENATED MODULE: ./src/components/FormatMessage.vue?vue&type=script&lang=js&
/* harmony default export */ var components_FormatMessagevue_type_script_lang_js_ = (FormatMessagevue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/components/FormatMessage.vue?vue&type=style&index=0&lang=scss&
var FormatMessagevue_type_style_index_0_lang_scss_ = __webpack_require__("c3ec");
// CONCATENATED MODULE: ./src/components/FormatMessage.vue
/* normalize component */
var FormatMessage_component = normalizeComponent(
components_FormatMessagevue_type_script_lang_js_,
FormatMessagevue_type_template_id_0ef5045f_render,
FormatMessagevue_type_template_id_0ef5045f_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var FormatMessage = (FormatMessage_component.exports);
// CONCATENATED MODULE: ./src/utils/typing-text.js
/* harmony default export */ var typing_text = (function (room, currentUserId, textMessages) {
if (room.typingUsers && room.typingUsers.length) {
var typingUsers = room.users.filter(function (user) {
if (user._id === currentUserId) return;
if (room.typingUsers.indexOf(user._id) === -1) return;
if (user.status && user.status.state === 'offline') return;
return true;
});
if (!typingUsers.length) return;
if (room.users.length === 2) {
return textMessages.IS_TYPING;
} else {
return typingUsers.map(function (user) {
return user.username;
}).join(', ') + ' ' + textMessages.IS_TYPING;
}
}
});
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomContent.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var _require = __webpack_require__("bd43"),
isAudioFile = _require.isAudioFile;
/* harmony default export */ var RoomContentvue_type_script_lang_js_ = ({
name: 'RoomsContent',
components: {
SvgIcon: SvgIcon,
FormatMessage: FormatMessage
},
directives: {
clickOutside: v_click_outside_umd_default.a.directive
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
room: {
type: Object,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
textMessages: {
type: Object,
required: true
},
roomActions: {
type: Array,
required: true
}
},
data: function data() {
return {
roomMenuOpened: null
};
},
computed: {
getLastMessage: function getLastMessage() {
var _this = this;
var isTyping = this.typingUsers;
if (isTyping) return isTyping;
var content = this.room.lastMessage.deleted ? this.textMessages.MESSAGE_DELETED : this.room.lastMessage.content;
if (this.room.users.length <= 2) {
return content;
}
var user = this.room.users.find(function (user) {
return user._id === _this.room.lastMessage.senderId;
});
if (this.room.lastMessage.username) {
return "".concat(this.room.lastMessage.username, " - ").concat(content);
} else if (!user || user._id === this.currentUserId) {
return content;
}
return "".concat(user.username, " - ").concat(content);
},
userStatus: function userStatus() {
var _this2 = this;
if (!this.room.users || this.room.users.length !== 2) return;
var user = this.room.users.find(function (u) {
return u._id !== _this2.currentUserId;
});
if (user && user.status) return user.status.state;
return null;
},
typingUsers: function typingUsers() {
return typing_text(this.room, this.currentUserId, this.textMessages);
},
isMessageCheckmarkVisible: function isMessageCheckmarkVisible() {
return !this.typingUsers && this.room.lastMessage && !this.room.lastMessage.deleted && this.room.lastMessage.senderId === this.currentUserId && (this.room.lastMessage.saved || this.room.lastMessage.distributed || this.room.lastMessage.seen);
},
formattedDuration: function formattedDuration() {
var file = this.room.lastMessage.file;
if (!file.duration) {
return "".concat(file.name, ".").concat(file.extension);
}
var s = Math.floor(file.duration);
return (s - (s %= 60)) / 60 + (s > 9 ? ':' : ':0') + s;
},
isAudio: function isAudio() {
return isAudioFile(this.room.lastMessage.file);
}
},
methods: {
roomActionHandler: function roomActionHandler(action) {
this.closeRoomMenu();
this.$emit('room-action-handler', {
action: action,
roomId: this.room.roomId
});
},
closeRoomMenu: function closeRoomMenu() {
this.roomMenuOpened = null;
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomContent.vue?vue&type=script&lang=js&
/* harmony default export */ var RoomsList_RoomContentvue_type_script_lang_js_ = (RoomContentvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/RoomsList/RoomContent.vue?vue&type=style&index=0&lang=scss&
var RoomContentvue_type_style_index_0_lang_scss_ = __webpack_require__("3687");
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomContent.vue
/* normalize component */
var RoomContent_component = normalizeComponent(
RoomsList_RoomContentvue_type_script_lang_js_,
RoomContentvue_type_template_id_2d7743ae_render,
RoomContentvue_type_template_id_2d7743ae_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomContent = (RoomContent_component.exports);
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.starts-with.js
var es6_string_starts_with = __webpack_require__("f559");
// CONCATENATED MODULE: ./src/utils/filter-items.js
/* harmony default export */ var filter_items = (function (items, prop, val) {
var startsWith = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (!val || val === '') return items;
return items.filter(function (v) {
if (startsWith) return formatString(v[prop]).startsWith(formatString(val));
return formatString(v[prop]).includes(formatString(val));
});
});
function formatString(string) {
return string.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/RoomsList/RoomsList.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var RoomsListvue_type_script_lang_js_ = ({
name: 'RoomsList',
components: {
InfiniteLoading: vue_infinite_loading_default.a,
Loader: Loader,
RoomsSearch: RoomsSearch,
RoomContent: RoomContent
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
textMessages: {
type: Object,
required: true
},
showRoomsList: {
type: Boolean,
required: true
},
showAddRoom: {
type: Boolean,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
isMobile: {
type: Boolean,
required: true
},
rooms: {
type: Array,
required: true
},
loadingRooms: {
type: Boolean,
required: true
},
roomsLoaded: {
type: Boolean,
required: true
},
room: {
type: Object,
required: true
},
roomActions: {
type: Array,
required: true
}
},
data: function data() {
return {
filteredRooms: this.rooms || [],
infiniteState: null,
loadingMoreRooms: false,
selectedRoomId: ''
};
},
watch: {
rooms: function rooms(newVal, oldVal) {
this.filteredRooms = newVal;
if (this.infiniteState && (newVal.length !== oldVal.length || this.roomsLoaded)) {
this.infiniteState.loaded();
this.loadingMoreRooms = false;
}
},
loadingRooms: function loadingRooms(val) {
if (val) this.infiniteState = null;
},
loadingMoreRooms: function loadingMoreRooms(val) {
this.$emit('loading-more-rooms', val);
},
roomsLoaded: function roomsLoaded(val) {
if (val && this.infiniteState) {
this.loadingMoreRooms = false;
this.infiniteState.complete();
}
},
room: {
immediate: true,
handler: function handler(val) {
if (val && !this.isMobile) this.selectedRoomId = val.roomId;
}
}
},
methods: {
searchRoom: function searchRoom(ev) {
this.filteredRooms = filter_items(this.rooms, 'roomName', ev.target.value);
},
openRoom: function openRoom(room) {
if (room.roomId === this.room.roomId && !this.isMobile) return;
if (!this.isMobile) this.selectedRoomId = room.roomId;
this.$emit('fetch-room', {
room: room
});
},
loadMoreRooms: function loadMoreRooms(infiniteState) {
if (this.loadingMoreRooms) return;
if (this.roomsLoaded) {
this.loadingMoreRooms = false;
return infiniteState.complete();
}
this.infiniteState = infiniteState;
this.$emit('fetch-more-rooms');
this.loadingMoreRooms = true;
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsList.vue?vue&type=script&lang=js&
/* harmony default export */ var RoomsList_RoomsListvue_type_script_lang_js_ = (RoomsListvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/RoomsList/RoomsList.vue?vue&type=style&index=0&lang=scss&
var RoomsListvue_type_style_index_0_lang_scss_ = __webpack_require__("7d66");
// CONCATENATED MODULE: ./src/ChatWindow/RoomsList/RoomsList.vue
/* normalize component */
var RoomsList_component = normalizeComponent(
RoomsList_RoomsListvue_type_script_lang_js_,
RoomsListvue_type_template_id_3c4495e5_render,
RoomsListvue_type_template_id_3c4495e5_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomsList = (RoomsList_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/Room.vue?vue&type=template&id=1a1a6e46&
var Roomvue_type_template_id_1a1a6e46_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{directives:[{name:"show",rawName:"v-show",value:((_vm.isMobile && !_vm.showRoomsList) || !_vm.isMobile || _vm.singleRoom),expression:"(isMobile && !showRoomsList) || !isMobile || singleRoom"}],staticClass:"vac-col-messages"},[(_vm.showNoRoom)?_vm._t("no-room-selected",[_c('div',{staticClass:"vac-container-center vac-room-empty"},[_c('div',[_vm._v(_vm._s(_vm.textMessages.ROOM_EMPTY))])])]):_c('room-header',{attrs:{"current-user-id":_vm.currentUserId,"text-messages":_vm.textMessages,"single-room":_vm.singleRoom,"show-rooms-list":_vm.showRoomsList,"is-mobile":_vm.isMobile,"room-info":_vm.roomInfo,"menu-actions":_vm.menuActions,"room":_vm.room},on:{"toggle-rooms-list":function($event){return _vm.$emit('toggle-rooms-list')},"room-info":function($event){return _vm.$emit('room-info')},"menu-action-handler":function($event){return _vm.$emit('menu-action-handler', $event)}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}),_c('div',{ref:"scrollContainer",staticClass:"vac-container-scroll",on:{"scroll":_vm.onContainerScroll}},[_c('loader',{attrs:{"show":_vm.loadingMessages}}),_c('div',{staticClass:"vac-messages-container"},[_c('div',{class:{ 'vac-messages-hidden': _vm.loadingMessages }},[_c('transition',{attrs:{"name":"vac-fade-message"}},[(_vm.showNoMessages)?_c('div',{staticClass:"vac-text-started"},[_vm._t("messages-empty",[_vm._v(" "+_vm._s(_vm.textMessages.MESSAGES_EMPTY)+" ")])],2):_vm._e(),(_vm.showMessagesStarted)?_c('div',{staticClass:"vac-text-started"},[_vm._v(" "+_vm._s(_vm.textMessages.CONVERSATION_STARTED)+" "+_vm._s(_vm.messages[0].date)+" ")]):_vm._e()]),_c('transition',{attrs:{"name":"vac-fade-message"}},[(_vm.messages.length)?_c('infinite-loading',{class:{ 'vac-infinite-loading': !_vm.messagesLoaded },attrs:{"force-use-infinite-wrapper":".vac-container-scroll","web-component-name":"vue-advanced-chat","spinner":"spiral","direction":"top","distance":40},on:{"infinite":_vm.loadMoreMessages}},[_c('div',{attrs:{"slot":"spinner"},slot:"spinner"},[_c('loader',{attrs:{"show":true,"infinite":true}})],1),_c('div',{attrs:{"slot":"no-results"},slot:"no-results"}),_c('div',{attrs:{"slot":"no-more"},slot:"no-more"})]):_vm._e()],1),_c('transition-group',{key:_vm.roomId,attrs:{"name":"vac-fade-message"}},_vm._l((_vm.messages),function(m,i){return _c('div',{key:m._id},[_c('message',{attrs:{"current-user-id":_vm.currentUserId,"message":m,"index":i,"messages":_vm.messages,"edited-message":_vm.editedMessage,"message-actions":_vm.messageActions,"room-users":_vm.room.users,"text-messages":_vm.textMessages,"room-footer-ref":_vm.$refs.roomFooter,"new-messages":_vm.newMessages,"show-reaction-emojis":_vm.showReactionEmojis,"show-new-messages-divider":_vm.showNewMessagesDivider,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"emojis-list":_vm.emojisList,"hide-options":_vm.hideOptions},on:{"message-added":_vm.onMessageAdded,"message-action-handler":_vm.messageActionHandler,"open-file":_vm.openFile,"open-user-tag":_vm.openUserTag,"send-message-reaction":_vm.sendMessageReaction,"hide-options":function($event){_vm.hideOptions = $event}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(idx,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)}),0)],1)])],1),(!_vm.loadingMessages)?_c('div',[_c('transition',{attrs:{"name":"vac-bounce"}},[(_vm.scrollIcon)?_c('div',{staticClass:"vac-icon-scroll",on:{"click":_vm.scrollToBottom}},[_c('transition',{attrs:{"name":"vac-bounce"}},[(_vm.scrollMessagesCount)?_c('div',{staticClass:"vac-badge-counter vac-messages-count"},[_vm._v(" "+_vm._s(_vm.scrollMessagesCount)+" ")]):_vm._e()]),_vm._t("scroll-icon",[_c('svg-icon',{attrs:{"name":"dropdown","param":"scroll"}})])],2):_vm._e()])],1):_vm._e(),_c('div',{directives:[{name:"show",rawName:"v-show",value:(Object.keys(_vm.room).length && _vm.showFooter),expression:"Object.keys(room).length && showFooter"}],ref:"roomFooter",staticClass:"vac-room-footer"},[_c('room-message-reply',{attrs:{"room":_vm.room,"message-reply":_vm.messageReply,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions},on:{"reset-message":_vm.resetMessage},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}),_c('room-emojis',{attrs:{"filtered-emojis":_vm.filteredEmojis},on:{"select-emoji":function($event){return _vm.selectEmoji($event)}}}),_c('room-users-tag',{attrs:{"filtered-users-tag":_vm.filteredUsersTag},on:{"select-user-tag":function($event){return _vm.selectUserTag($event)}}}),_c('div',{staticClass:"vac-box-footer",class:{
'vac-app-box-shadow': _vm.filteredEmojis.length || _vm.filteredUsersTag.length
}},[(_vm.showAudio && !_vm.imageFile && !_vm.videoFile)?_c('div',{staticClass:"vac-icon-textarea-left"},[(_vm.isRecording)?[_c('div',{staticClass:"vac-svg-button vac-icon-audio-stop",on:{"click":_vm.stopRecorder}},[_vm._t("audio-stop-icon",[_c('svg-icon',{attrs:{"name":"close-outline"}})])],2),_c('div',{staticClass:"vac-dot-audio-record"}),_c('div',{staticClass:"vac-dot-audio-record-time"},[_vm._v(" "+_vm._s(_vm.recordedTime)+" ")]),_c('div',{staticClass:"vac-svg-button vac-icon-audio-confirm",on:{"click":function($event){return _vm.toggleRecorder(false)}}},[_vm._t("audio-stop-icon",[_c('svg-icon',{attrs:{"name":"checkmark"}})])],2)]:_c('div',{staticClass:"vac-svg-button",on:{"click":function($event){return _vm.toggleRecorder(true)}}},[_vm._t("microphone-icon",[_c('svg-icon',{staticClass:"vac-icon-microphone",attrs:{"name":"microphone"}})])],2)],2):_vm._e(),(_vm.imageFile)?_c('div',{staticClass:"vac-media-container"},[_c('div',{staticClass:"vac-svg-button vac-icon-media",on:{"click":_vm.resetMediaFile}},[_vm._t("image-close-icon",[_c('svg-icon',{attrs:{"name":"close","param":"image"}})])],2),_c('div',{staticClass:"vac-media-file"},[_c('img',{ref:"mediaFile",attrs:{"src":_vm.imageFile},on:{"load":_vm.onMediaLoad}})])]):(_vm.videoFile)?_c('div',{staticClass:"vac-media-container"},[_c('div',{staticClass:"vac-svg-button vac-icon-media",on:{"click":_vm.resetMediaFile}},[_vm._t("image-close-icon",[_c('svg-icon',{attrs:{"name":"close","param":"image"}})])],2),_c('div',{ref:"mediaFile",staticClass:"vac-media-file"},[_c('video',{attrs:{"width":"100%","height":"100%","controls":""}},[_c('source',{attrs:{"src":_vm.videoFile}})])])]):(_vm.file)?_c('div',{staticClass:"vac-file-container",class:{ 'vac-file-container-edit': _vm.editedMessage._id }},[_c('div',{staticClass:"vac-icon-file"},[_vm._t("file-icon",[_c('svg-icon',{attrs:{"name":"file"}})])],2),_c('div',{staticClass:"vac-file-message"},[_vm._v(" "+_vm._s(_vm.file.audio ? _vm.file.name : _vm.message)+" ")]),_c('div',{staticClass:"vac-svg-button vac-icon-remove",on:{"click":function($event){return _vm.resetMessage(null, true)}}},[_vm._t("file-close-icon",[_c('svg-icon',{attrs:{"name":"close"}})])],2)]):_vm._e(),_c('textarea',{directives:[{name:"show",rawName:"v-show",value:(!_vm.file || _vm.imageFile || _vm.videoFile),expression:"!file || imageFile || videoFile"},{name:"model",rawName:"v-model",value:(_vm.message),expression:"message"}],ref:"roomTextarea",staticClass:"vac-textarea",class:{
'vac-textarea-outline': _vm.editedMessage._id
},style:({
'min-height': ((_vm.mediaDimensions ? _vm.mediaDimensions.height : 20) + "px"),
'padding-left': ((_vm.mediaDimensions ? _vm.mediaDimensions.width - 10 : 12) + "px")
}),attrs:{"placeholder":_vm.textMessages.TYPE_MESSAGE},domProps:{"value":(_vm.message)},on:{"input":[function($event){if($event.target.composing){ return; }_vm.message=$event.target.value},_vm.onChangeInput],"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"esc",27,$event.key,["Esc","Escape"])){ return null; }return _vm.escapeTextarea($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }if($event.ctrlKey||$event.shiftKey||$event.altKey||$event.metaKey){ return null; }$event.preventDefault();}]}}),_c('div',{staticClass:"vac-icon-textarea"},[(_vm.editedMessage._id)?_c('div',{staticClass:"vac-svg-button",on:{"click":_vm.resetMessage}},[_vm._t("edit-close-icon",[_c('svg-icon',{attrs:{"name":"close-outline"}})])],2):_vm._e(),(_vm.showEmojis && (!_vm.file || _vm.imageFile || _vm.videoFile))?_c('emoji-picker',{attrs:{"emoji-opened":_vm.emojiOpened,"position-top":true},on:{"add-emoji":_vm.addEmoji,"open-emoji":function($event){_vm.emojiOpened = $event}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):_vm._e(),(_vm.showFiles)?_c('div',{staticClass:"vac-svg-button",on:{"click":_vm.launchFilePicker}},[_vm._t("paperclip-icon",[_c('svg-icon',{attrs:{"name":"paperclip"}})])],2):_vm._e(),(_vm.textareaAction)?_c('div',{staticClass:"vac-svg-button",on:{"click":_vm.textareaActionHandler}},[_vm._t("custom-action-icon",[_c('svg-icon',{attrs:{"name":"deleted"}})])],2):_vm._e(),(_vm.showFiles)?_c('input',{ref:"file",staticStyle:{"display":"none"},attrs:{"type":"file","accept":_vm.acceptedFiles},on:{"change":function($event){return _vm.onFileChange($event.target.files)}}}):_vm._e(),(_vm.showSendIcon)?_c('div',{staticClass:"vac-svg-button",class:{ 'vac-send-disabled': _vm.isMessageEmpty },on:{"click":_vm.sendMessage}},[_vm._t("send-icon",[_c('svg-icon',{attrs:{"name":"send","param":_vm.isMessageEmpty ? 'disabled' : ''}})])],2):_vm._e()],1)])],1)],2)}
var Roomvue_type_template_id_1a1a6e46_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Room/Room.vue?vue&type=template&id=1a1a6e46&
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.to-string.js
var es6_object_to_string = __webpack_require__("06db");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.promise.js
var es6_promise = __webpack_require__("551c");
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.is-array.js
var es6_array_is_array = __webpack_require__("2caf");
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.iterator.js
var es6_string_iterator = __webpack_require__("5df3");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.iterator.js
var es6_array_iterator = __webpack_require__("cadf");
// EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom.iterable.js
var web_dom_iterable = __webpack_require__("ac6a");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.from.js
var es6_array_from = __webpack_require__("1c4c");
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/iterableToArray.js
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
// EXTERNAL MODULE: ./node_modules/regenerator-runtime/runtime.js
var runtime = __webpack_require__("96cf");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.object.assign.js
var es6_object_assign = __webpack_require__("f751");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.string.trim.js
var es6_string_trim = __webpack_require__("4f37");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.date.to-iso-string.js
var es6_date_to_iso_string = __webpack_require__("8ea5");
// CONCATENATED MODULE: ./node_modules/vue-emoji-picker/src/emojis.js
/* harmony default export */ var emojis = ({
'Frequently used': {
'thumbs_up': '👍',
'-1': '👎',
'sob': '😭',
'confused': '😕',
'neutral_face': '😐',
'blush': '😊',
'heart_eyes': '😍',
},
'People': {
'smile': '😄',
'smiley': '😃',
'grinning': '😀',
'blush': '😊',
'wink': '😉',
'heart_eyes': '😍',
'kissing_heart': '😘',
'kissing_closed_eyes': '😚',
'kissing': '😗',
'kissing_smiling_eyes': '😙',
'stuck_out_tongue_winking_eye': '😜',
'stuck_out_tongue_closed_eyes': '😝',
'stuck_out_tongue': '😛',
'flushed': '😳',
'grin': '😁',
'pensive': '😔',
'relieved': '😌',
'unamused': '😒',
'disappointed': '😞',
'persevere': '😣',
'cry': '😢',
'joy': '😂',
'sob': '😭',
'sleepy': '😪',
'disappointed_relieved': '😥',
'cold_sweat': '😰',
'sweat_smile': '😅',
'sweat': '😓',
'weary': '😩',
'tired_face': '😫',
'fearful': '😨',
'scream': '😱',
'angry': '😠',
'rage': '😡',
'triumph': '😤',
'confounded': '😖',
'laughing': '😆',
'yum': '😋',
'mask': '😷',
'sunglasses': '😎',
'sleeping': '😴',
'dizzy_face': '😵',
'astonished': '😲',
'worried': '😟',
'frowning': '😦',
'anguished': '😧',
'imp': '👿',
'open_mouth': '😮',
'grimacing': '😬',
'neutral_face': '😐',
'confused': '😕',
'hushed': '😯',
'smirk': '😏',
'expressionless': '😑',
'man_with_gua_pi_mao': '👲',
'man_with_turban': '👳',
'cop': '👮',
'construction_worker': '👷',
'guardsman': '💂',
'baby': '👶',
'boy': '👦',
'girl': '👧',
'man': '👨',
'woman': '👩',
'older_man': '👴',
'older_woman': '👵',
'person_with_blond_hair': '👱',
'angel': '👼',
'princess': '👸',
'smiley_cat': '😺',
'smile_cat': '😸',
'heart_eyes_cat': '😻',
'kissing_cat': '😽',
'smirk_cat': '😼',
'scream_cat': '🙀',
'crying_cat_face': '😿',
'joy_cat': '😹',
'pouting_cat': '😾',
'japanese_ogre': '👹',
'japanese_goblin': '👺',
'see_no_evil': '🙈',
'hear_no_evil': '🙉',
'speak_no_evil': '🙊',
'skull': '💀',
'alien': '👽',
'hankey': '💩',
'fire': '🔥',
'sparkles': '✨',
'star2': '🌟',
'dizzy': '💫',
'boom': '💥',
'anger': '💢',
'sweat_drops': '💦',
'droplet': '💧',
'zzz': '💤',
'dash': '💨',
'ear': '👂',
'eyes': '👀',
'nose': '👃',
'tongue': '👅',
'lips': '👄',
'thumbs_up': '👍',
'-1': '👎',
'ok_hand': '👌',
'facepunch': '👊',
'fist': '✊',
'wave': '👋',
'hand': '✋',
'open_hands': '👐',
'point_up_2': '👆',
'point_down': '👇',
'point_right': '👉',
'point_left': '👈',
'raised_hands': '🙌',
'pray': '🙏',
'clap': '👏',
'muscle': '💪',
'walking': '🚶',
'runner': '🏃',
'dancer': '💃',
'couple': '👫',
'family': '👪',
'couplekiss': '💏',
'couple_with_heart': '💑',
'dancers': '👯',
'ok_woman': '🙆',
'no_good': '🙅',
'information_desk_person': '💁',
'raising_hand': '🙋',
'massage': '💆',
'haircut': '💇',
'nail_care': '💅',
'bride_with_veil': '👰',
'person_with_pouting_face': '🙎',
'person_frowning': '🙍',
'bow': '🙇',
'tophat': '🎩',
'crown': '👑',
'womans_hat': '👒',
'athletic_shoe': '👟',
'mans_shoe': '👞',
'sandal': '👡',
'high_heel': '👠',
'boot': '👢',
'shirt': '👕',
'necktie': '👔',
'womans_clothes': '👚',
'dress': '👗',
'running_shirt_with_sash': '🎽',
'jeans': '👖',
'kimono': '👘',
'bikini': '👙',
'briefcase': '💼',
'handbag': '👜',
'pouch': '👝',
'purse': '👛',
'eyeglasses': '👓',
'ribbon': '🎀',
'closed_umbrella': '🌂',
'lipstick': '💄',
'yellow_heart': '💛',
'blue_heart': '💙',
'purple_heart': '💜',
'green_heart': '💚',
'broken_heart': '💔',
'heartpulse': '💗',
'heartbeat': '💓',
'two_hearts': '💕',
'sparkling_heart': '💖',
'revolving_hearts': '💞',
'cupid': '💘',
'love_letter': '💌',
'kiss': '💋',
'ring': '💍',
'gem': '💎',
'bust_in_silhouette': '👤',
'speech_balloon': '💬',
'footprints': '👣',
},
'Nature': {
'dog': '🐶',
'wolf': '🐺',
'cat': '🐱',
'mouse': '🐭',
'hamster': '🐹',
'rabbit': '🐰',
'frog': '🐸',
'tiger': '🐯',
'koala': '🐨',
'bear': '🐻',
'pig': '🐷',
'pig_nose': '🐽',
'cow': '🐮',
'boar': '🐗',
'monkey_face': '🐵',
'monkey': '🐒',
'horse': '🐴',
'sheep': '🐑',
'elephant': '🐘',
'panda_face': '🐼',
'penguin': '🐧',
'bird': '🐦',
'baby_chick': '🐤',
'hatched_chick': '🐥',
'hatching_chick': '🐣',
'chicken': '🐔',
'snake': '🐍',
'turtle': '🐢',
'bug': '🐛',
'bee': '🐝',
'ant': '🐜',
'beetle': '🐞',
'snail': '🐌',
'octopus': '🐙',
'shell': '🐚',
'tropical_fish': '🐠',
'fish': '🐟',
'dolphin': '🐬',
'whale': '🐳',
'racehorse': '🐎',
'dragon_face': '🐲',
'blowfish': '🐡',
'camel': '🐫',
'poodle': '🐩',
'feet': '🐾',
'bouquet': '💐',
'cherry_blossom': '🌸',
'tulip': '🌷',
'four_leaf_clover': '🍀',
'rose': '🌹',
'sunflower': '🌻',
'hibiscus': '🌺',
'maple_leaf': '🍁',
'leaves': '🍃',
'fallen_leaf': '🍂',
'herb': '🌿',
'ear_of_rice': '🌾',
'mushroom': '🍄',
'cactus': '🌵',
'palm_tree': '🌴',
'chestnut': '🌰',
'seedling': '🌱',
'blossom': '🌼',
'new_moon': '🌑',
'first_quarter_moon': '🌓',
'moon': '🌔',
'full_moon': '🌕',
'first_quarter_moon_with_face': '🌛',
'crescent_moon': '🌙',
'earth_asia': '🌏',
'volcano': '🌋',
'milky_way': '🌌',
'stars': '🌠',
'partly_sunny': '⛅',
'snowman': '⛄',
'cyclone': '🌀',
'foggy': '🌁',
'rainbow': '🌈',
'ocean': '🌊',
},
'Objects': {
'bamboo': '🎍',
'gift_heart': '💝',
'dolls': '🎎',
'school_satchel': '🎒',
'mortar_board': '🎓',
'flags': '🎏',
'fireworks': '🎆',
'sparkler': '🎇',
'wind_chime': '🎐',
'rice_scene': '🎑',
'jack_o_lantern': '🎃',
'ghost': '👻',
'santa': '🎅',
'christmas_tree': '🎄',
'gift': '🎁',
'tanabata_tree': '🎋',
'tada': '🎉',
'confetti_ball': '🎊',
'balloon': '🎈',
'crossed_flags': '🎌',
'crystal_ball': '🔮',
'movie_camera': '🎥',
'camera': '📷',
'video_camera': '📹',
'vhs': '📼',
'cd': '💿',
'dvd': '📀',
'minidisc': '💽',
'floppy_disk': '💾',
'computer': '💻',
'iphone': '📱',
'telephone_receiver': '📞',
'pager': '📟',
'fax': '📠',
'satellite': '📡',
'tv': '📺',
'radio': '📻',
'loud_sound': '🔊',
'bell': '🔔',
'loudspeaker': '📢',
'mega': '📣',
'hourglass_flowing_sand': '⏳',
'hourglass': '⌛',
'alarm_clock': '⏰',
'watch': '⌚',
'unlock': '🔓',
'lock': '🔒',
'lock_with_ink_pen': '🔏',
'closed_lock_with_key': '🔐',
'key': '🔑',
'mag_right': '🔎',
'bulb': '💡',
'flashlight': '🔦',
'electric_plug': '🔌',
'battery': '🔋',
'mag': '🔍',
'bath': '🛀',
'toilet': '🚽',
'wrench': '🔧',
'nut_and_bolt': '🔩',
'hammer': '🔨',
'door': '🚪',
'smoking': '🚬',
'bomb': '💣',
'gun': '🔫',
'hocho': '🔪',
'pill': '💊',
'syringe': '💉',
'moneybag': '💰',
'yen': '💴',
'dollar': '💵',
'credit_card': '💳',
'money_with_wings': '💸',
'calling': '📲',
'e-mail': '📧',
'inbox_tray': '📥',
'outbox_tray': '📤',
'envelope_with_arrow': '📩',
'incoming_envelope': '📨',
'mailbox': '📫',
'mailbox_closed': '📪',
'postbox': '📮',
'package': '📦',
'memo': '📝',
'page_facing_up': '📄',
'page_with_curl': '📃',
'bookmark_tabs': '📑',
'bar_chart': '📊',
'chart_with_upwards_trend': '📈',
'chart_with_downwards_trend': '📉',
'scroll': '📜',
'clipboard': '📋',
'date': '📅',
'calendar': '📆',
'card_index': '📇',
'file_folder': '📁',
'open_file_folder': '📂',
'pushpin': '📌',
'paperclip': '📎',
'straight_ruler': '📏',
'triangular_ruler': '📐',
'closed_book': '📕',
'green_book': '📗',
'blue_book': '📘',
'orange_book': '📙',
'notebook': '📓',
'notebook_with_decorative_cover': '📔',
'ledger': '📒',
'books': '📚',
'book': '📖',
'bookmark': '🔖',
'name_badge': '📛',
'newspaper': '📰',
'art': '🎨',
'clapper': '🎬',
'microphone': '🎤',
'headphones': '🎧',
'musical_score': '🎼',
'musical_note': '🎵',
'notes': '🎶',
'musical_keyboard': '🎹',
'violin': '🎻',
'trumpet': '🎺',
'saxophone': '🎷',
'guitar': '🎸',
'space_invader': '👾',
'video_game': '🎮',
'black_joker': '🃏',
'flower_playing_cards': '🎴',
'mahjong': '🀄',
'game_die': '🎲',
'dart': '🎯',
'football': '🏈',
'basketball': '🏀',
'soccer': '⚽',
'baseball': '⚾',
'tennis': '🎾',
'8ball': '🎱',
'bowling': '🎳',
'golf': '⛳',
'checkered_flag': '🏁',
'trophy': '🏆',
'ski': '🎿',
'snowboarder': '🏂',
'swimmer': '🏊',
'surfer': '🏄',
'fishing_pole_and_fish': '🎣',
'tea': '🍵',
'sake': '🍶',
'beer': '🍺',
'beers': '🍻',
'cocktail': '🍸',
'tropical_drink': '🍹',
'wine_glass': '🍷',
'fork_and_knife': '🍴',
'pizza': '🍕',
'hamburger': '🍔',
'fries': '🍟',
'poultry_leg': '🍗',
'meat_on_bone': '🍖',
'spaghetti': '🍝',
'curry': '🍛',
'fried_shrimp': '🍤',
'bento': '🍱',
'sushi': '🍣',
'fish_cake': '🍥',
'rice_ball': '🍙',
'rice_cracker': '🍘',
'rice': '🍚',
'ramen': '🍜',
'stew': '🍲',
'oden': '🍢',
'dango': '🍡',
'egg': '🍳',
'bread': '🍞',
'doughnut': '🍩',
'custard': '🍮',
'icecream': '🍦',
'ice_cream': '🍨',
'shaved_ice': '🍧',
'birthday': '🎂',
'cake': '🍰',
'cookie': '🍪',
'chocolate_bar': '🍫',
'candy': '🍬',
'lollipop': '🍭',
'honey_pot': '🍯',
'apple': '🍎',
'green_apple': '🍏',
'tangerine': '🍊',
'cherries': '🍒',
'grapes': '🍇',
'watermelon': '🍉',
'strawberry': '🍓',
'peach': '🍑',
'melon': '🍈',
'banana': '🍌',
'pineapple': '🍍',
'sweet_potato': '🍠',
'eggplant': '🍆',
'tomato': '🍅',
'corn': '🌽',
},
'Places': {
'house': '🏠',
'house_with_garden': '🏡',
'school': '🏫',
'office': '🏢',
'post_office': '🏣',
'hospital': '🏥',
'bank': '🏦',
'convenience_store': '🏪',
'love_hotel': '🏩',
'hotel': '🏨',
'wedding': '💒',
'church': '⛪',
'department_store': '🏬',
'city_sunrise': '🌇',
'city_sunset': '🌆',
'japanese_castle': '🏯',
'european_castle': '🏰',
'tent': '⛺',
'factory': '🏭',
'tokyo_tower': '🗼',
'japan': '🗾',
'mount_fuji': '🗻',
'sunrise_over_mountains': '🌄',
'sunrise': '🌅',
'night_with_stars': '🌃',
'statue_of_liberty': '🗽',
'bridge_at_night': '🌉',
'carousel_horse': '🎠',
'ferris_wheel': '🎡',
'fountain': '⛲',
'roller_coaster': '🎢',
'ship': '🚢',
'boat': '⛵',
'speedboat': '🚤',
'rocket': '🚀',
'seat': '💺',
'station': '🚉',
'bullettrain_side': '🚄',
'bullettrain_front': '🚅',
'metro': '🚇',
'railway_car': '🚃',
'bus': '🚌',
'blue_car': '🚙',
'car': '🚗',
'taxi': '🚕',
'truck': '🚚',
'rotating_light': '🚨',
'police_car': '🚓',
'fire_engine': '🚒',
'ambulance': '🚑',
'bike': '🚲',
'barber': '💈',
'busstop': '🚏',
'ticket': '🎫',
'traffic_light': '🚥',
'construction': '🚧',
'beginner': '🔰',
'fuelpump': '⛽',
'izakaya_lantern': '🏮',
'slot_machine': '🎰',
'moyai': '🗿',
'circus_tent': '🎪',
'performing_arts': '🎭',
'round_pushpin': '📍',
'triangular_flag_on_post': '🚩',
},
'Symbols': {
'keycap_ten': '🔟',
'1234': '🔢',
'symbols': '🔣',
'capital_abcd': '🔠',
'abcd': '🔡',
'abc': '🔤',
'arrow_up_small': '🔼',
'arrow_down_small': '🔽',
'rewind': '⏪',
'fast_forward': '⏩',
'arrow_double_up': '⏫',
'arrow_double_down': '⏬',
'ok': '🆗',
'new': '🆕',
'up': '🆙',
'cool': '🆒',
'free': '🆓',
'ng': '🆖',
'signal_strength': '📶',
'cinema': '🎦',
'koko': '🈁',
'u6307': '🈯',
'u7a7a': '🈳',
'u6e80': '🈵',
'u5408': '🈴',
'u7981': '🈲',
'ideograph_advantage': '🉐',
'u5272': '🈹',
'u55b6': '🈺',
'u6709': '🈶',
'u7121': '🈚',
'restroom': '🚻',
'mens': '🚹',
'womens': '🚺',
'baby_symbol': '🚼',
'wc': '🚾',
'no_smoking': '🚭',
'u7533': '🈸',
'accept': '🉑',
'cl': '🆑',
'sos': '🆘',
'id': '🆔',
'no_entry_sign': '🚫',
'underage': '🔞',
'no_entry': '⛔',
'negative_squared_cross_mark': '❎',
'white_check_mark': '✅',
'heart_decoration': '💟',
'vs': '🆚',
'vibration_mode': '📳',
'mobile_phone_off': '📴',
'ab': '🆎',
'diamond_shape_with_a_dot_inside': '💠',
'ophiuchus': '⛎',
'six_pointed_star': '🔯',
'atm': '🏧',
'chart': '💹',
'heavy_dollar_sign': '💲',
'currency_exchange': '💱',
'x': '❌',
'exclamation': '❗',
'question': '❓',
'grey_exclamation': '❕',
'grey_question': '❔',
'o': '⭕',
'top': '🔝',
'end': '🔚',
'back': '🔙',
'on': '🔛',
'soon': '🔜',
'arrows_clockwise': '🔃',
'clock12': '🕛',
'clock1': '🕐',
'clock2': '🕑',
'clock3': '🕒',
'clock4': '🕓',
'clock5': '🕔',
'clock6': '🕕',
'clock7': '🕖',
'clock8': '🕗',
'clock9': '🕘',
'clock10': '🕙',
'clock11': '🕚',
'heavy_plus_sign': '➕',
'heavy_minus_sign': '➖',
'heavy_division_sign': '➗',
'white_flower': '💮',
'100': '💯',
'radio_button': '🔘',
'link': '🔗',
'curly_loop': '➰',
'trident': '🔱',
'small_red_triangle': '🔺',
'black_square_button': '🔲',
'white_square_button': '🔳',
'red_circle': '🔴',
'large_blue_circle': '🔵',
'small_red_triangle_down': '🔻',
'white_large_square': '⬜',
'black_large_square': '⬛',
'large_orange_diamond': '🔶',
'large_blue_diamond': '🔷',
'small_orange_diamond': '🔸',
'small_blue_diamond': '🔹',
},
});
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/EmojiPicker.vue?vue&type=template&id=0e56d761&
var EmojiPickervue_type_template_id_0e56d761_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-wrapper"},[_c('emoji-picker',{attrs:{"search":_vm.search},on:{"emoji":_vm.append},scopedSlots:_vm._u([{key:"emoji-invoker",fn:function(ref){
var clickEvent = ref.events.click;
return _c('div',{staticClass:"vac-svg-button",class:{ 'vac-emoji-reaction': _vm.emojiReaction },on:{"click":[function($event){$event.stopPropagation();return clickEvent($event)},_vm.openEmoji]}},[_vm._t("emoji-picker-icon",[_c('svg-icon',{attrs:{"name":"emoji","param":_vm.emojiReaction ? 'reaction' : ''}})])],2)}},{key:"emoji-picker",fn:function(ref){
var emojis = ref.emojis;
var insert = ref.insert;
return (_vm.emojiOpened)?_c('div',{},[_c('transition',{attrs:{"name":"vac-slide-up","appear":""}},[_c('div',{staticClass:"vac-emoji-picker",class:{ 'vac-picker-reaction': _vm.emojiReaction },style:({
height: (_vm.emojiPickerHeight + "px"),
top: _vm.positionTop ? _vm.emojiPickerHeight : (_vm.emojiPickerTop + "px"),
right: _vm.emojiPickerRight,
display: _vm.emojiPickerTop || !_vm.emojiReaction ? 'initial' : 'none'
})},[_c('div',{staticClass:"vac-emoji-picker__search"},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.search),expression:"search"}],attrs:{"type":"text"},domProps:{"value":(_vm.search)},on:{"input":function($event){if($event.target.composing){ return; }_vm.search=$event.target.value}}})]),_c('div',_vm._l((emojis),function(emojiGroup,category){return _c('div',{key:category},[(category !== 'Frequently used')?_c('h5',[_vm._v(" "+_vm._s(category)+" ")]):_vm._e(),(category !== 'Frequently used')?_c('div',{staticClass:"vac-emojis"},_vm._l((emojiGroup),function(emoji,emojiName){return _c('span',{key:emojiName,attrs:{"title":emojiName},on:{"click":function($event){return insert({ emoji: emoji, emojiName: emojiName })}}},[_vm._v(" "+_vm._s(emoji)+" ")])}),0):_vm._e()])}),0)])])],1):_vm._e()}}],null,true)})],1)}
var EmojiPickervue_type_template_id_0e56d761_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/EmojiPicker.vue?vue&type=template&id=0e56d761&
// EXTERNAL MODULE: ./node_modules/vue-emoji-picker/dist-module/main.js
var main = __webpack_require__("669f");
var main_default = /*#__PURE__*/__webpack_require__.n(main);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/EmojiPicker.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var EmojiPickervue_type_script_lang_js_ = ({
components: {
EmojiPicker: main_default.a,
SvgIcon: SvgIcon
},
props: {
emojiOpened: {
type: Boolean,
"default": false
},
emojiReaction: {
type: Boolean,
"default": false
},
roomFooterRef: {
type: HTMLDivElement,
"default": null
},
positionTop: {
type: Boolean,
"default": false
},
positionRight: {
type: Boolean,
"default": false
}
},
data: function data() {
return {
search: '',
emojiPickerHeight: 320,
emojiPickerTop: 0,
emojiPickerRight: ''
};
},
methods: {
append: function append(_ref) {
var emoji = _ref.emoji,
emojiName = _ref.emojiName;
this.$emit('add-emoji', {
icon: emoji,
name: emojiName
});
},
openEmoji: function openEmoji(ev) {
this.$emit('open-emoji', true);
this.setEmojiPickerPosition(ev.clientY, ev.view.innerWidth, ev.view.innerHeight);
},
setEmojiPickerPosition: function setEmojiPickerPosition(clientY, innerWidth, innerHeight) {
var _this = this;
setTimeout(function () {
var mobileSize = innerWidth < 500 || innerHeight < 700;
if (!_this.roomFooterRef) {
if (mobileSize) _this.emojiPickerRight = '0px';
return;
}
if (mobileSize) {
_this.emojiPickerRight = innerWidth / 2 - 120 + 'px';
_this.emojiPickerTop = 100;
_this.emojiPickerHeight = innerHeight - 200;
} else {
var roomFooterTop = _this.roomFooterRef.getBoundingClientRect().top;
var pickerTopPosition = roomFooterTop - clientY > _this.emojiPickerHeight - 50;
if (pickerTopPosition) _this.emojiPickerTop = clientY + 10;else _this.emojiPickerTop = clientY - _this.emojiPickerHeight - 10;
_this.emojiPickerRight = _this.positionTop ? '-50px' : _this.positionRight ? '60px' : '';
}
});
}
}
});
// CONCATENATED MODULE: ./src/components/EmojiPicker.vue?vue&type=script&lang=js&
/* harmony default export */ var components_EmojiPickervue_type_script_lang_js_ = (EmojiPickervue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/components/EmojiPicker.vue?vue&type=style&index=0&lang=scss&
var EmojiPickervue_type_style_index_0_lang_scss_ = __webpack_require__("3c0d");
// CONCATENATED MODULE: ./src/components/EmojiPicker.vue
/* normalize component */
var EmojiPicker_component = normalizeComponent(
components_EmojiPickervue_type_script_lang_js_,
EmojiPickervue_type_template_id_0e56d761_render,
EmojiPickervue_type_template_id_0e56d761_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var EmojiPicker = (EmojiPicker_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomHeader.vue?vue&type=template&id=0afde938&
var RoomHeadervue_type_template_id_0afde938_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-room-header vac-app-border-b"},[_vm._t("room-header",[_c('div',{staticClass:"vac-room-wrapper"},[(!_vm.singleRoom)?_c('div',{staticClass:"vac-svg-button vac-toggle-button",class:{ 'vac-rotate-icon': !_vm.showRoomsList && !_vm.isMobile },on:{"click":function($event){return _vm.$emit('toggle-rooms-list')}}},[_vm._t("toggle-icon",[_c('svg-icon',{attrs:{"name":"toggle"}})])],2):_vm._e(),_c('div',{staticClass:"vac-info-wrapper",class:{ 'vac-item-clickable': _vm.roomInfo },on:{"click":function($event){return _vm.$emit('room-info')}}},[_vm._t("room-header-avatar",[(_vm.room.avatar)?_c('div',{staticClass:"vac-avatar",style:({ 'background-image': ("url('" + (_vm.room.avatar) + "')") })}):_vm._e()],null,{ room: _vm.room }),_vm._t("room-header-info",[_c('div',{staticClass:"vac-text-ellipsis"},[_c('div',{staticClass:"vac-room-name vac-text-ellipsis"},[_vm._v(" "+_vm._s(_vm.room.roomName)+" ")]),(_vm.typingUsers)?_c('div',{staticClass:"vac-room-info vac-text-ellipsis"},[_vm._v(" "+_vm._s(_vm.typingUsers)+" ")]):_c('div',{staticClass:"vac-room-info vac-text-ellipsis"},[_vm._v(" "+_vm._s(_vm.userStatus)+" ")])])],null,{ room: _vm.room, typingUsers: _vm.typingUsers, userStatus: _vm.userStatus })],2),(_vm.room.roomId)?_vm._t("room-options",[(_vm.menuActions.length)?_c('div',{staticClass:"vac-svg-button vac-room-options",on:{"click":function($event){_vm.menuOpened = !_vm.menuOpened}}},[_vm._t("menu-icon",[_c('svg-icon',{attrs:{"name":"menu"}})])],2):_vm._e(),(_vm.menuActions.length)?_c('transition',{attrs:{"name":"vac-slide-left"}},[(_vm.menuOpened)?_c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeMenu),expression:"closeMenu"}],staticClass:"vac-menu-options"},[_c('div',{staticClass:"vac-menu-list"},_vm._l((_vm.menuActions),function(action){return _c('div',{key:action.name},[_c('div',{staticClass:"vac-menu-item",on:{"click":function($event){return _vm.menuActionHandler(action)}}},[_vm._v(" "+_vm._s(action.title)+" ")])])}),0)]):_vm._e()]):_vm._e()]):_vm._e()],2)],null,{ room: _vm.room, typingUsers: _vm.typingUsers, userStatus: _vm.userStatus })],2)}
var RoomHeadervue_type_template_id_0afde938_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomHeader.vue?vue&type=template&id=0afde938&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomHeader.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var RoomHeadervue_type_script_lang_js_ = ({
name: 'RoomHeader',
components: {
SvgIcon: SvgIcon
},
directives: {
clickOutside: v_click_outside_umd_default.a.directive
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
textMessages: {
type: Object,
required: true
},
singleRoom: {
type: Boolean,
required: true
},
showRoomsList: {
type: Boolean,
required: true
},
isMobile: {
type: Boolean,
required: true
},
roomInfo: {
type: Function,
"default": null
},
menuActions: {
type: Array,
required: true
},
room: {
type: Object,
required: true
}
},
data: function data() {
return {
menuOpened: false
};
},
computed: {
typingUsers: function typingUsers() {
return typing_text(this.room, this.currentUserId, this.textMessages);
},
userStatus: function userStatus() {
var _this = this;
if (!this.room.users || this.room.users.length !== 2) return;
var user = this.room.users.find(function (u) {
return u._id !== _this.currentUserId;
});
if (!user.status) return;
var text = '';
if (user.status.state === 'online') {
text = this.textMessages.IS_ONLINE;
} else if (user.status.lastChanged) {
text = this.textMessages.LAST_SEEN + user.status.lastChanged;
}
return text;
}
},
methods: {
menuActionHandler: function menuActionHandler(action) {
this.closeMenu();
this.$emit('menu-action-handler', action);
},
closeMenu: function closeMenu() {
this.menuOpened = false;
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomHeader.vue?vue&type=script&lang=js&
/* harmony default export */ var Room_RoomHeadervue_type_script_lang_js_ = (RoomHeadervue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Room/RoomHeader.vue?vue&type=style&index=0&lang=scss&
var RoomHeadervue_type_style_index_0_lang_scss_ = __webpack_require__("e83d");
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomHeader.vue
/* normalize component */
var RoomHeader_component = normalizeComponent(
Room_RoomHeadervue_type_script_lang_js_,
RoomHeadervue_type_template_id_0afde938_render,
RoomHeadervue_type_template_id_0afde938_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomHeader = (RoomHeader_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomMessageReply.vue?vue&type=template&id=168137bc&
var RoomMessageReplyvue_type_template_id_168137bc_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"vac-slide-up"}},[(_vm.messageReply)?_c('div',{staticClass:"vac-reply-container",style:({ bottom: ((_vm.$parent.$refs.roomFooter.clientHeight) + "px") })},[_c('div',{staticClass:"vac-reply-box"},[(_vm.isImageFile)?_c('img',{staticClass:"vac-image-reply",attrs:{"src":_vm.messageReply.file.url}}):_vm._e(),_c('div',{staticClass:"vac-reply-info"},[_c('div',{staticClass:"vac-reply-username"},[_vm._v(" "+_vm._s(_vm.messageReply.username)+" ")]),_c('div',{staticClass:"vac-reply-content"},[_c('format-message',{attrs:{"content":_vm.messageReply.content,"users":_vm.room.users,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"reply":true},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)])]),_c('div',{staticClass:"vac-icon-reply"},[_c('div',{staticClass:"vac-svg-button",on:{"click":function($event){return _vm.$emit('reset-message')}}},[_vm._t("reply-close-icon",[_c('svg-icon',{attrs:{"name":"close-outline"}})])],2)])]):_vm._e()])}
var RoomMessageReplyvue_type_template_id_168137bc_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomMessageReply.vue?vue&type=template&id=168137bc&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomMessageReply.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var RoomMessageReplyvue_type_script_lang_js_require = __webpack_require__("bd43"),
_isImageFile = RoomMessageReplyvue_type_script_lang_js_require.isImageFile;
/* harmony default export */ var RoomMessageReplyvue_type_script_lang_js_ = ({
name: 'RoomMessageReply',
components: {
SvgIcon: SvgIcon,
FormatMessage: FormatMessage
},
props: {
room: {
type: Object,
required: true
},
messageReply: {
type: Object,
"default": null
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
}
},
computed: {
isImageFile: function isImageFile() {
return _isImageFile(this.messageReply.file);
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomMessageReply.vue?vue&type=script&lang=js&
/* harmony default export */ var Room_RoomMessageReplyvue_type_script_lang_js_ = (RoomMessageReplyvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Room/RoomMessageReply.vue?vue&type=style&index=0&lang=scss&
var RoomMessageReplyvue_type_style_index_0_lang_scss_ = __webpack_require__("3cd7");
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomMessageReply.vue
/* normalize component */
var RoomMessageReply_component = normalizeComponent(
Room_RoomMessageReplyvue_type_script_lang_js_,
RoomMessageReplyvue_type_template_id_168137bc_render,
RoomMessageReplyvue_type_template_id_168137bc_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomMessageReply = (RoomMessageReply_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomUsersTag.vue?vue&type=template&id=adecc494&
var RoomUsersTagvue_type_template_id_adecc494_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"vac-slide-up"}},[(_vm.filteredUsersTag.length)?_c('div',{staticClass:"vac-tags-container vac-app-box-shadow",style:({ bottom: ((_vm.$parent.$refs.roomFooter.clientHeight) + "px") })},_vm._l((_vm.filteredUsersTag),function(user){return _c('div',{key:user._id,staticClass:"vac-tags-box",on:{"click":function($event){return _vm.$emit('select-user-tag', user)}}},[_c('div',{staticClass:"vac-tags-info"},[(user.avatar)?_c('div',{staticClass:"vac-avatar vac-tags-avatar",style:({ 'background-image': ("url('" + (user.avatar) + "')") })}):_vm._e(),_c('div',{staticClass:"vac-tags-username"},[_vm._v(" "+_vm._s(user.username)+" ")])])])}),0):_vm._e()])}
var RoomUsersTagvue_type_template_id_adecc494_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomUsersTag.vue?vue&type=template&id=adecc494&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomUsersTag.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var RoomUsersTagvue_type_script_lang_js_ = ({
name: 'RoomUsersTag',
props: {
filteredUsersTag: {
type: Array,
required: true
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomUsersTag.vue?vue&type=script&lang=js&
/* harmony default export */ var Room_RoomUsersTagvue_type_script_lang_js_ = (RoomUsersTagvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Room/RoomUsersTag.vue?vue&type=style&index=0&lang=scss&
var RoomUsersTagvue_type_style_index_0_lang_scss_ = __webpack_require__("0ed5");
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomUsersTag.vue
/* normalize component */
var RoomUsersTag_component = normalizeComponent(
Room_RoomUsersTagvue_type_script_lang_js_,
RoomUsersTagvue_type_template_id_adecc494_render,
RoomUsersTagvue_type_template_id_adecc494_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomUsersTag = (RoomUsersTag_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomEmojis.vue?vue&type=template&id=04b99276&
var RoomEmojisvue_type_template_id_04b99276_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"vac-slide-up"}},[(_vm.filteredEmojis.length)?_c('div',{staticClass:"vac-emojis-container vac-app-box-shadow",style:({ bottom: ((_vm.$parent.$refs.roomFooter.clientHeight) + "px") })},_vm._l((_vm.filteredEmojis),function(emoji){return _c('div',{key:emoji,staticClass:"vac-emoji-element",on:{"click":function($event){return _vm.$emit('select-emoji', emoji)}}},[_vm._v(" "+_vm._s(emoji)+" ")])}),0):_vm._e()])}
var RoomEmojisvue_type_template_id_04b99276_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomEmojis.vue?vue&type=template&id=04b99276&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/RoomEmojis.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var RoomEmojisvue_type_script_lang_js_ = ({
name: 'RoomEmojis',
props: {
filteredEmojis: {
type: Array,
required: true
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomEmojis.vue?vue&type=script&lang=js&
/* harmony default export */ var Room_RoomEmojisvue_type_script_lang_js_ = (RoomEmojisvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Room/RoomEmojis.vue?vue&type=style&index=0&lang=scss&
var RoomEmojisvue_type_style_index_0_lang_scss_ = __webpack_require__("fb0c");
// CONCATENATED MODULE: ./src/ChatWindow/Room/RoomEmojis.vue
/* normalize component */
var RoomEmojis_component = normalizeComponent(
Room_RoomEmojisvue_type_script_lang_js_,
RoomEmojisvue_type_template_id_04b99276_render,
RoomEmojisvue_type_template_id_04b99276_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RoomEmojis = (RoomEmojis_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/Message.vue?vue&type=template&id=916bd03c&
var Messagevue_type_template_id_916bd03c_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{ref:_vm.message._id,staticClass:"vac-message-wrapper",attrs:{"id":_vm.message._id}},[(_vm.showDate)?_c('div',{staticClass:"vac-card-info vac-card-date"},[_vm._v(" "+_vm._s(_vm.message.date)+" ")]):_vm._e(),(_vm.newMessage._id === _vm.message._id)?_c('div',{staticClass:"vac-line-new"},[_vm._v(" "+_vm._s(_vm.textMessages.NEW_MESSAGES)+" ")]):_vm._e(),(_vm.message.system)?_c('div',{staticClass:"vac-card-info vac-card-system"},[_vm._v(" "+_vm._s(_vm.message.content)+" ")]):_c('div',{staticClass:"vac-message-box",class:{ 'vac-offset-current': _vm.message.senderId === _vm.currentUserId }},[_vm._t("message",[(_vm.message.avatar && _vm.message.senderId !== _vm.currentUserId)?_c('div',{staticClass:"vac-avatar",style:({ 'background-image': ("url('" + (_vm.message.avatar) + "')") })}):_vm._e(),_c('div',{staticClass:"vac-message-container",class:{
'vac-message-container-offset': _vm.messageOffset
}},[_c('div',{staticClass:"vac-message-card",class:{
'vac-message-highlight': _vm.isMessageHover,
'vac-message-current': _vm.message.senderId === _vm.currentUserId,
'vac-message-deleted': _vm.message.deleted
},on:{"mouseover":_vm.onHoverMessage,"mouseleave":_vm.onLeaveMessage}},[(_vm.roomUsers.length > 2 && _vm.message.senderId !== _vm.currentUserId)?_c('div',{staticClass:"vac-text-username",class:{
'vac-username-reply': !_vm.message.deleted && _vm.message.replyMessage
}},[_c('span',[_vm._v(_vm._s(_vm.message.username))])]):_vm._e(),(!_vm.message.deleted && _vm.message.replyMessage)?_c('message-reply',{attrs:{"message":_vm.message,"room-users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):_vm._e(),(_vm.message.deleted)?_c('div',[_vm._t("deleted-icon",[_c('svg-icon',{staticClass:"vac-icon-deleted",attrs:{"name":"deleted"}})]),_c('span',[_vm._v(_vm._s(_vm.textMessages.MESSAGE_DELETED))])],2):(!_vm.message.file)?_c('format-message',{attrs:{"content":_vm.message.content,"users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions},on:{"open-user-tag":_vm.openUserTag},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):(_vm.isImage)?_c('message-image',{attrs:{"current-user-id":_vm.currentUserId,"message":_vm.message,"room-users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"image-hover":_vm.imageHover},on:{"open-file":_vm.openFile},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):(_vm.isVideo)?_c('div',{staticClass:"vac-video-container"},[_c('video',{attrs:{"width":"100%","height":"100%","controls":""}},[_c('source',{attrs:{"src":_vm.message.file.url}})]),_c('format-message',{attrs:{"content":_vm.message.content,"users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions},on:{"open-user-tag":_vm.openUserTag},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1):(_vm.isAudio)?_c('audio-player',{attrs:{"src":_vm.message.file.url},on:{"update-progress-time":function($event){_vm.progressTime = $event},"hover-audio-progress":function($event){_vm.hoverAudioProgress = $event}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):_c('div',{staticClass:"vac-file-message"},[_c('div',{staticClass:"vac-svg-button vac-icon-file",on:{"click":function($event){$event.stopPropagation();return _vm.openFile('download')}}},[_vm._t("document-icon",[_c('svg-icon',{attrs:{"name":"document"}})])],2),_c('span',[_vm._v(_vm._s(_vm.message.content))])]),(_vm.isAudio && !_vm.message.deleted)?_c('div',{staticClass:"vac-progress-time"},[_vm._v(" "+_vm._s(_vm.progressTime)+" ")]):_vm._e(),_c('div',{staticClass:"vac-text-timestamp"},[(_vm.message.edited && !_vm.message.deleted)?_c('div',{staticClass:"vac-icon-edited"},[_vm._t("pencil-icon",[_c('svg-icon',{attrs:{"name":"pencil"}})])],2):_vm._e(),_c('span',[_vm._v(_vm._s(_vm.message.timestamp))]),(_vm.isCheckmarkVisible)?_c('span',[_vm._t("checkmark-icon",[_c('svg-icon',{staticClass:"vac-icon-check",attrs:{"name":_vm.message.distributed ? 'double-checkmark' : 'checkmark',"param":_vm.message.seen ? 'seen' : ''}})],null,{ message: _vm.message })],2):_vm._e()]),_c('message-actions',{attrs:{"current-user-id":_vm.currentUserId,"message":_vm.message,"message-actions":_vm.messageActions,"room-footer-ref":_vm.roomFooterRef,"show-reaction-emojis":_vm.showReactionEmojis,"hide-options":_vm.hideOptions,"message-hover":_vm.messageHover,"hover-message-id":_vm.hoverMessageId,"hover-audio-progress":_vm.hoverAudioProgress},on:{"hide-options":function($event){return _vm.$emit('hide-options', false)},"update-message-hover":function($event){_vm.messageHover = $event},"update-options-opened":function($event){_vm.optionsOpened = $event},"update-emoji-opened":function($event){_vm.emojiOpened = $event},"message-action-handler":_vm.messageActionHandler,"send-message-reaction":function($event){return _vm.sendMessageReaction($event)}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1),_c('message-reactions',{attrs:{"current-user-id":_vm.currentUserId,"message":_vm.message,"emojis-list":_vm.emojisList},on:{"send-message-reaction":function($event){return _vm.sendMessageReaction($event)}}})],1)],null,{ message: _vm.message })],2)])}
var Messagevue_type_template_id_916bd03c_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/Message.vue?vue&type=template&id=916bd03c&
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.array.reduce.js
var es6_array_reduce = __webpack_require__("0cd8");
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageReply.vue?vue&type=template&id=e3400edc&
var MessageReplyvue_type_template_id_e3400edc_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-reply-message"},[_c('div',{staticClass:"vac-reply-username"},[_vm._v(" "+_vm._s(_vm.replyUsername)+" ")]),(_vm.isImage)?_c('div',{staticClass:"vac-image-reply-container"},[_c('div',{staticClass:"vac-message-image vac-message-image-reply",style:({
'background-image': ("url('" + (_vm.message.replyMessage.file.url) + "')")
})})]):(_vm.isVideo)?_c('div',{staticClass:"vac-video-reply-container"},[_c('video',{attrs:{"width":"100%","height":"100%","controls":""}},[_c('source',{attrs:{"src":_vm.message.replyMessage.file.url}})])]):(_vm.isAudio)?_c('audio-player',{attrs:{"src":_vm.message.replyMessage.file.url},on:{"update-progress-time":function($event){_vm.progressTime = $event},"hover-audio-progress":function($event){_vm.hoverAudioProgress = $event}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)}):_vm._e(),_c('div',{staticClass:"vac-reply-content"},[_c('format-message',{attrs:{"content":_vm.message.replyMessage.content,"users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions,"reply":true},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)],1)}
var MessageReplyvue_type_template_id_e3400edc_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReply.vue?vue&type=template&id=e3400edc&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/AudioPlayer.vue?vue&type=template&id=122955c2&
var AudioPlayervue_type_template_id_122955c2_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',[_c('div',{staticClass:"vac-audio-player"},[_c('div',{staticClass:"vac-svg-button",on:{"click":_vm.playback}},[(_vm.isPlaying)?_vm._t("audio-pause-icon",[_c('svg-icon',{attrs:{"name":"audio-pause"}})]):_vm._t("audio-play-icon",[_c('svg-icon',{attrs:{"name":"audio-play"}})])],2),_c('audio-control',{attrs:{"percentage":_vm.progress},on:{"change-linehead":_vm.onUpdateProgress,"hover-audio-progress":function($event){return _vm.$emit('hover-audio-progress', $event)}}}),_c('audio',{attrs:{"id":_vm.playerUniqId,"src":_vm.audioSource}})],1)])}
var AudioPlayervue_type_template_id_122955c2_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioPlayer.vue?vue&type=template&id=122955c2&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/AudioControl.vue?vue&type=template&id=57945bd0&
var AudioControlvue_type_template_id_57945bd0_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{ref:"progress",staticClass:"vac-player-bar",on:{"mousedown":_vm.onMouseDown,"mouseover":function($event){return _vm.$emit('hover-audio-progress', true)},"mouseout":function($event){return _vm.$emit('hover-audio-progress', false)}}},[_c('div',{staticClass:"vac-player-progress"},[_c('div',{staticClass:"vac-line-container"},[_c('div',{staticClass:"vac-line-progress",style:({ width: (_vm.percentage + "%") })}),_c('div',{staticClass:"vac-line-dot",class:{ 'vac-line-dot__active': _vm.isMouseDown },style:({ left: (_vm.percentage + "%") })})])])])}
var AudioControlvue_type_template_id_57945bd0_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioControl.vue?vue&type=template&id=57945bd0&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/AudioControl.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var AudioControlvue_type_script_lang_js_ = ({
props: {
percentage: {
type: Number,
"default": 0
}
},
data: function data() {
return {
isMouseDown: false
};
},
methods: {
onMouseDown: function onMouseDown(ev) {
this.isMouseDown = true;
var seekPos = this.calculateLineHeadPosition(ev, this.$refs['progress']);
this.$emit('change-linehead', seekPos);
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
},
onMouseUp: function onMouseUp(ev) {
this.isMouseDown = false;
document.removeEventListener('mouseup', this.onMouseUp);
document.removeEventListener('mousemove', this.onMouseMove);
var seekPos = this.calculateLineHeadPosition(ev, this.$refs['progress']);
this.$emit('change-linehead', seekPos);
},
onMouseMove: function onMouseMove(ev) {
var seekPos = this.calculateLineHeadPosition(ev, this.$refs['progress']);
this.$emit('change-linehead', seekPos);
},
calculateLineHeadPosition: function calculateLineHeadPosition(ev, element) {
var progressWidth = element.getBoundingClientRect().width;
var leftPosition = element.getBoundingClientRect().left;
var pos = (ev.clientX - leftPosition) / progressWidth;
pos = pos < 0 ? 0 : pos;
pos = pos > 1 ? 1 : pos;
return pos;
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioControl.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_AudioControlvue_type_script_lang_js_ = (AudioControlvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/AudioControl.vue?vue&type=style&index=0&lang=scss&
var AudioControlvue_type_style_index_0_lang_scss_ = __webpack_require__("589c");
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioControl.vue
/* normalize component */
var AudioControl_component = normalizeComponent(
Message_AudioControlvue_type_script_lang_js_,
AudioControlvue_type_template_id_57945bd0_render,
AudioControlvue_type_template_id_57945bd0_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var AudioControl = (AudioControl_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/AudioPlayer.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var AudioPlayervue_type_script_lang_js_ = ({
name: 'AudioPlayer',
components: {
SvgIcon: SvgIcon,
AudioControl: AudioControl
},
props: {
src: {
type: String,
"default": null
}
},
data: function data() {
return {
isPlaying: false,
duration: this.convertTimeMMSS(0),
playedTime: this.convertTimeMMSS(0),
progress: 0
};
},
computed: {
playerUniqId: function playerUniqId() {
return "audio-player".concat(this._uid);
},
audioSource: function audioSource() {
if (this.src) return this.src;
this.resetProgress();
return null;
}
},
mounted: function mounted() {
var _this = this;
this.player = document.getElementById(this.playerUniqId);
this.player.addEventListener('ended', function () {
_this.isPlaying = false;
});
this.player.addEventListener('loadeddata', function () {
_this.resetProgress();
_this.duration = _this.convertTimeMMSS(_this.player.duration);
_this.updateProgressTime();
});
this.player.addEventListener('timeupdate', this.onTimeUpdate);
},
methods: {
convertTimeMMSS: function convertTimeMMSS(seconds) {
return new Date(seconds * 1000).toISOString().substr(14, 5);
},
playback: function playback() {
var _this2 = this;
if (!this.audioSource) return;
if (this.isPlaying) this.player.pause();else setTimeout(function () {
return _this2.player.play();
});
this.isPlaying = !this.isPlaying;
},
resetProgress: function resetProgress() {
if (this.isPlaying) this.player.pause();
this.duration = this.convertTimeMMSS(0);
this.playedTime = this.convertTimeMMSS(0);
this.progress = 0;
this.isPlaying = false;
this.updateProgressTime();
},
onTimeUpdate: function onTimeUpdate() {
this.playedTime = this.convertTimeMMSS(this.player.currentTime);
this.progress = this.player.currentTime / this.player.duration * 100;
this.updateProgressTime();
},
onUpdateProgress: function onUpdateProgress(pos) {
if (pos) this.player.currentTime = pos * this.player.duration;
},
updateProgressTime: function updateProgressTime() {
this.$emit('update-progress-time', this.progress > 1 ? this.playedTime : this.duration);
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioPlayer.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_AudioPlayervue_type_script_lang_js_ = (AudioPlayervue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/AudioPlayer.vue?vue&type=style&index=0&lang=scss&
var AudioPlayervue_type_style_index_0_lang_scss_ = __webpack_require__("f43c");
// CONCATENATED MODULE: ./src/ChatWindow/Message/AudioPlayer.vue
/* normalize component */
var AudioPlayer_component = normalizeComponent(
Message_AudioPlayervue_type_script_lang_js_,
AudioPlayervue_type_template_id_122955c2_render,
AudioPlayervue_type_template_id_122955c2_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var AudioPlayer = (AudioPlayer_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageReply.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var MessageReplyvue_type_script_lang_js_require = __webpack_require__("bd43"),
MessageReplyvue_type_script_lang_js_isAudioFile = MessageReplyvue_type_script_lang_js_require.isAudioFile,
isImageFile = MessageReplyvue_type_script_lang_js_require.isImageFile,
isVideoFile = MessageReplyvue_type_script_lang_js_require.isVideoFile;
/* harmony default export */ var MessageReplyvue_type_script_lang_js_ = ({
name: 'MessageReply',
components: {
AudioPlayer: AudioPlayer,
FormatMessage: FormatMessage
},
props: {
message: {
type: Object,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
roomUsers: {
type: Array,
required: true
}
},
computed: {
replyUsername: function replyUsername() {
var senderId = this.message.replyMessage.senderId;
var replyUser = this.roomUsers.find(function (user) {
return user._id === senderId;
});
return replyUser ? replyUser.username : '';
},
isAudio: function isAudio() {
return MessageReplyvue_type_script_lang_js_isAudioFile(this.message.replyMessage.file);
},
isImage: function isImage() {
return isImageFile(this.message.replyMessage.file);
},
isVideo: function isVideo() {
return isVideoFile(this.message.replyMessage.file);
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReply.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_MessageReplyvue_type_script_lang_js_ = (MessageReplyvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/MessageReply.vue?vue&type=style&index=0&lang=scss&
var MessageReplyvue_type_style_index_0_lang_scss_ = __webpack_require__("a916");
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReply.vue
/* normalize component */
var MessageReply_component = normalizeComponent(
Message_MessageReplyvue_type_script_lang_js_,
MessageReplyvue_type_template_id_e3400edc_render,
MessageReplyvue_type_template_id_e3400edc_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var MessageReply = (MessageReply_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageImage.vue?vue&type=template&id=db8562da&
var MessageImagevue_type_template_id_db8562da_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{ref:"imageRef",staticClass:"vac-image-container"},[_c('loader',{style:({ top: ((_vm.imageResponsive.loaderTop) + "px") }),attrs:{"show":_vm.isImageLoading}}),_c('div',{staticClass:"vac-message-image",class:{
'vac-image-loading':
_vm.isImageLoading && _vm.message.senderId === _vm.currentUserId
},style:({
'background-image': ("url('" + _vm.imageBackground + "')"),
'max-height': ((_vm.imageResponsive.maxHeight) + "px")
})},[_c('transition',{attrs:{"name":"vac-fade-image"}},[(_vm.imageHover && !_vm.isImageLoading)?_c('div',{staticClass:"vac-image-buttons"},[_c('div',{staticClass:"vac-svg-button vac-button-view",on:{"click":function($event){$event.stopPropagation();return _vm.$emit('open-file', 'preview')}}},[_vm._t("eye-icon",[_c('svg-icon',{attrs:{"name":"eye"}})])],2),_c('div',{staticClass:"vac-svg-button vac-button-download",on:{"click":function($event){$event.stopPropagation();return _vm.$emit('open-file', 'download')}}},[_vm._t("document-icon",[_c('svg-icon',{attrs:{"name":"document"}})])],2)]):_vm._e()])],1),_c('format-message',{attrs:{"content":_vm.message.content,"users":_vm.roomUsers,"text-formatting":_vm.textFormatting,"link-options":_vm.linkOptions},on:{"open-user-tag":function($event){return _vm.$emit('open-user-tag')}},scopedSlots:_vm._u([_vm._l((_vm.$scopedSlots),function(i,name){return {key:name,fn:function(data){return [_vm._t(name,null,null,data)]}}})],null,true)})],1)}
var MessageImagevue_type_template_id_db8562da_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageImage.vue?vue&type=template&id=db8562da&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageImage.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var MessageImagevue_type_script_lang_js_require = __webpack_require__("bd43"),
MessageImagevue_type_script_lang_js_isImageFile = MessageImagevue_type_script_lang_js_require.isImageFile;
/* harmony default export */ var MessageImagevue_type_script_lang_js_ = ({
name: 'MessageImage',
components: {
SvgIcon: SvgIcon,
Loader: Loader,
FormatMessage: FormatMessage
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
message: {
type: Object,
required: true
},
roomUsers: {
type: Array,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
imageHover: {
type: Boolean,
required: true
}
},
data: function data() {
return {
imageLoading: false,
imageResponsive: ''
};
},
computed: {
isImageLoading: function isImageLoading() {
return this.message.file.url.indexOf('blob:http') !== -1 || this.imageLoading;
},
imageBackground: function imageBackground() {
return this.isImageLoading ? this.message.file.preview || this.message.file.url : this.message.file.url;
}
},
watch: {
message: {
immediate: true,
handler: function handler() {
this.checkImgLoad();
}
}
},
mounted: function mounted() {
this.imageResponsive = {
maxHeight: this.$refs.imageRef.clientWidth - 18,
loaderTop: this.$refs.imageRef.clientWidth / 2
};
},
methods: {
checkImgLoad: function checkImgLoad() {
var _this = this;
if (!MessageImagevue_type_script_lang_js_isImageFile(this.message.file)) return;
this.imageLoading = true;
var image = new Image();
image.src = this.message.file.url;
image.addEventListener('load', function () {
return _this.imageLoading = false;
});
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageImage.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_MessageImagevue_type_script_lang_js_ = (MessageImagevue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/MessageImage.vue?vue&type=style&index=0&lang=scss&
var MessageImagevue_type_style_index_0_lang_scss_ = __webpack_require__("c48f");
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageImage.vue
/* normalize component */
var MessageImage_component = normalizeComponent(
Message_MessageImagevue_type_script_lang_js_,
MessageImagevue_type_template_id_db8562da_render,
MessageImagevue_type_template_id_db8562da_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var MessageImage = (MessageImage_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageActions.vue?vue&type=template&id=e5cea174&
var MessageActionsvue_type_template_id_e5cea174_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vac-message-actions-wrapper"},[_c('div',{staticClass:"vac-options-container",class:{ 'vac-options-image': _vm.isImage && !_vm.message.replyMessage },style:({
display: _vm.hoverAudioProgress ? 'none' : 'initial',
width:
_vm.filteredMessageActions.length && _vm.showReactionEmojis ? '70px' : '45px'
})},[_c('transition-group',{attrs:{"name":"vac-slide-left"}},[(_vm.isMessageActions || _vm.isMessageReactions)?_c('div',{key:"1",staticClass:"vac-blur-container",class:{
'vac-options-me': _vm.message.senderId === _vm.currentUserId
}}):_vm._e(),(_vm.isMessageActions)?_c('div',{key:"2",ref:"actionIcon",staticClass:"vac-svg-button vac-message-options",on:{"click":_vm.openOptions}},[_vm._t("dropdown-icon",[_c('svg-icon',{attrs:{"name":"dropdown","param":"message"}})])],2):_vm._e(),(_vm.isMessageReactions)?_c('emoji-picker',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeEmoji),expression:"closeEmoji"}],key:"3",staticClass:"vac-message-emojis",style:({ right: _vm.isMessageActions ? '30px' : '5px' }),attrs:{"emoji-opened":_vm.emojiOpened,"emoji-reaction":true,"room-footer-ref":_vm.roomFooterRef,"position-right":_vm.message.senderId === _vm.currentUserId},on:{"add-emoji":_vm.sendMessageReaction,"open-emoji":_vm.openEmoji},scopedSlots:_vm._u([{key:"emoji-picker-icon",fn:function(){return [_vm._t("emoji-picker-reaction-icon")]},proxy:true}],null,true)}):_vm._e()],1)],1),(_vm.filteredMessageActions.length)?_c('transition',{attrs:{"name":_vm.message.senderId === _vm.currentUserId
? 'vac-slide-left'
: 'vac-slide-right'}},[(_vm.optionsOpened)?_c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeOptions),expression:"closeOptions"}],ref:"menuOptions",staticClass:"vac-menu-options",class:{
'vac-menu-left': _vm.message.senderId !== _vm.currentUserId
},style:({ top: (_vm.menuOptionsTop + "px") })},[_c('div',{staticClass:"vac-menu-list"},_vm._l((_vm.filteredMessageActions),function(action){return _c('div',{key:action.name},[_c('div',{staticClass:"vac-menu-item",on:{"click":function($event){return _vm.messageActionHandler(action)}}},[_vm._v(" "+_vm._s(action.title)+" ")])])}),0)]):_vm._e()]):_vm._e()],1)}
var MessageActionsvue_type_template_id_e5cea174_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageActions.vue?vue&type=template&id=e5cea174&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageActions.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var MessageActionsvue_type_script_lang_js_require = __webpack_require__("bd43"),
MessageActionsvue_type_script_lang_js_isImageFile = MessageActionsvue_type_script_lang_js_require.isImageFile;
/* harmony default export */ var MessageActionsvue_type_script_lang_js_ = ({
name: 'MessageActions',
components: {
SvgIcon: SvgIcon,
EmojiPicker: EmojiPicker
},
directives: {
clickOutside: v_click_outside_umd_default.a.directive
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
message: {
type: Object,
required: true
},
messageActions: {
type: Array,
required: true
},
roomFooterRef: {
type: HTMLDivElement,
"default": null
},
showReactionEmojis: {
type: Boolean,
required: true
},
hideOptions: {
type: Boolean,
required: true
},
messageHover: {
type: Boolean,
required: true
},
hoverMessageId: {
type: [String, Number],
"default": null
},
hoverAudioProgress: {
type: Boolean,
required: true
}
},
data: function data() {
return {
menuOptionsTop: 0,
optionsOpened: false,
optionsClosing: false,
emojiOpened: false
};
},
computed: {
isImage: function isImage() {
return MessageActionsvue_type_script_lang_js_isImageFile(this.message.file);
},
isMessageActions: function isMessageActions() {
return this.filteredMessageActions.length && this.messageHover && !this.message.deleted && !this.message.disableActions && !this.hoverAudioProgress;
},
isMessageReactions: function isMessageReactions() {
return this.showReactionEmojis && this.messageHover && !this.message.deleted && !this.message.disableReactions && !this.hoverAudioProgress;
},
filteredMessageActions: function filteredMessageActions() {
return this.message.senderId === this.currentUserId ? this.messageActions : this.messageActions.filter(function (message) {
return !message.onlyMe;
});
}
},
watch: {
emojiOpened: function emojiOpened(val) {
this.$emit('update-emoji-opened', val);
if (val) this.optionsOpened = false;
},
hideOptions: function hideOptions(val) {
if (val) {
this.closeEmoji();
this.closeOptions();
}
},
optionsOpened: function optionsOpened(val) {
this.$emit('update-options-opened', val);
}
},
methods: {
openOptions: function openOptions() {
var _this = this;
if (this.optionsClosing) return;
this.optionsOpened = !this.optionsOpened;
if (!this.optionsOpened) return;
this.$emit('hide-options', false);
setTimeout(function () {
if (!_this.roomFooterRef || !_this.$refs.menuOptions || !_this.$refs.actionIcon) {
return;
}
var menuOptionsTop = _this.$refs.menuOptions.getBoundingClientRect().height;
var actionIconTop = _this.$refs.actionIcon.getBoundingClientRect().top;
var roomFooterTop = _this.roomFooterRef.getBoundingClientRect().top;
var optionsTopPosition = roomFooterTop - actionIconTop > menuOptionsTop + 50;
if (optionsTopPosition) _this.menuOptionsTop = 30;else _this.menuOptionsTop = -menuOptionsTop;
});
},
closeOptions: function closeOptions() {
var _this2 = this;
this.optionsOpened = false;
this.optionsClosing = true;
this.updateMessageHover();
setTimeout(function () {
return _this2.optionsClosing = false;
}, 100);
},
openEmoji: function openEmoji() {
this.emojiOpened = !this.emojiOpened;
this.$emit('hide-options', false);
},
closeEmoji: function closeEmoji() {
this.emojiOpened = false;
this.updateMessageHover();
},
updateMessageHover: function updateMessageHover() {
if (this.hoverMessageId !== this.message._id) {
this.$emit('update-message-hover', false);
}
},
messageActionHandler: function messageActionHandler(action) {
this.closeOptions();
this.$emit('message-action-handler', action);
},
sendMessageReaction: function sendMessageReaction(emoji, reaction) {
this.$emit('send-message-reaction', {
emoji: emoji,
reaction: reaction
});
this.closeEmoji();
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageActions.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_MessageActionsvue_type_script_lang_js_ = (MessageActionsvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/MessageActions.vue?vue&type=style&index=0&lang=scss&
var MessageActionsvue_type_style_index_0_lang_scss_ = __webpack_require__("7cec");
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageActions.vue
/* normalize component */
var MessageActions_component = normalizeComponent(
Message_MessageActionsvue_type_script_lang_js_,
MessageActionsvue_type_template_id_e5cea174_render,
MessageActionsvue_type_template_id_e5cea174_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var MessageActions = (MessageActions_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"710e1ed1-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageReactions.vue?vue&type=template&id=87a49e5e&
var MessageReactionsvue_type_template_id_87a49e5e_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (!_vm.message.deleted)?_c('transition-group',{attrs:{"name":"vac-slide-left"}},_vm._l((_vm.message.reactions),function(reaction,key){return _c('button',{directives:[{name:"show",rawName:"v-show",value:(reaction.length),expression:"reaction.length"}],key:key + 0,staticClass:"vac-button-reaction",class:{
'vac-reaction-me': reaction.indexOf(_vm.currentUserId) !== -1
},style:({
float: _vm.message.senderId === _vm.currentUserId ? 'right' : 'left'
}),on:{"click":function($event){return _vm.sendMessageReaction({ name: key }, reaction)}}},[_vm._v(" "+_vm._s(_vm.getEmojiByName(key))),_c('span',[_vm._v(_vm._s(reaction.length))])])}),0):_vm._e()}
var MessageReactionsvue_type_template_id_87a49e5e_staticRenderFns = []
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReactions.vue?vue&type=template&id=87a49e5e&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/MessageReactions.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var MessageReactionsvue_type_script_lang_js_ = ({
name: 'MessageReactions',
props: {
currentUserId: {
type: [String, Number],
required: true
},
message: {
type: Object,
required: true
},
emojisList: {
type: Object,
required: true
}
},
methods: {
getEmojiByName: function getEmojiByName(emojiName) {
return this.emojisList[emojiName];
},
sendMessageReaction: function sendMessageReaction(emoji, reaction) {
this.$emit('send-message-reaction', {
emoji: emoji,
reaction: reaction
});
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReactions.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_MessageReactionsvue_type_script_lang_js_ = (MessageReactionsvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/MessageReactions.vue?vue&type=style&index=0&lang=scss&
var MessageReactionsvue_type_style_index_0_lang_scss_ = __webpack_require__("e498");
// CONCATENATED MODULE: ./src/ChatWindow/Message/MessageReactions.vue
/* normalize component */
var MessageReactions_component = normalizeComponent(
Message_MessageReactionsvue_type_script_lang_js_,
MessageReactionsvue_type_template_id_87a49e5e_render,
MessageReactionsvue_type_template_id_87a49e5e_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var MessageReactions = (MessageReactions_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Message/Message.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var Messagevue_type_script_lang_js_require = __webpack_require__("4c1d"),
messagesValidation = Messagevue_type_script_lang_js_require.messagesValidation;
var _require2 = __webpack_require__("bd43"),
Messagevue_type_script_lang_js_isImageFile = _require2.isImageFile,
Messagevue_type_script_lang_js_isVideoFile = _require2.isVideoFile,
Messagevue_type_script_lang_js_isAudioFile = _require2.isAudioFile;
/* harmony default export */ var Messagevue_type_script_lang_js_ = ({
name: 'Message',
components: {
SvgIcon: SvgIcon,
FormatMessage: FormatMessage,
AudioPlayer: AudioPlayer,
MessageReply: MessageReply,
MessageImage: MessageImage,
MessageActions: MessageActions,
MessageReactions: MessageReactions
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
textMessages: {
type: Object,
required: true
},
index: {
type: Number,
required: true
},
message: {
type: Object,
required: true
},
messages: {
type: Array,
required: true
},
editedMessage: {
type: Object,
required: true
},
roomUsers: {
type: Array,
"default": function _default() {
return [];
}
},
messageActions: {
type: Array,
required: true
},
roomFooterRef: {
type: HTMLDivElement,
"default": null
},
newMessages: {
type: Array,
"default": function _default() {
return [];
}
},
showReactionEmojis: {
type: Boolean,
required: true
},
showNewMessagesDivider: {
type: Boolean,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
emojisList: {
type: Object,
required: true
},
hideOptions: {
type: Boolean,
required: true
}
},
data: function data() {
return {
hoverMessageId: null,
imageHover: false,
messageHover: false,
optionsOpened: false,
emojiOpened: false,
newMessage: {},
progressTime: '- : -',
hoverAudioProgress: false
};
},
computed: {
showDate: function showDate() {
return this.index > 0 && this.message.date !== this.messages[this.index - 1].date;
},
messageOffset: function messageOffset() {
return this.index > 0 && this.message.senderId !== this.messages[this.index - 1].senderId;
},
isMessageHover: function isMessageHover() {
return this.editedMessage._id === this.message._id || this.hoverMessageId === this.message._id;
},
isImage: function isImage() {
return Messagevue_type_script_lang_js_isImageFile(this.message.file);
},
isVideo: function isVideo() {
return Messagevue_type_script_lang_js_isVideoFile(this.message.file);
},
isAudio: function isAudio() {
return Messagevue_type_script_lang_js_isAudioFile(this.message.file);
},
isCheckmarkVisible: function isCheckmarkVisible() {
return this.message.senderId === this.currentUserId && !this.message.deleted && (this.message.saved || this.message.distributed || this.message.seen);
}
},
watch: {
newMessages: {
immediate: true,
handler: function handler(val) {
if (!val.length || !this.showNewMessagesDivider) {
return this.newMessage = {};
}
this.newMessage = val.reduce(function (res, obj) {
return obj.index < res.index ? obj : res;
});
}
}
},
mounted: function mounted() {
messagesValidation(this.message);
this.$emit('message-added', {
message: this.message,
index: this.index,
ref: this.$refs[this.message._id]
});
},
methods: {
onHoverMessage: function onHoverMessage() {
this.imageHover = true;
this.messageHover = true;
if (this.canEditMessage()) this.hoverMessageId = this.message._id;
},
canEditMessage: function canEditMessage() {
return !this.message.deleted;
},
onLeaveMessage: function onLeaveMessage() {
this.imageHover = false;
if (!this.optionsOpened && !this.emojiOpened) this.messageHover = false;
this.hoverMessageId = null;
},
openFile: function openFile(action) {
this.$emit('open-file', {
message: this.message,
action: action
});
},
openUserTag: function openUserTag(user) {
this.$emit('open-user-tag', {
user: user
});
},
messageActionHandler: function messageActionHandler(action) {
var _this = this;
this.messageHover = false;
this.hoverMessageId = null;
setTimeout(function () {
_this.$emit('message-action-handler', {
action: action,
message: _this.message
});
}, 300);
},
sendMessageReaction: function sendMessageReaction(_ref) {
var emoji = _ref.emoji,
reaction = _ref.reaction;
this.$emit('send-message-reaction', {
messageId: this.message._id,
reaction: emoji,
remove: reaction && reaction.indexOf(this.currentUserId) !== -1
});
this.messageHover = false;
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Message/Message.vue?vue&type=script&lang=js&
/* harmony default export */ var Message_Messagevue_type_script_lang_js_ = (Messagevue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Message/Message.vue?vue&type=style&index=0&lang=scss&
var Messagevue_type_style_index_0_lang_scss_ = __webpack_require__("2a92");
// CONCATENATED MODULE: ./src/ChatWindow/Message/Message.vue
/* normalize component */
var Message_component = normalizeComponent(
Message_Messagevue_type_script_lang_js_,
Messagevue_type_template_id_916bd03c_render,
Messagevue_type_template_id_916bd03c_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var Message = (Message_component.exports);
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.function.bind.js
var es6_function_bind = __webpack_require__("d92a");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.typed.int8-array.js
var es6_typed_int8_array = __webpack_require__("b05c");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.date.now.js
var es6_date_now = __webpack_require__("78ce");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.typed.float32-array.js
var es6_typed_float32_array = __webpack_require__("63d9");
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.typed.int16-array.js
var es6_typed_int16_array = __webpack_require__("15ac");
// CONCATENATED MODULE: ./src/utils/mp3-encoder.js
// Credits to https://github.com/grishkovelli/vue-audio-recorder
var lamejs;
try {
lamejs = __webpack_require__("db18");
} catch (_) {
lamejs = {
missing: true
};
}
var _lamejs = lamejs,
Mp3Encoder = _lamejs.Mp3Encoder;
var mp3_encoder_default = /*#__PURE__*/function () {
function _default(config) {
_classCallCheck(this, _default);
if (lamejs.missing) {
throw new Error('You must add lamejs in your dependencies to use the audio recorder. Please run "npm install lamejs --save"');
}
this.bitRate = config.bitRate;
this.sampleRate = config.sampleRate;
this.dataBuffer = [];
this.encoder = new Mp3Encoder(1, this.sampleRate, this.bitRate);
}
_createClass(_default, [{
key: "encode",
value: function encode(arrayBuffer) {
var maxSamples = 1152;
var samples = this._convertBuffer(arrayBuffer);
var remaining = samples.length;
for (var i = 0; remaining >= 0; i += maxSamples) {
var left = samples.subarray(i, i + maxSamples);
var buffer = this.encoder.encodeBuffer(left);
this.dataBuffer.push(new Int8Array(buffer));
remaining -= maxSamples;
}
}
}, {
key: "finish",
value: function finish() {
this.dataBuffer.push(this.encoder.flush());
var blob = new Blob(this.dataBuffer, {
type: 'audio/mp3'
});
this.dataBuffer = [];
return {
id: Date.now(),
blob: blob,
url: URL.createObjectURL(blob)
};
}
}, {
key: "_floatTo16BitPCM",
value: function _floatTo16BitPCM(input, output) {
for (var i = 0; i < input.length; i++) {
var s = Math.max(-1, Math.min(1, input[i]));
output[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
}
}, {
key: "_convertBuffer",
value: function _convertBuffer(arrayBuffer) {
var data = new Float32Array(arrayBuffer);
var out = new Int16Array(arrayBuffer.length);
this._floatTo16BitPCM(data, out);
return out;
}
}]);
return _default;
}();
// CONCATENATED MODULE: ./src/utils/recorder.js
// Credits to https://github.com/grishkovelli/vue-audio-recorder
var recorder_default = /*#__PURE__*/function () {
function _default() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, _default);
this.beforeRecording = options.beforeRecording;
this.pauseRecording = options.pauseRecording;
this.afterRecording = options.afterRecording;
this.micFailed = options.micFailed;
this.encoderOptions = {
bitRate: 128,
sampleRate: 44100
};
this.bufferSize = 4096;
this.records = [];
this.isPause = false;
this.isRecording = false;
this.duration = 0;
this.volume = 0;
this._duration = 0;
}
_createClass(_default, [{
key: "start",
value: function start() {
var constraints = {
video: false,
audio: {
channelCount: 1,
echoCancellation: false
}
};
this.beforeRecording && this.beforeRecording('start recording');
navigator.mediaDevices.getUserMedia(constraints).then(this._micCaptured.bind(this))["catch"](this._micError.bind(this));
this.isPause = false;
this.isRecording = true;
if (!this.lameEncoder) {
this.lameEncoder = new mp3_encoder_default(this.encoderOptions);
}
}
}, {
key: "stop",
value: function stop() {
this.stream.getTracks().forEach(function (track) {
return track.stop();
});
this.input.disconnect();
this.processor.disconnect();
this.context.close();
var record = null;
record = this.lameEncoder.finish();
record.duration = this.duration;
this.records.push(record);
this._duration = 0;
this.duration = 0;
this.isPause = false;
this.isRecording = false;
this.afterRecording && this.afterRecording(record);
}
}, {
key: "pause",
value: function pause() {
this.stream.getTracks().forEach(function (track) {
return track.stop();
});
this.input.disconnect();
this.processor.disconnect();
this._duration = this.duration;
this.isPause = true;
this.pauseRecording && this.pauseRecording('pause recording');
}
}, {
key: "_micCaptured",
value: function _micCaptured(stream) {
var _this = this;
this.context = new (window.AudioContext || window.webkitAudioContext)();
this.duration = this._duration;
this.input = this.context.createMediaStreamSource(stream);
this.processor = this.context.createScriptProcessor(this.bufferSize, 1, 1);
this.stream = stream;
this.processor.onaudioprocess = function (ev) {
var sample = ev.inputBuffer.getChannelData(0);
var sum = 0.0;
if (_this.lameEncoder) {
_this.lameEncoder.encode(sample);
}
for (var i = 0; i < sample.length; ++i) {
sum += sample[i] * sample[i];
}
_this.duration = parseFloat(_this._duration) + parseFloat(_this.context.currentTime.toFixed(2));
_this.volume = Math.sqrt(sum / sample.length).toFixed(2);
};
this.input.connect(this.processor);
this.processor.connect(this.context.destination);
}
}, {
key: "_micError",
value: function _micError(error) {
this.micFailed && this.micFailed(error);
}
}]);
return _default;
}();
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/Room/Room.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var Roomvue_type_script_lang_js_require = __webpack_require__("1a98"),
detectMobile = Roomvue_type_script_lang_js_require.detectMobile,
iOSDevice = Roomvue_type_script_lang_js_require.iOSDevice;
var Roomvue_type_script_lang_js_require2 = __webpack_require__("bd43"),
Roomvue_type_script_lang_js_isImageFile = Roomvue_type_script_lang_js_require2.isImageFile,
Roomvue_type_script_lang_js_isVideoFile = Roomvue_type_script_lang_js_require2.isVideoFile;
/* harmony default export */ var Roomvue_type_script_lang_js_ = ({
name: 'Room',
components: {
InfiniteLoading: vue_infinite_loading_default.a,
Loader: Loader,
SvgIcon: SvgIcon,
EmojiPicker: EmojiPicker,
RoomHeader: RoomHeader,
RoomMessageReply: RoomMessageReply,
RoomUsersTag: RoomUsersTag,
RoomEmojis: RoomEmojis,
Message: Message
},
directives: {
clickOutside: v_click_outside_umd_default.a.directive
},
props: {
currentUserId: {
type: [String, Number],
required: true
},
textMessages: {
type: Object,
required: true
},
singleRoom: {
type: Boolean,
required: true
},
showRoomsList: {
type: Boolean,
required: true
},
isMobile: {
type: Boolean,
required: true
},
rooms: {
type: Array,
required: true
},
roomId: {
type: [String, Number],
required: true
},
loadFirstRoom: {
type: Boolean,
required: true
},
messages: {
type: Array,
required: true
},
roomMessage: {
type: String,
"default": null
},
messagesLoaded: {
type: Boolean,
required: true
},
menuActions: {
type: Array,
required: true
},
messageActions: {
type: Array,
required: true
},
showSendIcon: {
type: Boolean,
required: true
},
showFiles: {
type: Boolean,
required: true
},
showAudio: {
type: Boolean,
required: true
},
showEmojis: {
type: Boolean,
required: true
},
showReactionEmojis: {
type: Boolean,
required: true
},
showNewMessagesDivider: {
type: Boolean,
required: true
},
showFooter: {
type: Boolean,
required: true
},
acceptedFiles: {
type: String,
required: true
},
textFormatting: {
type: Boolean,
required: true
},
linkOptions: {
type: Object,
required: true
},
loadingRooms: {
type: Boolean,
required: true
},
roomInfo: {
type: Function,
"default": null
},
textareaAction: {
type: Function,
"default": null
}
},
data: function data() {
return {
message: '',
editedMessage: {},
messageReply: null,
infiniteState: null,
loadingMessages: false,
loadingMoreMessages: false,
file: null,
imageFile: null,
videoFile: null,
mediaDimensions: null,
fileDialog: false,
emojiOpened: false,
hideOptions: true,
scrollIcon: false,
scrollMessagesCount: 0,
newMessages: [],
keepKeyboardOpen: false,
filteredEmojis: [],
filteredUsersTag: [],
selectedUsersTag: [],
textareaCursorPosition: null,
cursorRangePosition: null,
recorder: this.initRecorder(),
isRecording: false,
format: 'mp3'
};
},
computed: {
emojisList: function emojisList() {
var emojisTable = Object.keys(emojis).map(function (key) {
return emojis[key];
});
return Object.assign.apply(Object, [{}].concat(_toConsumableArray(emojisTable)));
},
room: function room() {
var _this = this;
return this.rooms.find(function (room) {
return room.roomId === _this.roomId;
}) || {};
},
showNoMessages: function showNoMessages() {
return this.room.roomId && !this.messages.length && !this.loadingMessages && !this.loadingRooms;
},
showNoRoom: function showNoRoom() {
var noRoomSelected = !this.rooms.length && !this.loadingRooms || !this.room.roomId && !this.loadFirstRoom;
if (noRoomSelected) {
this.loadingMessages = false;
/* eslint-disable-line vue/no-side-effects-in-computed-properties */
}
return noRoomSelected;
},
showMessagesStarted: function showMessagesStarted() {
return this.messages.length && this.messagesLoaded;
},
isMessageEmpty: function isMessageEmpty() {
return !this.file && !this.message.trim();
},
recordedTime: function recordedTime() {
return new Date(this.recorder.duration * 1000).toISOString().substr(14, 5);
}
},
watch: {
loadingMessages: function loadingMessages(val) {
if (val) {
this.infiniteState = null;
} else {
if (this.infiniteState) this.infiniteState.loaded();
this.focusTextarea(true);
}
},
room: {
immediate: true,
handler: function handler(newVal, oldVal) {
if (newVal.roomId && (!oldVal || newVal.roomId !== oldVal.roomId)) {
this.onRoomChanged();
}
}
},
roomMessage: {
immediate: true,
handler: function handler(val) {
if (val) this.message = this.roomMessage;
}
},
messages: function messages(newVal, oldVal) {
var _this2 = this;
newVal.forEach(function (message, i) {
if (_this2.showNewMessagesDivider && !message.seen && message.senderId !== _this2.currentUserId) {
_this2.newMessages.push({
_id: message._id,
index: i
});
}
});
if ((oldVal === null || oldVal === void 0 ? void 0 : oldVal.length) === (newVal === null || newVal === void 0 ? void 0 : newVal.length) - 1) {
this.newMessages = [];
}
if (this.infiniteState) {
this.infiniteState.loaded();
}
setTimeout(function () {
return _this2.loadingMoreMessages = false;
});
},
messagesLoaded: function messagesLoaded(val) {
if (val) this.loadingMessages = false;
if (this.infiniteState) this.infiniteState.complete();
}
},
mounted: function mounted() {
var _this3 = this;
this.newMessages = [];
var isMobile = detectMobile();
window.addEventListener('keyup', function (e) {
if (e.key === 'Enter' && !e.shiftKey && !_this3.fileDialog) {
if (isMobile) {
_this3.message = _this3.message + '\n';
setTimeout(function () {
return _this3.onChangeInput();
});
} else {
_this3.sendMessage();
}
}
_this3.updateFooterList('@');
_this3.updateFooterList(':');
});
this.$refs['roomTextarea'].addEventListener('click', function () {
if (isMobile) _this3.keepKeyboardOpen = true;
_this3.updateFooterList('@');
_this3.updateFooterList(':');
});
this.$refs['roomTextarea'].addEventListener('blur', function () {
_this3.resetFooterList();
if (isMobile) setTimeout(function () {
return _this3.keepKeyboardOpen = false;
});
});
},
beforeDestroy: function beforeDestroy() {
this.stopRecorder();
},
methods: {
onRoomChanged: function onRoomChanged() {
var _this4 = this;
this.loadingMessages = true;
this.scrollIcon = false;
this.scrollMessagesCount = 0;
this.resetMessage(true, null, true);
if (this.roomMessage) {
this.message = this.roomMessage;
setTimeout(function () {
return _this4.onChangeInput();
});
}
if (!this.messages.length && this.messagesLoaded) {
this.loadingMessages = false;
}
var unwatch = this.$watch(function () {
return _this4.messages;
}, function (val) {
if (!val || !val.length) return;
var element = _this4.$refs.scrollContainer;
if (!element) return;
unwatch();
setTimeout(function () {
element.scrollTo({
top: element.scrollHeight
});
_this4.loadingMessages = false;
});
});
},
onMessageAdded: function onMessageAdded(_ref) {
var _this5 = this;
var message = _ref.message,
index = _ref.index,
ref = _ref.ref;
if (index !== this.messages.length - 1) return;
var autoScrollOffset = ref.offsetHeight + 60;
setTimeout(function () {
if (_this5.getBottomScroll(_this5.$refs.scrollContainer) < autoScrollOffset) {
_this5.scrollToBottom();
} else {
if (message.senderId === _this5.currentUserId) {
_this5.scrollToBottom();
} else {
_this5.scrollIcon = true;
_this5.scrollMessagesCount++;
}
}
});
},
onContainerScroll: function onContainerScroll(e) {
this.hideOptions = true;
if (!e.target) return;
var bottomScroll = this.getBottomScroll(e.target);
if (bottomScroll < 60) this.scrollMessagesCount = 0;
this.scrollIcon = bottomScroll > 500 || this.scrollMessagesCount;
},
updateFooterList: function updateFooterList(tagChar) {
if (!this.$refs['roomTextarea']) return;
if (tagChar === '@' && (!this.room.users || this.room.users.length <= 2)) {
return;
}
if (this.textareaCursorPosition === this.$refs['roomTextarea'].selectionStart) {
return;
}
this.textareaCursorPosition = this.$refs['roomTextarea'].selectionStart;
var position = this.textareaCursorPosition;
while (position > 0 && this.message.charAt(position - 1) !== tagChar && this.message.charAt(position - 1) !== ' ') {
position--;
}
var beforeTag = this.message.charAt(position - 2);
var notLetterNumber = !beforeTag.match(/^[0-9a-zA-Z]+$/);
if (this.message.charAt(position - 1) === tagChar && (!beforeTag || beforeTag === ' ' || notLetterNumber)) {
var query = this.message.substring(position, this.textareaCursorPosition);
if (tagChar === ':') {
this.updateEmojis(query);
} else if (tagChar === '@') {
this.updateShowUsersTag(query);
}
} else {
this.resetFooterList();
}
},
getCharPosition: function getCharPosition(tagChar) {
var cursorPosition = this.$refs['roomTextarea'].selectionStart;
var position = cursorPosition;
while (position > 0 && this.message.charAt(position - 1) !== tagChar) {
position--;
}
var endPosition = position;
while (this.message.charAt(endPosition) && this.message.charAt(endPosition).trim()) {
endPosition++;
}
return {
position: position,
endPosition: endPosition
};
},
updateEmojis: function updateEmojis(query) {
var _this6 = this;
if (!query) return;
var emojisListKeys = Object.keys(this.emojisList);
var matchingKeys = emojisListKeys.filter(function (key) {
return key.startsWith(query);
});
this.filteredEmojis = matchingKeys.map(function (key) {
return _this6.emojisList[key];
});
},
selectEmoji: function selectEmoji(emoji) {
var _this$getCharPosition = this.getCharPosition(':'),
position = _this$getCharPosition.position,
endPosition = _this$getCharPosition.endPosition;
this.message = this.message.substr(0, position - 1) + emoji + this.message.substr(endPosition, this.message.length - 1);
this.cursorRangePosition = position;
this.focusTextarea();
},
updateShowUsersTag: function updateShowUsersTag(query) {
var _this7 = this;
this.filteredUsersTag = filter_items(this.room.users, 'username', query, true).filter(function (user) {
return user._id !== _this7.currentUserId;
});
},
selectUserTag: function selectUserTag(user) {
var _this$getCharPosition2 = this.getCharPosition('@'),
position = _this$getCharPosition2.position,
endPosition = _this$getCharPosition2.endPosition;
var space = this.message.substr(endPosition, endPosition).length ? '' : ' ';
this.message = this.message.substr(0, position) + user.username + space + this.message.substr(endPosition, this.message.length - 1);
this.selectedUsersTag = [].concat(_toConsumableArray(this.selectedUsersTag), [_objectSpread2({}, user)]);
this.cursorRangePosition = position + user.username.length + space.length + 1;
this.focusTextarea();
},
resetFooterList: function resetFooterList() {
this.filteredEmojis = [];
this.filteredUsersTag = [];
this.textareaCursorPosition = null;
},
onMediaLoad: function onMediaLoad() {
var height = this.$refs.mediaFile.clientHeight;
if (height < 30) height = 30;
this.mediaDimensions = {
height: this.$refs.mediaFile.clientHeight - 10,
width: this.$refs.mediaFile.clientWidth + 26
};
},
escapeTextarea: function escapeTextarea() {
if (this.filteredEmojis.length) this.filteredEmojis = [];else if (this.filteredUsersTag.length) this.filteredUsersTag = [];else this.resetMessage();
},
resetMessage: function resetMessage() {
var _this8 = this;
var disableMobileFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var editFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var initRoom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!initRoom) {
this.$emit('typing-message', null);
}
if (editFile) {
this.file = null;
this.message = '';
this.preventKeyboardFromClosing();
setTimeout(function () {
return _this8.focusTextarea(disableMobileFocus);
});
return;
}
this.selectedUsersTag = [];
this.resetFooterList();
this.resetTextareaSize();
this.message = '';
this.editedMessage = {};
this.messageReply = null;
this.file = null;
this.mediaDimensions = null;
this.imageFile = null;
this.videoFile = null;
this.emojiOpened = false;
this.preventKeyboardFromClosing();
setTimeout(function () {
return _this8.focusTextarea(disableMobileFocus);
});
},
resetMediaFile: function resetMediaFile() {
this.mediaDimensions = null;
this.imageFile = null;
this.videoFile = null;
this.editedMessage.file = null;
this.file = null;
this.focusTextarea();
},
resetTextareaSize: function resetTextareaSize() {
if (!this.$refs['roomTextarea']) return;
this.$refs['roomTextarea'].style.height = '20px';
},
focusTextarea: function focusTextarea(disableMobileFocus) {
var _this9 = this;
if (detectMobile() && disableMobileFocus) return;
if (!this.$refs['roomTextarea']) return;
this.$refs['roomTextarea'].focus();
if (this.cursorRangePosition) {
setTimeout(function () {
_this9.$refs['roomTextarea'].setSelectionRange(_this9.cursorRangePosition, _this9.cursorRangePosition);
_this9.cursorRangePosition = null;
});
}
},
preventKeyboardFromClosing: function preventKeyboardFromClosing() {
if (this.keepKeyboardOpen) this.$refs['roomTextarea'].focus();
},
sendMessage: function sendMessage() {
var message = this.message.trim();
if (!this.file && !message) return;
this.selectedUsersTag.forEach(function (user) {
message = message.replace("@".concat(user.username), "<usertag>".concat(user._id, "</usertag>"));
});
if (this.editedMessage._id) {
if (this.editedMessage.content !== message || this.file) {
this.$emit('edit-message', {
messageId: this.editedMessage._id,
newContent: message,
file: this.file,
replyMessage: this.messageReply,
usersTag: this.selectedUsersTag
});
}
} else {
this.$emit('send-message', {
content: message,
file: this.file,
replyMessage: this.messageReply,
usersTag: this.selectedUsersTag
});
}
this.resetMessage(true);
},
loadMoreMessages: function loadMoreMessages(infiniteState) {
var _this10 = this;
if (this.loadingMessages) {
this.infiniteState = infiniteState;
return;
}
setTimeout(function () {
if (_this10.loadingMoreMessages) return;
if (_this10.messagesLoaded || !_this10.room.roomId) {
return infiniteState.complete();
}
_this10.infiniteState = infiniteState;
_this10.$emit('fetch-messages');
_this10.loadingMoreMessages = true;
}, // prevent scroll bouncing issue on iOS devices
iOSDevice() ? 500 : 0);
},
messageActionHandler: function messageActionHandler(_ref2) {
var action = _ref2.action,
message = _ref2.message;
switch (action.name) {
case 'replyMessage':
return this.replyMessage(message);
case 'editMessage':
return this.editMessage(message);
case 'deleteMessage':
return this.$emit('delete-message', message);
default:
return this.$emit('message-action-handler', {
action: action,
message: message
});
}
},
sendMessageReaction: function sendMessageReaction(messageReaction) {
this.$emit('send-message-reaction', messageReaction);
},
replyMessage: function replyMessage(message) {
this.messageReply = message;
this.focusTextarea();
},
editMessage: function editMessage(message) {
var _this11 = this;
this.resetMessage();
this.editedMessage = _objectSpread2({}, message);
this.file = message.file;
if (Roomvue_type_script_lang_js_isImageFile(this.file)) {
this.imageFile = message.file.url;
setTimeout(function () {
return _this11.onMediaLoad();
});
} else if (Roomvue_type_script_lang_js_isVideoFile(this.file)) {
this.videoFile = message.file.url;
setTimeout(function () {
return _this11.onMediaLoad();
}, 50);
}
this.message = message.content;
},
getBottomScroll: function getBottomScroll(element) {
var scrollHeight = element.scrollHeight,
clientHeight = element.clientHeight,
scrollTop = element.scrollTop;
return scrollHeight - clientHeight - scrollTop;
},
scrollToBottom: function scrollToBottom() {
var _this12 = this;
setTimeout(function () {
var element = _this12.$refs.scrollContainer;
element.classList.add('vac-scroll-smooth');
element.scrollTo({
top: element.scrollHeight,
behavior: 'smooth'
});
setTimeout(function () {
return element.classList.remove('vac-scroll-smooth');
});
}, 50);
},
onChangeInput: function onChangeInput() {
this.keepKeyboardOpen = true;
this.resizeTextarea();
this.$emit('typing-message', this.message);
},
resizeTextarea: function resizeTextarea() {
var el = this.$refs['roomTextarea'];
if (!el) return;
var padding = window.getComputedStyle(el, null).getPropertyValue('padding-top').replace('px', '');
el.style.height = 0;
el.style.height = el.scrollHeight - padding * 2 + 'px';
},
addEmoji: function addEmoji(emoji) {
this.message += emoji.icon;
this.focusTextarea(true);
},
launchFilePicker: function launchFilePicker() {
this.$refs.file.value = '';
this.$refs.file.click();
},
onFileChange: function onFileChange(files) {
var _this13 = this;
return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
var file, fileURL, blobFile, typeIndex;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_this13.fileDialog = true;
_this13.resetMediaFile();
file = files[0];
fileURL = URL.createObjectURL(file);
_context.next = 6;
return fetch(fileURL).then(function (res) {
return res.blob();
});
case 6:
blobFile = _context.sent;
typeIndex = file.name.lastIndexOf('.');
_this13.file = {
blob: blobFile,
name: file.name.substring(0, typeIndex),
size: file.size,
type: file.type,
extension: file.name.substring(typeIndex + 1),
localUrl: fileURL
};
if (Roomvue_type_script_lang_js_isImageFile(_this13.file)) {
_this13.imageFile = fileURL;
} else if (Roomvue_type_script_lang_js_isVideoFile(_this13.file)) {
_this13.videoFile = fileURL;
setTimeout(function () {
return _this13.onMediaLoad();
}, 50);
} else {
_this13.message = file.name;
}
setTimeout(function () {
return _this13.fileDialog = false;
}, 500);
case 11:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
initRecorder: function initRecorder() {
this.isRecording = false;
return new recorder_default({
beforeRecording: null,
afterRecording: null,
pauseRecording: null,
micFailed: this.micFailed
});
},
micFailed: function micFailed() {
this.isRecording = false;
this.recorder = this.initRecorder();
},
toggleRecorder: function toggleRecorder(recording) {
var _this14 = this;
this.isRecording = recording;
if (!this.recorder.isRecording) {
setTimeout(function () {
return _this14.recorder.start();
}, 200);
} else {
try {
this.recorder.stop();
var record = this.recorder.records[0];
this.file = {
blob: record.blob,
name: "audio.".concat(this.format),
size: record.blob.size,
duration: record.duration,
type: record.blob.type,
audio: true,
localUrl: URL.createObjectURL(record.blob)
};
this.recorder = this.initRecorder();
this.sendMessage();
} catch (_unused) {
setTimeout(function () {
return _this14.stopRecorder();
}, 100);
}
}
},
stopRecorder: function stopRecorder() {
var _this15 = this;
if (this.recorder.isRecording) {
try {
this.recorder.stop();
this.recorder = this.initRecorder();
} catch (_unused2) {
setTimeout(function () {
return _this15.stopRecorder();
}, 100);
}
}
},
openFile: function openFile(_ref3) {
var message = _ref3.message,
action = _ref3.action;
this.$emit('open-file', {
message: message,
action: action
});
},
openUserTag: function openUserTag(user) {
this.$emit('open-user-tag', user);
},
textareaActionHandler: function textareaActionHandler() {
this.$emit('textarea-action-handler', this.message);
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/Room/Room.vue?vue&type=script&lang=js&
/* harmony default export */ var Room_Roomvue_type_script_lang_js_ = (Roomvue_type_script_lang_js_);
// EXTERNAL MODULE: ./src/ChatWindow/Room/Room.vue?vue&type=style&index=0&lang=scss&
var Roomvue_type_style_index_0_lang_scss_ = __webpack_require__("a6d4");
// CONCATENATED MODULE: ./src/ChatWindow/Room/Room.vue
/* normalize component */
var Room_component = normalizeComponent(
Room_Roomvue_type_script_lang_js_,
Roomvue_type_template_id_1a1a6e46_render,
Roomvue_type_template_id_1a1a6e46_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var Room = (Room_component.exports);
// CONCATENATED MODULE: ./src/locales/index.js
/* harmony default export */ var locales = ({
ROOMS_EMPTY: 'No rooms',
ROOM_EMPTY: 'No room selected',
NEW_MESSAGES: 'New Messages',
MESSAGE_DELETED: 'This message was deleted',
MESSAGES_EMPTY: 'No messages',
CONVERSATION_STARTED: 'Conversation started on:',
TYPE_MESSAGE: 'Type message',
SEARCH: 'Search',
IS_ONLINE: 'is online',
LAST_SEEN: 'last seen ',
IS_TYPING: 'is writing...'
});
// EXTERNAL MODULE: ./node_modules/core-js/modules/es6.regexp.search.js
var es6_regexp_search = __webpack_require__("386d");
// CONCATENATED MODULE: ./src/themes/index.js
var defaultThemeStyles = {
light: {
general: {
color: '#0a0a0a',
backgroundInput: '#fff',
colorPlaceholder: '#9ca6af',
colorCaret: '#1976d2',
colorSpinner: '#333',
borderStyle: '1px solid #e1e4e8',
backgroundScrollIcon: '#fff'
},
container: {
border: 'none',
borderRadius: '4px',
boxShadow: '0px 1px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12)'
},
header: {
background: '#fff',
colorRoomName: '#0a0a0a',
colorRoomInfo: '#9ca6af'
},
footer: {
background: '#f8f9fa',
borderStyleInput: '1px solid #e1e4e8',
borderInputSelected: '#1976d2',
backgroundReply: '#e5e5e6',
backgroundTagActive: '#e5e5e6'
},
content: {
background: '#f8f9fa'
},
sidemenu: {
background: '#fff',
backgroundHover: '#f6f6f6',
backgroundActive: '#e5effa',
colorActive: '#1976d2',
borderColorSearch: '#e1e5e8'
},
dropdown: {
background: '#fff',
backgroundHover: '#f6f6f6'
},
message: {
background: '#fff',
backgroundMe: '#ccf2cf',
color: '#0a0a0a',
colorStarted: '#9ca6af',
backgroundDeleted: '#dadfe2',
colorDeleted: '#757e85',
colorUsername: '#9ca6af',
colorTimestamp: '#828c94',
backgroundDate: '#e5effa',
colorDate: '#505a62',
backgroundSystem: '#e5effa',
colorSystem: '#505a62',
backgroundMedia: 'rgba(0, 0, 0, 0.15)',
backgroundReply: 'rgba(0, 0, 0, 0.08)',
colorReplyUsername: '#0a0a0a',
colorReply: '#6e6e6e',
colorTag: '#0d579c',
backgroundImage: '#ddd',
colorNewMessages: '#1976d2',
backgroundScrollCounter: '#0696c7',
colorScrollCounter: '#fff',
backgroundReaction: '#eee',
borderStyleReaction: '1px solid #eee',
backgroundReactionHover: '#fff',
borderStyleReactionHover: '1px solid #ddd',
colorReactionCounter: '#0a0a0a',
backgroundReactionMe: '#cfecf5',
borderStyleReactionMe: '1px solid #3b98b8',
backgroundReactionHoverMe: '#cfecf5',
borderStyleReactionHoverMe: '1px solid #3b98b8',
colorReactionCounterMe: '#0b59b3',
backgroundAudioRecord: '#eb4034',
backgroundAudioLine: 'rgba(0, 0, 0, 0.15)',
backgroundAudioProgress: '#455247',
backgroundAudioProgressSelector: '#455247'
},
markdown: {
background: 'rgba(239, 239, 239, 0.7)',
border: 'rgba(212, 212, 212, 0.9)',
color: '#e01e5a',
colorMulti: '#0a0a0a'
},
room: {
colorUsername: '#0a0a0a',
colorMessage: '#67717a',
colorTimestamp: '#a2aeb8',
colorStateOnline: '#4caf50',
colorStateOffline: '#9ca6af',
backgroundCounterBadge: '#0696c7',
colorCounterBadge: '#fff'
},
emoji: {
background: '#fff'
},
icons: {
search: '#9ca6af',
add: '#1976d2',
toggle: '#0a0a0a',
menu: '#0a0a0a',
close: '#9ca6af',
closeImage: '#fff',
file: '#1976d2',
paperclip: '#1976d2',
closeOutline: '#000',
send: '#1976d2',
sendDisabled: '#9ca6af',
emoji: '#1976d2',
emojiReaction: 'rgba(0, 0, 0, 0.3)',
document: '#1976d2',
pencil: '#9e9e9e',
checkmark: '#9e9e9e',
checkmarkSeen: '#0696c7',
eye: '#fff',
dropdownMessage: '#fff',
dropdownMessageBackground: 'rgba(0, 0, 0, 0.25)',
dropdownRoom: '#9e9e9e',
dropdownScroll: '#0a0a0a',
microphone: '#1976d2',
audioPlay: '#455247',
audioPause: '#455247',
audioCancel: '#eb4034',
audioConfirm: '#1ba65b'
}
},
dark: {
general: {
color: '#fff',
backgroundInput: '#202223',
colorPlaceholder: '#596269',
colorCaret: '#fff',
colorSpinner: '#fff',
borderStyle: 'none',
backgroundScrollIcon: '#fff'
},
container: {
border: 'none',
borderRadius: '4px',
boxShadow: '0px 1px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12)'
},
header: {
background: '#181a1b',
colorRoomName: '#fff',
colorRoomInfo: '#9ca6af'
},
footer: {
background: '#131415',
borderStyleInput: 'none',
borderInputSelected: '#1976d2',
backgroundReply: '#1b1c1c',
backgroundTagActive: '#1b1c1c'
},
content: {
background: '#131415'
},
sidemenu: {
background: '#181a1b',
backgroundHover: '#202224',
backgroundActive: '#151617',
colorActive: '#fff',
borderColorSearch: '#181a1b'
},
dropdown: {
background: '#2a2c33',
backgroundHover: '#26282e'
},
message: {
background: '#22242a',
backgroundMe: '#1f7e80',
color: '#fff',
colorStarted: '#9ca6af',
backgroundDeleted: '#1b1c21',
colorDeleted: '#a2a5a8',
colorUsername: '#b3bac9',
colorTimestamp: '#ebedf2',
backgroundDate: 'rgba(0, 0, 0, 0.3)',
colorDate: '#bec5cc',
backgroundSystem: 'rgba(0, 0, 0, 0.3)',
colorSystem: '#bec5cc',
backgroundMedia: 'rgba(0, 0, 0, 0.18)',
backgroundReply: 'rgba(0, 0, 0, 0.18)',
colorReplyUsername: '#fff',
colorReply: '#d6d6d6',
colorTag: '#f0c60a',
backgroundImage: '#ddd',
colorNewMessages: '#fff',
backgroundScrollCounter: '#1976d2',
colorScrollCounter: '#fff',
backgroundReaction: 'none',
borderStyleReaction: 'none',
backgroundReactionHover: '#202223',
borderStyleReactionHover: 'none',
colorReactionCounter: '#fff',
backgroundReactionMe: '#4e9ad1',
borderStyleReactionMe: 'none',
backgroundReactionHoverMe: '#4e9ad1',
borderStyleReactionHoverMe: 'none',
colorReactionCounterMe: '#fff',
backgroundAudioRecord: '#eb4034',
backgroundAudioLine: 'rgba(255, 255, 255, 0.15)',
backgroundAudioProgress: '#b7d4d3',
backgroundAudioProgressSelector: '#b7d4d3'
},
markdown: {
background: 'rgba(239, 239, 239, 0.7)',
border: 'rgba(212, 212, 212, 0.9)',
color: '#e01e5a',
colorMulti: '#0a0a0a'
},
room: {
colorUsername: '#fff',
colorMessage: '#6c7278',
colorTimestamp: '#6c7278',
colorStateOnline: '#4caf50',
colorStateOffline: '#596269',
backgroundCounterBadge: '#1976d2',
colorCounterBadge: '#fff'
},
emoji: {
background: '#343740'
},
icons: {
search: '#596269',
add: '#fff',
toggle: '#fff',
menu: '#fff',
close: '#9ca6af',
closeImage: '#fff',
file: '#1976d2',
paperclip: '#fff',
closeOutline: '#fff',
send: '#fff',
sendDisabled: '#646a70',
emoji: '#fff',
emojiReaction: '#fff',
document: '#1976d2',
pencil: '#ebedf2',
checkmark: '#ebedf2',
checkmarkSeen: '#f0d90a',
eye: '#fff',
dropdownMessage: '#fff',
dropdownMessageBackground: 'rgba(0, 0, 0, 0.25)',
dropdownRoom: '#fff',
dropdownScroll: '#0a0a0a',
microphone: '#fff',
audioPlay: '#b7d4d3',
audioPause: '#b7d4d3',
audioCancel: '#eb4034',
audioConfirm: '#1ba65b'
}
}
};
var cssThemeVars = function cssThemeVars(_ref) {
var general = _ref.general,
container = _ref.container,
header = _ref.header,
footer = _ref.footer,
sidemenu = _ref.sidemenu,
content = _ref.content,
dropdown = _ref.dropdown,
message = _ref.message,
markdown = _ref.markdown,
room = _ref.room,
emoji = _ref.emoji,
icons = _ref.icons;
return {
// general
'--chat-color': general.color,
'--chat-bg-color-input': general.backgroundInput,
'--chat-color-spinner': general.colorSpinner,
'--chat-color-placeholder': general.colorPlaceholder,
'--chat-color-caret': general.colorCaret,
'--chat-border-style': general.borderStyle,
'--chat-bg-scroll-icon': general.backgroundScrollIcon,
// container
'--chat-container-border': container.border,
'--chat-container-border-radius': container.borderRadius,
'--chat-container-box-shadow': container.boxShadow,
// header
'--chat-header-bg-color': header.background,
'--chat-header-color-name': header.colorRoomName,
'--chat-header-color-info': header.colorRoomInfo,
// footer
'--chat-footer-bg-color': footer.background,
'--chat-border-style-input': footer.borderStyleInput,
'--chat-border-color-input-selected': footer.borderInputSelected,
'--chat-footer-bg-color-reply': footer.backgroundReply,
'--chat-footer-bg-color-tag-active': footer.backgroundTagActive,
// content
'--chat-content-bg-color': content.background,
// sidemenu
'--chat-sidemenu-bg-color': sidemenu.background,
'--chat-sidemenu-bg-color-hover': sidemenu.backgroundHover,
'--chat-sidemenu-bg-color-active': sidemenu.backgroundActive,
'--chat-sidemenu-color-active': sidemenu.colorActive,
'--chat-sidemenu-border-color-search': sidemenu.borderColorSearch,
// dropdown
'--chat-dropdown-bg-color': dropdown.background,
'--chat-dropdown-bg-color-hover': dropdown.backgroundHover,
// message
'--chat-message-bg-color': message.background,
'--chat-message-bg-color-me': message.backgroundMe,
'--chat-message-color-started': message.colorStarted,
'--chat-message-bg-color-deleted': message.backgroundDeleted,
'--chat-message-color-deleted': message.colorDeleted,
'--chat-message-color-username': message.colorUsername,
'--chat-message-color-timestamp': message.colorTimestamp,
'--chat-message-bg-color-date': message.backgroundDate,
'--chat-message-color-date': message.colorDate,
'--chat-message-bg-color-system': message.backgroundSystem,
'--chat-message-color-system': message.colorSystem,
'--chat-message-color': message.color,
'--chat-message-bg-color-media': message.backgroundMedia,
'--chat-message-bg-color-reply': message.backgroundReply,
'--chat-message-color-reply-username': message.colorReplyUsername,
'--chat-message-color-reply-content': message.colorReply,
'--chat-message-color-tag': message.colorTag,
'--chat-message-bg-color-image': message.backgroundImage,
'--chat-message-color-new-messages': message.colorNewMessages,
'--chat-message-bg-color-scroll-counter': message.backgroundScrollCounter,
'--chat-message-color-scroll-counter': message.colorScrollCounter,
'--chat-message-bg-color-reaction': message.backgroundReaction,
'--chat-message-border-style-reaction': message.borderStyleReaction,
'--chat-message-bg-color-reaction-hover': message.backgroundReactionHover,
'--chat-message-border-style-reaction-hover': message.borderStyleReactionHover,
'--chat-message-color-reaction-counter': message.colorReactionCounter,
'--chat-message-bg-color-reaction-me': message.backgroundReactionMe,
'--chat-message-border-style-reaction-me': message.borderStyleReactionMe,
'--chat-message-bg-color-reaction-hover-me': message.backgroundReactionHoverMe,
'--chat-message-border-style-reaction-hover-me': message.borderStyleReactionHoverMe,
'--chat-message-color-reaction-counter-me': message.colorReactionCounterMe,
'--chat-message-bg-color-audio-record': message.backgroundAudioRecord,
'--chat-message-bg-color-audio-line': message.backgroundAudioLine,
'--chat-message-bg-color-audio-progress': message.backgroundAudioProgress,
'--chat-message-bg-color-audio-progress-selector': message.backgroundAudioProgressSelector,
// markdown
'--chat-markdown-bg': markdown.background,
'--chat-markdown-border': markdown.border,
'--chat-markdown-color': markdown.color,
'--chat-markdown-color-multi': markdown.colorMulti,
// room
'--chat-room-color-username': room.colorUsername,
'--chat-room-color-message': room.colorMessage,
'--chat-room-color-timestamp': room.colorTimestamp,
'--chat-room-color-online': room.colorStateOnline,
'--chat-room-color-offline': room.colorStateOffline,
'--chat-room-bg-color-badge': room.backgroundCounterBadge,
'--chat-room-color-badge': room.colorCounterBadge,
// emoji
'--chat-emoji-bg-color': emoji.background,
// icons
'--chat-icon-color-search': icons.search,
'--chat-icon-color-add': icons.add,
'--chat-icon-color-toggle': icons.toggle,
'--chat-icon-color-menu': icons.menu,
'--chat-icon-color-close': icons.close,
'--chat-icon-color-close-image': icons.closeImage,
'--chat-icon-color-file': icons.file,
'--chat-icon-color-paperclip': icons.paperclip,
'--chat-icon-color-close-outline': icons.closeOutline,
'--chat-icon-color-send': icons.send,
'--chat-icon-color-send-disabled': icons.sendDisabled,
'--chat-icon-color-emoji': icons.emoji,
'--chat-icon-color-emoji-reaction': icons.emojiReaction,
'--chat-icon-color-document': icons.document,
'--chat-icon-color-pencil': icons.pencil,
'--chat-icon-color-checkmark': icons.checkmark,
'--chat-icon-color-checkmark-seen': icons.checkmarkSeen,
'--chat-icon-color-eye': icons.eye,
'--chat-icon-color-dropdown-message': icons.dropdownMessage,
'--chat-icon-bg-dropdown-message': icons.dropdownMessageBackground,
'--chat-icon-color-dropdown-room': icons.dropdownRoom,
'--chat-icon-color-dropdown-scroll': icons.dropdownScroll,
'--chat-icon-color-microphone': icons.microphone,
'--chat-icon-color-audio-play': icons.audioPlay,
'--chat-icon-color-audio-pause': icons.audioPause,
'--chat-icon-color-audio-cancel': icons.audioCancel,
'--chat-icon-color-audio-confirm': icons.audioConfirm
};
};
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/ChatWindow/ChatWindow.vue?vue&type=script&lang=js&shadow
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var ChatWindowvue_type_script_lang_js_shadow_require = __webpack_require__("4c1d"),
roomsValidation = ChatWindowvue_type_script_lang_js_shadow_require.roomsValidation,
partcipantsValidation = ChatWindowvue_type_script_lang_js_shadow_require.partcipantsValidation;
/* harmony default export */ var ChatWindowvue_type_script_lang_js_shadow = ({
name: 'ChatContainer',
components: {
RoomsList: RoomsList,
Room: Room
},
props: {
height: {
type: String,
"default": '600px'
},
theme: {
type: String,
"default": 'light'
},
styles: {
type: Object,
"default": function _default() {
return {};
}
},
responsiveBreakpoint: {
type: Number,
"default": 900
},
singleRoom: {
type: Boolean,
"default": false
},
textMessages: {
type: Object,
"default": null
},
currentUserId: {
type: [String, Number],
"default": ''
},
rooms: {
type: Array,
"default": function _default() {
return [];
}
},
loadingRooms: {
type: Boolean,
"default": false
},
roomsLoaded: {
type: Boolean,
"default": false
},
roomId: {
type: [String, Number],
"default": null
},
loadFirstRoom: {
type: Boolean,
"default": true
},
messages: {
type: Array,
"default": function _default() {
return [];
}
},
messagesLoaded: {
type: Boolean,
"default": false
},
roomActions: {
type: Array,
"default": function _default() {
return [];
}
},
menuActions: {
type: Array,
"default": function _default() {
return [];
}
},
messageActions: {
type: Array,
"default": function _default() {
return [{
name: 'replyMessage',
title: 'Reply'
}, {
name: 'editMessage',
title: 'Edit Message',
onlyMe: true
}, {
name: 'deleteMessage',
title: 'Delete Message',
onlyMe: true
}];
}
},
showAddRoom: {
type: Boolean,
"default": true
},
showSendIcon: {
type: Boolean,
"default": true
},
showFiles: {
type: Boolean,
"default": true
},
showAudio: {
type: Boolean,
"default": true
},
showEmojis: {
type: Boolean,
"default": true
},
showReactionEmojis: {
type: Boolean,
"default": true
},
showNewMessagesDivider: {
type: Boolean,
"default": true
},
showFooter: {
type: Boolean,
"default": true
},
textFormatting: {
type: Boolean,
"default": true
},
linkOptions: {
type: Object,
"default": function _default() {
return {
disabled: false,
target: '_blank'
};
}
},
newMessage: {
type: Object,
"default": null
},
roomMessage: {
type: String,
"default": ''
},
acceptedFiles: {
type: String,
"default": '*'
}
},
data: function data() {
return {
room: {},
loadingMoreRooms: false,
showRoomsList: true,
isMobile: false
};
},
computed: {
t: function t() {
return _objectSpread2(_objectSpread2({}, locales), this.textMessages);
},
cssVars: function cssVars() {
var _this = this;
var defaultStyles = defaultThemeStyles[this.theme];
var customStyles = {};
Object.keys(defaultStyles).map(function (key) {
customStyles[key] = _objectSpread2(_objectSpread2({}, defaultStyles[key]), _this.styles[key] || {});
});
return cssThemeVars(customStyles);
},
orderedRooms: function orderedRooms() {
return this.rooms.slice().sort(function (a, b) {
var aVal = a.index || 0;
var bVal = b.index || 0;
return aVal > bVal ? -1 : bVal > aVal ? 1 : 0;
});
}
},
watch: {
rooms: {
immediate: true,
handler: function handler(newVal, oldVal) {
var _this2 = this;
if (!newVal[0] || !newVal.find(function (room) {
return room.roomId === _this2.room.roomId;
})) {
this.showRoomsList = true;
}
if (!this.loadingMoreRooms && this.loadFirstRoom && newVal[0] && (!oldVal || newVal.length !== oldVal.length)) {
if (this.roomId) {
var room = newVal.find(function (r) {
return r.roomId === _this2.roomId;
});
this.fetchRoom({
room: room
});
} else if (!this.isMobile || this.singleRoom) {
this.fetchRoom({
room: this.orderedRooms[0]
});
} else {
this.showRoomsList = true;
}
}
}
},
loadingRooms: function loadingRooms(val) {
if (val) this.room = {};
},
roomId: {
immediate: true,
handler: function handler(newVal, oldVal) {
if (newVal && !this.loadingRooms && this.rooms.length) {
var room = this.rooms.find(function (r) {
return r.roomId === newVal;
});
this.fetchRoom({
room: room
});
} else if (oldVal && !newVal) {
this.room = {};
}
}
},
room: function room(val) {
if (!val || Object.entries(val).length === 0) return;
roomsValidation(val);
val.users.forEach(function (user) {
partcipantsValidation(user);
});
},
newMessage: function newMessage(val) {
this.$set(this.messages, val.index, val.message);
}
},
created: function created() {
var _this3 = this;
this.updateResponsive();
window.addEventListener('resize', function (ev) {
if (ev.isTrusted) _this3.updateResponsive();
});
},
methods: {
updateResponsive: function updateResponsive() {
this.isMobile = window.innerWidth < this.responsiveBreakpoint;
},
toggleRoomsList: function toggleRoomsList() {
this.showRoomsList = !this.showRoomsList;
if (this.isMobile) this.room = {};
this.$emit('toggle-rooms-list', {
opened: this.showRoomsList
});
},
fetchRoom: function fetchRoom(_ref) {
var room = _ref.room;
this.room = room;
this.fetchMessages({
reset: true
});
if (this.isMobile) this.showRoomsList = false;
},
fetchMoreRooms: function fetchMoreRooms() {
this.$emit('fetch-more-rooms');
},
roomInfo: function roomInfo() {
this.$emit('room-info', this.room);
},
addRoom: function addRoom() {
this.$emit('add-room');
},
fetchMessages: function fetchMessages(options) {
this.$emit('fetch-messages', {
room: this.room,
options: options
});
},
sendMessage: function sendMessage(message) {
this.$emit('send-message', _objectSpread2(_objectSpread2({}, message), {}, {
roomId: this.room.roomId
}));
},
editMessage: function editMessage(message) {
this.$emit('edit-message', _objectSpread2(_objectSpread2({}, message), {}, {
roomId: this.room.roomId
}));
},
deleteMessage: function deleteMessage(message) {
this.$emit('delete-message', {
message: message,
roomId: this.room.roomId
});
},
openFile: function openFile(_ref2) {
var message = _ref2.message,
action = _ref2.action;
this.$emit('open-file', {
message: message,
action: action
});
},
openUserTag: function openUserTag(_ref3) {
var user = _ref3.user;
this.$emit('open-user-tag', {
user: user
});
},
menuActionHandler: function menuActionHandler(ev) {
this.$emit('menu-action-handler', {
action: ev,
roomId: this.room.roomId
});
},
roomActionHandler: function roomActionHandler(_ref4) {
var action = _ref4.action,
roomId = _ref4.roomId;
this.$emit('room-action-handler', {
action: action,
roomId: roomId
});
},
messageActionHandler: function messageActionHandler(ev) {
this.$emit('message-action-handler', _objectSpread2(_objectSpread2({}, ev), {}, {
roomId: this.room.roomId
}));
},
sendMessageReaction: function sendMessageReaction(messageReaction) {
this.$emit('send-message-reaction', _objectSpread2(_objectSpread2({}, messageReaction), {}, {
roomId: this.room.roomId
}));
},
typingMessage: function typingMessage(message) {
this.$emit('typing-message', {
message: message,
roomId: this.room.roomId
});
},
textareaActionHandler: function textareaActionHandler(message) {
this.$emit('textarea-action-handler', {
message: message,
roomId: this.room.roomId
});
}
}
});
// CONCATENATED MODULE: ./src/ChatWindow/ChatWindow.vue?vue&type=script&lang=js&shadow
/* harmony default export */ var ChatWindow_ChatWindowvue_type_script_lang_js_shadow = (ChatWindowvue_type_script_lang_js_shadow);
// CONCATENATED MODULE: ./src/ChatWindow/ChatWindow.vue?shadow
function injectStyles (context) {
var style0 = __webpack_require__("a589")
if (style0.__inject__) style0.__inject__(context)
}
/* normalize component */
var ChatWindowshadow_component = normalizeComponent(
ChatWindow_ChatWindowvue_type_script_lang_js_shadow,
render,
staticRenderFns,
false,
injectStyles,
null,
null
,true
)
/* harmony default export */ var ChatWindowshadow = (ChatWindowshadow_component.exports);
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-wc.js
// runtime shared by every component chunk
window.customElements.define('vue-advanced-chat', vue_wc_wrapper(external_Vue_default.a, ChatWindowshadow))
/***/ }),
/***/ "5ca1":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var core = __webpack_require__("8378");
var hide = __webpack_require__("32e9");
var redefine = __webpack_require__("2aba");
var ctx = __webpack_require__("9b43");
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/***/ "5cc5":
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__("2b4c")('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/***/ "5dbc":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
var setPrototypeOf = __webpack_require__("8b97").set;
module.exports = function (that, target, C) {
var S = target.constructor;
var P;
if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
setPrototypeOf(that, P);
} return that;
};
/***/ }),
/***/ "5df3":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__("02f4")(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__("01f9")(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/***/ "5eda":
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__("5ca1");
var core = __webpack_require__("8378");
var fails = __webpack_require__("79e5");
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/***/ "5eed":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-tags-container{position:absolute;display:flex;flex-direction:column;align-items:center;width:100%}.vac-tags-container .vac-tags-box{display:flex;width:100%;height:54px;overflow:hidden;cursor:pointer;background:var(--chat-footer-bg-color)}.vac-tags-container .vac-tags-box:hover{background:var(--chat-footer-bg-color-tag-active)}.vac-tags-container .vac-tags-box:hover,.vac-tags-container .vac-tags-box:not(:hover){transition:background-color .3s cubic-bezier(.25,.8,.5,1)}.vac-tags-container .vac-tags-info{display:flex;overflow:hidden;padding:0 20px;align-items:center}.vac-tags-container .vac-tags-avatar{height:34px;width:34px;min-height:34px;min-width:34px}.vac-tags-container .vac-tags-username{font-size:14px}@media only screen and (max-width:768px){.vac-tags-container .vac-tags-box{height:50px}.vac-tags-container .vac-tags-info{padding:0 12px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "5f1b":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var classof = __webpack_require__("23c6");
var builtinExec = RegExp.prototype.exec;
// `RegExpExec` abstract operation
// https://tc39.github.io/ecma262/#sec-regexpexec
module.exports = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw new TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classof(R) !== 'RegExp') {
throw new TypeError('RegExp#exec called on incompatible receiver');
}
return builtinExec.call(R, S);
};
/***/ }),
/***/ "6095":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $every = __webpack_require__("0a49")(4);
$export($export.P + $export.F * !__webpack_require__("2f21")([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments[1]);
}
});
/***/ }),
/***/ "613b":
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__("5537")('keys');
var uid = __webpack_require__("ca5a");
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/***/ "626a":
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__("2d95");
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/***/ "63d9":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("ec30")('Float32', 4, function (init) {
return function Float32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/***/ "6534":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("3afd");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("ef53abf2", content, shadowRoot)
};
/***/ }),
/***/ "669f":
/***/ (function(module, exports, __webpack_require__) {
!function(e,o){ true?module.exports=o():undefined}(this,function(){return function(e){function o(a){if(t[a])return t[a].exports;var n=t[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,o),n.l=!0,n.exports}var t={};return o.m=e,o.c=t,o.i=function(e){return e},o.d=function(e,t,a){o.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:a})},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,o){return Object.prototype.hasOwnProperty.call(e,o)},o.p="/dist-module/",o(o.s=3)}([function(e,o,t){var a=t(4)(t(1),t(5),null,null,null);e.exports=a.exports},function(e,o,t){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var a=t(2),n=function(e){return e&&e.__esModule?e:{default:e}}(a);o.default={props:{search:{type:String,required:!1,default:""},emojiTable:{type:Object,required:!1,default:function(){return n.default}}},data:function(){return{display:{x:0,y:0,visible:!1}}},computed:{emojis:function(){if(this.search){var e={};for(var o in this.emojiTable){e[o]={};for(var t in this.emojiTable[o])new RegExp(".*"+this.search+".*").test(t)&&(e[o][t]=this.emojiTable[o][t]);0===Object.keys(e[o]).length&&delete e[o]}return e}return this.emojiTable}},methods:{insert:function(e){this.$emit("emoji",e)},toggle:function(e){this.display.visible=!this.display.visible,this.display.x=e.clientX,this.display.y=e.clientY},hide:function(){this.display.visible=!1},escape:function(e){!0===this.display.visible&&27===e.keyCode&&(this.display.visible=!1)}},directives:{"click-outside":{bind:function(e,o,t){if("function"==typeof o.value){var a=o.modifiers.bubble,n=function(t){(a||!e.contains(t.target)&&e!==t.target)&&o.value(t)};e.__vueClickOutside__=n,document.addEventListener("click",n)}},unbind:function(e,o){document.removeEventListener("click",e.__vueClickOutside__),e.__vueClickOutside__=null}}},mounted:function(){document.addEventListener("keyup",this.escape)},destroyed:function(){document.removeEventListener("keyup",this.escape)}}},function(e,o,t){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.default={"Frequently used":{thumbs_up:"👍","-1":"👎",sob:"😭",confused:"😕",neutral_face:"😐",blush:"😊",heart_eyes:"😍"},People:{smile:"😄",smiley:"😃",grinning:"😀",blush:"😊",wink:"😉",heart_eyes:"😍",kissing_heart:"😘",kissing_closed_eyes:"😚",kissing:"😗",kissing_smiling_eyes:"😙",stuck_out_tongue_winking_eye:"😜",stuck_out_tongue_closed_eyes:"😝",stuck_out_tongue:"😛",flushed:"😳",grin:"😁",pensive:"😔",relieved:"😌",unamused:"😒",disappointed:"😞",persevere:"😣",cry:"😢",joy:"😂",sob:"😭",sleepy:"😪",disappointed_relieved:"😥",cold_sweat:"😰",sweat_smile:"😅",sweat:"😓",weary:"😩",tired_face:"😫",fearful:"😨",scream:"😱",angry:"😠",rage:"😡",triumph:"😤",confounded:"😖",laughing:"😆",yum:"😋",mask:"😷",sunglasses:"😎",sleeping:"😴",dizzy_face:"😵",astonished:"😲",worried:"😟",frowning:"😦",anguished:"😧",imp:"👿",open_mouth:"😮",grimacing:"😬",neutral_face:"😐",confused:"😕",hushed:"😯",smirk:"😏",expressionless:"😑",man_with_gua_pi_mao:"👲",man_with_turban:"👳",cop:"👮",construction_worker:"👷",guardsman:"💂",baby:"👶",boy:"👦",girl:"👧",man:"👨",woman:"👩",older_man:"👴",older_woman:"👵",person_with_blond_hair:"👱",angel:"👼",princess:"👸",smiley_cat:"😺",smile_cat:"😸",heart_eyes_cat:"😻",kissing_cat:"😽",smirk_cat:"😼",scream_cat:"🙀",crying_cat_face:"😿",joy_cat:"😹",pouting_cat:"😾",japanese_ogre:"👹",japanese_goblin:"👺",see_no_evil:"🙈",hear_no_evil:"🙉",speak_no_evil:"🙊",skull:"💀",alien:"👽",hankey:"💩",fire:"🔥",sparkles:"✨",star2:"🌟",dizzy:"💫",boom:"💥",anger:"💢",sweat_drops:"💦",droplet:"💧",zzz:"💤",dash:"💨",ear:"👂",eyes:"👀",nose:"👃",tongue:"👅",lips:"👄",thumbs_up:"👍","-1":"👎",ok_hand:"👌",facepunch:"👊",fist:"✊",wave:"👋",hand:"✋",open_hands:"👐",point_up_2:"👆",point_down:"👇",point_right:"👉",point_left:"👈",raised_hands:"🙌",pray:"🙏",clap:"👏",muscle:"💪",walking:"🚶",runner:"🏃",dancer:"💃",couple:"👫",family:"👪",couplekiss:"💏",couple_with_heart:"💑",dancers:"👯",ok_woman:"🙆",no_good:"🙅",information_desk_person:"💁",raising_hand:"🙋",massage:"💆",haircut:"💇",nail_care:"💅",bride_with_veil:"👰",person_with_pouting_face:"🙎",person_frowning:"🙍",bow:"🙇",tophat:"🎩",crown:"👑",womans_hat:"👒",athletic_shoe:"👟",mans_shoe:"👞",sandal:"👡",high_heel:"👠",boot:"👢",shirt:"👕",necktie:"👔",womans_clothes:"👚",dress:"👗",running_shirt_with_sash:"🎽",jeans:"👖",kimono:"👘",bikini:"👙",briefcase:"💼",handbag:"👜",pouch:"👝",purse:"👛",eyeglasses:"👓",ribbon:"🎀",closed_umbrella:"🌂",lipstick:"💄",yellow_heart:"💛",blue_heart:"💙",purple_heart:"💜",green_heart:"💚",broken_heart:"💔",heartpulse:"💗",heartbeat:"💓",two_hearts:"💕",sparkling_heart:"💖",revolving_hearts:"💞",cupid:"💘",love_letter:"💌",kiss:"💋",ring:"💍",gem:"💎",bust_in_silhouette:"👤",speech_balloon:"💬",footprints:"👣"},Nature:{dog:"🐶",wolf:"🐺",cat:"🐱",mouse:"🐭",hamster:"🐹",rabbit:"🐰",frog:"🐸",tiger:"🐯",koala:"🐨",bear:"🐻",pig:"🐷",pig_nose:"🐽",cow:"🐮",boar:"🐗",monkey_face:"🐵",monkey:"🐒",horse:"🐴",sheep:"🐑",elephant:"🐘",panda_face:"🐼",penguin:"🐧",bird:"🐦",baby_chick:"🐤",hatched_chick:"🐥",hatching_chick:"🐣",chicken:"🐔",snake:"🐍",turtle:"🐢",bug:"🐛",bee:"🐝",ant:"🐜",beetle:"🐞",snail:"🐌",octopus:"🐙",shell:"🐚",tropical_fish:"🐠",fish:"🐟",dolphin:"🐬",whale:"🐳",racehorse:"🐎",dragon_face:"🐲",blowfish:"🐡",camel:"🐫",poodle:"🐩",feet:"🐾",bouquet:"💐",cherry_blossom:"🌸",tulip:"🌷",four_leaf_clover:"🍀",rose:"🌹",sunflower:"🌻",hibiscus:"🌺",maple_leaf:"🍁",leaves:"🍃",fallen_leaf:"🍂",herb:"🌿",ear_of_rice:"🌾",mushroom:"🍄",cactus:"🌵",palm_tree:"🌴",chestnut:"🌰",seedling:"🌱",blossom:"🌼",new_moon:"🌑",first_quarter_moon:"🌓",moon:"🌔",full_moon:"🌕",first_quarter_moon_with_face:"🌛",crescent_moon:"🌙",earth_asia:"🌏",volcano:"🌋",milky_way:"🌌",stars:"🌠",partly_sunny:"⛅",snowman:"⛄",cyclone:"🌀",foggy:"🌁",rainbow:"🌈",ocean:"🌊"},Objects:{bamboo:"🎍",gift_heart:"💝",dolls:"🎎",school_satchel:"🎒",mortar_board:"🎓",flags:"🎏",fireworks:"🎆",sparkler:"🎇",wind_chime:"🎐",rice_scene:"🎑",jack_o_lantern:"🎃",ghost:"👻",santa:"🎅",christmas_tree:"🎄",gift:"🎁",tanabata_tree:"🎋",tada:"🎉",confetti_ball:"🎊",balloon:"🎈",crossed_flags:"🎌",crystal_ball:"🔮",movie_camera:"🎥",camera:"📷",video_camera:"📹",vhs:"📼",cd:"💿",dvd:"📀",minidisc:"💽",floppy_disk:"💾",computer:"💻",iphone:"📱",telephone_receiver:"📞",pager:"📟",fax:"📠",satellite:"📡",tv:"📺",radio:"📻",loud_sound:"🔊",bell:"🔔",loudspeaker:"📢",mega:"📣",hourglass_flowing_sand:"⏳",hourglass:"⌛",alarm_clock:"⏰",watch:"⌚",unlock:"🔓",lock:"🔒",lock_with_ink_pen:"🔏",closed_lock_with_key:"🔐",key:"🔑",mag_right:"🔎",bulb:"💡",flashlight:"🔦",electric_plug:"🔌",battery:"🔋",mag:"🔍",bath:"🛀",toilet:"🚽",wrench:"🔧",nut_and_bolt:"🔩",hammer:"🔨",door:"🚪",smoking:"🚬",bomb:"💣",gun:"🔫",hocho:"🔪",pill:"💊",syringe:"💉",moneybag:"💰",yen:"💴",dollar:"💵",credit_card:"💳",money_with_wings:"💸",calling:"📲","e-mail":"📧",inbox_tray:"📥",outbox_tray:"📤",envelope_with_arrow:"📩",incoming_envelope:"📨",mailbox:"📫",mailbox_closed:"📪",postbox:"📮",package:"📦",memo:"📝",page_facing_up:"📄",page_with_curl:"📃",bookmark_tabs:"📑",bar_chart:"📊",chart_with_upwards_trend:"📈",chart_with_downwards_trend:"📉",scroll:"📜",clipboard:"📋",date:"📅",calendar:"📆",card_index:"📇",file_folder:"📁",open_file_folder:"📂",pushpin:"📌",paperclip:"📎",straight_ruler:"📏",triangular_ruler:"📐",closed_book:"📕",green_book:"📗",blue_book:"📘",orange_book:"📙",notebook:"📓",notebook_with_decorative_cover:"📔",ledger:"📒",books:"📚",book:"📖",bookmark:"🔖",name_badge:"📛",newspaper:"📰",art:"🎨",clapper:"🎬",microphone:"🎤",headphones:"🎧",musical_score:"🎼",musical_note:"🎵",notes:"🎶",musical_keyboard:"🎹",violin:"🎻",trumpet:"🎺",saxophone:"🎷",guitar:"🎸",space_invader:"👾",video_game:"🎮",black_joker:"🃏",flower_playing_cards:"🎴",mahjong:"🀄",game_die:"🎲",dart:"🎯",football:"🏈",basketball:"🏀",soccer:"⚽",baseball:"⚾",tennis:"🎾","8ball":"🎱",bowling:"🎳",golf:"⛳",checkered_flag:"🏁",trophy:"🏆",ski:"🎿",snowboarder:"🏂",swimmer:"🏊",surfer:"🏄",fishing_pole_and_fish:"🎣",tea:"🍵",sake:"🍶",beer:"🍺",beers:"🍻",cocktail:"🍸",tropical_drink:"🍹",wine_glass:"🍷",fork_and_knife:"🍴",pizza:"🍕",hamburger:"🍔",fries:"🍟",poultry_leg:"🍗",meat_on_bone:"🍖",spaghetti:"🍝",curry:"🍛",fried_shrimp:"🍤",bento:"🍱",sushi:"🍣",fish_cake:"🍥",rice_ball:"🍙",rice_cracker:"🍘",rice:"🍚",ramen:"🍜",stew:"🍲",oden:"🍢",dango:"🍡",egg:"🍳",bread:"🍞",doughnut:"🍩",custard:"🍮",icecream:"🍦",ice_cream:"🍨",shaved_ice:"🍧",birthday:"🎂",cake:"🍰",cookie:"🍪",chocolate_bar:"🍫",candy:"🍬",lollipop:"🍭",honey_pot:"🍯",apple:"🍎",green_apple:"🍏",tangerine:"🍊",cherries:"🍒",grapes:"🍇",watermelon:"🍉",strawberry:"🍓",peach:"🍑",melon:"🍈",banana:"🍌",pineapple:"🍍",sweet_potato:"🍠",eggplant:"🍆",tomato:"🍅",corn:"🌽"},Places:{house:"🏠",house_with_garden:"🏡",school:"🏫",office:"🏢",post_office:"🏣",hospital:"🏥",bank:"🏦",convenience_store:"🏪",love_hotel:"🏩",hotel:"🏨",wedding:"💒",church:"⛪",department_store:"🏬",city_sunrise:"🌇",city_sunset:"🌆",japanese_castle:"🏯",european_castle:"🏰",tent:"⛺",factory:"🏭",tokyo_tower:"🗼",japan:"🗾",mount_fuji:"🗻",sunrise_over_mountains:"🌄",sunrise:"🌅",night_with_stars:"🌃",statue_of_liberty:"🗽",bridge_at_night:"🌉",carousel_horse:"🎠",ferris_wheel:"🎡",fountain:"⛲",roller_coaster:"🎢",ship:"🚢",boat:"⛵",speedboat:"🚤",rocket:"🚀",seat:"💺",station:"🚉",bullettrain_side:"🚄",bullettrain_front:"🚅",metro:"🚇",railway_car:"🚃",bus:"🚌",blue_car:"🚙",car:"🚗",taxi:"🚕",truck:"🚚",rotating_light:"🚨",police_car:"🚓",fire_engine:"🚒",ambulance:"🚑",bike:"🚲",barber:"💈",busstop:"🚏",ticket:"🎫",traffic_light:"🚥",construction:"🚧",beginner:"🔰",fuelpump:"⛽",izakaya_lantern:"🏮",slot_machine:"🎰",moyai:"🗿",circus_tent:"🎪",performing_arts:"🎭",round_pushpin:"📍",triangular_flag_on_post:"🚩"},Symbols:{keycap_ten:"🔟",1234:"🔢",symbols:"🔣",capital_abcd:"🔠",abcd:"🔡",abc:"🔤",arrow_up_small:"🔼",arrow_down_small:"🔽",rewind:"⏪",fast_forward:"⏩",arrow_double_up:"⏫",arrow_double_down:"⏬",ok:"🆗",new:"🆕",up:"🆙",cool:"🆒",free:"🆓",ng:"🆖",signal_strength:"📶",cinema:"🎦",koko:"🈁",u6307:"🈯",u7a7a:"🈳",u6e80:"🈵",u5408:"🈴",u7981:"🈲",ideograph_advantage:"🉐",u5272:"🈹",u55b6:"🈺",u6709:"🈶",u7121:"🈚",restroom:"🚻",mens:"🚹",womens:"🚺",baby_symbol:"🚼",wc:"🚾",no_smoking:"🚭",u7533:"🈸",accept:"🉑",cl:"🆑",sos:"🆘",id:"🆔",no_entry_sign:"🚫",underage:"🔞",no_entry:"⛔",negative_squared_cross_mark:"❎",white_check_mark:"✅",heart_decoration:"💟",vs:"🆚",vibration_mode:"📳",mobile_phone_off:"📴",ab:"🆎",diamond_shape_with_a_dot_inside:"💠",ophiuchus:"⛎",six_pointed_star:"🔯",atm:"🏧",chart:"💹",heavy_dollar_sign:"💲",currency_exchange:"💱",x:"❌",exclamation:"❗",question:"❓",grey_exclamation:"❕",grey_question:"❔",o:"⭕",top:"🔝",end:"🔚",back:"🔙",on:"🔛",soon:"🔜",arrows_clockwise:"🔃",clock12:"🕛",clock1:"🕐",clock2:"🕑",clock3:"🕒",clock4:"🕓",clock5:"🕔",clock6:"🕕",clock7:"🕖",clock8:"🕗",clock9:"🕘",clock10:"🕙",clock11:"🕚",heavy_plus_sign:"➕",heavy_minus_sign:"➖",heavy_division_sign:"➗",white_flower:"💮",100:"💯",radio_button:"🔘",link:"🔗",curly_loop:"➰",trident:"🔱",small_red_triangle:"🔺",black_square_button:"🔲",white_square_button:"🔳",red_circle:"🔴",large_blue_circle:"🔵",small_red_triangle_down:"🔻",white_large_square:"⬜",black_large_square:"⬛",large_orange_diamond:"🔶",large_blue_diamond:"🔷",small_orange_diamond:"🔸",small_blue_diamond:"🔹"}}},function(e,o,t){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.EmojiPickerPlugin=o.EmojiPicker=void 0;var a=t(0),n=function(e){return e&&e.__esModule?e:{default:e}}(a),i={install:function(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1];e.component("emoji-picker",n.default)}};"undefined"!=typeof window&&(window.EmojiPicker=i),o.EmojiPicker=n.default,o.EmojiPickerPlugin=i,o.default=n.default},function(e,o){e.exports=function(e,o,t,a,n){var i,r=e=e||{},s=typeof e.default;"object"!==s&&"function"!==s||(i=e,r=e.default);var l="function"==typeof r?r.options:r;o&&(l.render=o.render,l.staticRenderFns=o.staticRenderFns),a&&(l._scopeId=a);var _;if(n?(_=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),t&&t.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(n)},l._ssrRegister=_):t&&(_=t),_){var c=l.functional,u=c?l.render:l.beforeCreate;c?l.render=function(e,o){return _.call(o),u(e,o)}:l.beforeCreate=u?[].concat(u,_):[_]}return{esModule:i,exports:r,options:l}}},function(e,o){e.exports={render:function(){var e=this,o=e.$createElement,t=e._self._c||o;return t("div",[e._t("emoji-invoker",null,{events:{click:function(o){return e.toggle(o)}}}),e._v(" "),e.display.visible?t("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:e.hide,expression:"hide"}]},[e._t("emoji-picker",null,{emojis:e.emojis,insert:e.insert,display:e.display})],2):e._e()],2)},staticRenderFns:[]}}])});
//# sourceMappingURL=main.js.map
/***/ }),
/***/ "6762":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__("5ca1");
var $includes = __webpack_require__("c366")(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__("9c6c")('includes');
/***/ }),
/***/ "67ab":
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__("ca5a")('meta');
var isObject = __webpack_require__("d3f4");
var has = __webpack_require__("69a8");
var setDesc = __webpack_require__("86cc").f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !__webpack_require__("79e5")(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/***/ "6821":
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__("626a");
var defined = __webpack_require__("be13");
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/***/ "69a8":
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/***/ "6a99":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__("d3f4");
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ "6d67":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $map = __webpack_require__("0a49")(1);
$export($export.P + $export.F * !__webpack_require__("2f21")([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments[1]);
}
});
/***/ }),
/***/ "6dc2":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("3545");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("e312c1f2", content, shadowRoot)
};
/***/ }),
/***/ "7154":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-rooms-container{display:flex;flex-flow:column;flex:0 0 25%;min-width:260px;max-width:500px;position:relative;background:var(--chat-sidemenu-bg-color);height:100%;border-top-left-radius:var(--chat-container-border-radius);border-bottom-left-radius:var(--chat-container-border-radius)}.vac-rooms-container.vac-rooms-container-full{flex:0 0 100%;max-width:100%}.vac-rooms-container .vac-rooms-empty{font-size:14px;color:#9ca6af;font-style:italic;text-align:center;margin:40px 0;line-height:20px;white-space:pre-line}.vac-rooms-container .vac-room-list{flex:1;position:relative;max-width:100%;cursor:pointer;padding:0 10px 5px;overflow-y:auto}.vac-rooms-container .vac-room-item{border-radius:8px;align-items:center;display:flex;flex:1 1 100%;margin-bottom:5px;padding:0 14px;position:relative;min-height:71px}.vac-rooms-container .vac-room-item:hover{background:var(--chat-sidemenu-bg-color-hover)}.vac-rooms-container .vac-room-item:hover,.vac-rooms-container .vac-room-item:not(:hover){transition:background-color .3s cubic-bezier(.25,.8,.5,1)}.vac-rooms-container .vac-room-selected{color:var(--chat-sidemenu-color-active)!important}.vac-rooms-container .vac-room-selected,.vac-rooms-container .vac-room-selected:hover{background:var(--chat-sidemenu-bg-color-active)!important}@media only screen and (max-width:768px){.vac-rooms-container .vac-room-list{padding:0 7px 5px}.vac-rooms-container .vac-room-item{min-height:60px;padding:0 8px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "7333":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var DESCRIPTORS = __webpack_require__("9e1e");
var getKeys = __webpack_require__("0d58");
var gOPS = __webpack_require__("2621");
var pIE = __webpack_require__("52a7");
var toObject = __webpack_require__("4bf8");
var IObject = __webpack_require__("626a");
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__("79e5")(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
}
} return T;
} : $assign;
/***/ }),
/***/ "74fe":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("2d78");
/***/ }),
/***/ "7514":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__("5ca1");
var $find = __webpack_require__("0a49")(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__("9c6c")(KEY);
/***/ }),
/***/ "759f":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $some = __webpack_require__("0a49")(3);
$export($export.P + $export.F * !__webpack_require__("2f21")([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments[1]);
}
});
/***/ }),
/***/ "7656":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.AMPERSAND = exports.CLOSEPAREN = exports.CLOSEANGLEBRACKET = exports.CLOSEBRACKET = exports.CLOSEBRACE = exports.OPENPAREN = exports.OPENANGLEBRACKET = exports.OPENBRACKET = exports.OPENBRACE = exports.WS = exports.TLD = exports.SYM = exports.UNDERSCORE = exports.SLASH = exports.MAILTO = exports.PROTOCOL = exports.QUERY = exports.POUND = exports.PLUS = exports.NUM = exports.NL = exports.LOCALHOST = exports.PUNCTUATION = exports.DOT = exports.COLON = exports.AT = exports.DOMAIN = exports.Base = undefined;
var _createTokenClass = __webpack_require__("46f3");
var _class = __webpack_require__("254c");
/******************************************************************************
Text Tokens
Tokens composed of strings
******************************************************************************/
/**
Abstract class used for manufacturing text tokens.
Pass in the value this token represents
@class TextToken
@abstract
*/
var TextToken = (0, _createTokenClass.createTokenClass)();
TextToken.prototype = {
toString: function toString() {
return this.v + '';
}
};
function inheritsToken(value) {
var props = value ? { v: value } : {};
return (0, _class.inherits)(TextToken, (0, _createTokenClass.createTokenClass)(), props);
}
/**
A valid domain token
@class DOMAIN
@extends TextToken
*/
var DOMAIN = inheritsToken();
/**
@class AT
@extends TextToken
*/
var AT = inheritsToken('@');
/**
Represents a single colon `:` character
@class COLON
@extends TextToken
*/
var COLON = inheritsToken(':');
/**
@class DOT
@extends TextToken
*/
var DOT = inheritsToken('.');
/**
A character class that can surround the URL, but which the URL cannot begin
or end with. Does not include certain English punctuation like parentheses.
@class PUNCTUATION
@extends TextToken
*/
var PUNCTUATION = inheritsToken();
/**
The word localhost (by itself)
@class LOCALHOST
@extends TextToken
*/
var LOCALHOST = inheritsToken();
/**
Newline token
@class NL
@extends TextToken
*/
var NL = inheritsToken('\n');
/**
@class NUM
@extends TextToken
*/
var NUM = inheritsToken();
/**
@class PLUS
@extends TextToken
*/
var PLUS = inheritsToken('+');
/**
@class POUND
@extends TextToken
*/
var POUND = inheritsToken('#');
/**
Represents a web URL protocol. Supported types include
* `http:`
* `https:`
* `ftp:`
* `ftps:`
@class PROTOCOL
@extends TextToken
*/
var PROTOCOL = inheritsToken();
/**
Represents the start of the email URI protocol
@class MAILTO
@extends TextToken
*/
var MAILTO = inheritsToken('mailto:');
/**
@class QUERY
@extends TextToken
*/
var QUERY = inheritsToken('?');
/**
@class SLASH
@extends TextToken
*/
var SLASH = inheritsToken('/');
/**
@class UNDERSCORE
@extends TextToken
*/
var UNDERSCORE = inheritsToken('_');
/**
One ore more non-whitespace symbol.
@class SYM
@extends TextToken
*/
var SYM = inheritsToken();
/**
@class TLD
@extends TextToken
*/
var TLD = inheritsToken();
/**
Represents a string of consecutive whitespace characters
@class WS
@extends TextToken
*/
var WS = inheritsToken();
/**
Opening/closing bracket classes
*/
var OPENBRACE = inheritsToken('{');
var OPENBRACKET = inheritsToken('[');
var OPENANGLEBRACKET = inheritsToken('<');
var OPENPAREN = inheritsToken('(');
var CLOSEBRACE = inheritsToken('}');
var CLOSEBRACKET = inheritsToken(']');
var CLOSEANGLEBRACKET = inheritsToken('>');
var CLOSEPAREN = inheritsToken(')');
var AMPERSAND = inheritsToken('&');
exports.Base = TextToken;
exports.DOMAIN = DOMAIN;
exports.AT = AT;
exports.COLON = COLON;
exports.DOT = DOT;
exports.PUNCTUATION = PUNCTUATION;
exports.LOCALHOST = LOCALHOST;
exports.NL = NL;
exports.NUM = NUM;
exports.PLUS = PLUS;
exports.POUND = POUND;
exports.QUERY = QUERY;
exports.PROTOCOL = PROTOCOL;
exports.MAILTO = MAILTO;
exports.SLASH = SLASH;
exports.UNDERSCORE = UNDERSCORE;
exports.SYM = SYM;
exports.TLD = TLD;
exports.WS = WS;
exports.OPENBRACE = OPENBRACE;
exports.OPENBRACKET = OPENBRACKET;
exports.OPENANGLEBRACKET = OPENANGLEBRACKET;
exports.OPENPAREN = OPENPAREN;
exports.CLOSEBRACE = CLOSEBRACE;
exports.CLOSEBRACKET = CLOSEBRACKET;
exports.CLOSEANGLEBRACKET = CLOSEANGLEBRACKET;
exports.CLOSEPAREN = CLOSEPAREN;
exports.AMPERSAND = AMPERSAND;
/***/ }),
/***/ "7726":
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/***/ "77f1":
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__("4588");
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/***/ "78ce":
/***/ (function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__("5ca1");
$export($export.S, 'Date', { now: function () { return new Date().getTime(); } });
/***/ }),
/***/ "798f":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsSearch_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("9745");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsSearch_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsSearch_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "79e5":
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/***/ "7a56":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__("7726");
var dP = __webpack_require__("86cc");
var DESCRIPTORS = __webpack_require__("9e1e");
var SPECIES = __webpack_require__("2b4c")('species');
module.exports = function (KEY) {
var C = global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
/***/ }),
/***/ "7b23":
/***/ (function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__("d8e8");
var toObject = __webpack_require__("4bf8");
var IObject = __webpack_require__("626a");
var toLength = __webpack_require__("9def");
module.exports = function (that, callbackfn, aLen, memo, isRight) {
aFunction(callbackfn);
var O = toObject(that);
var self = IObject(O);
var length = toLength(O.length);
var index = isRight ? length - 1 : 0;
var i = isRight ? -1 : 1;
if (aLen < 2) for (;;) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (isRight ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;isRight ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ }),
/***/ "7bbc":
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__("6821");
var gOPN = __webpack_require__("9093").f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/***/ "7cec":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageActions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("f86d");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageActions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageActions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "7d66":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsList_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("384a");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsList_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomsList_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "7ebf":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("13fc");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("30082ac4", content, shadowRoot)
};
/***/ }),
/***/ "7f20":
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__("86cc").f;
var has = __webpack_require__("69a8");
var TAG = __webpack_require__("2b4c")('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/***/ "7f7f":
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__("86cc").f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || __webpack_require__("9e1e") && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});
/***/ }),
/***/ "8079":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var macrotask = __webpack_require__("1991").set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__("2d95")(process) == 'process';
module.exports = function () {
var head, last, notify;
var flush = function () {
var parent, fn;
if (isNode && (parent = process.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (e) {
if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
if (parent) parent.enter();
};
// Node.js
if (isNode) {
notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
} else if (Observer && !(global.navigator && global.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
var promise = Promise.resolve(undefined);
notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
};
/***/ }),
/***/ "8220":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-fade-spinner-enter{opacity:0}.vac-fade-spinner-enter-active{transition:opacity .8s}.vac-fade-spinner-leave-active{transition:opacity .2s;opacity:0}.vac-fade-image-enter{opacity:0}.vac-fade-image-enter-active{transition:opacity 1s}.vac-fade-image-leave-active{transition:opacity .5s;opacity:0}.vac-fade-message-enter{opacity:0}.vac-fade-message-enter-active{transition:opacity .5s}.vac-fade-message-leave-active{transition:opacity .2s;opacity:0}.vac-slide-left-enter-active,.vac-slide-right-enter-active{transition:all .3s ease;transition-property:transform,opacity}.vac-slide-left-leave-active,.vac-slide-right-leave-active{transition:all .2s cubic-bezier(1,.5,.8,1);transition-property:transform,opacity}.vac-slide-left-enter,.vac-slide-left-leave-to{transform:translateX(10px);opacity:0}.vac-slide-right-enter,.vac-slide-right-leave-to{transform:translateX(-10px);opacity:0}.vac-slide-up-enter-active{transition:all .3s ease}.vac-slide-up-leave-active{transition:all .2s cubic-bezier(1,.5,.8,1)}.vac-slide-up-enter,.vac-slide-up-leave-to{transform:translateY(10px);opacity:0}.vac-bounce-enter-active{-webkit-animation:vac-bounce-in .5s;animation:vac-bounce-in .5s}.vac-bounce-leave-active{animation:vac-bounce-in .3s reverse}@-webkit-keyframes vac-bounce-in{0%{transform:scale(0)}50%{transform:scale(1.05)}to{transform:scale(1)}}@keyframes vac-bounce-in{0%{transform:scale(0)}50%{transform:scale(1.05)}to{transform:scale(1)}}.vac-menu-list{border-radius:4px;display:block;cursor:pointer;background:var(--chat-dropdown-bg-color);padding:6px 0}.vac-menu-list :hover{background:var(--chat-dropdown-bg-color-hover)}.vac-menu-list :hover,.vac-menu-list :not(:hover){transition:background-color .3s cubic-bezier(.25,.8,.5,1)}.vac-menu-item{align-items:center;display:flex;flex:1 1 100%;min-height:30px;padding:5px 16px;position:relative;white-space:nowrap;line-height:30px}.vac-menu-options{position:absolute;right:10px;top:20px;z-index:9999;min-width:150px;display:inline-block;border-radius:4px;font-size:14px;color:var(--chat-color);overflow-y:auto;overflow-x:hidden;contain:content;box-shadow:0 2px 2px -4px rgba(0,0,0,.1),0 2px 2px 1px rgba(0,0,0,.12),0 1px 8px 1px rgba(0,0,0,.12)}.vac-app-border{border:var(--chat-border-style)}.vac-app-border-t{border-top:var(--chat-border-style)}.vac-app-border-r{border-right:var(--chat-border-style)}.vac-app-border-b{border-bottom:var(--chat-border-style)}.vac-app-box-shadow{box-shadow:0 2px 2px -4px rgba(0,0,0,.1),0 2px 2px 1px rgba(0,0,0,.12),0 1px 8px 1px rgba(0,0,0,.12)}.vac-item-clickable{cursor:pointer}.vac-vertical-center{display:flex;align-items:center;height:100%}.vac-vertical-center .vac-vertical-container{width:100%;text-align:center}.vac-svg-button{max-height:30px;display:flex;cursor:pointer;transition:all .2s}.vac-svg-button:hover{transform:scale(1.1);opacity:.7}.vac-avatar{background-size:cover;background-position:50%;background-repeat:no-repeat;background-color:#ddd;height:42px;width:42px;min-height:42px;min-width:42px;margin-right:15px;border-radius:50%}.vac-badge-counter{height:13px;width:auto;min-width:13px;border-radius:50%;display:flex;align-items:center;justify-content:center;padding:3px;font-size:11px;font-weight:500}.vac-text-ellipsis{width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vac-text-bold{font-weight:700}.vac-text-italic{font-style:italic}.vac-text-strike{text-decoration:line-through}.vac-text-underline{text-decoration:underline}.vac-text-inline-code{display:inline-block;color:var(--chat-markdown-color);margin:2px 0;padding:2px 3px}.vac-text-inline-code,.vac-text-multiline-code{font-size:12px;background:var(--chat-markdown-bg);border:1px solid var(--chat-markdown-border);border-radius:3px}.vac-text-multiline-code{display:block;color:var(--chat-markdown-color-multi);margin:4px 0;padding:7px}.vac-text-tag{color:var(--chat-message-color-tag);cursor:pointer}.vac-card-window{width:100%;display:block;max-width:100%;background:var(--chat-content-bg-color);color:var(--chat-color);overflow-wrap:break-word;position:relative;white-space:normal;border:var(--chat-container-border);border-radius:var(--chat-container-border-radius);box-shadow:var(--chat-container-box-shadow);-webkit-tap-highlight-color:transparent}.vac-card-window *{font-family:inherit}.vac-card-window a{color:#0d579c;font-weight:500}.vac-card-window .vac-chat-container{height:100%;display:flex}.vac-card-window .vac-chat-container input{min-width:10px}.vac-card-window .vac-chat-container input[type=search],.vac-card-window .vac-chat-container input[type=text],.vac-card-window .vac-chat-container textarea{-webkit-appearance:none}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "8378":
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.12' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/***/ "83a1":
/***/ (function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ }),
/***/ "83f9":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("8220");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("23c30434", content, shadowRoot)
};
/***/ }),
/***/ "84f2":
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/***/ "86cc":
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__("cb7c");
var IE8_DOM_DEFINE = __webpack_require__("c69a");
var toPrimitive = __webpack_require__("6a99");
var dP = Object.defineProperty;
exports.f = __webpack_require__("9e1e") ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/***/ "8875":
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// addapted from the document.currentScript polyfill by Adam Miller
// MIT license
// source: https://github.com/amiller-gh/currentScript-polyfill
// added support for Firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1620505
(function (root, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(typeof self !== 'undefined' ? self : this, function () {
function getCurrentScript () {
var descriptor = Object.getOwnPropertyDescriptor(document, 'currentScript')
// for chrome
if (!descriptor && 'currentScript' in document && document.currentScript) {
return document.currentScript
}
// for other browsers with native support for currentScript
if (descriptor && descriptor.get !== getCurrentScript && document.currentScript) {
return document.currentScript
}
// IE 8-10 support script readyState
// IE 11+ & Firefox support stack trace
try {
throw new Error();
}
catch (err) {
// Find the second match for the "at" string to get file src url from stack.
var ieStackRegExp = /.*at [^(]*\((.*):(.+):(.+)\)$/ig,
ffStackRegExp = /@([^@]*):(\d+):(\d+)\s*$/ig,
stackDetails = ieStackRegExp.exec(err.stack) || ffStackRegExp.exec(err.stack),
scriptLocation = (stackDetails && stackDetails[1]) || false,
line = (stackDetails && stackDetails[2]) || false,
currentLocation = document.location.href.replace(document.location.hash, ''),
pageSource,
inlineScriptSourceRegExp,
inlineScriptSource,
scripts = document.getElementsByTagName('script'); // Live NodeList collection
if (scriptLocation === currentLocation) {
pageSource = document.documentElement.outerHTML;
inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
}
for (var i = 0; i < scripts.length; i++) {
// If ready state is interactive, return the script tag
if (scripts[i].readyState === 'interactive') {
return scripts[i];
}
// If src matches, return the script tag
if (scripts[i].src === scriptLocation) {
return scripts[i];
}
// If inline source matches, return the script tag
if (
scriptLocation === currentLocation &&
scripts[i].innerHTML &&
scripts[i].innerHTML.trim() === inlineScriptSource
) {
return scripts[i];
}
}
// If no match, return null
return null;
}
};
return getCurrentScript
}));
/***/ }),
/***/ "88f6":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-room-container{display:flex;flex:1;align-items:center;width:100%}.vac-room-container .vac-name-container{flex:1}.vac-room-container .vac-title-container{display:flex;align-items:center;line-height:25px}.vac-room-container .vac-state-circle{width:9px;height:9px;border-radius:50%;background-color:var(--chat-room-color-offline);margin-right:6px;transition:.3s}.vac-room-container .vac-state-online{background-color:var(--chat-room-color-online)}.vac-room-container .vac-room-name{flex:1;color:var(--chat-room-color-username);font-weight:500}.vac-room-container .vac-text-date{margin-left:5px;font-size:11px;color:var(--chat-room-color-timestamp)}.vac-room-container .vac-text-last{display:flex;align-items:center;font-size:12px;line-height:19px;color:var(--chat-room-color-message)}.vac-room-container .vac-message-new{color:var(--chat-room-color-username);font-weight:500}.vac-room-container .vac-icon-check{display:flex;vertical-align:middle;height:14px;width:14px;margin-top:-2px;margin-right:2px}.vac-room-container .vac-icon-microphone{height:15px;width:15px;vertical-align:middle;margin:-3px 1px 0 -2px;fill:var(--chat-room-color-message)}.vac-room-container .vac-room-options-container{display:flex;margin-left:auto}.vac-room-container .vac-room-badge{background-color:var(--chat-room-bg-color-badge);color:var(--chat-room-color-badge);margin-left:5px}.vac-room-container .vac-list-room-options{height:19px;width:19px;align-items:center;margin-left:5px}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "8a81":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__("7726");
var has = __webpack_require__("69a8");
var DESCRIPTORS = __webpack_require__("9e1e");
var $export = __webpack_require__("5ca1");
var redefine = __webpack_require__("2aba");
var META = __webpack_require__("67ab").KEY;
var $fails = __webpack_require__("79e5");
var shared = __webpack_require__("5537");
var setToStringTag = __webpack_require__("7f20");
var uid = __webpack_require__("ca5a");
var wks = __webpack_require__("2b4c");
var wksExt = __webpack_require__("37c8");
var wksDefine = __webpack_require__("3a72");
var enumKeys = __webpack_require__("d4c0");
var isArray = __webpack_require__("1169");
var anObject = __webpack_require__("cb7c");
var isObject = __webpack_require__("d3f4");
var toObject = __webpack_require__("4bf8");
var toIObject = __webpack_require__("6821");
var toPrimitive = __webpack_require__("6a99");
var createDesc = __webpack_require__("4630");
var _create = __webpack_require__("2aeb");
var gOPNExt = __webpack_require__("7bbc");
var $GOPD = __webpack_require__("11e9");
var $GOPS = __webpack_require__("2621");
var $DP = __webpack_require__("86cc");
var $keys = __webpack_require__("0d58");
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__("9093").f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__("52a7").f = $propertyIsEnumerable;
$GOPS.f = $getOwnPropertySymbols;
if (DESCRIPTORS && !__webpack_require__("2d00")) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });
$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return $GOPS.f(toObject(it));
}
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__("32e9")($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/***/ "8b97":
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__("d3f4");
var anObject = __webpack_require__("cb7c");
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = __webpack_require__("9b43")(Function.call, __webpack_require__("11e9").f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/***/ "8bbf":
/***/ (function(module, exports) {
module.exports = Vue;
/***/ }),
/***/ "8e6e":
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__("5ca1");
var ownKeys = __webpack_require__("990b");
var toIObject = __webpack_require__("6821");
var gOPD = __webpack_require__("11e9");
var createProperty = __webpack_require__("f1ae");
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIObject(object);
var getDesc = gOPD.f;
var keys = ownKeys(O);
var result = {};
var i = 0;
var key, desc;
while (keys.length > i) {
desc = getDesc(O, key = keys[i++]);
if (desc !== undefined) createProperty(result, key, desc);
}
return result;
}
});
/***/ }),
/***/ "8ea5":
/***/ (function(module, exports, __webpack_require__) {
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__("5ca1");
var toISOString = __webpack_require__("8ed0");
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', {
toISOString: toISOString
});
/***/ }),
/***/ "8ed0":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var fails = __webpack_require__("79e5");
var getTime = Date.prototype.getTime;
var $toISOString = Date.prototype.toISOString;
var lz = function (num) {
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
module.exports = (fails(function () {
return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
}) || !fails(function () {
$toISOString.call(new Date(NaN));
})) ? function toISOString() {
if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
var d = this;
var y = d.getUTCFullYear();
var m = d.getUTCMilliseconds();
var s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
} : $toISOString;
/***/ }),
/***/ "9093":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__("ce10");
var hiddenKeys = __webpack_require__("e11e").concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/***/ "96cf":
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
true ? module.exports : undefined
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
/***/ }),
/***/ "9745":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("b92f");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("4aceb9cc", content, shadowRoot)
};
/***/ }),
/***/ "9865":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var toIObject = __webpack_require__("6821");
var toInteger = __webpack_require__("4588");
var toLength = __webpack_require__("9def");
var $native = [].lastIndexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__("2f21")($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;
var O = toIObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;
return -1;
}
});
/***/ }),
/***/ "98c5":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("e4dc");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("f6e9c3e2", content, shadowRoot)
};
/***/ }),
/***/ "990b":
/***/ (function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__("9093");
var gOPS = __webpack_require__("2621");
var anObject = __webpack_require__("cb7c");
var Reflect = __webpack_require__("7726").Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
var keys = gOPN.f(anObject(it));
var getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ }),
/***/ "9926":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("3039");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("210280e9", content, shadowRoot)
};
/***/ }),
/***/ "9986":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__("6821");
var $getOwnPropertyDescriptor = __webpack_require__("11e9").f;
__webpack_require__("5eda")('getOwnPropertyDescriptor', function () {
return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ }),
/***/ "9b43":
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__("d8e8");
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ "9c6c":
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__("2b4c")('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__("32e9")(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ }),
/***/ "9c80":
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
/***/ }),
/***/ "9def":
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__("4588");
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/***/ "9e1e":
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__("79e5")(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "a071":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Loader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("3fee");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Loader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Loader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "a25f":
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__("7726");
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
/***/ }),
/***/ "a481":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__("cb7c");
var toObject = __webpack_require__("4bf8");
var toLength = __webpack_require__("9def");
var toInteger = __webpack_require__("4588");
var advanceStringIndex = __webpack_require__("0390");
var regExpExec = __webpack_require__("5f1b");
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
var SUBSTITUTION_SYMBOLS = /\$([$&`']|\d\d?|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&`']|\d\d?)/g;
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// @@replace logic
__webpack_require__("214f")('replace', 2, function (defined, REPLACE, $replace, maybeCallNative) {
return [
// `String.prototype.replace` method
// https://tc39.github.io/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
function (regexp, replaceValue) {
var res = maybeCallNative($replace, regexp, this, replaceValue);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regExpExec(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max(min(toInteger(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
// https://tc39.github.io/ecma262/#sec-getsubstitution
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return $replace.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
}
});
/***/ }),
/***/ "a589":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ChatWindow_vue_vue_type_style_index_0_lang_scss_shadow__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("83f9");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ChatWindow_vue_vue_type_style_index_0_lang_scss_shadow__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ChatWindow_vue_vue_type_style_index_0_lang_scss_shadow__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ChatWindow_vue_vue_type_style_index_0_lang_scss_shadow__WEBPACK_IMPORTED_MODULE_0__) if(["default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ChatWindow_vue_vue_type_style_index_0_lang_scss_shadow__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/***/ }),
/***/ "a5b8":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__("d8e8");
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
/***/ }),
/***/ "a6d4":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Room_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("0b68");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Room_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Room_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "a916":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("6dc2");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReply_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "aa77":
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__("5ca1");
var defined = __webpack_require__("be13");
var fails = __webpack_require__("79e5");
var spaces = __webpack_require__("fdef");
var space = '[' + spaces + ']';
var non = '\u200b\u0085';
var ltrim = RegExp('^' + space + space + '*');
var rtrim = RegExp(space + space + '*$');
var exporter = function (KEY, exec, ALIAS) {
var exp = {};
var FORCE = fails(function () {
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if (ALIAS) exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function (string, TYPE) {
string = String(defined(string));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ }),
/***/ "aae3":
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__("d3f4");
var cof = __webpack_require__("2d95");
var MATCH = __webpack_require__("2b4c")('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ }),
/***/ "ac6a":
/***/ (function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__("cadf");
var getKeys = __webpack_require__("0d58");
var redefine = __webpack_require__("2aba");
var global = __webpack_require__("7726");
var hide = __webpack_require__("32e9");
var Iterators = __webpack_require__("84f2");
var wks = __webpack_require__("2b4c");
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;
var DOMIterables = {
CSSRuleList: true, // TODO: Not spec compliant, should be false.
CSSStyleDeclaration: false,
CSSValueList: false,
ClientRectList: false,
DOMRectList: false,
DOMStringList: false,
DOMTokenList: true,
DataTransferItemList: false,
FileList: false,
HTMLAllCollection: false,
HTMLCollection: false,
HTMLFormElement: false,
HTMLSelectElement: false,
MediaList: true, // TODO: Not spec compliant, should be false.
MimeTypeArray: false,
NamedNodeMap: false,
NodeList: true,
PaintRequestList: false,
Plugin: false,
PluginArray: false,
SVGLengthList: false,
SVGNumberList: false,
SVGPathSegList: false,
SVGPointList: false,
SVGStringList: false,
SVGTransformList: false,
SourceBufferList: false,
StyleSheetList: true, // TODO: Not spec compliant, should be false.
TextTrackCueList: false,
TextTrackList: false,
TouchList: false
};
for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
var NAME = collections[i];
var explicit = DOMIterables[NAME];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
var key;
if (proto) {
if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
/***/ }),
/***/ "b05c":
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__("ec30")('Int8', 1, function (init) {
return function Int8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/***/ "b0c5":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpExec = __webpack_require__("520a");
__webpack_require__("5ca1")({
target: 'RegExp',
proto: true,
forced: regexpExec !== /./.exec
}, {
exec: regexpExec
});
/***/ }),
/***/ "b467":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-room-header{position:absolute;display:flex;align-items:center;height:64px;width:100%;z-index:10;margin-right:1px;background:var(--chat-header-bg-color);border-top-right-radius:var(--chat-container-border-radius)}.vac-room-header .vac-room-wrapper{display:flex;align-items:center;min-width:0;height:100%;width:100%;padding:0 16px}.vac-room-header .vac-toggle-button{margin-right:15px}.vac-room-header .vac-toggle-button svg{height:26px;width:26px}.vac-room-header .vac-rotate-icon{transform:rotate(180deg)!important}.vac-room-header .vac-info-wrapper{display:flex;align-items:center;min-width:0;width:100%;height:100%}.vac-room-header .vac-room-name{font-size:17px;font-weight:500;line-height:22px;color:var(--chat-header-color-name)}.vac-room-header .vac-room-info{font-size:13px;line-height:18px;color:var(--chat-header-color-info)}.vac-room-header .vac-room-options{margin-left:auto}@media only screen and (max-width:768px){.vac-room-header{height:50px}.vac-room-header .vac-room-wrapper{padding:0 10px}.vac-room-header .vac-room-name{font-size:16px;line-height:22px}.vac-room-header .vac-room-info{font-size:12px;line-height:16px}.vac-room-header .vac-avatar{height:37px;width:37px;min-height:37px;min-width:37px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "b7fe":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.start = exports.run = exports.TOKENS = exports.State = undefined;
var _state = __webpack_require__("1652");
var _text = __webpack_require__("7656");
var TOKENS = _interopRequireWildcard(_text);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var tlds = 'aaa|aarp|abarth|abb|abbott|abbvie|abc|able|abogado|abudhabi|ac|academy|accenture|accountant|accountants|aco|active|actor|ad|adac|ads|adult|ae|aeg|aero|aetna|af|afamilycompany|afl|africa|ag|agakhan|agency|ai|aig|aigo|airbus|airforce|airtel|akdn|al|alfaromeo|alibaba|alipay|allfinanz|allstate|ally|alsace|alstom|am|americanexpress|americanfamily|amex|amfam|amica|amsterdam|analytics|android|anquan|anz|ao|aol|apartments|app|apple|aq|aquarelle|ar|arab|aramco|archi|army|arpa|art|arte|as|asda|asia|associates|at|athleta|attorney|au|auction|audi|audible|audio|auspost|author|auto|autos|avianca|aw|aws|ax|axa|az|azure|ba|baby|baidu|banamex|bananarepublic|band|bank|bar|barcelona|barclaycard|barclays|barefoot|bargains|baseball|basketball|bauhaus|bayern|bb|bbc|bbt|bbva|bcg|bcn|bd|be|beats|beauty|beer|bentley|berlin|best|bestbuy|bet|bf|bg|bh|bharti|bi|bible|bid|bike|bing|bingo|bio|biz|bj|black|blackfriday|blanco|blockbuster|blog|bloomberg|blue|bm|bms|bmw|bn|bnl|bnpparibas|bo|boats|boehringer|bofa|bom|bond|boo|book|booking|boots|bosch|bostik|boston|bot|boutique|box|br|bradesco|bridgestone|broadway|broker|brother|brussels|bs|bt|budapest|bugatti|build|builders|business|buy|buzz|bv|bw|by|bz|bzh|ca|cab|cafe|cal|call|calvinklein|cam|camera|camp|cancerresearch|canon|capetown|capital|capitalone|car|caravan|cards|care|career|careers|cars|cartier|casa|case|caseih|cash|casino|cat|catering|catholic|cba|cbn|cbre|cbs|cc|cd|ceb|center|ceo|cern|cf|cfa|cfd|cg|ch|chanel|channel|chase|chat|cheap|chintai|chloe|christmas|chrome|chrysler|church|ci|cipriani|circle|cisco|citadel|citi|citic|city|cityeats|ck|cl|claims|cleaning|click|clinic|clinique|clothing|cloud|club|clubmed|cm|cn|co|coach|codes|coffee|college|cologne|com|comcast|commbank|community|company|compare|computer|comsec|condos|construction|consulting|contact|contractors|cooking|cookingchannel|cool|coop|corsica|country|coupon|coupons|courses|cr|credit|creditcard|creditunion|cricket|crown|crs|cruise|cruises|csc|cu|cuisinella|cv|cw|cx|cy|cymru|cyou|cz|dabur|dad|dance|data|date|dating|datsun|day|dclk|dds|de|deal|dealer|deals|degree|delivery|dell|deloitte|delta|democrat|dental|dentist|desi|design|dev|dhl|diamonds|diet|digital|direct|directory|discount|discover|dish|diy|dj|dk|dm|dnp|do|docs|doctor|dodge|dog|doha|domains|dot|download|drive|dtv|dubai|duck|dunlop|duns|dupont|durban|dvag|dvr|dz|earth|eat|ec|eco|edeka|edu|education|ee|eg|email|emerck|energy|engineer|engineering|enterprises|epost|epson|equipment|er|ericsson|erni|es|esq|estate|esurance|et|etisalat|eu|eurovision|eus|events|everbank|exchange|expert|exposed|express|extraspace|fage|fail|fairwinds|faith|family|fan|fans|farm|farmers|fashion|fast|fedex|feedback|ferrari|ferrero|fi|fiat|fidelity|fido|film|final|finance|financial|fire|firestone|firmdale|fish|fishing|fit|fitness|fj|fk|flickr|flights|flir|florist|flowers|fly|fm|fo|foo|food|foodnetwork|football|ford|forex|forsale|forum|foundation|fox|fr|free|fresenius|frl|frogans|frontdoor|frontier|ftr|fujitsu|fujixerox|fun|fund|furniture|futbol|fyi|ga|gal|gallery|gallo|gallup|game|games|gap|garden|gb|gbiz|gd|gdn|ge|gea|gent|genting|george|gf|gg|ggee|gh|gi|gift|gifts|gives|giving|gl|glade|glass|gle|global|globo|gm|gmail|gmbh|gmo|gmx|gn|godaddy|gold|goldpoint|golf|goo|goodhands|goodyear|goog|google|gop|got|gov|gp|gq|gr|grainger|graphics|gratis|green|gripe|grocery|group|gs|gt|gu|guardian|gucci|guge|guide|guitars|guru|gw|gy|hair|hamburg|hangout|haus|hbo|hdfc|hdfcbank|health|healthcare|help|helsinki|here|hermes|hgtv|hiphop|hisamitsu|hitachi|hiv|hk|hkt|hm|hn|hockey|holdings|holiday|homedepot|homegoods|homes|homesense|honda|honeywell|horse|hospital|host|hosting|hot|hoteles|hotels|hotmail|house|how|hr|hsbc|ht|htc|hu|hughes|hyatt|hyundai|ibm|icbc|ice|icu|id|ie|ieee|ifm|ikano|il|im|imamat|imdb|immo|immobilien|in|industries|infiniti|info|ing|ink|institute|insurance|insure|int|intel|international|intuit|investments|io|ipiranga|iq|ir|irish|is|iselect|ismaili|ist|istanbul|it|itau|itv|iveco|iwc|jaguar|java|jcb|jcp|je|jeep|jetzt|jewelry|jio|jlc|jll|jm|jmp|jnj|jo|jobs|joburg|jot|joy|jp|jpmorgan|jprs|juegos|juniper|kaufen|kddi|ke|kerryhotels|kerrylogistics|kerryproperties|kfh|kg|kh|ki|kia|kim|kinder|kindle|kitchen|kiwi|km|kn|koeln|komatsu|kosher|kp|kpmg|kpn|kr|krd|kred|kuokgroup|kw|ky|kyoto|kz|la|lacaixa|ladbrokes|lamborghini|lamer|lancaster|lancia|lancome|land|landrover|lanxess|lasalle|lat|latino|latrobe|law|lawyer|lb|lc|lds|lease|leclerc|lefrak|legal|lego|lexus|lgbt|li|liaison|lidl|life|lifeinsurance|lifestyle|lighting|like|lilly|limited|limo|lincoln|linde|link|lipsy|live|living|lixil|lk|loan|loans|locker|locus|loft|lol|london|lotte|lotto|love|lpl|lplfinancial|lr|ls|lt|ltd|ltda|lu|lundbeck|lupin|luxe|luxury|lv|ly|ma|macys|madrid|maif|maison|makeup|man|management|mango|map|market|marketing|markets|marriott|marshalls|maserati|mattel|mba|mc|mckinsey|md|me|med|media|meet|melbourne|meme|memorial|men|menu|meo|merckmsd|metlife|mg|mh|miami|microsoft|mil|mini|mint|mit|mitsubishi|mk|ml|mlb|mls|mm|mma|mn|mo|mobi|mobile|mobily|moda|moe|moi|mom|monash|money|monster|mopar|mormon|mortgage|moscow|moto|motorcycles|mov|movie|movistar|mp|mq|mr|ms|msd|mt|mtn|mtr|mu|museum|mutual|mv|mw|mx|my|mz|na|nab|nadex|nagoya|name|nationwide|natura|navy|nba|nc|ne|nec|net|netbank|netflix|network|neustar|new|newholland|news|next|nextdirect|nexus|nf|nfl|ng|ngo|nhk|ni|nico|nike|nikon|ninja|nissan|nissay|nl|no|nokia|northwesternmutual|norton|now|nowruz|nowtv|np|nr|nra|nrw|ntt|nu|nyc|nz|obi|observer|off|office|okinawa|olayan|olayangroup|oldnavy|ollo|om|omega|one|ong|onl|online|onyourside|ooo|open|oracle|orange|org|organic|origins|osaka|otsuka|ott|ovh|pa|page|panasonic|panerai|paris|pars|partners|parts|party|passagens|pay|pccw|pe|pet|pf|pfizer|pg|ph|pharmacy|phd|philips|phone|photo|photography|photos|physio|piaget|pics|pictet|pictures|pid|pin|ping|pink|pioneer|pizza|pk|pl|place|play|playstation|plumbing|plus|pm|pn|pnc|pohl|poker|politie|porn|post|pr|pramerica|praxi|press|prime|pro|prod|productions|prof|progressive|promo|properties|property|protection|pru|prudential|ps|pt|pub|pw|pwc|py|qa|qpon|quebec|quest|qvc|racing|radio|raid|re|read|realestate|realtor|realty|recipes|red|redstone|redumbrella|rehab|reise|reisen|reit|reliance|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rexroth|rich|richardli|ricoh|rightathome|ril|rio|rip|rmit|ro|rocher|rocks|rodeo|rogers|room|rs|rsvp|ru|rugby|ruhr|run|rw|rwe|ryukyu|sa|saarland|safe|safety|sakura|sale|salon|samsclub|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|sas|save|saxo|sb|sbi|sbs|sc|sca|scb|schaeffler|schmidt|scholarships|school|schule|schwarz|science|scjohnson|scor|scot|sd|se|search|seat|secure|security|seek|select|sener|services|ses|seven|sew|sex|sexy|sfr|sg|sh|shangrila|sharp|shaw|shell|shia|shiksha|shoes|shop|shopping|shouji|show|showtime|shriram|si|silk|sina|singles|site|sj|sk|ski|skin|sky|skype|sl|sling|sm|smart|smile|sn|sncf|so|soccer|social|softbank|software|sohu|solar|solutions|song|sony|soy|space|spiegel|spot|spreadbetting|sr|srl|srt|st|stada|staples|star|starhub|statebank|statefarm|statoil|stc|stcgroup|stockholm|storage|store|stream|studio|study|style|su|sucks|supplies|supply|support|surf|surgery|suzuki|sv|swatch|swiftcover|swiss|sx|sy|sydney|symantec|systems|sz|tab|taipei|talk|taobao|target|tatamotors|tatar|tattoo|tax|taxi|tc|tci|td|tdk|team|tech|technology|tel|telecity|telefonica|temasek|tennis|teva|tf|tg|th|thd|theater|theatre|tiaa|tickets|tienda|tiffany|tips|tires|tirol|tj|tjmaxx|tjx|tk|tkmaxx|tl|tm|tmall|tn|to|today|tokyo|tools|top|toray|toshiba|total|tours|town|toyota|toys|tr|trade|trading|training|travel|travelchannel|travelers|travelersinsurance|trust|trv|tt|tube|tui|tunes|tushu|tv|tvs|tw|tz|ua|ubank|ubs|uconnect|ug|uk|unicom|university|uno|uol|ups|us|uy|uz|va|vacations|vana|vanguard|vc|ve|vegas|ventures|verisign|versicherung|vet|vg|vi|viajes|video|vig|viking|villas|vin|vip|virgin|visa|vision|vista|vistaprint|viva|vivo|vlaanderen|vn|vodka|volkswagen|volvo|vote|voting|voto|voyage|vu|vuelos|wales|walmart|walter|wang|wanggou|warman|watch|watches|weather|weatherchannel|webcam|weber|website|wed|wedding|weibo|weir|wf|whoswho|wien|wiki|williamhill|win|windows|wine|winners|wme|wolterskluwer|woodside|work|works|world|wow|ws|wtc|wtf|xbox|xerox|xfinity|xihuan|xin|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--30rr7y|xn--3bst00m|xn--3ds443g|xn--3e0b707e|xn--3hcrj9c|xn--3oq18vl8pn36a|xn--3pxu8k|xn--42c2d9a|xn--45br5cyl|xn--45brj9c|xn--45q11c|xn--4gbrim|xn--54b7fta0cc|xn--55qw42g|xn--55qx5d|xn--5su34j936bgsg|xn--5tzm5g|xn--6frz82g|xn--6qq986b3xl|xn--80adxhks|xn--80ao21a|xn--80aqecdr1a|xn--80asehdb|xn--80aswg|xn--8y0a063a|xn--90a3ac|xn--90ae|xn--90ais|xn--9dbq2a|xn--9et52u|xn--9krt00a|xn--b4w605ferd|xn--bck1b9a5dre4c|xn--c1avg|xn--c2br7g|xn--cck2b3b|xn--cg4bki|xn--clchc0ea0b2g2a9gcd|xn--czr694b|xn--czrs0t|xn--czru2d|xn--d1acj3b|xn--d1alf|xn--e1a4c|xn--eckvdtc9d|xn--efvy88h|xn--estv75g|xn--fct429k|xn--fhbei|xn--fiq228c5hs|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--fjq720a|xn--flw351e|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--fzys8d69uvgm|xn--g2xx48c|xn--gckr3f0f|xn--gecrj9c|xn--gk3at1e|xn--h2breg3eve|xn--h2brj9c|xn--h2brj9c8c|xn--hxt814e|xn--i1b6b1a6a2e|xn--imr513n|xn--io0a7i|xn--j1aef|xn--j1amh|xn--j6w193g|xn--jlq61u9w7b|xn--jvr189m|xn--kcrx77d1x4a|xn--kprw13d|xn--kpry57d|xn--kpu716f|xn--kput3i|xn--l1acc|xn--lgbbat1ad8j|xn--mgb9awbf|xn--mgba3a3ejt|xn--mgba3a4f16a|xn--mgba7c0bbn0a|xn--mgbaakc7dvf|xn--mgbaam7a8h|xn--mgbab2bd|xn--mgbai9azgqp6j|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a|xn--mgbbh1a71e|xn--mgbc0a9azcg|xn--mgbca7dzdo|xn--mgberp4a5d4ar|xn--mgbgu82a|xn--mgbi4ecexp|xn--mgbpl2fh|xn--mgbt3dhd|xn--mgbtx2b|xn--mgbx4cd0ab|xn--mix891f|xn--mk1bu44c|xn--mxtq1m|xn--ngbc5azd|xn--ngbe9e0a|xn--ngbrx|xn--node|xn--nqv7f|xn--nqv7fs00ema|xn--nyqy26a|xn--o3cw4h|xn--ogbpf8fl|xn--p1acf|xn--p1ai|xn--pbt977c|xn--pgbs0dh|xn--pssy2u|xn--q9jyb4c|xn--qcka1pmc|xn--qxam|xn--rhqv96g|xn--rovu88b|xn--rvc1e0am3e|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--tckwe|xn--tiq49xqyj|xn--unup4y|xn--vermgensberater-ctb|xn--vermgensberatung-pwb|xn--vhquv|xn--vuq861b|xn--w4r85el8fhu5dnra|xn--w4rs40l|xn--wgbh1c|xn--wgbl6a|xn--xhq521b|xn--xkc2al3hye2a|xn--xkc2dl3a5ee0h|xn--y9a3aq|xn--yfro4i67o|xn--ygbi2ammx|xn--zfr164b|xperia|xxx|xyz|yachts|yahoo|yamaxun|yandex|ye|yodobashi|yoga|yokohama|you|youtube|yt|yun|za|zappos|zara|zero|zip|zippo|zm|zone|zuerich|zw'.split('|'); // macro, see gulpfile.js
/**
The scanner provides an interface that takes a string of text as input, and
outputs an array of tokens instances that can be used for easy URL parsing.
@module linkify
@submodule scanner
@main scanner
*/
var NUMBERS = '0123456789'.split('');
var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
var WHITESPACE = [' ', '\f', '\r', '\t', '\v', '\xA0', '\u1680', '\u180E']; // excluding line breaks
var domainStates = []; // states that jump to DOMAIN on /[a-z0-9]/
var makeState = function makeState(tokenClass) {
return new _state.CharacterState(tokenClass);
};
// Frequently used states
var S_START = makeState();
var S_NUM = makeState(_text.NUM);
var S_DOMAIN = makeState(_text.DOMAIN);
var S_DOMAIN_HYPHEN = makeState(); // domain followed by 1 or more hyphen characters
var S_WS = makeState(_text.WS);
// States for special URL symbols
S_START.on('@', makeState(_text.AT)).on('.', makeState(_text.DOT)).on('+', makeState(_text.PLUS)).on('#', makeState(_text.POUND)).on('?', makeState(_text.QUERY)).on('/', makeState(_text.SLASH)).on('_', makeState(_text.UNDERSCORE)).on(':', makeState(_text.COLON)).on('{', makeState(_text.OPENBRACE)).on('[', makeState(_text.OPENBRACKET)).on('<', makeState(_text.OPENANGLEBRACKET)).on('(', makeState(_text.OPENPAREN)).on('}', makeState(_text.CLOSEBRACE)).on(']', makeState(_text.CLOSEBRACKET)).on('>', makeState(_text.CLOSEANGLEBRACKET)).on(')', makeState(_text.CLOSEPAREN)).on('&', makeState(_text.AMPERSAND)).on([',', ';', '!', '"', '\''], makeState(_text.PUNCTUATION));
// Whitespace jumps
// Tokens of only non-newline whitespace are arbitrarily long
S_START.on('\n', makeState(_text.NL)).on(WHITESPACE, S_WS);
// If any whitespace except newline, more whitespace!
S_WS.on(WHITESPACE, S_WS);
// Generates states for top-level domains
// Note that this is most accurate when tlds are in alphabetical order
for (var i = 0; i < tlds.length; i++) {
var newStates = (0, _state.stateify)(tlds[i], S_START, _text.TLD, _text.DOMAIN);
domainStates.push.apply(domainStates, newStates);
}
// Collect the states generated by different protocls
var partialProtocolFileStates = (0, _state.stateify)('file', S_START, _text.DOMAIN, _text.DOMAIN);
var partialProtocolFtpStates = (0, _state.stateify)('ftp', S_START, _text.DOMAIN, _text.DOMAIN);
var partialProtocolHttpStates = (0, _state.stateify)('http', S_START, _text.DOMAIN, _text.DOMAIN);
var partialProtocolMailtoStates = (0, _state.stateify)('mailto', S_START, _text.DOMAIN, _text.DOMAIN);
// Add the states to the array of DOMAINeric states
domainStates.push.apply(domainStates, partialProtocolFileStates);
domainStates.push.apply(domainStates, partialProtocolFtpStates);
domainStates.push.apply(domainStates, partialProtocolHttpStates);
domainStates.push.apply(domainStates, partialProtocolMailtoStates);
// Protocol states
var S_PROTOCOL_FILE = partialProtocolFileStates.pop();
var S_PROTOCOL_FTP = partialProtocolFtpStates.pop();
var S_PROTOCOL_HTTP = partialProtocolHttpStates.pop();
var S_MAILTO = partialProtocolMailtoStates.pop();
var S_PROTOCOL_SECURE = makeState(_text.DOMAIN);
var S_FULL_PROTOCOL = makeState(_text.PROTOCOL); // Full protocol ends with COLON
var S_FULL_MAILTO = makeState(_text.MAILTO); // Mailto ends with COLON
// Secure protocols (end with 's')
S_PROTOCOL_FTP.on('s', S_PROTOCOL_SECURE).on(':', S_FULL_PROTOCOL);
S_PROTOCOL_HTTP.on('s', S_PROTOCOL_SECURE).on(':', S_FULL_PROTOCOL);
domainStates.push(S_PROTOCOL_SECURE);
// Become protocol tokens after a COLON
S_PROTOCOL_FILE.on(':', S_FULL_PROTOCOL);
S_PROTOCOL_SECURE.on(':', S_FULL_PROTOCOL);
S_MAILTO.on(':', S_FULL_MAILTO);
// Localhost
var partialLocalhostStates = (0, _state.stateify)('localhost', S_START, _text.LOCALHOST, _text.DOMAIN);
domainStates.push.apply(domainStates, partialLocalhostStates);
// Everything else
// DOMAINs make more DOMAINs
// Number and character transitions
S_START.on(NUMBERS, S_NUM);
S_NUM.on('-', S_DOMAIN_HYPHEN).on(NUMBERS, S_NUM).on(ALPHANUM, S_DOMAIN); // number becomes DOMAIN
S_DOMAIN.on('-', S_DOMAIN_HYPHEN).on(ALPHANUM, S_DOMAIN);
// All the generated states should have a jump to DOMAIN
for (var _i = 0; _i < domainStates.length; _i++) {
domainStates[_i].on('-', S_DOMAIN_HYPHEN).on(ALPHANUM, S_DOMAIN);
}
S_DOMAIN_HYPHEN.on('-', S_DOMAIN_HYPHEN).on(NUMBERS, S_DOMAIN).on(ALPHANUM, S_DOMAIN);
// Set default transition
S_START.defaultTransition = makeState(_text.SYM);
/**
Given a string, returns an array of TOKEN instances representing the
composition of that string.
@method run
@param {String} str Input string to scan
@return {Array} Array of TOKEN instances
*/
var run = function run(str) {
// The state machine only looks at lowercase strings.
// This selective `toLowerCase` is used because lowercasing the entire
// string causes the length and character position to vary in some in some
// non-English strings. This happens only on V8-based runtimes.
var lowerStr = str.replace(/[A-Z]/g, function (c) {
return c.toLowerCase();
});
var len = str.length;
var tokens = []; // return value
var cursor = 0;
// Tokenize the string
while (cursor < len) {
var state = S_START;
var nextState = null;
var tokenLength = 0;
var latestAccepting = null;
var sinceAccepts = -1;
while (cursor < len && (nextState = state.next(lowerStr[cursor]))) {
state = nextState;
// Keep track of the latest accepting state
if (state.accepts()) {
sinceAccepts = 0;
latestAccepting = state;
} else if (sinceAccepts >= 0) {
sinceAccepts++;
}
tokenLength++;
cursor++;
}
if (sinceAccepts < 0) {
continue;
} // Should never happen
// Roll back to the latest accepting state
cursor -= sinceAccepts;
tokenLength -= sinceAccepts;
// Get the class for the new token
var TOKEN = latestAccepting.emit(); // Current token class
// No more jumps, just make a new token
tokens.push(new TOKEN(str.substr(cursor - tokenLength, tokenLength)));
}
return tokens;
};
var start = S_START;
exports.State = _state.CharacterState;
exports.TOKENS = TOKENS;
exports.run = run;
exports.start = start;
/***/ }),
/***/ "b92f":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-box-search{position:sticky;display:flex;align-items:center;height:64px;padding:0 15px}.vac-box-search .vac-icon-search{display:flex;position:absolute;left:30px}.vac-box-search .vac-icon-search svg{width:18px;height:18px}.vac-box-search .vac-input{height:38px;width:100%;background:var(--chat-bg-color-input);color:var(--chat-color);border-radius:4px;font-size:15px;outline:0;caret-color:var(--chat-color-caret);padding:10px 10px 10px 40px;border:1px solid var(--chat-sidemenu-border-color-search);border-radius:20px}.vac-box-search .vac-input::-moz-placeholder{color:var(--chat-color-placeholder)}.vac-box-search .vac-input:-ms-input-placeholder{color:var(--chat-color-placeholder)}.vac-box-search .vac-input::placeholder{color:var(--chat-color-placeholder)}.vac-box-search .vac-add-icon{margin-left:auto;padding-left:10px}@media only screen and (max-width:768px){.vac-box-search{height:58px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "ba92":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var toObject = __webpack_require__("4bf8");
var toAbsoluteIndex = __webpack_require__("77f1");
var toLength = __webpack_require__("9def");
module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
var O = toObject(this);
var len = toLength(O.length);
var to = toAbsoluteIndex(target, len);
var from = toAbsoluteIndex(start, len);
var end = arguments.length > 2 ? arguments[2] : undefined;
var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
var inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O) O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ }),
/***/ "bcaa":
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__("cb7c");
var isObject = __webpack_require__("d3f4");
var newPromiseCapability = __webpack_require__("a5b8");
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
/***/ }),
/***/ "bd43":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isImageFile", function() { return isImageFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isVideoFile", function() { return isVideoFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAudioFile", function() { return isAudioFile; });
/* harmony import */ var core_js_modules_es6_array_some_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("759f");
/* harmony import */ var core_js_modules_es6_array_some_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es6_array_some_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("2fdb");
/* harmony import */ var core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es6_string_includes_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("6762");
/* harmony import */ var core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es7_array_includes_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("c9d9");
function checkMediaType(types, file) {
if (!file || !file.type) return;
return types.some(function (t) {
return file.type.toLowerCase().includes(t);
});
}
function isImageFile(file) {
return checkMediaType(_constants__WEBPACK_IMPORTED_MODULE_3__[/* IMAGE_TYPES */ "b"], file);
}
function isVideoFile(file) {
return checkMediaType(_constants__WEBPACK_IMPORTED_MODULE_3__[/* VIDEO_TYPES */ "c"], file);
}
function isAudioFile(file) {
return checkMediaType(_constants__WEBPACK_IMPORTED_MODULE_3__[/* AUDIO_TYPES */ "a"], file);
}
/***/ }),
/***/ "be13":
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ "bea1":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.URL = exports.TEXT = exports.NL = exports.EMAIL = exports.MAILTOEMAIL = exports.Base = undefined;
var _createTokenClass = __webpack_require__("46f3");
var _class = __webpack_require__("254c");
var _text = __webpack_require__("7656");
/******************************************************************************
Multi-Tokens
Tokens composed of arrays of TextTokens
******************************************************************************/
// Is the given token a valid domain token?
// Should nums be included here?
function isDomainToken(token) {
return token instanceof _text.DOMAIN || token instanceof _text.TLD;
}
/**
Abstract class used for manufacturing tokens of text tokens. That is rather
than the value for a token being a small string of text, it's value an array
of text tokens.
Used for grouping together URLs, emails, hashtags, and other potential
creations.
@class MultiToken
@abstract
*/
var MultiToken = (0, _createTokenClass.createTokenClass)();
MultiToken.prototype = {
/**
String representing the type for this token
@property type
@default 'TOKEN'
*/
type: 'token',
/**
Is this multitoken a link?
@property isLink
@default false
*/
isLink: false,
/**
Return the string this token represents.
@method toString
@return {String}
*/
toString: function toString() {
var result = [];
for (var i = 0; i < this.v.length; i++) {
result.push(this.v[i].toString());
}
return result.join('');
},
/**
What should the value for this token be in the `href` HTML attribute?
Returns the `.toString` value by default.
@method toHref
@return {String}
*/
toHref: function toHref() {
return this.toString();
},
/**
Returns a hash of relevant values for this token, which includes keys
* type - Kind of token ('url', 'email', etc.)
* value - Original text
* href - The value that should be added to the anchor tag's href
attribute
@method toObject
@param {String} [protocol] `'http'` by default
@return {Object}
*/
toObject: function toObject() {
var protocol = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'http';
return {
type: this.type,
value: this.toString(),
href: this.toHref(protocol)
};
}
};
/**
Represents an arbitrarily mailto email address with the prefix included
@class MAILTO
@extends MultiToken
*/
var MAILTOEMAIL = (0, _class.inherits)(MultiToken, (0, _createTokenClass.createTokenClass)(), {
type: 'email',
isLink: true
});
/**
Represents a list of tokens making up a valid email address
@class EMAIL
@extends MultiToken
*/
var EMAIL = (0, _class.inherits)(MultiToken, (0, _createTokenClass.createTokenClass)(), {
type: 'email',
isLink: true,
toHref: function toHref() {
return 'mailto:' + this.toString();
}
});
/**
Represents some plain text
@class TEXT
@extends MultiToken
*/
var TEXT = (0, _class.inherits)(MultiToken, (0, _createTokenClass.createTokenClass)(), { type: 'text' });
/**
Multi-linebreak token - represents a line break
@class NL
@extends MultiToken
*/
var NL = (0, _class.inherits)(MultiToken, (0, _createTokenClass.createTokenClass)(), { type: 'nl' });
/**
Represents a list of tokens making up a valid URL
@class URL
@extends MultiToken
*/
var URL = (0, _class.inherits)(MultiToken, (0, _createTokenClass.createTokenClass)(), {
type: 'url',
isLink: true,
/**
Lowercases relevant parts of the domain and adds the protocol if
required. Note that this will not escape unsafe HTML characters in the
URL.
@method href
@param {String} protocol
@return {String}
*/
toHref: function toHref() {
var protocol = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'http';
var hasProtocol = false;
var hasSlashSlash = false;
var tokens = this.v;
var result = [];
var i = 0;
// Make the first part of the domain lowercase
// Lowercase protocol
while (tokens[i] instanceof _text.PROTOCOL) {
hasProtocol = true;
result.push(tokens[i].toString().toLowerCase());
i++;
}
// Skip slash-slash
while (tokens[i] instanceof _text.SLASH) {
hasSlashSlash = true;
result.push(tokens[i].toString());
i++;
}
// Lowercase all other characters in the domain
while (isDomainToken(tokens[i])) {
result.push(tokens[i].toString().toLowerCase());
i++;
}
// Leave all other characters as they were written
for (; i < tokens.length; i++) {
result.push(tokens[i].toString());
}
result = result.join('');
if (!(hasProtocol || hasSlashSlash)) {
result = protocol + '://' + result;
}
return result;
},
hasProtocol: function hasProtocol() {
return this.v[0] instanceof _text.PROTOCOL;
}
});
exports.Base = MultiToken;
exports.MAILTOEMAIL = MAILTOEMAIL;
exports.EMAIL = EMAIL;
exports.NL = NL;
exports.TEXT = TEXT;
exports.URL = URL;
/***/ }),
/***/ "c1c7":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("f139");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("27cd4e4b", content, shadowRoot)
};
/***/ }),
/***/ "c28b":
/***/ (function(module, exports, __webpack_require__) {
!function(e,n){ true?module.exports=n():undefined}(this,function(){var e="undefined"!=typeof window,n="undefined"!=typeof navigator,t=e&&("ontouchstart"in window||n&&navigator.msMaxTouchPoints>0)?["touchstart"]:["click"];function i(e){var n=e.event,t=e.handler;(0,e.middleware)(n)&&t(n)}function r(e,n){var r=function(e){var n="function"==typeof e;if(!n&&"object"!=typeof e)throw new Error("v-click-outside: Binding value must be a function or an object");return{handler:n?e:e.handler,middleware:e.middleware||function(e){return e},events:e.events||t,isActive:!(!1===e.isActive),detectIframe:!(!1===e.detectIframe)}}(n.value),d=r.handler,o=r.middleware,a=r.detectIframe;if(r.isActive){if(e["__v-click-outside"]=r.events.map(function(n){return{event:n,srcTarget:document.documentElement,handler:function(n){return function(e){var n=e.el,t=e.event,r=e.handler,d=e.middleware,o=t.path||t.composedPath&&t.composedPath();(o?o.indexOf(n)<0:!n.contains(t.target))&&i({event:t,handler:r,middleware:d})}({el:e,event:n,handler:d,middleware:o})}}}),a){var c={event:"blur",srcTarget:window,handler:function(n){return function(e){var n=e.el,t=e.event,r=e.handler,d=e.middleware;setTimeout(function(){var e=document.activeElement;e&&"IFRAME"===e.tagName&&!n.contains(e)&&i({event:t,handler:r,middleware:d})},0)}({el:e,event:n,handler:d,middleware:o})}};e["__v-click-outside"]=[].concat(e["__v-click-outside"],[c])}e["__v-click-outside"].forEach(function(n){var t=n.event,i=n.srcTarget,r=n.handler;return setTimeout(function(){e["__v-click-outside"]&&i.addEventListener(t,r,!1)},0)})}}function d(e){(e["__v-click-outside"]||[]).forEach(function(e){return e.srcTarget.removeEventListener(e.event,e.handler,!1)}),delete e["__v-click-outside"]}var o=e?{bind:r,update:function(e,n){var t=n.value,i=n.oldValue;JSON.stringify(t)!==JSON.stringify(i)&&(d(e),r(e,{value:t}))},unbind:d}:{};return{install:function(e){e.directive("click-outside",o)},directive:o}});
//# sourceMappingURL=v-click-outside.umd.js.map
/***/ }),
/***/ "c366":
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__("6821");
var toLength = __webpack_require__("9def");
var toAbsoluteIndex = __webpack_require__("77f1");
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/***/ "c3ec":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_FormatMessage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("c749");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_FormatMessage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_FormatMessage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "c48f":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageImage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("9926");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageImage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageImage_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "c5f6":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__("7726");
var has = __webpack_require__("69a8");
var cof = __webpack_require__("2d95");
var inheritIfRequired = __webpack_require__("5dbc");
var toPrimitive = __webpack_require__("6a99");
var fails = __webpack_require__("79e5");
var gOPN = __webpack_require__("9093").f;
var gOPD = __webpack_require__("11e9").f;
var dP = __webpack_require__("86cc").f;
var $trim = __webpack_require__("aa77").trim;
var NUMBER = 'Number';
var $Number = global[NUMBER];
var Base = $Number;
var proto = $Number.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_COF = cof(__webpack_require__("2aeb")(proto)) == NUMBER;
var TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
if (typeof it == 'string' && it.length > 2) {
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0);
var third, radix, maxCode;
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default: return +it;
}
for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) {
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) {
$Number = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for (var keys = __webpack_require__("9e1e") ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++) {
if (has(Base, key = keys[j]) && !has($Number, key)) {
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__("2aba")(global, NUMBER, $Number);
}
/***/ }),
/***/ "c69a":
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__("9e1e") && !__webpack_require__("79e5")(function () {
return Object.defineProperty(__webpack_require__("230e")('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/***/ "c735":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-loader-wrapper.vac-container-center{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);z-index:9}.vac-loader-wrapper.vac-container-top{padding:21px}.vac-loader-wrapper.vac-container-top #vac-circle{height:20px;width:20px}.vac-loader-wrapper #vac-circle{margin:auto;height:28px;width:28px;border:3px solid rgba(0,0,0,.25);border-top:3px var(--chat-color-spinner) solid;border-right:3px var(--chat-color-spinner) solid;border-bottom:3px var(--chat-color-spinner) solid;border-radius:50%;-webkit-animation:vac-spin 1s linear infinite;animation:vac-spin 1s linear infinite}@media only screen and (max-width:768px){.vac-loader-wrapper #vac-circle{height:24px;width:24px}.vac-loader-wrapper.vac-container-top{padding:18px}.vac-loader-wrapper.vac-container-top #vac-circle{height:16px;width:16px}}@-webkit-keyframes vac-spin{0%{transform:rotate(0deg)}to{transform:rotate(359deg)}}@keyframes vac-spin{0%{transform:rotate(0deg)}to{transform:rotate(359deg)}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "c749":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("22bf");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("5284f0fe", content, shadowRoot)
};
/***/ }),
/***/ "c9d9":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return IMAGE_TYPES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return VIDEO_TYPES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AUDIO_TYPES; });
var IMAGE_TYPES = ['png', 'jpg', 'jpeg', 'webp', 'svg', 'gif'];
var VIDEO_TYPES = ['mp4', 'video/ogg', 'webm', 'quicktime'];
var AUDIO_TYPES = ['mp3', 'audio/ogg', 'wav', 'mpeg'];
/***/ }),
/***/ "ca5a":
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/***/ "cadf":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__("9c6c");
var step = __webpack_require__("d53b");
var Iterators = __webpack_require__("84f2");
var toIObject = __webpack_require__("6821");
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__("01f9")(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/***/ "cb7c":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/***/ "cd1c":
/***/ (function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__("e853");
module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
/***/ }),
/***/ "ce10":
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__("69a8");
var toIObject = __webpack_require__("6821");
var arrayIndexOf = __webpack_require__("c366")(false);
var IE_PROTO = __webpack_require__("613b")('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/***/ "d25f":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $filter = __webpack_require__("0a49")(2);
$export($export.P + $export.F * !__webpack_require__("2f21")([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ }),
/***/ "d2c8":
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__("aae3");
var defined = __webpack_require__("be13");
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ }),
/***/ "d3f4":
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/***/ "d48d":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-wrapper{position:relative;display:flex}.vac-wrapper .vac-emoji-picker{position:absolute;z-index:9999;bottom:32px;right:10px;width:240px;overflow:scroll;padding:16px;box-sizing:border-box;border-radius:.5rem;background:var(--chat-emoji-bg-color);box-shadow:0 1px 2px -2px rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1),0 1px 2px 1px rgba(0,0,0,.1)}.vac-wrapper .vac-picker-reaction{position:fixed;top:auto;right:auto}.vac-wrapper .vac-emoji-picker__search{display:flex}.vac-wrapper .vac-emoji-picker__search>input{flex:1;border-radius:10rem;border:var(--chat-border-style);padding:5px 10px;outline:none;background:var(--chat-bg-color-input);color:var(--chat-color)}.vac-wrapper .vac-emoji-picker h5{margin:15px 0 8px;color:#b1b1b1;text-transform:uppercase;font-size:.8rem;cursor:default}.vac-wrapper .vac-emoji-picker .vac-emojis{display:flex;flex-wrap:wrap;justify-content:space-between}.vac-wrapper .vac-emoji-picker .vac-emojis:after{content:\"\";flex:auto}.vac-wrapper .vac-emoji-picker .vac-emojis span{padding:.2rem;cursor:pointer;border-radius:5px}.vac-wrapper .vac-emoji-picker .vac-emojis span:hover{background:var(--chat-sidemenu-bg-color-hover);cursor:pointer}.vac-wrapper .vac-emoji-reaction svg{height:19px;width:19px}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "d4c0":
/***/ (function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__("0d58");
var gOPS = __webpack_require__("2621");
var pIE = __webpack_require__("52a7");
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
/***/ }),
/***/ "d53b":
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/***/ "d62c":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("172b");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("3934ec4b", content, shadowRoot)
};
/***/ }),
/***/ "d8e8":
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/***/ "d92a":
/***/ (function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__("5ca1");
$export($export.P, 'Function', { bind: __webpack_require__("f0c1") });
/***/ }),
/***/ "db18":
/***/ (function(module, exports) {
if(typeof lamejs === 'undefined') {var e = new Error("Cannot find module 'lamejs'"); e.code = 'MODULE_NOT_FOUND'; throw e;}
module.exports = lamejs;
/***/ }),
/***/ "dcbc":
/***/ (function(module, exports, __webpack_require__) {
var redefine = __webpack_require__("2aba");
module.exports = function (target, src, safe) {
for (var key in src) redefine(target, key, src[key], safe);
return target;
};
/***/ }),
/***/ "e11e":
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/***/ "e166":
/***/ (function(module, exports, __webpack_require__) {
/*!
* vue-infinite-loading v2.4.5
* (c) 2016-2021 PeachScript
* MIT License
*/
!function(t,e){ true?module.exports=e():undefined}(this,(function(){return function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=9)}([function(t,e,n){var i=n(6);i.__esModule&&(i=i.default),"string"==typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);(0,n(3).default)("09280948",i,!0,{})},function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n=function(t,e){var n=t[1]||"",i=t[3];if(!i)return n;if(e&&"function"==typeof btoa){var r=(o=i,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */"),a=i.sources.map((function(t){return"/*# sourceURL="+i.sourceRoot+t+" */"}));return[n].concat(a).concat([r]).join("\n")}var o;return[n].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+n+"}":n})).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var i={},r=0;r<this.length;r++){var a=this[r][0];"number"==typeof a&&(i[a]=!0)}for(r=0;r<t.length;r++){var o=t[r];"number"==typeof o[0]&&i[o[0]]||(n&&!o[2]?o[2]=n:n&&(o[2]="("+o[2]+") and ("+n+")"),e.push(o))}},e}},function(t,e,n){var i=n(8);i.__esModule&&(i=i.default),"string"==typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);(0,n(3).default)("5f444915",i,!0,{})},function(t,e,n){"use strict";function i(t,e){for(var n=[],i={},r=0;r<e.length;r++){var a=e[r],o=a[0],s={id:t+":"+r,css:a[1],media:a[2],sourceMap:a[3]};i[o]?i[o].parts.push(s):n.push(i[o]={id:o,parts:[s]})}return n}n.r(e),n.d(e,"default",(function(){return f}));var r="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!r)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var a={},o=r&&(document.head||document.getElementsByTagName("head")[0]),s=null,l=0,d=!1,c=function(){},u=null,p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function f(t,e,n,r){d=n,u=r||{};var o=i(t,e);return b(o),function(e){for(var n=[],r=0;r<o.length;r++){var s=o[r];(l=a[s.id]).refs--,n.push(l)}e?b(o=i(t,e)):o=[];for(r=0;r<n.length;r++){var l;if(0===(l=n[r]).refs){for(var d=0;d<l.parts.length;d++)l.parts[d]();delete a[l.id]}}}}function b(t){for(var e=0;e<t.length;e++){var n=t[e],i=a[n.id];if(i){i.refs++;for(var r=0;r<i.parts.length;r++)i.parts[r](n.parts[r]);for(;r<n.parts.length;r++)i.parts.push(m(n.parts[r]));i.parts.length>n.parts.length&&(i.parts.length=n.parts.length)}else{var o=[];for(r=0;r<n.parts.length;r++)o.push(m(n.parts[r]));a[n.id]={id:n.id,refs:1,parts:o}}}}function h(){var t=document.createElement("style");return t.type="text/css",o.appendChild(t),t}function m(t){var e,n,i=document.querySelector('style[data-vue-ssr-id~="'+t.id+'"]');if(i){if(d)return c;i.parentNode.removeChild(i)}if(p){var r=l++;i=s||(s=h()),e=w.bind(null,i,r,!1),n=w.bind(null,i,r,!0)}else i=h(),e=x.bind(null,i),n=function(){i.parentNode.removeChild(i)};return e(t),function(i){if(i){if(i.css===t.css&&i.media===t.media&&i.sourceMap===t.sourceMap)return;e(t=i)}else n()}}var g,v=(g=[],function(t,e){return g[t]=e,g.filter(Boolean).join("\n")});function w(t,e,n,i){var r=n?"":i.css;if(t.styleSheet)t.styleSheet.cssText=v(e,r);else{var a=document.createTextNode(r),o=t.childNodes;o[e]&&t.removeChild(o[e]),o.length?t.insertBefore(a,o[e]):t.appendChild(a)}}function x(t,e){var n=e.css,i=e.media,r=e.sourceMap;if(i&&t.setAttribute("media",i),u.ssrId&&t.setAttribute("data-vue-ssr-id",e.id),r&&(n+="\n/*# sourceURL="+r.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}},function(t,e){function n(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?(t.exports=n=function(t){return typeof t},t.exports.default=t.exports,t.exports.__esModule=!0):(t.exports=n=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.default=t.exports,t.exports.__esModule=!0),n(e)}t.exports=n,t.exports.default=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";n.r(e);var i=n(0);for(var r in i)["default"].indexOf(r)<0&&function(t){n.d(e,t,(function(){return i[t]}))}(r)},function(t,e,n){(t.exports=n(1)(!1)).push([t.i,'.loading-wave-dots[data-v-46b20d22]{position:relative}.loading-wave-dots[data-v-46b20d22] .wave-item{position:absolute;top:50%;left:50%;display:inline-block;margin-top:-4px;width:8px;height:8px;border-radius:50%;-webkit-animation:loading-wave-dots-data-v-46b20d22 linear 2.8s infinite;animation:loading-wave-dots-data-v-46b20d22 linear 2.8s infinite}.loading-wave-dots[data-v-46b20d22] .wave-item:first-child{margin-left:-36px}.loading-wave-dots[data-v-46b20d22] .wave-item:nth-child(2){margin-left:-20px;-webkit-animation-delay:.14s;animation-delay:.14s}.loading-wave-dots[data-v-46b20d22] .wave-item:nth-child(3){margin-left:-4px;-webkit-animation-delay:.28s;animation-delay:.28s}.loading-wave-dots[data-v-46b20d22] .wave-item:nth-child(4){margin-left:12px;-webkit-animation-delay:.42s;animation-delay:.42s}.loading-wave-dots[data-v-46b20d22] .wave-item:last-child{margin-left:28px;-webkit-animation-delay:.56s;animation-delay:.56s}@-webkit-keyframes loading-wave-dots-data-v-46b20d22{0%{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}10%{-webkit-transform:translateY(-6px);transform:translateY(-6px);background:#999}20%{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}to{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}}@keyframes loading-wave-dots-data-v-46b20d22{0%{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}10%{-webkit-transform:translateY(-6px);transform:translateY(-6px);background:#999}20%{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}to{-webkit-transform:translateY(0);transform:translateY(0);background:#bbb}}.loading-circles[data-v-46b20d22] .circle-item{width:5px;height:5px;-webkit-animation:loading-circles-data-v-46b20d22 linear .75s infinite;animation:loading-circles-data-v-46b20d22 linear .75s infinite}.loading-circles[data-v-46b20d22] .circle-item:first-child{margin-top:-14.5px;margin-left:-2.5px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(2){margin-top:-11.26px;margin-left:6.26px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(3){margin-top:-2.5px;margin-left:9.5px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(4){margin-top:6.26px;margin-left:6.26px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(5){margin-top:9.5px;margin-left:-2.5px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(6){margin-top:6.26px;margin-left:-11.26px}.loading-circles[data-v-46b20d22] .circle-item:nth-child(7){margin-top:-2.5px;margin-left:-14.5px}.loading-circles[data-v-46b20d22] .circle-item:last-child{margin-top:-11.26px;margin-left:-11.26px}@-webkit-keyframes loading-circles-data-v-46b20d22{0%{background:#dfdfdf}90%{background:#505050}to{background:#dfdfdf}}@keyframes loading-circles-data-v-46b20d22{0%{background:#dfdfdf}90%{background:#505050}to{background:#dfdfdf}}.loading-bubbles[data-v-46b20d22] .bubble-item{background:#666;-webkit-animation:loading-bubbles-data-v-46b20d22 linear .75s infinite;animation:loading-bubbles-data-v-46b20d22 linear .75s infinite}.loading-bubbles[data-v-46b20d22] .bubble-item:first-child{margin-top:-12.5px;margin-left:-.5px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(2){margin-top:-9.26px;margin-left:8.26px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(3){margin-top:-.5px;margin-left:11.5px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(4){margin-top:8.26px;margin-left:8.26px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(5){margin-top:11.5px;margin-left:-.5px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(6){margin-top:8.26px;margin-left:-9.26px}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(7){margin-top:-.5px;margin-left:-12.5px}.loading-bubbles[data-v-46b20d22] .bubble-item:last-child{margin-top:-9.26px;margin-left:-9.26px}@-webkit-keyframes loading-bubbles-data-v-46b20d22{0%{width:1px;height:1px;box-shadow:0 0 0 3px #666}90%{width:1px;height:1px;box-shadow:0 0 0 0 #666}to{width:1px;height:1px;box-shadow:0 0 0 3px #666}}@keyframes loading-bubbles-data-v-46b20d22{0%{width:1px;height:1px;box-shadow:0 0 0 3px #666}90%{width:1px;height:1px;box-shadow:0 0 0 0 #666}to{width:1px;height:1px;box-shadow:0 0 0 3px #666}}.loading-default[data-v-46b20d22]{position:relative;border:1px solid #999;-webkit-animation:loading-rotating-data-v-46b20d22 ease 1.5s infinite;animation:loading-rotating-data-v-46b20d22 ease 1.5s infinite}.loading-default[data-v-46b20d22]:before{content:"";position:absolute;display:block;top:0;left:50%;margin-top:-3px;margin-left:-3px;width:6px;height:6px;background-color:#999;border-radius:50%}.loading-spiral[data-v-46b20d22]{border:2px solid #777;border-right-color:transparent;-webkit-animation:loading-rotating-data-v-46b20d22 linear .85s infinite;animation:loading-rotating-data-v-46b20d22 linear .85s infinite}@-webkit-keyframes loading-rotating-data-v-46b20d22{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes loading-rotating-data-v-46b20d22{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.loading-bubbles[data-v-46b20d22],.loading-circles[data-v-46b20d22]{position:relative}.loading-bubbles[data-v-46b20d22] .bubble-item,.loading-circles[data-v-46b20d22] .circle-item{position:absolute;top:50%;left:50%;display:inline-block;border-radius:50%}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(2),.loading-circles[data-v-46b20d22] .circle-item:nth-child(2){-webkit-animation-delay:93ms;animation-delay:93ms}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(3),.loading-circles[data-v-46b20d22] .circle-item:nth-child(3){-webkit-animation-delay:.186s;animation-delay:.186s}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(4),.loading-circles[data-v-46b20d22] .circle-item:nth-child(4){-webkit-animation-delay:.279s;animation-delay:.279s}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(5),.loading-circles[data-v-46b20d22] .circle-item:nth-child(5){-webkit-animation-delay:.372s;animation-delay:.372s}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(6),.loading-circles[data-v-46b20d22] .circle-item:nth-child(6){-webkit-animation-delay:.465s;animation-delay:.465s}.loading-bubbles[data-v-46b20d22] .bubble-item:nth-child(7),.loading-circles[data-v-46b20d22] .circle-item:nth-child(7){-webkit-animation-delay:.558s;animation-delay:.558s}.loading-bubbles[data-v-46b20d22] .bubble-item:last-child,.loading-circles[data-v-46b20d22] .circle-item:last-child{-webkit-animation-delay:.651s;animation-delay:.651s}',""])},function(t,e,n){"use strict";n.r(e);var i=n(2);for(var r in i)["default"].indexOf(r)<0&&function(t){n.d(e,t,(function(){return i[t]}))}(r)},function(t,e,n){(t.exports=n(1)(!1)).push([t.i,".infinite-loading-container[data-v-670d0042]{clear:both;text-align:center}.infinite-loading-container[data-v-670d0042] [class^=loading-]{display:inline-block;margin:5px 0;width:28px;height:28px;font-size:28px;line-height:28px;border-radius:50%}.btn-try-infinite[data-v-670d0042]{margin-top:5px;padding:5px 10px;color:#999;font-size:14px;line-height:1;background:transparent;border:1px solid #ccc;border-radius:3px;outline:none;cursor:pointer}.btn-try-infinite[data-v-670d0042]:not(:active):hover{opacity:.8}",""])},function(t,e,n){"use strict";n.r(e);var i={throttleLimit:50,loopCheckTimeout:1e3,loopCheckMaxCalls:10},r=function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){return t={passive:!0},!0}});window.addEventListener("testpassive",e,e),window.remove("testpassive",e,e)}catch(t){}return t}(),a={STATE_CHANGER:["emit `loaded` and `complete` event through component instance of `$refs` may cause error, so it will be deprecated soon, please use the `$state` argument instead (`$state` just the special `$event` variable):","\ntemplate:",'<infinite-loading @infinite="infiniteHandler"></infinite-loading>',"\nscript:\n...\ninfiniteHandler($state) {\n ajax('https://www.example.com/api/news')\n .then((res) => {\n if (res.data.length) {\n $state.loaded();\n } else {\n $state.complete();\n }\n });\n}\n...","","more details: https://github.com/PeachScript/vue-infinite-loading/issues/57#issuecomment-324370549"].join("\n"),INFINITE_EVENT:"`:on-infinite` property will be deprecated soon, please use `@infinite` event instead.",IDENTIFIER:"the `reset` event will be deprecated soon, please reset this component by change the `identifier` property."},o={INFINITE_LOOP:["executed the callback function more than ".concat(i.loopCheckMaxCalls," times for a short time, it looks like searched a wrong scroll wrapper that doest not has fixed height or maximum height, please check it. If you want to force to set a element as scroll wrapper ranther than automatic searching, you can do this:"),'\n\x3c!-- add a special attribute for the real scroll wrapper --\x3e\n<div infinite-wrapper>\n ...\n \x3c!-- set force-use-infinite-wrapper --\x3e\n <infinite-loading force-use-infinite-wrapper></infinite-loading>\n</div>\nor\n<div class="infinite-wrapper">\n ...\n \x3c!-- set force-use-infinite-wrapper as css selector of the real scroll wrapper --\x3e\n <infinite-loading force-use-infinite-wrapper=".infinite-wrapper"></infinite-loading>\n</div>\n ',"more details: https://github.com/PeachScript/vue-infinite-loading/issues/55#issuecomment-316934169"].join("\n")},s={READY:0,LOADING:1,COMPLETE:2,ERROR:3},l={color:"#666",fontSize:"14px",padding:"10px 0"},d={mode:"development",props:{spinner:"default",distance:100,forceUseInfiniteWrapper:!1},system:i,slots:{noResults:"No results :(",noMore:"No more data :)",error:"Opps, something went wrong :(",errorBtnText:"Retry",spinner:""},WARNINGS:a,ERRORS:o,STATUS:s},c=n(4),u=n.n(c),p={BUBBLES:{render:function(t){return t("span",{attrs:{class:"loading-bubbles"}},Array.apply(Array,Array(8)).map((function(){return t("span",{attrs:{class:"bubble-item"}})})))}},CIRCLES:{render:function(t){return t("span",{attrs:{class:"loading-circles"}},Array.apply(Array,Array(8)).map((function(){return t("span",{attrs:{class:"circle-item"}})})))}},DEFAULT:{render:function(t){return t("i",{attrs:{class:"loading-default"}})}},SPIRAL:{render:function(t){return t("i",{attrs:{class:"loading-spiral"}})}},WAVEDOTS:{render:function(t){return t("span",{attrs:{class:"loading-wave-dots"}},Array.apply(Array,Array(5)).map((function(){return t("span",{attrs:{class:"wave-item"}})})))}}};function f(t,e,n,i,r,a,o,s){var l,d="function"==typeof t?t.options:t;if(e&&(d.render=e,d.staticRenderFns=n,d._compiled=!0),i&&(d.functional=!0),a&&(d._scopeId="data-v-"+a),o?(l=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},d._ssrRegister=l):r&&(l=s?function(){r.call(this,(d.functional?this.parent:this).$root.$options.shadowRoot)}:r),l)if(d.functional){d._injectStyles=l;var c=d.render;d.render=function(t,e){return l.call(e),c(t,e)}}else{var u=d.beforeCreate;d.beforeCreate=u?[].concat(u,l):[l]}return{exports:t,options:d}}var b=f({name:"Spinner",computed:{spinnerView:function(){return p[(this.$attrs.spinner||"").toUpperCase()]||this.spinnerInConfig},spinnerInConfig:function(){return d.slots.spinner&&"string"==typeof d.slots.spinner?{render:function(){return this._v(d.slots.spinner)}}:"object"===u()(d.slots.spinner)?d.slots.spinner:p[d.props.spinner.toUpperCase()]||p.DEFAULT}}},(function(){var t=this.$createElement;return(this._self._c||t)(this.spinnerView,{tag:"component"})}),[],!1,(function(t){var e=n(5);e.__inject__&&e.__inject__(t)}),"46b20d22",null).exports;function h(t){"production"!==d.mode&&console.warn("[Vue-infinite-loading warn]: ".concat(t))}function m(t){console.error("[Vue-infinite-loading error]: ".concat(t))}var g={timers:[],caches:[],throttle:function(t){var e=this;-1===this.caches.indexOf(t)&&(this.caches.push(t),this.timers.push(setTimeout((function(){t(),e.caches.splice(e.caches.indexOf(t),1),e.timers.shift()}),d.system.throttleLimit)))},reset:function(){this.timers.forEach((function(t){clearTimeout(t)})),this.timers.length=0,this.caches=[]}},v={isChecked:!1,timer:null,times:0,track:function(){var t=this;this.times+=1,clearTimeout(this.timer),this.timer=setTimeout((function(){t.isChecked=!0}),d.system.loopCheckTimeout),this.times>d.system.loopCheckMaxCalls&&(m(o.INFINITE_LOOP),this.isChecked=!0)}},w={key:"_infiniteScrollHeight",getScrollElm:function(t){return t===window?document.documentElement:t},save:function(t){var e=this.getScrollElm(t);e[this.key]=e.scrollHeight},restore:function(t){var e=this.getScrollElm(t);"number"==typeof e[this.key]&&(e.scrollTop=e.scrollHeight-e[this.key]+e.scrollTop),this.remove(e)},remove:function(t){void 0!==t[this.key]&&delete t[this.key]}};function x(t){return t.replace(/[A-Z]/g,(function(t){return"-".concat(t.toLowerCase())}))}function y(t){return t.offsetWidth+t.offsetHeight>0}var k=f({name:"InfiniteLoading",data:function(){return{scrollParent:null,scrollHandler:null,isFirstLoad:!0,status:s.READY,slots:d.slots}},components:{Spinner:b},computed:{isShowSpinner:function(){return this.status===s.LOADING},isShowError:function(){return this.status===s.ERROR},isShowNoResults:function(){return this.status===s.COMPLETE&&this.isFirstLoad},isShowNoMore:function(){return this.status===s.COMPLETE&&!this.isFirstLoad},slotStyles:function(){var t=this,e={};return Object.keys(d.slots).forEach((function(n){var i=x(n);(!t.$slots[i]&&!d.slots[n].render||t.$slots[i]&&!t.$slots[i][0].tag)&&(e[n]=l)})),e}},props:{distance:{type:Number,default:d.props.distance},spinner:String,direction:{type:String,default:"bottom"},forceUseInfiniteWrapper:{type:[Boolean,String],default:d.props.forceUseInfiniteWrapper},identifier:{default:+new Date},webComponentName:{type:[String]},onInfinite:Function},watch:{identifier:function(){this.stateChanger.reset()}},mounted:function(){var t=this;this.$watch("forceUseInfiniteWrapper",(function(){t.scrollParent=t.getScrollParent()}),{immediate:!0}),this.scrollHandler=function(e){t.status===s.READY&&(e&&e.constructor===Event&&y(t.$el)?g.throttle(t.attemptLoad):t.attemptLoad())},setTimeout((function(){t.scrollHandler(),t.scrollParent.addEventListener("scroll",t.scrollHandler,r)}),1),this.$on("$InfiniteLoading:loaded",(function(e){t.isFirstLoad=!1,"top"===t.direction&&t.$nextTick((function(){w.restore(t.scrollParent)})),t.status===s.LOADING&&t.$nextTick(t.attemptLoad.bind(null,!0)),e&&e.target===t||h(a.STATE_CHANGER)})),this.$on("$InfiniteLoading:complete",(function(e){t.status=s.COMPLETE,t.$nextTick((function(){t.$forceUpdate()})),t.scrollParent.removeEventListener("scroll",t.scrollHandler,r),e&&e.target===t||h(a.STATE_CHANGER)})),this.$on("$InfiniteLoading:reset",(function(e){t.status=s.READY,t.isFirstLoad=!0,w.remove(t.scrollParent),t.scrollParent.addEventListener("scroll",t.scrollHandler,r),setTimeout((function(){g.reset(),t.scrollHandler()}),1),e&&e.target===t||h(a.IDENTIFIER)})),this.stateChanger={loaded:function(){t.$emit("$InfiniteLoading:loaded",{target:t})},complete:function(){t.$emit("$InfiniteLoading:complete",{target:t})},reset:function(){t.$emit("$InfiniteLoading:reset",{target:t})},error:function(){t.status=s.ERROR,g.reset()}},this.onInfinite&&h(a.INFINITE_EVENT)},deactivated:function(){this.status===s.LOADING&&(this.status=s.READY),this.scrollParent.removeEventListener("scroll",this.scrollHandler,r)},activated:function(){this.scrollParent.addEventListener("scroll",this.scrollHandler,r)},methods:{attemptLoad:function(t){var e=this;this.status!==s.COMPLETE&&y(this.$el)&&this.getCurrentDistance()<=this.distance?(this.status=s.LOADING,"top"===this.direction&&this.$nextTick((function(){w.save(e.scrollParent)})),"function"==typeof this.onInfinite?this.onInfinite.call(null,this.stateChanger):this.$emit("infinite",this.stateChanger),!t||this.forceUseInfiniteWrapper||v.isChecked||v.track()):this.status===s.LOADING&&(this.status=s.READY)},getCurrentDistance:function(){var t;"top"===this.direction?t="number"==typeof this.scrollParent.scrollTop?this.scrollParent.scrollTop:this.scrollParent.pageYOffset:t=this.$el.getBoundingClientRect().top-(this.scrollParent===window?window.innerHeight:this.scrollParent.getBoundingClientRect().bottom);return t},getScrollParent:function(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.$el;"string"==typeof this.forceUseInfiniteWrapper&&(this.webComponentName&&(e=document.querySelector(this.webComponentName)),t=e?e.shadowRoot.querySelector(this.forceUseInfiniteWrapper):document.querySelector(this.forceUseInfiniteWrapper));return t||("BODY"===n.tagName?t=window:(!this.forceUseInfiniteWrapper&&["scroll","auto"].indexOf(getComputedStyle(n).overflowY)>-1||n.hasAttribute("infinite-wrapper")||n.hasAttribute("data-infinite-wrapper"))&&(t=n)),t||this.getScrollParent(n.parentNode)}},destroyed:function(){!this.status!==s.COMPLETE&&(g.reset(),w.remove(this.scrollParent),this.scrollParent.removeEventListener("scroll",this.scrollHandler,r))}},(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"infinite-loading-container"},[n("div",{directives:[{name:"show",rawName:"v-show",value:t.isShowSpinner,expression:"isShowSpinner"}],staticClass:"infinite-status-prompt",style:t.slotStyles.spinner},[t._t("spinner",[n("spinner",{attrs:{spinner:t.spinner}})],null,{isFirstLoad:t.isFirstLoad})],2),t._v(" "),n("div",{directives:[{name:"show",rawName:"v-show",value:t.isShowNoResults,expression:"isShowNoResults"}],staticClass:"infinite-status-prompt",style:t.slotStyles.noResults},[t._t("no-results",[t.slots.noResults.render?n(t.slots.noResults,{tag:"component"}):[t._v(t._s(t.slots.noResults))]])],2),t._v(" "),n("div",{directives:[{name:"show",rawName:"v-show",value:t.isShowNoMore,expression:"isShowNoMore"}],staticClass:"infinite-status-prompt",style:t.slotStyles.noMore},[t._t("no-more",[t.slots.noMore.render?n(t.slots.noMore,{tag:"component"}):[t._v(t._s(t.slots.noMore))]])],2),t._v(" "),n("div",{directives:[{name:"show",rawName:"v-show",value:t.isShowError,expression:"isShowError"}],staticClass:"infinite-status-prompt",style:t.slotStyles.error},[t._t("error",[t.slots.error.render?n(t.slots.error,{tag:"component",attrs:{trigger:t.attemptLoad}}):[t._v("\n "+t._s(t.slots.error)+"\n "),n("br"),t._v(" "),n("button",{staticClass:"btn-try-infinite",domProps:{textContent:t._s(t.slots.errorBtnText)},on:{click:t.attemptLoad}})]],{trigger:t.attemptLoad})],2)])}),[],!1,(function(t){var e=n(7);e.__inject__&&e.__inject__(t)}),"670d0042",null).exports;function _(t){d.mode=t.config.productionTip?"development":"production"}Object.defineProperty(k,"install",{configurable:!1,enumerable:!1,value:function(t,e){Object.assign(d.props,e&&e.props),Object.assign(d.slots,e&&e.slots),Object.assign(d.system,e&&e.system),t.component("infinite-loading",k),_(t)}}),"undefined"!=typeof window&&window.Vue&&(window.Vue.component("infinite-loading",k),_(window.Vue));e.default=k}])}));
/***/ }),
/***/ "e325":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-audio-player{display:flex;margin:8px 0 5px}.vac-audio-player .vac-svg-button{max-width:18px;margin-left:7px}@media only screen and (max-width:768px){.vac-audio-player{margin:4px 0 0}.vac-audio-player .vac-svg-button{max-width:16px;margin-left:5px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "e498":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReactions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("6534");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReactions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MessageReactions_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "e4a8":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("e325");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("e8f1516a", content, shadowRoot)
};
/***/ }),
/***/ "e4dc":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-player-bar{display:flex;align-items:center;max-width:calc(100% - 18px);margin-right:7px;margin-left:20px}.vac-player-bar .vac-player-progress{width:190px}.vac-player-bar .vac-player-progress .vac-line-container{position:relative;height:4px;border-radius:5px;background-color:var(--chat-message-bg-color-audio-line)}.vac-player-bar .vac-player-progress .vac-line-container .vac-line-progress{position:absolute;height:inherit;background-color:var(--chat-message-bg-color-audio-progress);border-radius:inherit}.vac-player-bar .vac-player-progress .vac-line-container .vac-line-dot{position:absolute;top:-5px;margin-left:-7px;height:14px;width:14px;border-radius:50%;background-color:var(--chat-message-bg-color-audio-progress-selector);transition:transform .25s}.vac-player-bar .vac-player-progress .vac-line-container .vac-line-dot__active{transform:scale(1.2)}@media only screen and (max-width:768px){.vac-player-bar{margin-right:5px}.vac-player-bar .vac-player-progress .vac-line-container{height:3px}.vac-player-bar .vac-player-progress .vac-line-container .vac-line-dot{height:12px;width:12px;top:-5px;margin-left:-5px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "e787":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("5eed");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("2ed4582b", content, shadowRoot)
};
/***/ }),
/***/ "e83d":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomHeader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("23e8");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomHeader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomHeader_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "e853":
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__("d3f4");
var isArray = __webpack_require__("1169");
var SPECIES = __webpack_require__("2b4c")('species');
module.exports = function (original) {
var C;
if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ }),
/***/ "ebd6":
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__("cb7c");
var aFunction = __webpack_require__("d8e8");
var SPECIES = __webpack_require__("2b4c")('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ }),
/***/ "ec30":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
if (__webpack_require__("9e1e")) {
var LIBRARY = __webpack_require__("2d00");
var global = __webpack_require__("7726");
var fails = __webpack_require__("79e5");
var $export = __webpack_require__("5ca1");
var $typed = __webpack_require__("0f88");
var $buffer = __webpack_require__("ed0b");
var ctx = __webpack_require__("9b43");
var anInstance = __webpack_require__("f605");
var propertyDesc = __webpack_require__("4630");
var hide = __webpack_require__("32e9");
var redefineAll = __webpack_require__("dcbc");
var toInteger = __webpack_require__("4588");
var toLength = __webpack_require__("9def");
var toIndex = __webpack_require__("09fa");
var toAbsoluteIndex = __webpack_require__("77f1");
var toPrimitive = __webpack_require__("6a99");
var has = __webpack_require__("69a8");
var classof = __webpack_require__("23c6");
var isObject = __webpack_require__("d3f4");
var toObject = __webpack_require__("4bf8");
var isArrayIter = __webpack_require__("33a4");
var create = __webpack_require__("2aeb");
var getPrototypeOf = __webpack_require__("38fd");
var gOPN = __webpack_require__("9093").f;
var getIterFn = __webpack_require__("27ee");
var uid = __webpack_require__("ca5a");
var wks = __webpack_require__("2b4c");
var createArrayMethod = __webpack_require__("0a49");
var createArrayIncludes = __webpack_require__("c366");
var speciesConstructor = __webpack_require__("ebd6");
var ArrayIterators = __webpack_require__("cadf");
var Iterators = __webpack_require__("84f2");
var $iterDetect = __webpack_require__("5cc5");
var setSpecies = __webpack_require__("7a56");
var arrayFill = __webpack_require__("36bd");
var arrayCopyWithin = __webpack_require__("ba92");
var $DP = __webpack_require__("86cc");
var $GOPD = __webpack_require__("11e9");
var dP = $DP.f;
var gOPD = $GOPD.f;
var RangeError = global.RangeError;
var TypeError = global.TypeError;
var Uint8Array = global.Uint8Array;
var ARRAY_BUFFER = 'ArrayBuffer';
var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;
var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
var PROTOTYPE = 'prototype';
var ArrayProto = Array[PROTOTYPE];
var $ArrayBuffer = $buffer.ArrayBuffer;
var $DataView = $buffer.DataView;
var arrayForEach = createArrayMethod(0);
var arrayFilter = createArrayMethod(2);
var arraySome = createArrayMethod(3);
var arrayEvery = createArrayMethod(4);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var arrayIncludes = createArrayIncludes(true);
var arrayIndexOf = createArrayIncludes(false);
var arrayValues = ArrayIterators.values;
var arrayKeys = ArrayIterators.keys;
var arrayEntries = ArrayIterators.entries;
var arrayLastIndexOf = ArrayProto.lastIndexOf;
var arrayReduce = ArrayProto.reduce;
var arrayReduceRight = ArrayProto.reduceRight;
var arrayJoin = ArrayProto.join;
var arraySort = ArrayProto.sort;
var arraySlice = ArrayProto.slice;
var arrayToString = ArrayProto.toString;
var arrayToLocaleString = ArrayProto.toLocaleString;
var ITERATOR = wks('iterator');
var TAG = wks('toStringTag');
var TYPED_CONSTRUCTOR = uid('typed_constructor');
var DEF_CONSTRUCTOR = uid('def_constructor');
var ALL_CONSTRUCTORS = $typed.CONSTR;
var TYPED_ARRAY = $typed.TYPED;
var VIEW = $typed.VIEW;
var WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function (O, length) {
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function () {
// eslint-disable-next-line no-undef
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {
new Uint8Array(1).set({});
});
var toOffset = function (it, BYTES) {
var offset = toInteger(it);
if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');
return offset;
};
var validate = function (it) {
if (isObject(it) && TYPED_ARRAY in it) return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function (C, length) {
if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function (O, list) {
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function (C, list) {
var index = 0;
var length = list.length;
var result = allocate(C, length);
while (length > index) result[index] = list[index++];
return result;
};
var addGetter = function (it, key, internal) {
dP(it, key, { get: function () { return this._d[internal]; } });
};
var $from = function from(source /* , mapfn, thisArg */) {
var O = toObject(source);
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iterFn = getIterFn(O);
var i, length, values, result, step, iterator;
if (iterFn != undefined && !isArrayIter(iterFn)) {
for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {
values.push(step.value);
} O = values;
}
if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);
for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/* ...items */) {
var index = 0;
var length = arguments.length;
var result = allocate(this, length);
while (length > index) result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString() {
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /* , end */) {
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /* , thisArg */) {
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /* , thisArg */) {
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /* , thisArg */) {
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /* , thisArg */) {
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /* , thisArg */) {
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /* , fromIndex */) {
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /* , fromIndex */) {
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator) { // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /* , thisArg */) {
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse() {
var that = this;
var length = validate(that).length;
var middle = Math.floor(length / 2);
var index = 0;
var value;
while (index < middle) {
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /* , thisArg */) {
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn) {
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end) {
var O = validate(this);
var length = O.length;
var $begin = toAbsoluteIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end) {
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /* , offset */) {
validate(this);
var offset = toOffset(arguments[1], 1);
var length = this.length;
var src = toObject(arrayLike);
var len = toLength(src.length);
var index = 0;
if (len + offset > length) throw RangeError(WRONG_LENGTH);
while (index < len) this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries() {
return arrayEntries.call(validate(this));
},
keys: function keys() {
return arrayKeys.call(validate(this));
},
values: function values() {
return arrayValues.call(validate(this));
}
};
var isTAIndex = function (target, key) {
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key) {
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc) {
if (isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
) {
target[key] = desc.value;
return target;
} return dP(target, key, desc);
};
if (!ALL_CONSTRUCTORS) {
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if (fails(function () { arrayToString.call({}); })) {
arrayToString = arrayToLocaleString = function toString() {
return arrayJoin.call(this);
};
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function () { /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function () { return this[TYPED_ARRAY]; }
});
// eslint-disable-next-line max-statements
module.exports = function (KEY, BYTES, wrapper, CLAMPED) {
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';
var GETTER = 'get' + KEY;
var SETTER = 'set' + KEY;
var TypedArray = global[NAME];
var Base = TypedArray || {};
var TAC = TypedArray && getPrototypeOf(TypedArray);
var FORCED = !TypedArray || !$typed.ABV;
var O = {};
var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function (that, index) {
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function (that, index, value) {
var data = that._d;
if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function (that, index) {
dP(that, index, {
get: function () {
return getter(this, index);
},
set: function (value) {
return setter(this, index, value);
},
enumerable: true
});
};
if (FORCED) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME, '_d');
var index = 0;
var offset = 0;
var buffer, byteLength, length, klass;
if (!isObject(data)) {
length = toIndex(data);
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if ($length === undefined) {
if ($len % BYTES) throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if (byteLength < 0) throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if (TYPED_ARRAY in data) {
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while (index < length) addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if (!fails(function () {
TypedArray(1);
}) || !fails(function () {
new TypedArray(-1); // eslint-disable-line no-new
}) || !$iterDetect(function (iter) {
new TypedArray(); // eslint-disable-line no-new
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(1.5); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if (!isObject(data)) return new Base(toIndex(data));
if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if (TYPED_ARRAY in data) return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {
if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR];
var CORRECT_ITER_NAME = !!$nativeIterator
&& ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);
var $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {
dP(TypedArrayPrototype, TAG, {
get: function () { return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES
});
$export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {
from: $from,
of: $of
});
if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, { set: $set });
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;
$export($export.P + $export.F * fails(function () {
new TypedArray(1).slice();
}), NAME, { slice: $slice });
$export($export.P + $export.F * (fails(function () {
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();
}) || !fails(function () {
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, { toLocaleString: $toLocaleString });
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function () { /* empty */ };
/***/ }),
/***/ "ed0b":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__("7726");
var DESCRIPTORS = __webpack_require__("9e1e");
var LIBRARY = __webpack_require__("2d00");
var $typed = __webpack_require__("0f88");
var hide = __webpack_require__("32e9");
var redefineAll = __webpack_require__("dcbc");
var fails = __webpack_require__("79e5");
var anInstance = __webpack_require__("f605");
var toInteger = __webpack_require__("4588");
var toLength = __webpack_require__("9def");
var toIndex = __webpack_require__("09fa");
var gOPN = __webpack_require__("9093").f;
var dP = __webpack_require__("86cc").f;
var arrayFill = __webpack_require__("36bd");
var setToStringTag = __webpack_require__("7f20");
var ARRAY_BUFFER = 'ArrayBuffer';
var DATA_VIEW = 'DataView';
var PROTOTYPE = 'prototype';
var WRONG_LENGTH = 'Wrong length!';
var WRONG_INDEX = 'Wrong index!';
var $ArrayBuffer = global[ARRAY_BUFFER];
var $DataView = global[DATA_VIEW];
var Math = global.Math;
var RangeError = global.RangeError;
// eslint-disable-next-line no-shadow-restricted-names
var Infinity = global.Infinity;
var BaseBuffer = $ArrayBuffer;
var abs = Math.abs;
var pow = Math.pow;
var floor = Math.floor;
var log = Math.log;
var LN2 = Math.LN2;
var BUFFER = 'buffer';
var BYTE_LENGTH = 'byteLength';
var BYTE_OFFSET = 'byteOffset';
var $BUFFER = DESCRIPTORS ? '_b' : BUFFER;
var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH;
var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
function packIEEE754(value, mLen, nBytes) {
var buffer = new Array(nBytes);
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0;
var i = 0;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
var e, m, c;
value = abs(value);
// eslint-disable-next-line no-self-compare
if (value != value || value === Infinity) {
// eslint-disable-next-line no-self-compare
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if (value * (c = pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
}
function unpackIEEE754(buffer, mLen, nBytes) {
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = eLen - 7;
var i = nBytes - 1;
var s = buffer[i--];
var e = s & 127;
var m;
s >>= 7;
for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
}
function unpackI32(bytes) {
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
}
function packI8(it) {
return [it & 0xff];
}
function packI16(it) {
return [it & 0xff, it >> 8 & 0xff];
}
function packI32(it) {
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
}
function packF64(it) {
return packIEEE754(it, 52, 8);
}
function packF32(it) {
return packIEEE754(it, 23, 4);
}
function addGetter(C, key, internal) {
dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } });
}
function get(view, bytes, index, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
}
function set(view, bytes, index, conversion, value, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = conversion(+value);
for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
}
if (!$typed.ABV) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
var byteLength = toIndex(length);
this._b = arrayFill.call(new Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength) {
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH];
var offset = toInteger(byteOffset);
if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if (DESCRIPTORS) {
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset) {
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset) {
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if (!fails(function () {
$ArrayBuffer(1);
}) || !fails(function () {
new $ArrayBuffer(-1); // eslint-disable-line no-new
}) || fails(function () {
new $ArrayBuffer(); // eslint-disable-line no-new
new $ArrayBuffer(1.5); // eslint-disable-line no-new
new $ArrayBuffer(NaN); // eslint-disable-line no-new
return $ArrayBuffer.name != ARRAY_BUFFER;
})) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer);
return new BaseBuffer(toIndex(length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) {
if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]);
}
if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2));
var $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ }),
/***/ "f0c1":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var aFunction = __webpack_require__("d8e8");
var isObject = __webpack_require__("d3f4");
var invoke = __webpack_require__("31f4");
var arraySlice = [].slice;
var factories = {};
var construct = function (F, len, args) {
if (!(len in factories)) {
for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction(this);
var partArgs = arraySlice.call(arguments, 1);
var bound = function (/* args... */) {
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if (isObject(fn.prototype)) bound.prototype = fn.prototype;
return bound;
};
/***/ }),
/***/ "f139":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-message-wrapper .vac-card-info{border-radius:4px;text-align:center;margin:10px auto;font-size:12px;padding:4px;display:block;overflow-wrap:break-word;position:relative;white-space:normal;box-shadow:0 1px 1px -1px rgba(0,0,0,.1),0 1px 1px -1px rgba(0,0,0,.11),0 1px 2px -1px rgba(0,0,0,.11)}.vac-message-wrapper .vac-card-date{max-width:150px;font-weight:500;text-transform:uppercase;color:var(--chat-message-color-date);background:var(--chat-message-bg-color-date)}.vac-message-wrapper .vac-card-system{max-width:250px;padding:8px 4px;color:var(--chat-message-color-system);background:var(--chat-message-bg-color-system)}.vac-message-wrapper .vac-line-new{color:var(--chat-message-color-new-messages);position:relative;text-align:center;font-size:13px;padding:10px 0}.vac-message-wrapper .vac-line-new:after,.vac-message-wrapper .vac-line-new:before{border-top:1px solid var(--chat-message-color-new-messages);content:\"\";left:0;position:absolute;top:50%;width:calc(50% - 60px)}.vac-message-wrapper .vac-line-new:before{left:auto;right:0}.vac-message-wrapper .vac-message-box{display:flex;flex:0 0 50%;max-width:50%;justify-content:flex-start;line-height:1.4}.vac-message-wrapper .vac-avatar{height:28px;width:28px;min-height:28px;min-width:28px;margin:0 0 2px 0;align-self:flex-end}.vac-message-wrapper .vac-message-container{position:relative;padding:2px 10px;align-items:end;min-width:100px;box-sizing:content-box}.vac-message-wrapper .vac-message-container-offset{margin-top:10px}.vac-message-wrapper .vac-offset-current{margin-left:50%;justify-content:flex-end}.vac-message-wrapper .vac-message-card{background:var(--chat-message-bg-color);color:var(--chat-message-color);border-radius:8px;font-size:14px;padding:6px 9px 3px;white-space:pre-line;max-width:100%;transition-property:box-shadow,opacity;transition:box-shadow .28s cubic-bezier(.4,0,.2,1);will-change:box-shadow;box-shadow:0 1px 1px -1px rgba(0,0,0,.1),0 1px 1px -1px rgba(0,0,0,.11),0 1px 2px -1px rgba(0,0,0,.11)}.vac-message-wrapper .vac-message-highlight{box-shadow:0 1px 2px -1px rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.11),0 1px 5px -1px rgba(0,0,0,.11)}.vac-message-wrapper .vac-message-current{background:var(--chat-message-bg-color-me)!important}.vac-message-wrapper .vac-message-deleted{color:var(--chat-message-color-deleted)!important;font-size:13px!important;font-style:italic!important;background:var(--chat-message-bg-color-deleted)!important}.vac-message-wrapper .vac-icon-deleted{height:14px;width:14px;vertical-align:middle;margin:-2px 2px 0 0;fill:var(--chat-message-color-deleted)}.vac-message-wrapper .vac-video-container{width:350px;max-width:100%;margin:4px auto 5px}.vac-message-wrapper .vac-video-container video{border-radius:4px}.vac-message-wrapper .vac-message-image{position:relative;background-color:var(--chat-message-bg-color-image)!important;background-size:cover!important;background-position:50%!important;background-repeat:no-repeat!important;height:250px;width:250px;max-width:100%;border-radius:4px;margin:4px auto 5px;transition:filter .4s linear}.vac-message-wrapper .vac-text-username{font-size:13px;color:var(--chat-message-color-username);margin-bottom:2px}.vac-message-wrapper .vac-username-reply{margin-bottom:5px}.vac-message-wrapper .vac-text-timestamp{font-size:10px;color:var(--chat-message-color-timestamp);text-align:right}.vac-message-wrapper .vac-progress-time{float:left;margin:-2px 0 0 40px;color:var(--chat-color);font-size:12px}.vac-message-wrapper .vac-file-message{display:flex;flex-wrap:wrap;align-items:center;margin-top:3px}.vac-message-wrapper .vac-file-message span{max-width:100%}.vac-message-wrapper .vac-file-message .vac-icon-file svg{margin-right:5px}.vac-message-wrapper .vac-icon-edited{align-items:center;display:inline-flex;justify-content:center;letter-spacing:normal;line-height:1;text-indent:0;vertical-align:middle;margin:0 4px 2px}.vac-message-wrapper .vac-icon-edited svg{height:12px;width:12px}.vac-message-wrapper .vac-icon-check{height:14px;width:14px;vertical-align:middle;margin:-3px -3px 0 3px}@media only screen and (max-width:768px){.vac-message-wrapper .vac-message-container{padding:2px 3px 1px}.vac-message-wrapper .vac-message-container-offset{margin-top:10px}.vac-message-wrapper .vac-message-box{flex:0 0 80%;max-width:80%}.vac-message-wrapper .vac-avatar{height:25px;width:25px;min-height:25px;min-width:25px;margin:0 6px 1px 0}.vac-message-wrapper .vac-offset-current{margin-left:20%}.vac-message-wrapper .vac-progress-time{margin-left:37px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "f1ae":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__("86cc");
var createDesc = __webpack_require__("4630");
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/***/ "f3e2":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__("5ca1");
var $forEach = __webpack_require__("0a49")(0);
var STRICT = __webpack_require__("2f21")([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ }),
/***/ "f43c":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioPlayer_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("e4a8");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioPlayer_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AudioPlayer_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "f559":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
var $export = __webpack_require__("5ca1");
var toLength = __webpack_require__("9def");
var context = __webpack_require__("d2c8");
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__("5147")(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ }),
/***/ "f605":
/***/ (function(module, exports) {
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/***/ "f751":
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__("5ca1");
$export($export.S + $export.F, 'Object', { assign: __webpack_require__("7333") });
/***/ }),
/***/ "f86d":
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__("2c2f");
if(content.__esModule) content = content.default;
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add CSS to Shadow Root
var add = __webpack_require__("35d6").default
module.exports.__inject__ = function (shadowRoot) {
add("3aeb0e6d", content, shadowRoot)
};
/***/ }),
/***/ "fa4d":
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__("24fb");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".vac-emojis-container{position:absolute;width:calc(100% - 16px);padding:10px 8px;background:var(--chat-footer-bg-color);display:flex;align-items:center;overflow:auto}.vac-emojis-container .vac-emoji-element{padding:0 8px;font-size:30px;border-radius:4px;cursor:pointer}.vac-emojis-container .vac-emoji-element:hover{background:var(--chat-footer-bg-color-tag-active)}.vac-emojis-container .vac-emoji-element:hover,.vac-emojis-container .vac-emoji-element:not(:hover){transition:background-color .3s cubic-bezier(.25,.8,.5,1)}@media only screen and (max-width:768px){.vac-emojis-container{width:calc(100% - 10px);padding:7px 5px}.vac-emojis-container .vac-emoji-element{padding:0 7px;font-size:26px}}", ""]);
// Exports
module.exports = exports;
/***/ }),
/***/ "fa5b":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("5537")('native-function-to-string', Function.toString);
/***/ }),
/***/ "fab2":
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__("7726").document;
module.exports = document && document.documentElement;
/***/ }),
/***/ "fb0c":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomEmojis_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("0218");
/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomEmojis_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_RoomEmojis_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */
/***/ }),
/***/ "fdef":
/***/ (function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ }),
/***/ "ffc1":
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__("5ca1");
var $entries = __webpack_require__("504c")(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
/***/ })
/******/ });
//# sourceMappingURL=vue-advanced-chat.js.map |
'use strict'
import {StyleSheet} from 'react-native'
module.exports = StyleSheet.create({
innerContainer: {
margin: 7,
marginLeft: 11,
},
button: {
borderRadius: 5,
flex: 1,
height: 44,
alignSelf: 'stretch',
justifyContent: 'center',
overflow: 'hidden'
},
buttonText: {
fontSize: 18,
margin: 5,
textAlign: 'center',
},
pic: {
height: 35, width: 35, borderRadius: 3, backgroundColor: 'blue', margin: 4
},
Row: {
flexDirection: 'row'
},
funcView: {
backgroundColor: 'lightblue',
marginHorizontal: 4,
borderRadius: 5,
height: 80 || null
},
funcViewMulti: {
backgroundColor: 'lightblue',
marginHorizontal: 4,
borderRadius: 5,
height: 80 || null,
flex: 1
},
optionViewSucsess: {
backgroundColor: 'lightgreen',
marginHorizontal: 15,
height: 70 || null,
justifyContent: 'center',
flex: 1,
},
optionViewFail: {
backgroundColor: 'lightgreen',
marginBottom: 4,
marginHorizontal: 15,
borderBottomLeftRadius: 9,
borderBottomRightRadius: 9,
height: 55 || null,
justifyContent: 'center',
flex: 1,
},
optionViewDeadEnd: {
backgroundColor: 'red',
marginBottom: 4,
marginHorizontal: 15,
borderBottomLeftRadius: 9,
borderBottomRightRadius: 9,
height: 55 || null,
justifyContent: 'center',
flex: 1,
},
outerBorder: {
backgroundColor: 'white',
margin: 10,
flex: 1,
},
})
|
// ##### ARRAYS INICIAIS ##### //
var firstDeck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var secondDeck = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var dealerHand = [];
var playerHand = [];
var playerName = '';
var playerCoins = 500;
var thisBet = 0;
// ----- Sounds ----- //
var audioClick = new Audio('../sounds/click.mp3');
var audioDraw = new Audio('../sounds/draw.mp3');
var audioWin = new Audio('../sounds/win.mp3');
var audioLose = new Audio('../sounds/lose.mp3');
// ----- Points info ----- //
function renderCoinsInfoContainer() {
if (document.querySelector('.info-coins') == null) {
// Criar quadro de coins
var coinsInfoContainer = document.createElement('div');
coinsInfoContainer.setAttribute('class', 'info-coins');
coinsInfoContainer.innerHTML = `<p>${playerCoins} coins</p>`;
document.body.appendChild(coinsInfoContainer);
} else {
// Remover quadro de coins
const toBeRemoved = document.querySelector('.info-coins')
document.body.removeChild(toBeRemoved);
// Recriar quadro de coins
var coinsInfoContainer = document.createElement('div');
coinsInfoContainer.setAttribute('class', 'info-coins');
coinsInfoContainer.innerHTML = `<p>${playerCoins} coins</p>`;
document.body.appendChild(coinsInfoContainer);
}
}
// ----- Carregar primeiras informações ----- //
firstLoad();
renderCoinsInfoContainer();
// ----- Função que executa o primeiro carregamento ----- //
function firstLoad() {
randomPick(firstDeck, playerHand);
randomPick(secondDeck, playerHand);
dealerHand[0] = '?';
randomPick(secondDeck, dealerHand);
}
// ----- Função do botão HIT ----- //
function hit(hand) {
if (playerHand.length < 1) {
randomPick(firstDeck, hand);
} else {
randomPick(secondDeck, hand);
}
var playerDivDel = document.querySelector('#player');
playerDivDel.parentElement.removeChild(playerDivDel);
playerRender(points(playerHand));
playerWinChecker();
}
// ----- Função do botão STAND ----- //
function stand() {
let loadIndex0 = [];
randomPick(firstDeck, loadIndex0);
dealerHand[0] = loadIndex0[0];
do {
hit(dealerHand);
} while (points(dealerHand) < 18)
dealerRender(points(dealerHand));
compare(points(playerHand), points(dealerHand));
}
// ----- Função de comprar carta aleatóriamente ----- //
function randomPick(originDeck, finalDeck) {
var randValue = originDeck[Math.floor(Math.random() * originDeck.length)];
finalDeck.push(randValue);
}
// ----- Função para calcular os pontos ----- //
function points(hand) {
let points = 0;
for (let index = 0; index < hand.length; index++) {
points += hand[index];
}
return points;
}
// ----- Função de comparação de pontos ----- //
function compare(player, dealer) {
if (dealer == 21) {
audioLose.play();
divAlert('renderFinalPage(false)', 'You lose!');
playerCoins = parseInt(playerCoins) - parseInt(thisBet);
renderCoinsInfoContainer();
} else if (dealer > 21) {
audioWin.play();
divAlert('renderFinalPage(true)', 'You win!');
playerCoins = parseInt(playerCoins) + parseInt(thisBet);
renderCoinsInfoContainer();
} else if (player > dealer) {
audioWin.play();
divAlert('renderFinalPage(true)', 'You win!');
playerCoins = parseInt(playerCoins) + parseInt(thisBet);
renderCoinsInfoContainer();
} else {
audioLose.play();
divAlert('renderFinalPage(false)', 'You lose!');
playerCoins = parseInt(playerCoins) - parseInt(thisBet);
renderCoinsInfoContainer();
}
}
// ----- Função que checa a vitória do player para redirecionar a renderização ----- //
function playerWinChecker() {
if (points(playerHand) > 21) {
audioLose.play();
divAlert('renderFinalPage(false)', 'You lose!');
playerCoins = parseInt(playerCoins) - parseInt(thisBet);
renderCoinsInfoContainer();
} else if (points(playerHand) == 21) {
audioWin.play();
divAlert('renderFinalPage(true)', 'You win!');
playerCoins = parseInt(playerCoins) + parseInt(thisBet);
renderCoinsInfoContainer();
}
}
// |#################################| //
// |--------- RENDERIZAÇÕES ---------| //
// |#################################| //
// -------------------- Selecionando a div app ------------------ //
// ----- (vai ser útil para várias funções de renderização) ----- //
var app = document.querySelector('#app');
// ----- Renderizar a mão do desafiante ----- //
function dealerRender(points) {
if (typeof points == "string") {
points = '?'
}
var dealer = document.createElement('div');
var dealerCards = document.createElement('div');
dealer.setAttribute('id', 'dealer');
dealerCards.setAttribute('id', 'dealerCards')
dealer.innerHTML = `<p>Dealer: ${points}</p>`
dealer.appendChild(dealerCards);
for (card in dealerHand) {
let dealerCardDiv = document.createElement('div');
dealerCardDiv.innerHTML = `${dealerHand[card]}`
dealerCards.appendChild(dealerCardDiv);
}
app.appendChild(dealer);
}
// ----- Renderizar campo com informação do valor apostado ----- //
function betRender() {
var bet = document.createElement('div');
bet.setAttribute('id', 'bet');
bet.innerHTML = `<p><strong>Bet:</strong> ${thisBet} coins</p>`
app.appendChild(bet);
}
// ----- Renderizar a mão do jogador ----- //
function playerRender(points) {
var player = document.createElement('div');
var playerCards = document.createElement('div');
player.setAttribute('id', 'player');
playerCards.setAttribute('id', 'playerCards')
for (card in playerHand) {
let dealerCardDiv = document.createElement('div');
dealerCardDiv.innerHTML = `${playerHand[card]}`
playerCards.appendChild(dealerCardDiv);
}
player.appendChild(playerCards);
player.innerHTML += `<p>${playerName}: ${points}</p>`
app.appendChild(player);
}
// ----- Renderizar os botões da tela do jogo ----- //
function gameButtonsRender() {
var buttons = document.createElement('div');
var hitButton = document.createElement('button');
var standButton = document.createElement('button');
hitButton.setAttribute('id', 'hit');
hitButton.setAttribute('onclick', 'hit(playerHand), audioDraw.play()');
hitButton.innerHTML = 'Hit';
standButton.setAttribute('id', 'stand');
standButton.setAttribute('onclick', 'stand(firstDeck, secondDeck)');
standButton.innerHTML = 'Stand'
buttons.setAttribute('id', 'buttons');
buttons.setAttribute('class', 'buttons')
buttons.appendChild(hitButton);
buttons.appendChild(standButton);
app.appendChild(buttons);
}
// ----- Função de caixa de alert ----- //
function divAlert(renderFunction, msg) {
let divBlock = document.createElement('div');
divBlock.setAttribute('id', 'divBlock');
document.body.appendChild(divBlock);
let divAlertBox = document.createElement('div');
let buttonAlertBox = document.createElement('button');
buttonAlertBox.setAttribute('onclick', `${renderFunction}`);
buttonAlertBox.innerHTML = 'OK!';
divAlertBox.setAttribute('id', 'divAlertBox');
divAlertBox.innerHTML = `<p>${msg}</p>`;
divAlertBox.appendChild(buttonAlertBox);
document.body.appendChild(divAlertBox);
}
// ----- Função de caixa de aposta ----- //
function betAlert(renderFunction, backFunction) {
let divBetButtons = document.createElement('div');
divBetButtons.setAttribute('id', 'divBetButtons');
let inputBet = document.createElement('input');
inputBet.setAttribute('value', 100)
inputBet.setAttribute('type', 'number');
inputBet.setAttribute('id', 'inputBet');
let divBetBox = document.createElement('div');
let btnBetBoxConfirm = document.createElement('button');
btnBetBoxConfirm.setAttribute('onclick', `${renderFunction}`);
btnBetBoxConfirm.innerHTML = 'Confirm Bet';
let btnBetBoxBack = document.createElement('button');
btnBetBoxBack.setAttribute('onclick', `${backFunction}`);
btnBetBoxBack.innerHTML = 'Back';
divBetBox.setAttribute('id', 'betAlertBox');
divBetBox.innerHTML = `<p>Hello, ${playerName}!<br>How much do you want to bet?<br>Available Coins: ${playerCoins}</p>`;
divBetButtons.appendChild(btnBetBoxConfirm);
divBetButtons.appendChild(btnBetBoxBack);
divBetBox.appendChild(inputBet);
divBetBox.appendChild(divBetButtons);
document.body.appendChild(divBetBox);
}
// ----- Renderizar a página inicial ----- //
function renderFirstPage() {
let boxName = document.createElement('div');
boxName.setAttribute('id', 'blackBox');
app.appendChild(boxName);
boxName.innerHTML = `<p>Calicojack<br><small>from Stardew Valley</small></p> `;
let inputName = document.createElement('input');
inputName.setAttribute('id', 'inputName')
inputName.setAttribute('type', 'text');
inputName.setAttribute('placeholder', 'Enter your name here');
boxName.appendChild(inputName);
let coinsInfo = document.createElement('p');
coinsInfo.innerHTML = 'New players start with 500 coins.';
coinsInfo.setAttribute('id', 'coinsInfo')
boxName.appendChild(coinsInfo);
let startButton = document.createElement('button');
startButton.setAttribute('id', 'startButton');
startButton.setAttribute('onclick', 'startBtnFunc()')
startButton.innerHTML = 'Start!'
boxName.appendChild(startButton);
}
// ----- Renderizar o jogo, a página principal ----- //
function renderAppMain() {
dealerRender(points(dealerHand));
betRender();
playerRender(points(playerHand));
gameButtonsRender();
}
// ----- Renderizar a tela de resultados, a página final ----- //
function renderFinalPage(result) {
// Limpeza do App //
document.body.removeChild(divAlertBox);
document.body.removeChild(divBlock);
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = ''
document.body.appendChild(app)
// Preenchimento do App
let divResultMsg = document.createElement('div');
divResultMsg.setAttribute('id', 'divResultMsg');
let divResultCoins = document.createElement('div');
divResultCoins.setAttribute('id', 'divResultCoins');
let divResultButtons = document.createElement('div');
divResultButtons.setAttribute('id', 'divResultButtons');
let divResultBtn2OrN = document.createElement('button');
let divResultBtnNewGame = document.createElement('button');
let divResultBtnQuit = document.createElement('button');
divResultBtn2OrN.setAttribute('onclick', 'doubleOrNothing()');
divResultBtnNewGame.setAttribute('onclick', 'newGame()');
divResultBtnQuit.setAttribute('onclick', 'quit()');
divResultBtn2OrN.setAttribute('id', 'btn2OrN');
divResultBtnNewGame.setAttribute('id', 'btnNewGame');
divResultBtnQuit.setAttribute('id', 'btnQuit');
divResultButtons.appendChild(divResultBtn2OrN);
divResultButtons.appendChild(divResultBtnNewGame);
divResultButtons.appendChild(divResultBtnQuit);
divResultBtnQuit.setAttribute('onclick', 'quitBtnFunc()')
if (result == true) {
divResultMsg.innerHTML = `<p>That's a Calicojack!<br>You win!</p>`;
divResultCoins.innerHTML = `<p>Result: ${thisBet} coins</p>`;
} else {
divResultMsg.innerHTML = `<p>You lose!</p>`;
divResultCoins.innerHTML = `<p>Result: -${thisBet} coins</p>`;
}
divResultBtn2OrN.innerHTML = 'Double or Nothing';
divResultBtnNewGame.innerHTML = 'New Game';
divResultBtnQuit.innerHTML = 'Quit';
app.appendChild(divResultMsg);
app.appendChild(divResultCoins);
app.appendChild(divResultButtons);
}
function doubleOrNothing() {
audioClick.play();
dealerHand = [];
playerHand = [];
firstLoad();
if (playerCoins >= thisBet * 2) {
thisBet *= 2;
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = '';
document.body.appendChild(app);
renderAppMain();
} else {
alert('You do not have the required amount to double the bet.')
}
}
function newGame() {
audioClick.play();
if (playerCoins < 100) {
alert('The minimum bet is 100 coins. You do not have that amount of coins.');
} else {
thisBet = 100;
dealerHand = [];
playerHand = [];
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = '';
document.body.appendChild(app);
firstLoad();
renderAppMain();
}
}
// ----- Função do botão QUIT da tela de resultados ----- //
function quitBtnFunc() {
audioClick.play();
dealerHand = [];
playerHand = [];
playerName = '';
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = '';
document.body.appendChild(app);
firstLoad();
renderFirstPage();
}
// ----- Função do botão START da tela inicial ----- //
function startBtnFunc() {
audioClick.play();
// Salvar nome
playerName = document.querySelector('#blackBox input').value;
// Verificar preenchimento do campo Nome
if (playerName == "") {
alert('Please enter your name before starting.')
} else {
// Limpeza do App
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = ''
document.body.appendChild(app);
// Preenchimento do App
betAlert('confirmBetBtnFunc()', 'backBetBtnFunc()');
}
}
function backBetBtnFunc() {
audioClick.play();
document.body.removeChild(betAlertBox);
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = '';
document.body.appendChild(app);
renderFirstPage();
}
function confirmBetBtnFunc() {
audioClick.play();
if (document.querySelector('#inputBet').value > playerCoins) {
alert('You do not have that amount of coins.');
} else if (document.querySelector('#inputBet').value < 100) {
alert('The minimum bet is 100 coins.');
} else {
thisBet = parseInt(document.querySelector('#inputBet').value);
document.body.removeChild(betAlertBox);
let appDivDel = document.querySelector('#app');
appDivDel.parentElement.removeChild(appDivDel);
app.innerHTML = '';
document.body.appendChild(app);
renderAppMain();
}
}
// ----- Chamando primeira página ----- //
renderFirstPage(); |
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from app import app
class MainHandler(RequestHandler):
def get(self):
self.write("This message comes from Peng")
tr = WSGIContainer(app)
application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])
if __name__ == "__main__":
application.listen(80)
IOLoop.instance().start()
|
// This file was procedurally generated from the following sources:
// - src/identifier-names/break-escaped.case
// - src/identifier-names/default/covered-obj-prop-name.template
/*---
description: break is a valid identifier name, using escape (PropertyName in a CoverParenthesizedExpressionAndArrowParameterList)
esid: prod-PropertyDefinition
flags: [generated]
info: |
ObjectLiteral :
{ PropertyDefinitionList }
{ PropertyDefinitionList , }
PropertyDefinitionList:
PropertyDefinition
PropertyDefinitionList , PropertyDefinition
PropertyDefinition:
IdentifierReference
PropertyName : AssignmentExpression
MethodDefinition
... AssignmentExpression
...
PropertyName:
LiteralPropertyName
...
LiteralPropertyName:
IdentifierName
...
Reserved Words
A reserved word is an IdentifierName that cannot be used as an Identifier.
---*/
var obj = ({ bre\u0061k: 42 });
assert.sameValue(obj['break'], 42, 'property exists');
|
/* global heimdall */
/**
@module ember-data
*/
import $ from 'jquery';
import { Promise as EmberPromise } from 'rsvp';
import MapWithDefault from '@ember/map/with-default';
import { get } from '@ember/object';
import { run } from '@ember/runloop';
import Adapter from "../adapter";
import {
parseResponseHeaders,
BuildURLMixin,
isEnabled,
AdapterError,
InvalidError,
UnauthorizedError,
ForbiddenError,
NotFoundError,
ConflictError,
ServerError,
TimeoutError,
AbortError
} from '../-private';
import { instrument } from 'ember-data/-debug';
import { warn, deprecate } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
const Promise = EmberPromise;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## Success and failure
The REST adapter will consider a success any response with a status code
of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other
status code will be considered a failure.
On success, the request promise will be resolved with the full response
payload.
Failed responses with status code 422 ("Unprocessable Entity") will be
considered "invalid". The response will be discarded, except for the
`errors` key. The request promise will be rejected with a `DS.InvalidError`.
This error object will encapsulate the saved `errors` value.
Any other status codes will be treated as an "adapter error". The request
promise will be rejected, similarly to the "invalid" case, but with
an instance of `DS.AdapterError` instead.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"posts": {
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
Similarly, in response to a `GET` request for `/posts`, the JSON should
look like this:
```js
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
```
Note that the object root can be pluralized for both a single-object response
and an array response: the REST adapter is not strict on this. Further, if the
HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a
`findRecord` query) with more than one object in the array, Ember Data will
only display the object with the matching ID.
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"people": {
"id": 5,
"firstName": "Zaphod",
"lastName": "Beeblebrox",
"occupation": "President"
}
}
```
#### Relationships
Relationships are usually represented by ids to the record in the
relationship. The related records can then be sideloaded in the
response under a key for the type.
```js
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz",
"comments": [1, 2]
},
"comments": [{
"id": 1,
"author": "User 1",
"message": "First!",
}, {
"id": 2,
"author": "User 2",
"message": "Good Luck!",
}]
}
```
If the records in the relationship are not known when the response
is serialized its also possible to represent the relationship as a
url using the `links` key in the response. Ember Data will fetch
this url to resolve the relationship when it is accessed for the
first time.
```js
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz",
"links": {
"comments": "/posts/5/comments"
}
}
}
```
### Errors
If a response is considered a failure, the JSON payload is expected to include
a top-level key `errors`, detailing any specific issues. For example:
```js
{
"errors": {
"msg": "Something went wrong"
}
}
```
This adapter does not make any assumptions as to the format of the `errors`
object. It will simply be passed along as is, wrapped in an instance
of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it
afterwards.
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for the `Person` model would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
'API_KEY': 'secret key',
'ANOTHER_HEADER': 'Some header value'
}
});
```
`headers` can also be used as a computed property to support dynamic
headers. In the example below, the `session` object has been
injected into an adapter by Ember's container.
```app/adapters/application.js
import DS from 'ember-data';
import { computed } from '@ember/object';
export default DS.RESTAdapter.extend({
headers: computed('session.authToken', function() {
return {
'API_KEY': this.get('session.authToken'),
'ANOTHER_HEADER': 'Some header value'
};
})
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```app/adapters/application.js
import DS from 'ember-data';
import { get } from '@ember/object';
import { computed } from '@ember/object';
export default DS.RESTAdapter.extend({
headers: computed(function() {
return {
'API_KEY': get(document.cookie.match(/apiKey\=([^;]*)/), '1'),
'ANOTHER_HEADER': 'Some header value'
};
}).volatile()
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
@uses DS.BuildURLMixin
*/
const RESTAdapter = Adapter.extend(BuildURLMixin, {
defaultSerializer: '-rest',
/**
By default, the RESTAdapter will send the query params sorted alphabetically to the
server.
For example:
```js
store.query('posts', { sort: 'price', category: 'pets' });
```
will generate a requests like this `/posts?category=pets&sort=price`, even if the
parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms
in the backend.
Setting `sortQueryParams` to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set
`sortQueryParams` to your custom sort function.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
sortQueryParams(params) {
let sortedKeys = Object.keys(params).sort().reverse();
let len = sortedKeys.length, newParams = {};
for (let i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
});
```
@method sortQueryParams
@param {Object} obj
@return {Object}
*/
sortQueryParams(obj) {
let keys = Object.keys(obj);
let len = keys.length;
if (len < 2) {
return obj;
}
let newQueryParams = {};
let sortedKeys = keys.sort();
for (let i = 0; i < len; i++) {
newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]];
}
return newQueryParams;
},
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.findRecord('comment', 1);
store.findRecord('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for the `Post` model would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
Requests for the `Post` model would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API
key. Arbitrary headers can be set as key/value pairs on the
`RESTAdapter`'s `headers` object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
'API_KEY': 'secret key',
'ANOTHER_HEADER': 'Some header value'
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `findRecord` method makes an Ajax request to a URL computed by
`buildURL`, and returns a promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@since 1.13.0
@method findRecord
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
findRecord(store, type, id, snapshot) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, id, snapshot,
requestType: 'findRecord'
});
return this._makeRequest(request);
} else {
let url = this.buildURL(type.modelName, id, snapshot, 'findRecord');
let query = this.buildQuery(snapshot);
return this.ajax(url, 'GET', { data: query });
}
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@param {DS.SnapshotRecordArray} snapshotRecordArray
@return {Promise} promise
*/
findAll(store, type, sinceToken, snapshotRecordArray) {
let query = this.buildQuery(snapshotRecordArray);
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, sinceToken, query,
snapshots: snapshotRecordArray,
requestType: 'findAll'
});
return this._makeRequest(request);
} else {
let url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll');
if (sinceToken) {
query.since = sinceToken;
}
return this.ajax(url, 'GET', { data: query });
}
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `query` method makes an Ajax (HTTP GET) request to a URL
computed by `buildURL`, and returns a promise for the resulting
payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@method query
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
query(store, type, query) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, query,
requestType: 'query'
});
return this._makeRequest(request);
} else {
let url = this.buildURL(type.modelName, null, null, 'query', query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, 'GET', { data: query });
}
},
/**
Called by the store in order to fetch a JSON object for
the record that matches a particular query.
The `queryRecord` method makes an Ajax (HTTP GET) request to a URL
computed by `buildURL`, and returns a promise for the resulting
payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@since 1.13.0
@method queryRecord
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
queryRecord(store, type, query) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, query,
requestType: 'queryRecord'
});
return this._makeRequest(request);
} else {
let url = this.buildURL(type.modelName, null, null, 'queryRecord', query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, 'GET', { data: query });
}
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {DS.Model} type
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany(store, type, ids, snapshots) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, ids, snapshots,
requestType: 'findMany'
});
return this._makeRequest(request);
} else {
let url = this.buildURL(type.modelName, ids, snapshots, 'findMany');
return this.ajax(url, 'GET', { data: { ids: ids } });
}
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your `links` value will influence the final request URL via the `urlPrefix` method:
* Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation.
* Links beginning with a single `/` will have the current adapter's `host` value prepended to it.
* Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`.
@method findHasMany
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@param {Object} relationship meta object describing the relationship
@return {Promise} promise
*/
findHasMany(store, snapshot, url, relationship) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, snapshot, url, relationship,
requestType: 'findHasMany'
});
return this._makeRequest(request);
} else {
let id = snapshot.id;
let type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany'));
return this.ajax(url, 'GET');
}
},
/**
Called by the store in order to fetch the JSON for the unloaded record in a
belongs-to relationship that was originally specified as a URL (inside of
`links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your `links` value will influence the final request URL via the `urlPrefix` method:
* Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation.
* Links beginning with a single `/` will have the current adapter's `host` value prepended to it.
* Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@param {Object} relationship meta object describing the relationship
@return {Promise} promise
*/
findBelongsTo(store, snapshot, url, relationship) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, snapshot, url, relationship,
requestType: 'findBelongsTo'
});
return this._makeRequest(request);
} else {
let id = snapshot.id;
let type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo'));
return this.ajax(url, 'GET');
}
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord(store, type, snapshot) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, snapshot,
requestType: 'createRecord'
});
return this._makeRequest(request);
} else {
let data = {};
let serializer = store.serializerFor(type.modelName);
let url = this.buildURL(type.modelName, null, snapshot, 'createRecord');
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return this.ajax(url, "POST", { data: data });
}
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord(store, type, snapshot) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, snapshot,
requestType: 'updateRecord'
});
return this._makeRequest(request);
} else {
let data = {};
let serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot);
let id = snapshot.id;
let url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
return this.ajax(url, "PUT", { data: data });
}
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord(store, type, snapshot) {
if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) {
let request = this._requestFor({
store, type, snapshot,
requestType: 'deleteRecord'
});
return this._makeRequest(request);
} else {
let id = snapshot.id;
return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE");
}
},
_stripIDFromURL(store, snapshot) {
let url = this.buildURL(snapshot.modelName, snapshot.id, snapshot);
let expandedURL = url.split('/');
// Case when the url is of the format ...something/:id
// We are decodeURIComponent-ing the lastSegment because if it represents
// the id, it has been encodeURIComponent-ified within `buildURL`. If we
// don't do this, then records with id having special characters are not
// coalesced correctly (see GH #4190 for the reported bug)
let lastSegment = expandedURL[expandedURL.length - 1];
let id = snapshot.id;
if (decodeURIComponent(lastSegment) === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (endsWith(lastSegment, '?id=' + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join('/');
},
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
maxURLLength: 2048,
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
This implementation groups together records that have the same base URL but
differing ids. For example `/comments/1` and `/comments/2` will be grouped together
because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2`
It also supports urls where ids are passed as a query param, such as `/comments?id=1`
but not those where there is more than 1 query param such as `/comments?id=2&name=David`
Currently only the query param of `id` is supported. If you need to support others, please
override this or the `_stripIDFromURL` method.
It does not group records that have differing base urls, such as for example: `/posts/1/comments/2`
and `/posts/2/comments/3`
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany(store, snapshots) {
let groups = MapWithDefault.create({ defaultValue() { return []; } });
let adapter = this;
let maxURLLength = this.maxURLLength;
snapshots.forEach((snapshot) => {
let baseUrl = adapter._stripIDFromURL(store, snapshot);
groups.get(baseUrl).push(snapshot);
});
function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) {
let idsSize = 0;
let baseUrl = adapter._stripIDFromURL(store, group[0]);
let splitGroups = [[]];
group.forEach((snapshot) => {
let additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength;
if (baseUrl.length + idsSize + additionalLength >= maxURLLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
let lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(snapshot);
});
return splitGroups;
}
let groupsArray = [];
groups.forEach((group, key) => {
let paramNameLength = '&ids%5B%5D='.length;
let splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength);
splitGroups.forEach((splitGroup) => groupsArray.push(splitGroup));
});
return groupsArray;
},
/**
Takes an ajax response, and returns the json payload or an error.
By default this hook just returns the json payload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the response headers.
Response headers are passed in as the second argument.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object. You can return a `DS.InvalidError` or a
`DS.AdapterError` (or a sub class) from this hook and it will automatically
reject the promise and put your record into the invalid or error state.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record. When returning an
`DS.InvalidError` the store will attempt to normalize the error data
returned from the server using the serializer's `extractErrors`
method.
@since 1.13.0
@method handleResponse
@param {Number} status
@param {Object} headers
@param {Object} payload
@param {Object} requestData - the original request information
@return {Object | DS.AdapterError} response
*/
handleResponse(status, headers, payload, requestData) {
if (this.isSuccess(status, headers, payload)) {
return payload;
} else if (this.isInvalid(status, headers, payload)) {
return new InvalidError(payload.errors);
}
let errors = this.normalizeErrorResponse(status, headers, payload);
let detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData);
switch (status) {
case 401:
return new UnauthorizedError(errors, detailedMessage);
case 403:
return new ForbiddenError(errors, detailedMessage);
case 404:
return new NotFoundError(errors, detailedMessage);
case 409:
return new ConflictError(errors, detailedMessage);
default:
if (status >= 500) {
return new ServerError(errors, detailedMessage);
}
}
return new AdapterError(errors, detailedMessage);
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is a success.
@since 1.13.0
@method isSuccess
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isSuccess(status, headers, payload) {
return status >= 200 && status < 300 || status === 304;
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is an invalid error.
@since 1.13.0
@method isInvalid
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isInvalid(status, headers, payload) {
return status === 422;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Promise} promise
*/
ajax(url, type, options) {
let token = heimdall.start('adapter.ajax');
let adapter = this;
let requestData = {
url: url,
method: type
};
return new Promise(function(resolve, reject) {
let hash = adapter.ajaxOptions(url, type, options);
hash.success = function(payload, textStatus, jqXHR) {
heimdall.stop(token);
let response = ajaxSuccess(adapter, jqXHR, payload, requestData);
run.join(null, resolve, response);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
heimdall.stop(token);
let responseData = {
textStatus,
errorThrown
};
let error = ajaxError(adapter, jqXHR, requestData, responseData);
run.join(null, reject, error);
};
adapter._ajaxRequest(hash);
}, 'DS: RESTAdapter#ajax ' + type + ' to ' + url);
},
/**
@method _ajaxRequest
@private
@param {Object} options jQuery ajax options to be used for the ajax request
*/
_ajaxRequest(options) {
$.ajax(options);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Object}
*/
ajaxOptions(url, type, options) {
let hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
instrument(function() {
hash.converters = {
'text json': function(payload) {
let token = heimdall.start('json.parse');
let json;
try {
json = $.parseJSON(payload);
} catch (e) {
json = payload;
}
heimdall.stop(token);
return json;
}
};
});
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
let headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return hash;
},
/**
@method parseErrorResponse
@private
@param {String} responseText
@return {Object}
*/
parseErrorResponse(responseText) {
let json = responseText;
try {
json = $.parseJSON(responseText);
} catch (e) {
// ignored
}
return json;
},
/**
@method normalizeErrorResponse
@private
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Array} errors payload
*/
normalizeErrorResponse(status, headers, payload) {
if (payload && typeof payload === 'object' && payload.errors) {
return payload.errors;
} else {
return [
{
status: `${status}`,
title: "The backend responded with an error",
detail: `${payload}`
}
];
}
},
/**
Generates a detailed ("friendly") error message, with plenty
of information for debugging (good luck!)
@method generatedDetailedMessage
@private
@param {Number} status
@param {Object} headers
@param {Object} payload
@param {Object} requestData
@return {String} detailed error message
*/
generatedDetailedMessage: function(status, headers, payload, requestData) {
let shortenedPayload;
let payloadContentType = headers["Content-Type"] || "Empty Content-Type";
if (payloadContentType === "text/html" && payload.length > 250) {
shortenedPayload = "[Omitted Lengthy HTML]";
} else {
shortenedPayload = payload;
}
let requestDescription = requestData.method + ' ' + requestData.url;
let payloadDescription = 'Payload (' + payloadContentType + ')';
return ['Ember Data Request ' + requestDescription + ' returned a ' + status,
payloadDescription,
shortenedPayload].join('\n');
},
// @since 2.5.0
buildQuery(snapshot) {
let query = {};
if (snapshot) {
let { include } = snapshot;
if (include) {
query.include = include;
}
}
return query;
},
_hasCustomizedAjax() {
if (this.ajax !== RESTAdapter.prototype.ajax) {
deprecate('RESTAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.rest-adapter.ajax',
until: '3.0.0'
});
return true;
}
if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) {
deprecate('RESTAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.rest-adapter.ajax-options',
until: '3.0.0'
});
return true;
}
return false;
}
});
if (isEnabled('ds-improved-ajax')) {
RESTAdapter.reopen({
/*
* Get the data (body or query params) for a request.
*
* @public
* @method dataForRequest
* @param {Object} params
* @return {Object} data
*/
dataForRequest(params) {
let { store, type, snapshot, requestType, query } = params;
// type is not passed to findBelongsTo and findHasMany
type = type || (snapshot && snapshot.type);
let serializer = store.serializerFor(type.modelName);
let data = {};
switch (requestType) {
case 'createRecord':
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
break;
case 'updateRecord':
serializer.serializeIntoHash(data, type, snapshot);
break;
case 'findRecord':
data = this.buildQuery(snapshot);
break;
case 'findAll':
if (params.sinceToken) {
query = query || {};
query.since = params.sinceToken;
}
data = query;
break;
case 'query':
case 'queryRecord':
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
data = query;
break;
case 'findMany':
data = { ids: params.ids };
break;
default:
data = undefined;
break;
}
return data;
},
/*
* Get the HTTP method for a request.
*
* @public
* @method methodForRequest
* @param {Object} params
* @return {String} HTTP method
*/
methodForRequest(params) {
let { requestType } = params;
switch (requestType) {
case 'createRecord': return 'POST';
case 'updateRecord': return 'PUT';
case 'deleteRecord': return 'DELETE';
}
return 'GET';
},
/*
* Get the URL for a request.
*
* @public
* @method urlForRequest
* @param {Object} params
* @return {String} URL
*/
urlForRequest(params) {
let { type, id, ids, snapshot, snapshots, requestType, query } = params;
// type and id are not passed from updateRecord and deleteRecord, hence they
// are defined if not set
type = type || (snapshot && snapshot.type);
id = id || (snapshot && snapshot.id);
switch (requestType) {
case 'findAll':
return this.buildURL(type.modelName, null, snapshots, requestType);
case 'query':
case 'queryRecord':
return this.buildURL(type.modelName, null, null, requestType, query);
case 'findMany':
return this.buildURL(type.modelName, ids, snapshots, requestType);
case 'findHasMany':
case 'findBelongsTo': {
let url = this.buildURL(type.modelName, id, snapshot, requestType);
return this.urlPrefix(params.url, url);
}
}
return this.buildURL(type.modelName, id, snapshot, requestType, query);
},
/*
* Get the headers for a request.
*
* By default the value of the `headers` property of the adapter is
* returned.
*
* @public
* @method headersForRequest
* @param {Object} params
* @return {Object} headers
*/
headersForRequest(params) {
return this.get('headers');
},
/*
* Get an object which contains all properties for a request which should
* be made.
*
* @private
* @method _requestFor
* @param {Object} params
* @return {Object} request object
*/
_requestFor(params) {
let method = this.methodForRequest(params);
let url = this.urlForRequest(params);
let headers = this.headersForRequest(params);
let data = this.dataForRequest(params);
return { method, url, headers, data };
},
/*
* Convert a request object into a hash which can be passed to `jQuery.ajax`.
*
* @private
* @method _requestToJQueryAjaxHash
* @param {Object} request
* @return {Object} jQuery ajax hash
*/
_requestToJQueryAjaxHash(request) {
let hash = {};
hash.type = request.method;
hash.url = request.url;
hash.dataType = 'json';
hash.context = this;
if (request.data) {
if (request.method !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(request.data);
} else {
hash.data = request.data;
}
}
let headers = request.headers;
if (headers !== undefined) {
hash.beforeSend = function(xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return hash;
},
/*
* Make a request using `jQuery.ajax`.
*
* @private
* @method _makeRequest
* @param {Object} request
* @return {Promise} promise
*/
_makeRequest(request) {
let token = heimdall.start('adapter._makeRequest');
let adapter = this;
let hash = this._requestToJQueryAjaxHash(request);
let { method, url } = request;
let requestData = { method, url };
return new Promise((resolve, reject) => {
hash.success = function(payload, textStatus, jqXHR) {
heimdall.stop(token);
let response = ajaxSuccess(adapter, jqXHR, payload, requestData);
run.join(null, resolve, response);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
heimdall.stop(token);
let responseData = {
textStatus,
errorThrown
};
let error = ajaxError(adapter, jqXHR, requestData, responseData);
run.join(null, reject, error);
};
instrument(function() {
hash.converters = {
'text json': function(payload) {
let token = heimdall.start('json.parse');
let json;
try {
json = $.parseJSON(payload);
} catch (e) {
json = payload;
}
heimdall.stop(token);
return json;
}
};
});
adapter._ajaxRequest(hash);
}, `DS: RESTAdapter#makeRequest: ${method} ${url}`);
}
});
}
function ajaxSuccess(adapter, jqXHR, payload, requestData) {
let response;
try {
response = adapter.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
payload,
requestData
);
} catch (error) {
return Promise.reject(error);
}
if (response && response.isAdapterError) {
return Promise.reject(response);
} else {
return response;
}
}
function ajaxError(adapter, jqXHR, requestData, responseData) {
if (DEBUG) {
let message = `The server returned an empty string for ${requestData.method} ${requestData.url}, which cannot be parsed into a valid JSON. Return either null or {}.`;
let validJSONString = !(responseData.textStatus === "parsererror" && jqXHR.responseText === "");
warn(message, validJSONString, {
id: 'ds.adapter.returned-empty-string-as-JSON'
});
}
let error;
if (responseData.errorThrown instanceof Error) {
error = responseData.errorThrown;
} else if (responseData.textStatus === 'timeout') {
error = new TimeoutError();
} else if (responseData.textStatus === 'abort' || jqXHR.status === 0) {
error = new AbortError();
} else {
try {
error = adapter.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown,
requestData
);
} catch (e) {
error = e;
}
}
return error;
}
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== 'function') {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
export default RESTAdapter;
|
#pragma once
#include <cstdint>
#include <list>
#include <memory>
#include "envoy/common/random_generator.h"
#include "envoy/event/deferred_deletable.h"
#include "envoy/event/timer.h"
#include "envoy/http/codec.h"
#include "envoy/network/connection.h"
#include "envoy/network/filter.h"
#include "envoy/upstream/upstream.h"
#include "source/common/common/assert.h"
#include "source/common/common/linked_object.h"
#include "source/common/common/logger.h"
#include "source/common/http/codec_wrappers.h"
#include "source/common/network/filter_impl.h"
namespace Envoy {
namespace Http {
/**
* Callbacks specific to a codec client.
*/
class CodecClientCallbacks {
public:
virtual ~CodecClientCallbacks() = default;
// Called in onPreDecodeComplete
virtual void onStreamPreDecodeComplete() {}
/**
* Called every time an owned stream is destroyed, whether complete or not.
*/
virtual void onStreamDestroy() PURE;
/**
* Called when a stream is reset by the client.
* @param reason supplies the reset reason.
*/
virtual void onStreamReset(StreamResetReason reason) PURE;
};
/**
* This is an HTTP client that multiple stream management and underlying connection management
* across multiple HTTP codec types.
*/
class CodecClient : protected Logger::Loggable<Logger::Id::client>,
public Http::ConnectionCallbacks,
public Network::ConnectionCallbacks,
public Event::DeferredDeletable {
public:
/**
* Type of HTTP codec to use.
*/
// This is a legacy alias.
using Type = Envoy::Http::CodecType;
/**
* Add a connection callback to the underlying network connection.
*/
void addConnectionCallbacks(Network::ConnectionCallbacks& cb) {
connection_->addConnectionCallbacks(cb);
}
/**
* Return if half-close semantics are enabled on the underlying connection.
*/
bool isHalfCloseEnabled() { return connection_->isHalfCloseEnabled(); }
/**
* Close the underlying network connection. This is immediate and will not attempt to flush any
* pending write data.
*/
void close();
/**
* Send a codec level go away indication to the peer.
*/
void goAway() { codec_->goAway(); }
/**
* @return the underlying connection ID.
*/
uint64_t id() const { return connection_->id(); }
/**
* @return the underlying codec protocol.
*/
Protocol protocol() { return codec_->protocol(); }
/**
* @return the underlying connection error.
*/
absl::string_view connectionFailureReason() { return connection_->transportFailureReason(); }
/**
* @return size_t the number of outstanding requests that have not completed or been reset.
*/
size_t numActiveRequests() { return active_requests_.size(); }
/**
* Create a new stream. Note: The CodecClient will NOT buffer multiple requests for HTTP1
* connections. Thus, calling newStream() before the previous request has been fully encoded
* is an error. Pipelining is supported however.
* @param response_decoder supplies the decoder to use for response callbacks.
* @return StreamEncoder& the encoder to use for encoding the request.
*/
RequestEncoder& newStream(ResponseDecoder& response_decoder);
void setConnectionStats(const Network::Connection::ConnectionStats& stats) {
connection_->setConnectionStats(stats);
}
void setCodecClientCallbacks(CodecClientCallbacks& callbacks) {
codec_client_callbacks_ = &callbacks;
}
void setCodecConnectionCallbacks(Http::ConnectionCallbacks& callbacks) {
codec_callbacks_ = &callbacks;
}
bool remoteClosed() const { return remote_closed_; }
CodecType type() const { return type_; }
// Note this is the L4 stream info, not L7.
const StreamInfo::StreamInfo& streamInfo() { return connection_->streamInfo(); }
/**
* Connect to the host.
* Needs to be called after codec_ is instantiated.
*/
void connect();
protected:
/**
* Create a codec client and connect to a remote host/port.
* @param type supplies the codec type.
* @param connection supplies the connection to communicate on.
* @param host supplies the owning host.
*/
CodecClient(CodecType type, Network::ClientConnectionPtr&& connection,
Upstream::HostDescriptionConstSharedPtr host, Event::Dispatcher& dispatcher);
// Http::ConnectionCallbacks
void onGoAway(GoAwayErrorCode error_code) override {
if (codec_callbacks_) {
codec_callbacks_->onGoAway(error_code);
}
}
void onSettings(ReceivedSettings& settings) override {
if (codec_callbacks_) {
codec_callbacks_->onSettings(settings);
}
}
void onMaxStreamsChanged(uint32_t num_streams) override {
if (codec_callbacks_) {
codec_callbacks_->onMaxStreamsChanged(num_streams);
}
}
void onIdleTimeout() {
host_->cluster().stats().upstream_cx_idle_timeout_.inc();
close();
}
void disableIdleTimer() {
if (idle_timer_ != nullptr) {
idle_timer_->disableTimer();
}
}
void enableIdleTimer() {
if (idle_timer_ != nullptr) {
idle_timer_->enableTimer(idle_timeout_.value());
}
}
const CodecType type_;
// The order of host_, connection_, and codec_ matter as during destruction each can refer to
// the previous, at least in tests.
Upstream::HostDescriptionConstSharedPtr host_;
Network::ClientConnectionPtr connection_;
ClientConnectionPtr codec_;
Event::TimerPtr idle_timer_;
const absl::optional<std::chrono::milliseconds> idle_timeout_;
private:
/**
* Wrapper read filter to drive incoming connection data into the codec. We could potentially
* support other filters in the future.
*/
struct CodecReadFilter : public Network::ReadFilterBaseImpl {
CodecReadFilter(CodecClient& parent) : parent_(parent) {}
// Network::ReadFilter
Network::FilterStatus onData(Buffer::Instance& data, bool end_stream) override {
parent_.onData(data);
if (end_stream && parent_.isHalfCloseEnabled()) {
// Note that this results in the connection closed as if it was closed
// locally, it would be more correct to convey the end stream to the
// response decoder, but it would require some refactoring.
parent_.close();
}
return Network::FilterStatus::StopIteration;
}
CodecClient& parent_;
};
struct ActiveRequest;
/**
* Wrapper for an outstanding request. Designed for handling stream multiplexing.
*/
struct ActiveRequest : LinkedObject<ActiveRequest>,
public Event::DeferredDeletable,
public StreamCallbacks,
public ResponseDecoderWrapper {
ActiveRequest(CodecClient& parent, ResponseDecoder& inner)
: ResponseDecoderWrapper(inner), parent_(parent) {}
// StreamCallbacks
void onResetStream(StreamResetReason reason, absl::string_view) override {
parent_.onReset(*this, reason);
}
void onAboveWriteBufferHighWatermark() override {}
void onBelowWriteBufferLowWatermark() override {}
// StreamDecoderWrapper
void onPreDecodeComplete() override { parent_.responsePreDecodeComplete(*this); }
void onDecodeComplete() override {}
RequestEncoder* encoder_{};
CodecClient& parent_;
};
using ActiveRequestPtr = std::unique_ptr<ActiveRequest>;
/**
* Called when a response finishes decoding. This is called *before* forwarding on to the
* wrapped decoder.
*/
void responsePreDecodeComplete(ActiveRequest& request);
void deleteRequest(ActiveRequest& request);
void onReset(ActiveRequest& request, StreamResetReason reason);
void onData(Buffer::Instance& data);
// Network::ConnectionCallbacks
void onEvent(Network::ConnectionEvent event) override;
// Pass watermark events from the connection on to the codec which will pass it to the underlying
// streams.
void onAboveWriteBufferHighWatermark() override {
codec_->onUnderlyingConnectionAboveWriteBufferHighWatermark();
}
void onBelowWriteBufferLowWatermark() override {
codec_->onUnderlyingConnectionBelowWriteBufferLowWatermark();
}
std::list<ActiveRequestPtr> active_requests_;
Http::ConnectionCallbacks* codec_callbacks_{};
CodecClientCallbacks* codec_client_callbacks_{};
bool connected_{};
bool remote_closed_{};
bool protocol_error_{false};
bool connect_called_{false};
};
using CodecClientPtr = std::unique_ptr<CodecClient>;
/**
* Production implementation that installs a real codec without automatically connecting.
* TODO(danzh) deprecate this class and make CodecClientProd to have the option to defer connect
* once "envoy.reloadable_features.postpone_h3_client_connect_to_next_loop" is deprecated.
*/
class NoConnectCodecClientProd : public CodecClient {
public:
NoConnectCodecClientProd(CodecType type, Network::ClientConnectionPtr&& connection,
Upstream::HostDescriptionConstSharedPtr host,
Event::Dispatcher& dispatcher,
Random::RandomGenerator& random_generator);
};
/**
* Production implementation that installs a real codec.
*/
class CodecClientProd : public NoConnectCodecClientProd {
public:
CodecClientProd(CodecType type, Network::ClientConnectionPtr&& connection,
Upstream::HostDescriptionConstSharedPtr host, Event::Dispatcher& dispatcher,
Random::RandomGenerator& random_generator);
};
} // namespace Http
} // namespace Envoy
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:31:48 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /usr/lib/libacmobileshim.dylib
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libacmobileshim.dylib/ACMKeychainTGTStoragePolicy.h>
@class NSData;
@interface ACMExternalTGTStoragePolicy : ACMKeychainTGTStoragePolicy {
NSData* _secret;
}
@property (nonatomic,readonly) id<ACFCryptographProtocol> cryptograph;
@property (nonatomic,readonly) NSData * secret; //@synthesize secret=_secret - In the implementation block
-(id)service;
-(id)preferences;
-(NSData *)secret;
-(int)storeItemWithInfo:(id)arg1 ;
-(id)tokenDataWithDictionary:(id)arg1 ;
-(id)encryptTokenData:(id)arg1 ;
-(id)decryptTokenData:(id)arg1 ;
-(id)tokenDictionaryWithData:(id)arg1 ;
-(void)resetSecret;
-(BOOL)performRemoveTokenWithPrincipal:(id)arg1 service:(id)arg2 ;
-(id<ACFCryptographProtocol>)cryptograph;
-(id)searchItemWithInfo:(id)arg1 ;
@end
|
//
// LevelDB.h
//
// Copyright 2011 Pave Labs.
// See LICENCE for details.
//
#import <Foundation/Foundation.h>
@class LDBSnapshot;
@class LDBWritebatch;
typedef struct LevelDBOptions {
BOOL createIfMissing ;
BOOL createIntermediateDirectories;
BOOL errorIfExists ;
BOOL paranoidCheck ;
BOOL compression ;
int filterPolicy ;
size_t cacheSize;
} LevelDBOptions;
typedef struct {
const char * data;
NSUInteger length;
} LevelDBKey;
typedef NSData * (^LevelDBEncoderBlock) (LevelDBKey * key, id object);
typedef id (^LevelDBDecoderBlock) (LevelDBKey * key, id data);
typedef void (^LevelDBKeyBlock) (LevelDBKey * key, BOOL *stop);
typedef void (^LevelDBKeyValueBlock)(LevelDBKey * key, id value, BOOL *stop);
typedef id (^LevelDBValueGetterBlock) (void);
typedef void (^LevelDBLazyKeyValueBlock) (LevelDBKey * key, LevelDBValueGetterBlock lazyValue, BOOL *stop);
FOUNDATION_EXPORT NSString * const kLevelDBChangeType;
FOUNDATION_EXPORT NSString * const kLevelDBChangeTypePut;
FOUNDATION_EXPORT NSString * const kLevelDBChangeTypeDelete;
FOUNDATION_EXPORT NSString * const kLevelDBChangeValue;
FOUNDATION_EXPORT NSString * const kLevelDBChangeKey;
#ifdef __cplusplus
extern "C" {
#endif
NSString * NSStringFromLevelDBKey(LevelDBKey * key);
NSData * NSDataFromLevelDBKey (LevelDBKey * key);
#ifdef __cplusplus
}
#endif
@interface LevelDB : NSObject
///------------------------------------------------------------------------
/// @name A LevelDB object, used to query to the database instance on disk
///------------------------------------------------------------------------
/**
The path of the database on disk
*/
@property (nonatomic, retain) NSString *path;
/**
The name of the database.
*/
@property (nonatomic, retain) NSString *name;
/**
A boolean value indicating whether write operations should be synchronous (flush to disk before returning).
*/
@property (nonatomic) BOOL safe;
/**
A boolean value indicating whether read operations should try to use the configured cache (defaults to true).
*/
@property (nonatomic) BOOL useCache;
/**
A boolean readonly value indicating whether the database is closed or not.
*/
@property (readonly) BOOL closed;
/**
The data encoding block.
*/
@property (nonatomic, copy) LevelDBEncoderBlock encoder;
/**
The data decoding block.
*/
@property (nonatomic, copy) LevelDBDecoderBlock decoder;
/**
A class method that returns a LevelDBOptions struct, which can be modified to finetune leveldb
*/
+ (LevelDBOptions) makeOptions;
/**
A class method that returns an autoreleased instance of LevelDB with the given name, inside the Library folder
@param name The database's filename
*/
+ (id) databaseInLibraryWithName:(NSString *)name;
/**
A class method that returns an autoreleased instance of LevelDB with the given name and options, inside the Library folder
@param name The database's filename
@param opts A LevelDBOptions struct with options for fine tuning leveldb
*/
+ (id) databaseInLibraryWithName:(NSString *)name andOptions:(LevelDBOptions)opts;
/**
Initialize a leveldb instance
@param path The parent directory of the database file on disk
@param name the filename of the database file on disk
*/
- (id) initWithPath:(NSString *)path andName:(NSString *)name;
/**
Initialize a leveldb instance
@param path The parent directory of the database file on disk
@param name the filename of the database file on disk
@param opts A LevelDBOptions struct with options for fine tuning leveldb
*/
- (id) initWithPath:(NSString *)path name:(NSString *)name andOptions:(LevelDBOptions)opts;
/**
Delete the database file on disk
*/
- (void) deleteDatabaseFromDisk;
/**
Close the database.
@warning The instance cannot be used to perform any query after it has been closed.
*/
- (void) close;
#pragma mark - Setters
/**
Set the value associated with a key in the database
The instance's encoder block will be used to produce a NSData instance from the provided value.
@param value The value to put in the database
@param key The key at which the value can be found
*/
- (void) setObject:(id)value forKey:(id)key;
/**
Same as `[self setObject:forKey:]`
*/
- (void) setObject:(id)value forKeyedSubscript:(id)key;
/**
Same as `[self setObject:forKey:]`
*/
- (void) setValue:(id)value forKey:(NSString *)key ;
/**
Take all key-value pairs in the provided dictionary and insert them in the database
@param dictionary A dictionary from which key-value pairs will be inserted
*/
- (void) addEntriesFromDictionary:(NSDictionary *)dictionary;
#pragma mark - Write batches
/**
Return an retained LDBWritebatch instance for this database
*/
- (LDBWritebatch *) newWritebatch;
/**
Apply the operations from a writebatch into the current database
*/
- (void) applyWritebatch:(LDBWritebatch *)writeBatch;
#pragma mark - Getters
/**
Return the value associated with a key
@param key The key to retrieve from the database
*/
- (id) objectForKey:(id)key;
/**
Same as `[self objectForKey:]`
*/
- (id) objectForKeyedSubscript:(id)key;
/**
Same as `[self objectForKey:]`
*/
- (id) valueForKey:(NSString *)key;
/**
Return an array containing the values associated with the provided list of keys.
For keys that can't be found in the database, the `marker` value is used in place.
@warning marker should not be `nil`
@param keys The list of keys to fetch from the database
@param marker The value to associate to missing keys
*/
- (id) objectsForKeys:(NSArray *)keys notFoundMarker:(id)marker;
/**
Return a boolean value indicating whether or not the key exists in the database
@param key The key to check for existence
*/
- (BOOL) objectExistsForKey:(id)key;
#pragma mark - Removers
/**
Remove a key (and its associated value) from the database
@param key The key to remove from the database
*/
- (void) removeObjectForKey:(id)key;
/**
Remove a set of keys (and their associated values) from the database
@param keyArray An array of keys to remove from the database
*/
- (void) removeObjectsForKeys:(NSArray *)keyArray;
/**
Remove all objects from the database
*/
- (void) removeAllObjects;
/**
Remove all objects prefixed with a given value (`NSString` or `NSData`)
@param prefix The key prefix used to remove all matching keys (of type `NSString` or `NSData`)
*/
- (void) removeAllObjectsWithPrefix:(id)prefix;
#pragma mark - Selection
/**
Return an array containing all the keys of the database
@warning This shouldn't be used with very large databases, since every key will be stored in memory
*/
- (NSArray *) allKeys;
/**
Return an array of key for which the value match the given predicate
@param predicate A `NSPredicate` instance tested against the database's values to retrieve the corresponding keys
*/
- (NSArray *) keysByFilteringWithPredicate:(NSPredicate *)predicate;
/**
Return a dictionary with all key-value pairs, where values match the given predicate
@param predicate A `NSPredicate` instance tested against the database's values to retrieve the corresponding key-value pairs
*/
- (NSDictionary *) dictionaryByFilteringWithPredicate:(NSPredicate *)predicate;
/**
Return an retained LDBSnapshot instance for this database
LDBSnapshots are a way to "freeze" the state of the database. Write operation applied to the database after the
snapshot was taken do not affect the snapshot. Most *read* methods available in the LevelDB class are also
available in the LDBSnapshot class.
*/
- (LDBSnapshot *) newSnapshot;
#pragma mark - Enumeration
/**
Enumerate over the keys in the database, in order.
Same as `[self enumerateKeysBackward:FALSE startingAtKey:nil filteredByPredicate:nil andPrefix:nil usingBlock:block]`
@param block The enumeration block used when iterating over all the keys.
*/
- (void) enumerateKeysUsingBlock:(LevelDBKeyBlock)block;
/**
Enumerate over the keys in the database, in direct or backward order, with some options to control the keys iterated over
@param backward A boolean value indicating whether the enumeration happens in direct or backward order
@param key (optional) The key at which to start iteration. If the key isn't present in the database, the enumeration starts at the key immediately greater than the provided one. The key can be a `NSData` or `NSString`
@param predicate A `NSPredicate` instance tested against the values. The iteration block will only be called for keys associated to values matching the predicate. If `nil`, this is ignored.
@param prefix A `NSString` or `NSData` prefix used to filter the keys. If provided, only the keys prefixed with this value will be iterated over.
@param block The enumeration block used when iterating over all the keys. It takes two arguments: the first is a pointer to a `LevelDBKey` struct. You can convert this to a `NSString` or `NSData` instance, using `NSDataFromLevelDBKey(LevelDBKey *key)` and `NSStringFromLevelDBKey(LevelDBKey *key)` respectively. The second arguments to the block is a `BOOL *` that can be used to stop enumeration at any time (e.g. `*stop = TRUE;`).
*/
- (void) enumerateKeysBackward:(BOOL)backward
startingAtKey:(id)key
filteredByPredicate:(NSPredicate *)predicate
andPrefix:(id)prefix
usingBlock:(LevelDBKeyBlock)block;
/**
Enumerate over the key value pairs in the database, in order.
Same as `[self enumerateKeysAndObjectsBackward:FALSE startingAtKey:nil filteredByPredicate:nil andPrefix:nil usingBlock:block]`
@param block The enumeration block used when iterating over all the key value pairs.
*/
- (void) enumerateKeysAndObjectsUsingBlock:(LevelDBKeyValueBlock)block;
/**
Enumerate over the keys in the database, in direct or backward order, with some options to control the keys iterated over
@param backward A boolean value indicating whether the enumeration happens in direct or backward order
@param key (optional) The key at which to start iteration. If the key isn't present in the database, the enumeration starts at the key immediately greater than the provided one. The key can be a `NSData` or `NSString`
@param predicate A `NSPredicate` instance tested against the values. The iteration block will only be called for keys associated to values matching the predicate. If `nil`, this is ignored.
@param prefix A `NSString` or `NSData` prefix used to filter the keys. If provided, only the keys prefixed with this value will be iterated over.
@param block The enumeration block used when iterating over all the keys. It takes three arguments: the first is a pointer to a `LevelDBKey` struct. You can convert this to a `NSString` or `NSData` instance, using `NSDataFromLevelDBKey(LevelDBKey *key)` and `NSStringFromLevelDBKey(LevelDBKey *key)` respectively. The second argument is the value associated with the key. The third arguments to the block is a `BOOL *` that can be used to stop enumeration at any time (e.g. `*stop = TRUE;`).
*/
- (void) enumerateKeysAndObjectsBackward:(BOOL)backward
lazily:(BOOL)lazily
startingAtKey:(id)key
filteredByPredicate:(NSPredicate *)predicate
andPrefix:(id)prefix
usingBlock:(id)block;
@end
|
const mp3Duration = require('mp3-duration');
const voices = require('./info').voices;
const asset = require('../asset/main');
const qs = require('querystring');
const brotli = require('brotli');
const md5 = require("js-md5");
const base64 = require("base64-js");
const https = require('https');
const http = require('http');
function processVoice(voiceName, text) {
return new Promise((res, rej) => {
const voice = voices[voiceName];
switch (voice.source) {
case "polly": {
https.get('https://voicemaker.in/', r => {
const cookie = r.headers['set-cookie'];
var req = https.request({
hostname: "voicemaker.in",
port: "443",
path: "/voice/standard",
method: "POST",
headers: {
"content-type": "application/json",
cookie: cookie,
"csrf-token": "",
origin: "https://voicemaker.in",
referer: "https://voicemaker.in/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36",
"x-requested-with": "XMLHttpRequest",
},
},
(r) => {
var buffers = [];
r.on("data", (b) => buffers.push(b));
r.on("end", () => {
var json = JSON.parse(Buffer.concat(buffers));
get(`https://voicemaker.in${json.path.replace(".", "")}`).then(res).catch(rej);
});
r.on("error", rej);
});
req.write(`{"Engine":"${voice.polly_engine}","Provider":"ai101","OutputFormat":"mp3","VoiceId":"${voice.arg}","LanguageCode":"${voice.language}-${voice.country}","SampleRate":"22050","effect":"default","master_VC":"advanced","speed":"0","master_volume":"0","pitch":"0","Text":"${text}","TextType":"text","fileName":""}`);
req.end();
});
break;
}
/* WARNING: NUANCE TTS API HAS BACKGROUND MUSIC */
case "nuance": {
var q = qs.encode({
voice_name: voice.arg,
speak_text: text,
});
https.get({
host: "voicedemo.codefactoryglobal.com",
path: `/generate_audio.asp?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
case "cepstral": {
https.get('https://www.cepstral.com/en/demos', r => {
const cookie = r.headers['set-cookie'];
var q = qs.encode({
voiceText: text,
voice: voice.arg,
createTime: 666,
rate: 170,
pitch: 1,
sfx: 'none',
});
var buffers = [];
var req = https.get({
host: 'www.cepstral.com',
path: `/demos/createAudio.php?${q}`,
headers: { Cookie: cookie },
method: 'GET',
}, r => {
r.on('data', b => buffers.push(b));
r.on('end', () => {
var json = JSON.parse(Buffer.concat(buffers));
get(`https://www.cepstral.com${json.mp3_loc}`).then(res).catch(rej);
})
});
});
break;
}
case "vocalware": {
var [eid, lid, vid] = voice.arg;
var cs = md5(`${eid}${lid}${vid}${text}1mp35883747uetivb9tb8108wfj`);
var q = qs.encode({
EID: voice.arg[0],
LID: voice.arg[1],
VID: voice.arg[2],
TXT: text,
EXT: "mp3",
IS_UTF8: 1,
ACC: 5883747,
cache_flag: 3,
CS: cs,
});
var req = https.get(
{
host: "cache-a.oddcast.com",
path: `/tts/gen.php?${q}`,
headers: {
Referer: "https://www.oddcast.com/",
Origin: "https://www.oddcast.com/",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
},
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
case "watson": {
var q = qs.encode({
text: text,
voice: voice.arg,
download: true,
accept: "audio/mp3",
});
https.get(
{
host: "text-to-speech-demo.ng.bluemix.net",
path: `/api/v3/synthesize?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
/* case "acapela": {
var buffers = [];
var acapelaArray = [];
for (var c = 0; c < 15; c++) acapelaArray.push(~~(65 + Math.random() * 26));
var email = `${String.fromCharCode.apply(null, acapelaArray)}@gmail.com`;
var req = https.request(
{
hostname: "acapelavoices.acapela-group.com",
path: "/index/getnonce",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
(r) => {
r.on("data", (b) => buffers.push(b));
r.on("end", () => {
var nonce = JSON.parse(Buffer.concat(buffers)).nonce;
var req = http.request(
{
hostname: "acapela-group.com",
port: "8080",
path: "/webservices/1-34-01-Mobility/Synthesizer",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => {
const html = Buffer.concat(buffers);
const beg = html.indexOf("&snd_url=") + 9;
const end = html.indexOf("&", beg);
const sub = html.subarray(beg, end).toString();
http.get(sub, (r) => {
r.on("data", (d) => buffers.push(d));
r.on("end", () => {
res(Buffer.concat(buffers));
});
});
});
r.on("error", rej);
}
);
req.end(
qs.encode({
req_voice: voice.arg,
cl_pwd: "",
cl_vers: "1-30",
req_echo: "ON",
cl_login: "AcapelaGroup",
req_comment: `{"nonce":"${nonce}","user":"${email}"}`,
req_text: text,
cl_env: "ACAPELA_VOICES",
prot_vers: 2,
cl_app: "AcapelaGroup_WebDemo_Android",
})
);
});
}
);
req.end(
qs.encode({
json: `{"googleid":"${email}"`,
})
);
break;
} */
case "acapela": {
var buffers = [];
var req = https.request({
hostname: "acapela-box.com",
path: "/AcaBox/dovaas.php",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
Cookie: "AcaBoxLogged=logged; AcaBoxUsername=goaniwrap; acabox=92s39r5vu676g5ekqehbu2o0f2; AcaBoxFirstname=Keegan",
Origin: "https://acapela-box.com",
Referer: "https://acapela-box.com/AcaBox/index.php",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36",
},
},
(r) => {
r.on("data", (b) => buffers.push(b));
r.on("end", () => {
var json = JSON.parse(Buffer.concat(buffers));
get(`${json.snd_url}`).then(res).catch(rej);
});
}
);
req.write(qs.encode({
text: text,
voice: voice.arg,
listen: 1,
format: "MP3",
codecMP3: 1,
spd: 180,
vct: 100,
byline: 0,
ts: 666
}));
req.end();
break;
}
case "acapelaOld": {
var q = qs.encode({
inputText: base64.encode(text),
});
https.get(
{
host: "voice.reverso.net",
path: `/RestPronunciation.svc/v1/output=json/GetVoiceStream/voiceName=${voice.arg}?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
case "voiceforge": {
/* Special thanks to ItsCrazyScout for helping us find the new VoiceForge link and being kind enough to host xom's VFProxy on his site! */
var q = qs.encode({
voice: voice.arg,
msg: text,
});
http.get(
{
host: "seamus-server.tk",
path: `/vfproxy/speech.php?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
case "svox": {
var q = qs.encode({
apikey: "e3a4477c01b482ea5acc6ed03b1f419f",
action: "convert",
format: "mp3",
voice: voice.arg,
speed: 0,
text: text,
version: "0.2.99",
});
https.get(
{
host: "api.ispeech.org",
path: `/api/rest?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => res(Buffer.concat(buffers)));
r.on("error", rej);
}
);
break;
}
case "wavenet": {
var req = https.request({
hostname: "texttospeechapi.wideo.co",
path: "/api/wideo-text-to-speech",
method: "POST",
headers: {
"Content-Type": "application/json",
Origin: "https://texttospeech.wideo.co",
Referer: "https://texttospeech.wideo.co/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36",
},
},
(r) => {
var buffers = [];
r.on("data", (b) => buffers.push(b));
r.on("end", () => {
var json = JSON.parse(Buffer.concat(buffers));
get(`${json.url}`).then(res).catch(rej);
});
r.on("error", rej);
});
req.write(`{"data":{"text":"${text}","speed":1,"voice":"${voice.arg}"}}`);
req.end();
break;
}
/*
case "acapela": {
var q = qs.encode({
cl_login: "VAAS_MKT",
req_snd_type: "",
req_voice: voice.arg,
cl_app: "seriousbusiness",
req_text: text,
cl_pwd: "M5Awq9xu",
});
http.get(
{
host: "vaassl3.acapela-group.com",
path: `/Services/AcapelaTV/Synthesizer?${q}`,
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => {
const html = Buffer.concat(buffers);
const beg = html.indexOf("&snd_url=") + 9;
const end = html.indexOf("&", beg);
const sub = html.subarray(beg + 4, end).toString();
if (!sub.startsWith("://")) return rej();
get(`https${sub}`).then(res).catch(rej);
});
r.on("error", rej);
}
);
break;
}
*/
case "readloud": {
const req = https.request(
{
host: "readloud.net",
path: voice.arg,
method: "POST",
port: "443",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => {
const html = Buffer.concat(buffers);
const beg = html.indexOf("/tmp/");
const end = html.indexOf(".mp3", beg) + 4;
const sub = html.subarray(beg, end).toString();
const loc = `https://readloud.net${sub}`;
get(loc).then(res).catch(rej);
});
r.on("error", rej);
}
);
req.end(
qs.encode({
but1: text,
but: "Submit",
})
);
break;
}
case "cereproc": {
const req = https.request(
{
hostname: "www.cereproc.com",
path: "/themes/benchpress/livedemo.php",
method: "POST",
headers: {
"content-type": "text/xml",
"accept-encoding": "gzip, deflate, br",
origin: "https://www.cereproc.com",
referer: "https://www.cereproc.com/en/products/voices",
"x-requested-with": "XMLHttpRequest",
cookie: "Drupal.visitor.liveDemo=666",
},
},
(r) => {
var buffers = [];
r.on("data", (d) => buffers.push(d));
r.on("end", () => {
const xml = String.fromCharCode.apply(null, brotli.decompress(Buffer.concat(buffers)));
const beg = xml.indexOf("https://cerevoice.s3.amazonaws.com/");
const end = xml.indexOf(".mp3", beg) + 4;
const loc = xml.substr(beg, end - beg).toString();
get(loc).then(res).catch(rej);
});
r.on("error", rej);
}
);
req.end(
`<speakExtended key='666'><voice>${voice.arg}</voice><text>${text}</text><audioFormat>mp3</audioFormat></speakExtended>`
);
break;
}
}
});
}
module.exports = function (req, res, url) {
if (req.method != 'POST' || url.path != '/goapi/convertTextToSoundAsset/') return;
loadPost(req, res).then(data => {
processVoice(data.voice, data.text).then(buffer => {
mp3Duration(buffer, (e, duration) => {
if (e || !duration) return res.end(1 + process.env.FAILURE_XML);
const title = `[${voices[data.voice].desc}] ${data.text}`;
const id = asset.saveLocal(buffer, data.presaveId, '-tts.mp3');
res.end(`0<response><asset><id>${id}</id><enc_asset_id>${id}</enc_asset_id><type>sound</type><subtype>tts</subtype><title>${title}</title><published>0</published><tags></tags><duration>${1e3 * duration}</duration><downloadtype>progressive</downloadtype><file>${id}</file></asset></response>`)
});
});
});
return true;
}
|
/*************************************************************************************************/
/*!
* \file
*
* \brief ATT client supported features module.
*
* Copyright (c) 2019 Arm Ltd.
*
* Copyright (c) 2019 Packetcraft, 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.
*/
/*************************************************************************************************/
#include <string.h>
#include "wsf_types.h"
#include "wsf_assert.h"
#include "wsf_trace.h"
#include "att_api.h"
#include "att_main.h"
#include "atts_main.h"
#include "util/bstream.h"
#include "svc_core.h"
/**************************************************************************************************
Local Variables
**************************************************************************************************/
/* Control block */
attsCsfCb_t attsCsfCb;
/*************************************************************************************************/
/*!
* \brief Set status of on-going database hash update operation.
*
* \param isUpdating \ref TRUE is updating, otherwise \ref FALSE;
*
* \return None.
*/
/*************************************************************************************************/
void attsCsfSetHashUpdateStatus(bool_t isUpdating)
{
if (attsCsfCb.isHashUpdating == isUpdating)
{
/* Already in the current state, nothing to do. */
return;
}
else
{
/* Update state. */
attsCsfCb.isHashUpdating = isUpdating;
}
/* Update complete.
* Check if clients were pending on the hash value and fulfill their requests.
*/
if (isUpdating == FALSE)
{
ATT_TRACE_INFO0("Database hash calculation complete");
attsCheckPendDbHashReadRsp();
/* Note: Clients which were pending on a Database Hash read from a Read by Type Request are not
* transitioned to the change-aware state here. The application is expected to initiate the
* state transition of all clients when the new hash is set. If this is not done, the
* state of pending Clients will be out of sync, and will be corrected on the next database
* sync.
*/
}
else
{
ATT_TRACE_INFO0("Calculating database hash");
/* If the application, for whatever reason, previously recalculated the database hash over an
* unchanged database and a client pended on a Read By Type Request of the database hash, then
* that clients state may be out of step if the application did not initiate a state
* transition. That state transition is forced here to keep handle next transition.
*/
for (uint8_t i = 0; i < DM_CONN_MAX; i++)
{
if (attsCsfCb.attsCsfTable[i].changeAwareState == ATTS_CLIENT_CHANGE_AWARE_DB_READ_PENDING)
{
attsCsfCb.attsCsfTable[i].changeAwareState = ATTS_CLIENT_CHANGE_PENDING_AWARE;
}
}
}
}
/*************************************************************************************************/
/*!
* \brief Check if database hash update is in progress.
*
* \return \ref TRUE if update in progress, \ref FALSE otherwise.
*/
/*************************************************************************************************/
uint8_t attsCsfGetHashUpdateStatus(void)
{
return attsCsfCb.isHashUpdating;
}
/*************************************************************************************************/
/*!
* \brief Check client awareness to database hash before sending notification or indication.
*
* \param connId DM connection ID.
* \param handle ATT handle.
*
* \return \ref TRUE if client is aware, otherwise \ref FALSE.
*/
/*************************************************************************************************/
uint8_t attsCsfIsClientChangeAware(dmConnId_t connId, uint16_t handle)
{
if ((attsCsfCb.attsCsfTable[connId - 1].csf & ATTS_CSF_ROBUST_CACHING) &&
(attsCsfCb.attsCsfTable[connId - 1].changeAwareState == ATTS_CLIENT_CHANGE_UNAWARE) &&
(handle != GATT_SC_HDL))
{
return FALSE;
}
return TRUE;
}
/*************************************************************************************************/
/*!
* \brief Update client change-aware state based on protocol event.
*
* \param connId Connection handle.
* \param opcode ATT PDU type.
* \param pPacket Data packet from L2CAP.
*
* \return \ref ATT_SUCCESS if client is change-aware, else \ref ATT_ERR_DATABASE_OUT_OF_SYNC.
*/
/*************************************************************************************************/
uint8_t attsCsfActClientState(uint16_t handle, uint8_t opcode, uint8_t *pPacket)
{
uint8_t err = ATT_SUCCESS;
attsCsfRec_t *pRec;
/* PDU which do not operate on att handles are handled agnostically of the client's state. */
if (opcode == ATT_PDU_MTU_REQ || opcode == ATT_PDU_VALUE_CNF)
{
return err;
}
pRec = &attsCsfCb.attsCsfTable[handle];
/* If the client is change-unaware */
if (pRec->changeAwareState == ATTS_CLIENT_CHANGE_UNAWARE)
{
/* If not a command */
if ((opcode & ATT_PDU_MASK_COMMAND) == 0)
{
/* Note: there is no need to call back to the application here. The application only
* needs to know when a transition to or from the change-aware state occurs.
*/
/* Move client change-aware state to pending */
pRec->changeAwareState = ATTS_CLIENT_CHANGE_PENDING_AWARE;
ATT_TRACE_INFO2("ConnId %d change aware state is %d", handle + 1,
ATTS_CLIENT_CHANGE_PENDING_AWARE);
}
/* If this is a command or the Client has indicated Robust Caching, set an error so that
* this command or request is not processed.
*/
if ((opcode & ATT_PDU_MASK_COMMAND) ||
(pRec->csf & ATTS_CSF_ROBUST_CACHING))
{
/* return a database out of sync error */
err = ATT_ERR_DATABASE_OUT_OF_SYNC;
}
}
else if (pRec->changeAwareState == ATTS_CLIENT_CHANGE_PENDING_AWARE)
{
/* If not a command */
if ((opcode & ATT_PDU_MASK_COMMAND) == 0)
{
/* Move client change-aware state to aware */
pRec->changeAwareState = ATTS_CLIENT_CHANGE_AWARE;
ATT_TRACE_INFO2("ConnId %d change aware state is %d", handle + 1, ATTS_CLIENT_CHANGE_AWARE);
/* Callback to application to store updated awareness, if bonded. */
if (attsCsfCb.writeCback != NULL)
{
attsCsfCb.writeCback(handle + 1, pRec->changeAwareState, &pRec->csf);
}
}
else
{
/* Return an error so that command is not processed. */
err = ATT_ERR_DATABASE_OUT_OF_SYNC;
}
}
/* If this is Read by Type request */
if (opcode == ATT_PDU_READ_TYPE_REQ)
{
uint16_t uuid;
/* Extract UUID: Skip L2C, ATT Header and 4 byte handle range */
BYTES_TO_UINT16(uuid, (pPacket + L2C_PAYLOAD_START + ATT_HDR_LEN + 4));
/* If this is a Read By Type Request of the Database Hash characteristic value */
if (uuid == ATT_UUID_DATABASE_HASH)
{
err = ATT_SUCCESS;
/* Reading the hash during a hash update causes the new hash to be returned and counts
* towards the peer's progression towards a change-aware state.
*/
if (attsCsfCb.isHashUpdating)
{
/* This read will not be processed until after the hash update completes, so this read
* request shall be counted as a move from change-unaware to chang-aware pending.
*/
pRec->changeAwareState = ATTS_CLIENT_CHANGE_AWARE_DB_READ_PENDING;
ATT_TRACE_INFO2("ConnId %d change aware state is %d", handle + 1,
ATTS_CLIENT_CHANGE_AWARE_DB_READ_PENDING);
}
}
}
if (err == ATT_ERR_DATABASE_OUT_OF_SYNC)
{
ATT_TRACE_INFO2("ConnId %d out of sync, PDU with opcode 0x%02x ignored!", handle + 1, opcode);
}
return err;
}
/*************************************************************************************************/
/*!
* \brief Update a client's state of awareness to a change in the database.
*
* \param connId DM connection ID. if \ref DM_CONN_ID_NONE, sets the state for all connected
* clients.
* \param state The state of awareness to a change, see ::attClientAwareStates.
*
* \return None.
*
* \note A callback to application is not needed as it is expected the caller (i.e. the
* application) will have updated all persistent records prior to calling this function.
*/
/*************************************************************************************************/
void AttsCsfSetClientsChangeAwarenessState(dmConnId_t connId, uint8_t state)
{
if (connId == DM_CONN_ID_NONE)
{
for (uint8_t i = 0; i < DM_CONN_MAX; i++)
{
if (attsCsfCb.attsCsfTable[i].changeAwareState == ATTS_CLIENT_CHANGE_AWARE_DB_READ_PENDING)
{
attsCsfCb.attsCsfTable[i].changeAwareState = ATTS_CLIENT_CHANGE_PENDING_AWARE;
}
else
{
attsCsfCb.attsCsfTable[i].changeAwareState = state;
}
}
}
else
{
attsCsfCb.attsCsfTable[connId - 1].changeAwareState = state;
ATT_TRACE_INFO2("ConnId %d change aware state is %d", connId, state);
}
}
/*************************************************************************************************/
/*!
* \brief Initialize the client supported features for a connection.
*
* \param connId DM connection ID.
* \param changeAwareState The state of awareness to a change in the database.
* \param pCsf Pointer to the client supported features value to cache. \ref NULL or
* buffer of length \ref ATT_CSF_LEN.
*
* \return None.
*/
/*************************************************************************************************/
void AttsCsfConnOpen(dmConnId_t connId, uint8_t changeAwareState, uint8_t *pCsf)
{
if (pCsf != NULL)
{
attsCsfCb.attsCsfTable[connId - 1].changeAwareState = changeAwareState;
memcpy(&attsCsfCb.attsCsfTable[connId - 1].csf, pCsf, ATT_CSF_LEN);
}
else
{
/* Note: this set client to the change-aware state. */
memset(&attsCsfCb.attsCsfTable[connId - 1], 0, sizeof(attsCsfRec_t));
}
}
/*************************************************************************************************/
/*!
* \brief Register callback.
*
* \param writeCback Application callback for when features or status change.
*
* \return None.
*/
/*************************************************************************************************/
void AttsCsfRegister(attsCsfWriteCback_t writeCback)
{
attsCsfCb.writeCback = writeCback;
}
/*************************************************************************************************/
/*!
* \brief Initialize ATTS client supported features module.
*
* \return None.
*/
/*************************************************************************************************/
void AttsCsfInit(void)
{
attsCsfCb.isHashUpdating = FALSE;
attsCsfCb.writeCback = NULL;
}
/*************************************************************************************************/
/*!
* \brief GATT write of client supported feature characteristic value.
*
* \param connId DM connection ID.
* \param offset offset into csf characteristic.
* \param valueLen length of write in bytes.
* \param pValue Pointer to client's supported features characteristic value.
*
* \return \ref ATT_SUCCESS is successful, \ref ATT_ERR_VALUE_NOT_ALLOWED if any supported
* features are flipped from 1 to 0.
*/
/*************************************************************************************************/
uint8_t AttsCsfWriteFeatures(dmConnId_t connId, uint16_t offset, uint16_t valueLen, uint8_t *pValue)
{
attsCsfRec_t *pCsfRec = &attsCsfCb.attsCsfTable[connId - 1];
/* future parameter in case the client supported features characteristic becomes a multi-octet
* structure.
*/
(void)offset;
if (valueLen > ATT_CSF_LEN)
{
return ATT_ERR_LENGTH;
}
/* A client can not clear any bits it has set. */
if ((pCsfRec->csf & *pValue) < pCsfRec->csf)
{
return ATT_ERR_VALUE_NOT_ALLOWED;
}
pCsfRec->csf = *pValue & ATTS_CSF_OCT0_FEATURES;
ATT_TRACE_INFO2("connId %d updated csf to 0x%02x", connId, pCsfRec->csf);
/* Callback to application to store updated features, if bonded. */
if (attsCsfCb.writeCback != NULL)
{
attsCsfCb.writeCback(connId, pCsfRec->changeAwareState, &pCsfRec->csf);
}
return ATT_SUCCESS;
}
/*************************************************************************************************/
/*!
* \brief Get client supported feature record.
*
* \param connId DM connection ID.
* \param pCsfOut Output parameter for client supported features buffer.
* \param pCsfOutLen Length of output parameter buffer.
*
* \return None.
*/
/*************************************************************************************************/
void AttsCsfGetFeatures(dmConnId_t connId, uint8_t *pCsfOut, uint8_t pCsfOutLen)
{
if (pCsfOutLen <= ATT_CSF_LEN)
{
memcpy(pCsfOut, &attsCsfCb.attsCsfTable[connId - 1].csf, pCsfOutLen);
}
}
/*************************************************************************************************/
/*!
* \brief Get client state of awareness to a change in the database.
*
* \param connId DM connection ID.
*
* \return Client's change-aware state.
*/
/*************************************************************************************************/
uint8_t AttsCsfGetChangeAwareState(dmConnId_t connId)
{
return attsCsfCb.attsCsfTable[connId - 1].changeAwareState;
}
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2008-2016, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTITVINF.H
*
*******************************************************************************
*/
#ifndef __DTITVINF_H__
#define __DTITVINF_H__
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Date/Time interval patterns for formatting date/time interval
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/udat.h"
#include "unicode/locid.h"
#include "unicode/ucal.h"
#include "unicode/dtptngen.h"
U_NAMESPACE_BEGIN
/**
* DateIntervalInfo is a public class for encapsulating localizable
* date time interval patterns. It is used by DateIntervalFormat.
*
* <P>
* For most users, ordinary use of DateIntervalFormat does not need to create
* DateIntervalInfo object directly.
* DateIntervalFormat will take care of it when creating a date interval
* formatter when user pass in skeleton and locale.
*
* <P>
* For power users, who want to create their own date interval patterns,
* or want to re-set date interval patterns, they could do so by
* directly creating DateIntervalInfo and manupulating it.
*
* <P>
* Logically, the interval patterns are mappings
* from (skeleton, the_largest_different_calendar_field)
* to (date_interval_pattern).
*
* <P>
* A skeleton
* <ol>
* <li>
* only keeps the field pattern letter and ignores all other parts
* in a pattern, such as space, punctuations, and string literals.
* <li>
* hides the order of fields.
* <li>
* might hide a field's pattern letter length.
*
* For those non-digit calendar fields, the pattern letter length is
* important, such as MMM, MMMM, and MMMMM; EEE and EEEE,
* and the field's pattern letter length is honored.
*
* For the digit calendar fields, such as M or MM, d or dd, yy or yyyy,
* the field pattern length is ignored and the best match, which is defined
* in date time patterns, will be returned without honor the field pattern
* letter length in skeleton.
* </ol>
*
* <P>
* The calendar fields we support for interval formatting are:
* year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute.
* Those calendar fields can be defined in the following order:
* year > month > date > am-pm > hour > minute
*
* The largest different calendar fields between 2 calendars is the
* first different calendar field in above order.
*
* For example: the largest different calendar fields between "Jan 10, 2007"
* and "Feb 20, 2008" is year.
*
* <P>
* There is a set of pre-defined static skeleton strings.
* There are pre-defined interval patterns for those pre-defined skeletons
* in locales' resource files.
* For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd",
* in en_US, if the largest different calendar field between date1 and date2
* is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy",
* such as "Jan 10, 2007 - Jan 10, 2008".
* If the largest different calendar field between date1 and date2 is "month",
* the date interval pattern is "MMM d - MMM d, yyyy",
* such as "Jan 10 - Feb 10, 2007".
* If the largest different calendar field between date1 and date2 is "day",
* the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007".
*
* For date skeleton, the interval patterns when year, or month, or date is
* different are defined in resource files.
* For time skeleton, the interval patterns when am/pm, or hour, or minute is
* different are defined in resource files.
*
*
* <P>
* There are 2 dates in interval pattern. For most locales, the first date
* in an interval pattern is the earlier date. There might be a locale in which
* the first date in an interval pattern is the later date.
* We use fallback format for the default order for the locale.
* For example, if the fallback format is "{0} - {1}", it means
* the first date in the interval pattern for this locale is earlier date.
* If the fallback format is "{1} - {0}", it means the first date is the
* later date.
* For a particular interval pattern, the default order can be overriden
* by prefixing "latestFirst:" or "earliestFirst:" to the interval pattern.
* For example, if the fallback format is "{0}-{1}",
* but for skeleton "yMMMd", the interval pattern when day is different is
* "latestFirst:d-d MMM yy", it means by default, the first date in interval
* pattern is the earlier date. But for skeleton "yMMMd", when day is different,
* the first date in "d-d MMM yy" is the later date.
*
* <P>
* The recommended way to create a DateIntervalFormat object is to pass in
* the locale.
* By using a Locale parameter, the DateIntervalFormat object is
* initialized with the pre-defined interval patterns for a given or
* default locale.
* <P>
* Users can also create DateIntervalFormat object
* by supplying their own interval patterns.
* It provides flexibility for power users.
*
* <P>
* After a DateIntervalInfo object is created, clients may modify
* the interval patterns using setIntervalPattern function as so desired.
* Currently, users can only set interval patterns when the following
* calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH,
* DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, and MINUTE.
* Interval patterns when other calendar fields are different is not supported.
* <P>
* DateIntervalInfo objects are cloneable.
* When clients obtain a DateIntervalInfo object,
* they can feel free to modify it as necessary.
* <P>
* DateIntervalInfo are not expected to be subclassed.
* Data for a calendar is loaded out of resource bundles.
* Through ICU 4.4, date interval patterns are only supported in the Gregorian
* calendar; non-Gregorian calendars are supported from ICU 4.4.1.
* @stable ICU 4.0
**/
class U_I18N_API DateIntervalInfo U_FINAL : public UObject {
public:
/**
* Default constructor.
* It does not initialize any interval patterns except
* that it initialize default fall-back pattern as "{0} - {1}",
* which can be reset by setFallbackIntervalPattern().
* It should be followed by setFallbackIntervalPattern() and
* setIntervalPattern(),
* and is recommended to be used only for power users who
* wants to create their own interval patterns and use them to create
* date interval formatter.
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
DateIntervalInfo(UErrorCode& status);
/**
* Construct DateIntervalInfo for the given locale,
* @param locale the interval patterns are loaded from the appropriate calendar
* data (specified calendar or default calendar) in this locale.
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
DateIntervalInfo(const Locale& locale, UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 4.0
*/
DateIntervalInfo(const DateIntervalInfo&);
/**
* Assignment operator
* @stable ICU 4.0
*/
DateIntervalInfo& operator=(const DateIntervalInfo&);
/**
* Clone this object polymorphically.
* The caller owns the result and should delete it when done.
* @return a copy of the object
* @stable ICU 4.0
*/
virtual DateIntervalInfo* clone(void) const;
/**
* Destructor.
* It is virtual to be safe, but it is not designed to be subclassed.
* @stable ICU 4.0
*/
virtual ~DateIntervalInfo();
/**
* Return true if another object is semantically equal to this one.
*
* @param other the DateIntervalInfo object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 4.0
*/
virtual UBool operator==(const DateIntervalInfo& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the DateIntervalInfo object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 4.0
*/
UBool operator!=(const DateIntervalInfo& other) const;
/**
* Provides a way for client to build interval patterns.
* User could construct DateIntervalInfo by providing a list of skeletons
* and their patterns.
* <P>
* For example:
* <pre>
* UErrorCode status = U_ZERO_ERROR;
* DateIntervalInfo dIntervalInfo = new DateIntervalInfo();
* dIntervalInfo->setFallbackIntervalPattern("{0} ~ {1}");
* dIntervalInfo->setIntervalPattern("yMd", UCAL_YEAR, "'from' yyyy-M-d 'to' yyyy-M-d", status);
* dIntervalInfo->setIntervalPattern("yMMMd", UCAL_MONTH, "'from' yyyy MMM d 'to' MMM d", status);
* dIntervalInfo->setIntervalPattern("yMMMd", UCAL_DAY, "yyyy MMM d-d", status, status);
* </pre>
*
* Restriction:
* Currently, users can only set interval patterns when the following
* calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH,
* DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, and MINUTE.
* Interval patterns when other calendar fields are different are
* not supported.
*
* @param skeleton the skeleton on which interval pattern based
* @param lrgDiffCalUnit the largest different calendar unit.
* @param intervalPattern the interval pattern on the largest different
* calendar unit.
* For example, if lrgDiffCalUnit is
* "year", the interval pattern for en_US when year
* is different could be "'from' yyyy 'to' yyyy".
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
void setIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status);
/**
* Get the interval pattern given skeleton and
* the largest different calendar field.
* @param skeleton the skeleton
* @param field the largest different calendar field
* @param result output param to receive the pattern
* @param status output param set to success/failure code on exit
* @return a reference to 'result'
* @stable ICU 4.0
*/
UnicodeString& getIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields field,
UnicodeString& result,
UErrorCode& status) const;
/**
* Get the fallback interval pattern.
* @param result output param to receive the pattern
* @return a reference to 'result'
* @stable ICU 4.0
*/
UnicodeString& getFallbackIntervalPattern(UnicodeString& result) const;
/**
* Re-set the fallback interval pattern.
*
* In construction, default fallback pattern is set as "{0} - {1}".
* And constructor taking locale as parameter will set the
* fallback pattern as what defined in the locale resource file.
*
* This method provides a way for user to replace the fallback pattern.
*
* @param fallbackPattern fall-back interval pattern.
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
void setFallbackIntervalPattern(const UnicodeString& fallbackPattern,
UErrorCode& status);
/** Get default order -- whether the first date in pattern is later date
or not.
* return default date ordering in interval pattern. TRUE if the first date
* in pattern is later date, FALSE otherwise.
* @stable ICU 4.0
*/
UBool getDefaultOrder() const;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.0
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* DateIntervalFormat will need access to
* getBestSkeleton(), parseSkeleton(), enum IntervalPatternIndex,
* and calendarFieldToPatternIndex().
*
* Instead of making above public,
* make DateIntervalFormat a friend of DateIntervalInfo.
*/
friend class DateIntervalFormat;
/**
* Internal struct used to load resource bundle data.
*/
struct DateIntervalSink;
/**
* Following is for saving the interval patterns.
* We only support interval patterns on
* ERA, YEAR, MONTH, DAY, AM_PM, HOUR, and MINUTE
*/
enum IntervalPatternIndex
{
kIPI_ERA,
kIPI_YEAR,
kIPI_MONTH,
kIPI_DATE,
kIPI_AM_PM,
kIPI_HOUR,
kIPI_MINUTE,
kIPI_SECOND,
kIPI_MAX_INDEX
};
public:
#ifndef U_HIDE_INTERNAL_API
/**
* Max index for stored interval patterns
* @internal ICU 4.4
*/
enum {
kMaxIntervalPatternIndex = kIPI_MAX_INDEX
};
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Initialize the DateIntervalInfo from locale
* @param locale the given locale.
* @param status output param set to success/failure code on exit
*/
void initializeData(const Locale& locale, UErrorCode& status);
/* Set Interval pattern.
*
* It sets interval pattern into the hash map.
*
* @param skeleton skeleton on which the interval pattern based
* @param lrgDiffCalUnit the largest different calendar unit.
* @param intervalPattern the interval pattern on the largest different
* calendar unit.
* @param status output param set to success/failure code on exit
*/
void setIntervalPatternInternally(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status);
/**given an input skeleton, get the best match skeleton
* which has pre-defined interval pattern in resource file.
* Also return the difference between the input skeleton
* and the best match skeleton.
*
* TODO (xji): set field weight or
* isolate the funtionality in DateTimePatternGenerator
* @param skeleton input skeleton
* @param bestMatchDistanceInfo the difference between input skeleton
* and best match skeleton.
* 0, if there is exact match for input skeleton
* 1, if there is only field width difference between
* the best match and the input skeleton
* 2, the only field difference is 'v' and 'z'
* -1, if there is calendar field difference between
* the best match and the input skeleton
* @return best match skeleton
*/
const UnicodeString* getBestSkeleton(const UnicodeString& skeleton,
int8_t& bestMatchDistanceInfo) const;
/**
* Parse skeleton, save each field's width.
* It is used for looking for best match skeleton,
* and adjust pattern field width.
* @param skeleton skeleton to be parsed
* @param skeletonFieldWidth parsed skeleton field width
*/
static void U_EXPORT2 parseSkeleton(const UnicodeString& skeleton,
int32_t* skeletonFieldWidth);
/**
* Check whether one field width is numeric while the other is string.
*
* TODO (xji): make it general
*
* @param fieldWidth one field width
* @param anotherFieldWidth another field width
* @param patternLetter pattern letter char
* @return true if one field width is numeric and the other is string,
* false otherwise.
*/
static UBool U_EXPORT2 stringNumeric(int32_t fieldWidth,
int32_t anotherFieldWidth,
char patternLetter);
/**
* Convert calendar field to the interval pattern index in
* hash table.
*
* Since we only support the following calendar fields:
* ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_WEEK,
* AM_PM, HOUR, HOUR_OF_DAY, and MINUTE,
* We reserve only 4 interval patterns for a skeleton.
*
* @param field calendar field
* @param status output param set to success/failure code on exit
* @return interval pattern index in hash table
*/
static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex(
UCalendarDateFields field,
UErrorCode& status);
/**
* delete hash table (of type fIntervalPatterns).
*
* @param hTable hash table to be deleted
*/
void deleteHash(Hashtable* hTable);
/**
* initialize hash table (of type fIntervalPatterns).
*
* @param status output param set to success/failure code on exit
* @return hash table initialized
*/
Hashtable* initHash(UErrorCode& status);
/**
* copy hash table (of type fIntervalPatterns).
*
* @param source the source to copy from
* @param target the target to copy to
* @param status output param set to success/failure code on exit
*/
void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status);
// data members
// fallback interval pattern
UnicodeString fFallbackIntervalPattern;
// default order
UBool fFirstDateInPtnIsLaterDate;
// HashMap<UnicodeString, UnicodeString[kIPI_MAX_INDEX]>
// HashMap( skeleton, pattern[largest_different_field] )
Hashtable* fIntervalPatterns;
};// end class DateIntervalInfo
inline UBool
DateIntervalInfo::operator!=(const DateIntervalInfo& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif
#endif
|
module.exports = require('@leanup/stack-vue3/snowpack.config');
|
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""argparse.ArgumentParser subclass to parse qutebrowser commands."""
import argparse
from PyQt5.QtCore import QUrl
from qutebrowser.commands import cmdexc
from qutebrowser.utils import utils, objreg, log
SUPPRESS = argparse.SUPPRESS
class ArgumentParserError(Exception):
"""Exception raised when the ArgumentParser signals an error."""
class ArgumentParserExit(Exception):
"""Exception raised when the argument parser exited.
Attributes:
status: The exit status.
"""
def __init__(self, status, msg):
self.status = status
super().__init__(msg)
class HelpAction(argparse.Action):
"""Argparse action to open the help page in the browser.
This is horrible encapsulation, but I can't think of a good way to do this
better...
"""
def __call__(self, parser, _namespace, _values, _option_string=None):
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window='last-focused')
tabbed_browser.tabopen(
QUrl('qute://help/commands.html#{}'.format(parser.name)))
parser.exit()
class ArgumentParser(argparse.ArgumentParser):
"""Subclass ArgumentParser to be more suitable for runtime parsing.
Attributes:
name: The command name.
"""
def __init__(self, name, **kwargs):
self.name = name
super().__init__(add_help=False, prog=name, **kwargs)
def exit(self, status=0, message=None):
raise ArgumentParserExit(status, message)
def error(self, message):
raise ArgumentParserError(message.capitalize())
def arg_name(name):
"""Get the name an argument should have based on its Python name."""
return name.rstrip('_').replace('_', '-')
def _check_choices(param, value, choices):
if value not in choices:
expected_values = ', '.join(arg_name(val) for val in choices)
raise cmdexc.ArgumentTypeError("{}: Invalid value {} - expected "
"one of: {}".format(
param.name, value, expected_values))
def type_conv(param, typ, value, *, str_choices=None):
"""Convert a value based on a type.
Args:
param: The argparse.Parameter we're checking
types: The allowed type
value: The value to convert
str_choices: The allowed choices if the type ends up being a string
Return:
The converted value
"""
if isinstance(typ, str):
raise TypeError("{}: Legacy string type!".format(param.name))
if value is param.default:
return value
assert isinstance(value, str), repr(value)
if utils.is_enum(typ):
_check_choices(param, value, [arg_name(e.name) for e in typ])
return typ[value.replace('-', '_')]
elif typ is str:
if str_choices is not None:
_check_choices(param, value, str_choices)
return value
elif callable(typ):
# int, float, etc.
try:
return typ(value)
except (TypeError, ValueError):
msg = '{}: Invalid {} value {}'.format(
param.name, typ.__name__, value)
raise cmdexc.ArgumentTypeError(msg)
else:
raise ValueError("{}: Unknown type {!r}!".format(param.name, typ))
def multitype_conv(param, types, value, *, str_choices=None):
"""Convert a value based on a choice of types.
Args:
param: The inspect.Parameter we're checking
types: The allowed types ("overloads")
value: The value to convert
str_choices: The allowed choices if the type ends up being a string
Return:
The converted value
"""
types = list(set(types))
if str in types:
# Make sure str is always the last type in the list, so e.g. '23' gets
# returned as 23 if we have typing.Union[str, int]
types.remove(str)
types.append(str)
for typ in types:
log.commands.debug("Trying to parse {!r} as {}".format(value, typ))
try:
return type_conv(param, typ, value, str_choices=str_choices)
except cmdexc.ArgumentTypeError as e:
log.commands.debug("Got {} for {}".format(e, typ))
raise cmdexc.ArgumentTypeError('{}: Invalid value {}'.format(
param.name, value))
|
var frozenMoment = require('../../frozen-moment');
/**************************************************
Macedonian
*************************************************/
exports['locale:mk'] = {
'setUp' : function (cb) {
frozenMoment.locale('mk');
frozenMoment.createFromInputFallback = function () {
throw new Error('input not handled by frozenMoment');
};
cb();
},
'tearDown' : function (cb) {
frozenMoment.locale('en');
cb();
},
'parse' : function (test) {
var tests = 'јануари јан_февруари фев_март мар_април апр_мај мај_јуни јун_јули јул_август авг_септември сеп_октомври окт_ноември ное_декември дек'.split('_'), i;
function equalTest(input, mmm, i) {
test.equal(frozenMoment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
test.done();
},
'format' : function (test) {
var a = [
['dddd, MMMM Do YYYY, H:mm:ss', 'недела, февруари 14-ти 2010, 15:25:50'],
['ddd, hA', 'нед, 3PM'],
['M Mo MM MMMM MMM', '2 2-ри 02 февруари фев'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14-ти 14'],
['d do dddd ddd dd', '0 0-ев недела нед нe'],
['DDD DDDo DDDD', '45 45-ти 045'],
['w wo ww', '7 7-ми 07'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', 'pm PM'],
['[the] DDDo [day of the year]', 'the 45-ти day of the year'],
['LTS', '15:25:50'],
['L', '14.02.2010'],
['LL', '14 февруари 2010'],
['LLL', '14 февруари 2010 15:25'],
['LLLL', 'недела, 14 февруари 2010 15:25'],
['l', '14.2.2010'],
['ll', '14 фев 2010'],
['lll', '14 фев 2010 15:25'],
['llll', 'нед, 14 фев 2010 15:25']
],
b = frozenMoment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
test.done();
},
'format ordinal' : function (test) {
test.equal(frozenMoment([2011, 0, 1]).format('DDDo'), '1-ви', '1-ви');
test.equal(frozenMoment([2011, 0, 2]).format('DDDo'), '2-ри', '2-ри');
test.equal(frozenMoment([2011, 0, 3]).format('DDDo'), '3-ти', '3-ти');
test.equal(frozenMoment([2011, 0, 4]).format('DDDo'), '4-ти', '4-ти');
test.equal(frozenMoment([2011, 0, 5]).format('DDDo'), '5-ти', '5-ти');
test.equal(frozenMoment([2011, 0, 6]).format('DDDo'), '6-ти', '6-ти');
test.equal(frozenMoment([2011, 0, 7]).format('DDDo'), '7-ми', '7-ми');
test.equal(frozenMoment([2011, 0, 8]).format('DDDo'), '8-ми', '8-ми');
test.equal(frozenMoment([2011, 0, 9]).format('DDDo'), '9-ти', '9-ти');
test.equal(frozenMoment([2011, 0, 10]).format('DDDo'), '10-ти', '10-ти');
test.equal(frozenMoment([2011, 0, 11]).format('DDDo'), '11-ти', '11-ти');
test.equal(frozenMoment([2011, 0, 12]).format('DDDo'), '12-ти', '12-ти');
test.equal(frozenMoment([2011, 0, 13]).format('DDDo'), '13-ти', '13-ти');
test.equal(frozenMoment([2011, 0, 14]).format('DDDo'), '14-ти', '14-ти');
test.equal(frozenMoment([2011, 0, 15]).format('DDDo'), '15-ти', '15-ти');
test.equal(frozenMoment([2011, 0, 16]).format('DDDo'), '16-ти', '16-ти');
test.equal(frozenMoment([2011, 0, 17]).format('DDDo'), '17-ти', '17-ти');
test.equal(frozenMoment([2011, 0, 18]).format('DDDo'), '18-ти', '18-ти');
test.equal(frozenMoment([2011, 0, 19]).format('DDDo'), '19-ти', '19-ти');
test.equal(frozenMoment([2011, 0, 20]).format('DDDo'), '20-ти', '20-ти');
test.equal(frozenMoment([2011, 0, 21]).format('DDDo'), '21-ви', '21-ви');
test.equal(frozenMoment([2011, 0, 22]).format('DDDo'), '22-ри', '22-ри');
test.equal(frozenMoment([2011, 0, 23]).format('DDDo'), '23-ти', '23-ти');
test.equal(frozenMoment([2011, 0, 24]).format('DDDo'), '24-ти', '24-ти');
test.equal(frozenMoment([2011, 0, 25]).format('DDDo'), '25-ти', '25-ти');
test.equal(frozenMoment([2011, 0, 26]).format('DDDo'), '26-ти', '26-ти');
test.equal(frozenMoment([2011, 0, 27]).format('DDDo'), '27-ми', '27-ми');
test.equal(frozenMoment([2011, 0, 28]).format('DDDo'), '28-ми', '28-ми');
test.equal(frozenMoment([2011, 0, 29]).format('DDDo'), '29-ти', '29-ти');
test.equal(frozenMoment([2011, 0, 30]).format('DDDo'), '30-ти', '30-ти');
test.equal(frozenMoment([2011, 0, 31]).format('DDDo'), '31-ви', '31-ви');
test.done();
},
'format month' : function (test) {
var expected = 'јануари јан_февруари фев_март мар_април апр_мај мај_јуни јун_јули јул_август авг_септември сеп_октомври окт_ноември ное_декември дек'.split('_'), i;
for (i = 0; i < expected.length; i++) {
test.equal(frozenMoment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
test.done();
},
'format week' : function (test) {
var expected = 'недела нед нe_понеделник пон пo_вторник вто вт_среда сре ср_четврток чет че_петок пет пе_сабота саб сa'.split('_'), i;
for (i = 0; i < expected.length; i++) {
test.equal(frozenMoment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
test.done();
},
'from' : function (test) {
var start = frozenMoment([2007, 1, 28]);
test.equal(start.from(frozenMoment([2007, 1, 28]).add({s: 44}), true), 'неколку секунди', '44 seconds = a few seconds');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({s: 45}), true), 'минута', '45 seconds = a minute');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({s: 89}), true), 'минута', '89 seconds = a minute');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({s: 90}), true), '2 минути', '90 seconds = 2 minutes');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({m: 44}), true), '44 минути', '44 minutes = 44 minutes');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({m: 45}), true), 'час', '45 minutes = an hour');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({m: 89}), true), 'час', '89 minutes = an hour');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({m: 90}), true), '2 часа', '90 minutes = 2 hours');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({h: 5}), true), '5 часа', '5 hours = 5 hours');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({h: 21}), true), '21 часа', '21 hours = 21 hours');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({h: 22}), true), 'ден', '22 hours = a day');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({h: 35}), true), 'ден', '35 hours = a day');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({h: 36}), true), '2 дена', '36 hours = 2 days');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 1}), true), 'ден', '1 day = a day');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 5}), true), '5 дена', '5 days = 5 days');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 25}), true), '25 дена', '25 days = 25 days');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 26}), true), 'месец', '26 days = a month');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 30}), true), 'месец', '30 days = a month');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 43}), true), 'месец', '43 days = a month');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 46}), true), '2 месеци', '46 days = 2 months');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 74}), true), '2 месеци', '75 days = 2 months');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 76}), true), '3 месеци', '76 days = 3 months');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({M: 1}), true), 'месец', '1 month = a month');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({M: 5}), true), '5 месеци', '5 months = 5 months');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 345}), true), 'година', '345 days = a year');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({d: 548}), true), '2 години', '548 days = 2 years');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({y: 1}), true), 'година', '1 year = a year');
test.equal(start.from(frozenMoment([2007, 1, 28]).add({y: 5}), true), '5 години', '5 years = 5 years');
test.done();
},
'suffix' : function (test) {
test.equal(frozenMoment(30000).from(0), 'после неколку секунди', 'prefix');
test.equal(frozenMoment(0).from(30000), 'пред неколку секунди', 'suffix');
test.done();
},
'now from now' : function (test) {
test.equal(frozenMoment().fromNow(), 'пред неколку секунди', 'now from now should display as in the past');
test.done();
},
'fromNow' : function (test) {
test.equal(frozenMoment().add({s: 30}).fromNow(), 'после неколку секунди', 'in a few seconds');
test.equal(frozenMoment().add({d: 5}).fromNow(), 'после 5 дена', 'in 5 days');
test.done();
},
'calendar day' : function (test) {
var a = frozenMoment().hours(2).minutes(0).seconds(0);
test.equal(frozenMoment(a).calendar(), 'Денес во 2:00', 'today at the same time');
test.equal(frozenMoment(a).add({m: 25}).calendar(), 'Денес во 2:25', 'Now plus 25 min');
test.equal(frozenMoment(a).add({h: 1}).calendar(), 'Денес во 3:00', 'Now plus 1 hour');
test.equal(frozenMoment(a).add({d: 1}).calendar(), 'Утре во 2:00', 'tomorrow at the same time');
test.equal(frozenMoment(a).subtract({h: 1}).calendar(), 'Денес во 1:00', 'Now minus 1 hour');
test.equal(frozenMoment(a).subtract({d: 1}).calendar(), 'Вчера во 2:00', 'yesterday at the same time');
test.done();
},
'calendar next week' : function (test) {
var i, m;
for (i = 2; i < 7; i++) {
m = frozenMoment().add({d: i});
test.equal(m.calendar(), m.format('dddd [во] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('dddd [во] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('dddd [во] LT'), 'Today + ' + i + ' days end of day');
}
test.done();
},
'calendar last week' : function (test) {
var i, m;
function makeFormat(d) {
switch (d.day()) {
case 0:
case 3:
case 6:
return '[Во изминатата] dddd [во] LT';
case 1:
case 2:
case 4:
case 5:
return '[Во изминатиот] dddd [во] LT';
}
}
for (i = 2; i < 7; i++) {
m = frozenMoment().subtract({d: i});
test.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day');
}
test.done();
},
'calendar all else' : function (test) {
var weeksAgo = frozenMoment().subtract({w: 1}),
weeksFromNow = frozenMoment().add({w: 1});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = frozenMoment().subtract({w: 2});
weeksFromNow = frozenMoment().add({w: 2});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
test.done();
},
// Monday is the first day of the week.
// The week that contains Jan 1st is the first week of the year.
'weeks year starting sunday' : function (test) {
test.equal(frozenMoment([2011, 11, 26]).week(), 1, 'Dec 26 2011 should be week 1');
test.equal(frozenMoment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1');
test.equal(frozenMoment([2012, 0, 2]).week(), 2, 'Jan 2 2012 should be week 2');
test.equal(frozenMoment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2');
test.equal(frozenMoment([2012, 0, 9]).week(), 3, 'Jan 9 2012 should be week 3');
test.done();
},
'weeks year starting monday' : function (test) {
test.equal(frozenMoment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
test.equal(frozenMoment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1');
test.equal(frozenMoment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2');
test.equal(frozenMoment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2');
test.equal(frozenMoment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3');
test.done();
},
'weeks year starting tuesday' : function (test) {
test.equal(frozenMoment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1');
test.equal(frozenMoment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
test.equal(frozenMoment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1');
test.equal(frozenMoment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2');
test.equal(frozenMoment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2');
test.equal(frozenMoment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3');
test.done();
},
'weeks year starting wednesday' : function (test) {
test.equal(frozenMoment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1');
test.equal(frozenMoment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
test.equal(frozenMoment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1');
test.equal(frozenMoment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2');
test.equal(frozenMoment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2');
test.equal(frozenMoment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3');
test.done();
},
'weeks year starting thursday' : function (test) {
test.equal(frozenMoment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1');
test.equal(frozenMoment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
test.equal(frozenMoment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1');
test.equal(frozenMoment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2');
test.equal(frozenMoment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2');
test.equal(frozenMoment([2009, 0, 12]).week(), 3, 'Jan 12 2009 should be week 3');
test.done();
},
'weeks year starting friday' : function (test) {
test.equal(frozenMoment([2009, 11, 28]).week(), 1, 'Dec 28 2009 should be week 1');
test.equal(frozenMoment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
test.equal(frozenMoment([2010, 0, 3]).week(), 1, 'Jan 3 2010 should be week 1');
test.equal(frozenMoment([2010, 0, 4]).week(), 2, 'Jan 4 2010 should be week 2');
test.equal(frozenMoment([2010, 0, 10]).week(), 2, 'Jan 10 2010 should be week 2');
test.equal(frozenMoment([2010, 0, 11]).week(), 3, 'Jan 11 2010 should be week 3');
test.done();
},
'weeks year starting saturday' : function (test) {
test.equal(frozenMoment([2010, 11, 27]).week(), 1, 'Dec 27 2010 should be week 1');
test.equal(frozenMoment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
test.equal(frozenMoment([2011, 0, 2]).week(), 1, 'Jan 2 2011 should be week 1');
test.equal(frozenMoment([2011, 0, 3]).week(), 2, 'Jan 3 2011 should be week 2');
test.equal(frozenMoment([2011, 0, 9]).week(), 2, 'Jan 9 2011 should be week 2');
test.equal(frozenMoment([2011, 0, 10]).week(), 3, 'Jan 10 2011 should be week 3');
test.done();
},
'weeks year starting sunday formatted' : function (test) {
test.equal(frozenMoment([2011, 11, 26]).format('w ww wo'), '1 01 1-ви', 'Dec 26 2011 should be week 1');
test.equal(frozenMoment([2012, 0, 1]).format('w ww wo'), '1 01 1-ви', 'Jan 1 2012 should be week 1');
test.equal(frozenMoment([2012, 0, 2]).format('w ww wo'), '2 02 2-ри', 'Jan 2 2012 should be week 2');
test.equal(frozenMoment([2012, 0, 8]).format('w ww wo'), '2 02 2-ри', 'Jan 8 2012 should be week 2');
test.equal(frozenMoment([2012, 0, 9]).format('w ww wo'), '3 03 3-ти', 'Jan 9 2012 should be week 3');
test.done();
},
'lenient ordinal parsing' : function (test) {
var i, ordinalStr, testMoment;
for (i = 1; i <= 31; ++i) {
ordinalStr = frozenMoment([2014, 0, i]).format('YYYY MM Do');
testMoment = frozenMoment(ordinalStr, 'YYYY MM Do');
test.equal(testMoment.year(), 2014,
'lenient ordinal parsing ' + i + ' year check');
test.equal(testMoment.month(), 0,
'lenient ordinal parsing ' + i + ' month check');
test.equal(testMoment.date(), i,
'lenient ordinal parsing ' + i + ' date check');
}
test.done();
},
'lenient ordinal parsing of number' : function (test) {
var i, testMoment;
for (i = 1; i <= 31; ++i) {
testMoment = frozenMoment('2014 01 ' + i, 'YYYY MM Do');
test.equal(testMoment.year(), 2014,
'lenient ordinal parsing of number ' + i + ' year check');
test.equal(testMoment.month(), 0,
'lenient ordinal parsing of number ' + i + ' month check');
test.equal(testMoment.date(), i,
'lenient ordinal parsing of number ' + i + ' date check');
}
test.done();
},
'strict ordinal parsing' : function (test) {
var i, ordinalStr, testMoment;
for (i = 1; i <= 31; ++i) {
ordinalStr = frozenMoment([2014, 0, i]).format('YYYY MM Do');
testMoment = frozenMoment(ordinalStr, 'YYYY MM Do', true);
test.ok(testMoment.isValid(), 'strict ordinal parsing ' + i);
}
test.done();
}
};
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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.
#
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.compute_v1.types import compute
from .transports.base import ReservationsTransport, DEFAULT_CLIENT_INFO
from .transports.rest import ReservationsRestTransport
class ReservationsClientMeta(type):
"""Metaclass for the Reservations client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = OrderedDict() # type: Dict[str, Type[ReservationsTransport]]
_transport_registry["rest"] = ReservationsRestTransport
def get_transport_class(cls, label: str = None,) -> Type[ReservationsTransport]:
"""Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class ReservationsClient(metaclass=ReservationsClientMeta):
"""The Reservations API."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "compute.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
ReservationsClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_info(info)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
ReservationsClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@property
def transport(self) -> ReservationsTransport:
"""Return the transport used by the client instance.
Returns:
ReservationsTransport: The transport used by the client instance.
"""
return self._transport
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
"""Return a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_folder_path(folder: str,) -> str:
"""Return a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
def parse_common_folder_path(path: str) -> Dict[str, str]:
"""Parse a folder path into its component segments."""
m = re.match(r"^folders/(?P<folder>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_organization_path(organization: str,) -> str:
"""Return a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
def parse_common_organization_path(path: str) -> Dict[str, str]:
"""Parse a organization path into its component segments."""
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_project_path(project: str,) -> str:
"""Return a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
def parse_common_project_path(path: str) -> Dict[str, str]:
"""Parse a project path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_location_path(project: str, location: str,) -> str:
"""Return a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@staticmethod
def parse_common_location_path(path: str) -> Dict[str, str]:
"""Parse a location path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
return m.groupdict() if m else {}
def __init__(
self,
*,
credentials: Optional[credentials.Credentials] = None,
transport: Union[str, ReservationsTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiate the reservations client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, ReservationsTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
use_client_cert = bool(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
client_cert_source_func = (
mtls.default_client_cert_source() if is_mtls else None
)
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
api_endpoint = (
self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
)
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, ReservationsTransport):
# transport is a ReservationsTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, "
"provide its scopes directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
def aggregated_list(
self,
request: compute.AggregatedListReservationsRequest = None,
*,
project: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.ReservationAggregatedList:
r"""Retrieves an aggregated list of reservations.
Args:
request (google.cloud.compute_v1.types.AggregatedListReservationsRequest):
The request object. A request message for
Reservations.AggregatedList. See the method description
for details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.ReservationAggregatedList:
Contains a list of reservations.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.AggregatedListReservationsRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.AggregatedListReservationsRequest):
request = compute.AggregatedListReservationsRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.aggregated_list]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def delete(
self,
request: compute.DeleteReservationRequest = None,
*,
project: str = None,
zone: str = None,
reservation: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
r"""Deletes the specified reservation.
Args:
request (google.cloud.compute_v1.types.DeleteReservationRequest):
The request object. A request message for
Reservations.Delete. See the method description for
details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
Name of the zone for this request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
reservation (str):
Name of the reservation to delete.
This corresponds to the ``reservation`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Operation:
Represents an Operation resource.
Google Compute Engine has three Operation resources:
- [Global](/compute/docs/reference/rest/{$api_version}/globalOperations)
\*
[Regional](/compute/docs/reference/rest/{$api_version}/regionOperations)
\*
[Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations)
You can use an operation resource to manage
asynchronous API requests. For more information, read
Handling API responses.
Operations can be global, regional or zonal. - For
global operations, use the globalOperations resource.
- For regional operations, use the regionOperations
resource. - For zonal operations, use the
zonalOperations resource.
For more information, read Global, Regional, and
Zonal Resources. (== resource_for
{$api_version}.globalOperations ==) (== resource_for
{$api_version}.regionOperations ==) (== resource_for
{$api_version}.zoneOperations ==)
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project, zone, reservation])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.DeleteReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.DeleteReservationRequest):
request = compute.DeleteReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if reservation is not None:
request.reservation = reservation
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def get(
self,
request: compute.GetReservationRequest = None,
*,
project: str = None,
zone: str = None,
reservation: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Reservation:
r"""Retrieves information about the specified
reservation.
Args:
request (google.cloud.compute_v1.types.GetReservationRequest):
The request object. A request message for
Reservations.Get. See the method description for
details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
Name of the zone for this request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
reservation (str):
Name of the reservation to retrieve.
This corresponds to the ``reservation`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Reservation:
Represents a reservation resource. A reservation ensures
that capacity is held in a specific zone even if the
reserved VMs are not running. For more information, read
Reserving zonal resources. (== resource_for
{$api_version}.reservations ==)
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project, zone, reservation])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.GetReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.GetReservationRequest):
request = compute.GetReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if reservation is not None:
request.reservation = reservation
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def get_iam_policy(
self,
request: compute.GetIamPolicyReservationRequest = None,
*,
project: str = None,
zone: str = None,
resource: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Policy:
r"""Gets the access control policy for a resource. May be
empty if no such policy or resource exists.
Args:
request (google.cloud.compute_v1.types.GetIamPolicyReservationRequest):
The request object. A request message for
Reservations.GetIamPolicy. See the method description
for details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
The name of the zone for this
request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
resource (str):
Name or id of the resource for this
request.
This corresponds to the ``resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Policy:
An Identity and Access Management (IAM) policy, which
specifies access controls for Google Cloud resources.
A Policy is a collection of bindings. A binding binds
one or more members to a single role. Members can be
user accounts, service accounts, Google groups, and
domains (such as G Suite). A role is a named list of
permissions; each role can be an IAM predefined role
or a user-created custom role.
For some types of Google Cloud resources, a binding
can also specify a condition, which is a logical
expression that allows access to a resource only if
the expression evaluates to true. A condition can add
constraints based on attributes of the request, the
resource, or both. To learn which resources support
conditions in their IAM policies, see the [IAM
documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
**JSON example:**
{ "bindings": [ { "role":
"roles/resourcemanager.organizationAdmin", "members":
[ "user:[email protected]",
"group:[email protected]", "domain:google.com",
"serviceAccount:[email protected]"
] }, { "role":
"roles/resourcemanager.organizationViewer",
"members": [ "user:[email protected]" ], "condition": {
"title": "expirable access", "description": "Does not
grant access after Sep 2020", "expression":
"request.time <
timestamp('2020-10-01T00:00:00.000Z')", } } ],
"etag": "BwWWja0YfJA=", "version": 3 }
**YAML example:**
bindings: - members: - user:\ [email protected] -
group:\ [email protected] - domain:google.com -
serviceAccount:\ [email protected]
role: roles/resourcemanager.organizationAdmin -
members: - user:\ [email protected] role:
roles/resourcemanager.organizationViewer condition:
title: expirable access description: Does not grant
access after Sep 2020 expression: request.time <
timestamp('2020-10-01T00:00:00.000Z') - etag:
BwWWja0YfJA= - version: 3
For a description of IAM and its features, see the
[IAM
documentation](\ https://cloud.google.com/iam/docs/).
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project, zone, resource])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.GetIamPolicyReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.GetIamPolicyReservationRequest):
request = compute.GetIamPolicyReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if resource is not None:
request.resource = resource
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def insert(
self,
request: compute.InsertReservationRequest = None,
*,
project: str = None,
zone: str = None,
reservation_resource: compute.Reservation = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
r"""Creates a new reservation. For more information, read
Reserving zonal resources.
Args:
request (google.cloud.compute_v1.types.InsertReservationRequest):
The request object. A request message for
Reservations.Insert. See the method description for
details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
Name of the zone for this request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
reservation_resource (google.cloud.compute_v1.types.Reservation):
The body resource for this request
This corresponds to the ``reservation_resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Operation:
Represents an Operation resource.
Google Compute Engine has three Operation resources:
- [Global](/compute/docs/reference/rest/{$api_version}/globalOperations)
\*
[Regional](/compute/docs/reference/rest/{$api_version}/regionOperations)
\*
[Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations)
You can use an operation resource to manage
asynchronous API requests. For more information, read
Handling API responses.
Operations can be global, regional or zonal. - For
global operations, use the globalOperations resource.
- For regional operations, use the regionOperations
resource. - For zonal operations, use the
zonalOperations resource.
For more information, read Global, Regional, and
Zonal Resources. (== resource_for
{$api_version}.globalOperations ==) (== resource_for
{$api_version}.regionOperations ==) (== resource_for
{$api_version}.zoneOperations ==)
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project, zone, reservation_resource])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.InsertReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.InsertReservationRequest):
request = compute.InsertReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if reservation_resource is not None:
request.reservation_resource = reservation_resource
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.insert]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def list(
self,
request: compute.ListReservationsRequest = None,
*,
project: str = None,
zone: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.ReservationList:
r"""A list of all the reservations that have been
configured for the specified project in specified zone.
Args:
request (google.cloud.compute_v1.types.ListReservationsRequest):
The request object. A request message for
Reservations.List. See the method description for
details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
Name of the zone for this request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.ReservationList:
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([project, zone])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.ListReservationsRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.ListReservationsRequest):
request = compute.ListReservationsRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def resize(
self,
request: compute.ResizeReservationRequest = None,
*,
project: str = None,
zone: str = None,
reservation: str = None,
reservations_resize_request_resource: compute.ReservationsResizeRequest = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
r"""Resizes the reservation (applicable to standalone
reservations only). For more information, read Modifying
reservations.
Args:
request (google.cloud.compute_v1.types.ResizeReservationRequest):
The request object. A request message for
Reservations.Resize. See the method description for
details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
Name of the zone for this request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
reservation (str):
Name of the reservation to update.
This corresponds to the ``reservation`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
reservations_resize_request_resource (google.cloud.compute_v1.types.ReservationsResizeRequest):
The body resource for this request
This corresponds to the ``reservations_resize_request_resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Operation:
Represents an Operation resource.
Google Compute Engine has three Operation resources:
- [Global](/compute/docs/reference/rest/{$api_version}/globalOperations)
\*
[Regional](/compute/docs/reference/rest/{$api_version}/regionOperations)
\*
[Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations)
You can use an operation resource to manage
asynchronous API requests. For more information, read
Handling API responses.
Operations can be global, regional or zonal. - For
global operations, use the globalOperations resource.
- For regional operations, use the regionOperations
resource. - For zonal operations, use the
zonalOperations resource.
For more information, read Global, Regional, and
Zonal Resources. (== resource_for
{$api_version}.globalOperations ==) (== resource_for
{$api_version}.regionOperations ==) (== resource_for
{$api_version}.zoneOperations ==)
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any(
[project, zone, reservation, reservations_resize_request_resource]
)
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.ResizeReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.ResizeReservationRequest):
request = compute.ResizeReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if reservation is not None:
request.reservation = reservation
if reservations_resize_request_resource is not None:
request.reservations_resize_request_resource = (
reservations_resize_request_resource
)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.resize]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def set_iam_policy(
self,
request: compute.SetIamPolicyReservationRequest = None,
*,
project: str = None,
zone: str = None,
resource: str = None,
zone_set_policy_request_resource: compute.ZoneSetPolicyRequest = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Policy:
r"""Sets the access control policy on the specified
resource. Replaces any existing policy.
Args:
request (google.cloud.compute_v1.types.SetIamPolicyReservationRequest):
The request object. A request message for
Reservations.SetIamPolicy. See the method description
for details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
The name of the zone for this
request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
resource (str):
Name or id of the resource for this
request.
This corresponds to the ``resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest):
The body resource for this request
This corresponds to the ``zone_set_policy_request_resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.Policy:
An Identity and Access Management (IAM) policy, which
specifies access controls for Google Cloud resources.
A Policy is a collection of bindings. A binding binds
one or more members to a single role. Members can be
user accounts, service accounts, Google groups, and
domains (such as G Suite). A role is a named list of
permissions; each role can be an IAM predefined role
or a user-created custom role.
For some types of Google Cloud resources, a binding
can also specify a condition, which is a logical
expression that allows access to a resource only if
the expression evaluates to true. A condition can add
constraints based on attributes of the request, the
resource, or both. To learn which resources support
conditions in their IAM policies, see the [IAM
documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
**JSON example:**
{ "bindings": [ { "role":
"roles/resourcemanager.organizationAdmin", "members":
[ "user:[email protected]",
"group:[email protected]", "domain:google.com",
"serviceAccount:[email protected]"
] }, { "role":
"roles/resourcemanager.organizationViewer",
"members": [ "user:[email protected]" ], "condition": {
"title": "expirable access", "description": "Does not
grant access after Sep 2020", "expression":
"request.time <
timestamp('2020-10-01T00:00:00.000Z')", } } ],
"etag": "BwWWja0YfJA=", "version": 3 }
**YAML example:**
bindings: - members: - user:\ [email protected] -
group:\ [email protected] - domain:google.com -
serviceAccount:\ [email protected]
role: roles/resourcemanager.organizationAdmin -
members: - user:\ [email protected] role:
roles/resourcemanager.organizationViewer condition:
title: expirable access description: Does not grant
access after Sep 2020 expression: request.time <
timestamp('2020-10-01T00:00:00.000Z') - etag:
BwWWja0YfJA= - version: 3
For a description of IAM and its features, see the
[IAM
documentation](\ https://cloud.google.com/iam/docs/).
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any(
[project, zone, resource, zone_set_policy_request_resource]
)
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.SetIamPolicyReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.SetIamPolicyReservationRequest):
request = compute.SetIamPolicyReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if resource is not None:
request.resource = resource
if zone_set_policy_request_resource is not None:
request.zone_set_policy_request_resource = (
zone_set_policy_request_resource
)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def test_iam_permissions(
self,
request: compute.TestIamPermissionsReservationRequest = None,
*,
project: str = None,
zone: str = None,
resource: str = None,
test_permissions_request_resource: compute.TestPermissionsRequest = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.TestPermissionsResponse:
r"""Returns permissions that a caller has on the
specified resource.
Args:
request (google.cloud.compute_v1.types.TestIamPermissionsReservationRequest):
The request object. A request message for
Reservations.TestIamPermissions. See the method
description for details.
project (str):
Project ID for this request.
This corresponds to the ``project`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
zone (str):
The name of the zone for this
request.
This corresponds to the ``zone`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
resource (str):
Name or id of the resource for this
request.
This corresponds to the ``resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest):
The body resource for this request
This corresponds to the ``test_permissions_request_resource`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.compute_v1.types.TestPermissionsResponse:
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any(
[project, zone, resource, test_permissions_request_resource]
)
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a compute.TestIamPermissionsReservationRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, compute.TestIamPermissionsReservationRequest):
request = compute.TestIamPermissionsReservationRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if project is not None:
request.project = project
if zone is not None:
request.zone = zone
if resource is not None:
request.resource = resource
if test_permissions_request_resource is not None:
request.test_permissions_request_resource = (
test_permissions_request_resource
)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = ("ReservationsClient",)
|
/**
* @license
* Copyright 2015 Google Inc. 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.
*/
CLASS({
package: 'foam.ui',
name: 'PropertyView',
extends: 'foam.ui.AsyncLoadingView',
documentation: function() {/*
Apply this trait to a $$DOC{ref:'BaseView'} (such as $$DOC{ref:'HTMLView'}).</p>
<p>Used by $$DOC{ref:'foam.ui.DetailView'} to generate a sub-$$DOC{ref:'foam.ui.View'} for one
$$DOC{ref:'Property'}. The $$DOC{ref:'foam.ui.View'} chosen can be based off the
$$DOC{ref:'Property.view',text:'Property.view'} value, the $$DOC{ref:'.innerView'} value, or
$$DOC{ref:'.args'}.model_.
*/},
properties: [
{
name: 'prop',
documentation: function() {/*
The $$DOC{ref:'Property'} for which to generate a $$DOC{ref:'foam.ui.View'}.
*/},
postSet: function(old, nu) {
if ( old && this.bound_ ) this.unbindData(this.data);
if ( nu && ! this.bound_ ) this.bindData(this.data);
this.args = nu;
this.model = this.innerView || nu.view;
}
},
{
name: 'data',
documentation: function() {/*
The $$DOC{ref:'.data'} for which to generate a $$DOC{ref:'foam.ui.View'}.
*/},
postSet: function(old, nu) {
if ( old && this.bound_ ) this.unbindData(old);
if ( nu ) this.bindData(nu);
}
},
{
name: 'childData'
},
{
name: 'innerView',
help: 'Override for prop.view',
documentation: function() {/*
The optional name of the desired sub-$$DOC{ref:'foam.ui.View'}. If not specified,
prop.$$DOC{ref:'Property.view'} is used. DEPRECATED. Use $$DOC{ref:'.model'} instead.
*/},
postSet: function(old,nu) {
this.model = nu;
}
},
{
name: 'view',
// type: 'foam.ui.View',
adapt: function(_, v) { return v && v.toView_ ? v.toView_() : v; },
documentation: function() {/*
The new sub-$$DOC{ref:'foam.ui.View'} generated for the given $$DOC{ref:'Property'}.
*/}
},
{
name: 'bound_',
type: 'Boolean',
defaultValue: false
},
{
name: 'parent',
// type: 'foam.ui.View',
postSet: function(_, p) {
if ( ! p ) return; // TODO(jacksonic): We shouldn't pretend we aren't part of the tree
p[this.prop.name + 'View'] = this.view.cview || this.view;
if ( this.view ) this.view.parent = p;
},
documentation: function() {/*
The $$DOC{ref:'foam.ui.View'} to use as the parent container for the new
sub-$$DOC{ref:'foam.ui.View'}.
*/}
},
],
methods: {
unbindData: function(oldData) {
if ( ! this.bound_ || ! oldData || ! this.prop ) return;
var pValue = oldData.propertyValue(this.prop.name);
Events.unlink(pValue, this.childData$);
this.bound_ = false;
},
bindData: function(data) {
var self = this;
if ( this.bound_ || ! data || ! this.prop) return;
var pValue = data.propertyValue(this.prop.name);
Events.link(pValue, this.childData$);
if ( this.prop.validate ) {
this.X.dynamic3(data, this.prop.validate, function(error) {
// console.log('************************** error, ', self.prop.name, error, self.view.$);
if ( ! self.view ) return;
self.view.$.style.border = error ? '2px solid red' : '';
});
}
this.bound_ = true;
},
toString: function() { /* Name info. */ return 'PropertyView(' + this.prop.name + ', ' + this.view + ')'; },
destroy: function( isParentDestroyed ) { /* Passthrough to $$DOC{ref:'.view'} */
// always unbind, since if our parent was the top level destroy we need
// to unhook if we were created as an addSelfDataChild
this.unbindData(this.data);
this.SUPER( isParentDestroyed );
},
construct: function() {
// if not bound yet and we do have data set, bind it
this.bindData(this.data);
this.SUPER();
},
finishRender: function(view) {
view.prop = this.prop;
this.SUPER(view);
},
addDataChild: function(child) {
Events.link(this.childData$, child.data$);
this.addChild(child);
}
}
});
|
#!/usr/bin/env python3
#coding: utf-8
import argparse
import random
from sqlitedborm import db
def main():
# Get arguments. Handle if none was informed.
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=["demo", "create", "drop", "truncate", "select", "update", "delete", "insert", "search"])
args = parser.parse_args()
data = db.Database('testdata')
if args.action == 'demo':
print('demo')
elif args.action == 'create':
columns = []
columns.append({'name': 'id', 'type': 'INTEGER', 'extra': ['PRIMARY KEY', 'AUTOINCREMENT', 'NOT NULL']})
columns.append({'name': 'name', 'type': 'VARCHAR', 'size': 80, 'extra': ['NOT NULL']})
columns.append({'name': 'address', 'type': 'VARCHAR', 'size': 80})
columns.append({'name': 'created_at', 'type': 'DATETIME', 'default': "CURRENT_TIMESTAMP"})
columns.append({'name': 'updated_at', 'type': 'DATETIME', 'default': "CURRENT_TIMESTAMP"})
data.create('tb_contacts', columns)
print('Tabela criada com sucesso.')
elif args.action == 'drop':
data.drop('tb_contacts')
print('Tabela eliminada com sucesso.')
elif args.action == 'truncate':
data.truncate('tb_contacts')
print('Tabela limpa com sucesso.')
elif args.action == 'select':
tbContacts = db.Table(data, 'tb_contacts')
res = tbContacts.getAll()
for row in res:
print(row)
elif args.action == 'update':
tbContacts = db.Table(data, 'tb_contacts')
res = tbContacts.getAll()
for i, row in enumerate(res):
record = f"{(i + 1)}. [{row['id']}] - {row['name']}"
print(record)
c = False
while (not c):
c = True
q = input('Indique qual deseja alterar: ')
try:
q = int(q)
if q not in list(range(1, len(res) + 1)):
c = False
except ValueError:
c = False
row = res[q - 1]
for col in row.keys():
if col not in ['id', 'created_at', 'updated_at']:
q = input(f'{col} ({row[col]}): ') or row[col]
row[col] = q
tbContacts.update(row).where({'id': row['id']}).exec()
print('Registo atualizado com sucesso.')
elif args.action == 'delete':
tbContacts = db.Table(data, 'tb_contacts')
res = tbContacts.getAll()
for i, row in enumerate(res):
record = f"{(i + 1)}. [{row['id']}] - {row['name']}"
print(record)
c = False
while (not c):
c = True
q = input('Indique qual deseja eliminar: ')
try:
q = int(q)
if q not in list(range(1, len(res) + 1)):
c = False
except ValueError:
c = False
row = res[q - 1]
tbContacts.delete().where({'id': row['id']}).exec()
print('Registo eliminado com sucesso.')
elif args.action == 'insert':
first_names = ['João', 'Raquel', 'Luciano', 'Ana', 'José', 'Fernanda', 'Carlos', 'Paula']
middle_names = ['Gomes', 'Ferreira', 'Paula', 'Assis', 'Aguiar', 'Marcos']
last_names = ['da Silva', 'Neves', 'Rodrigues', 'Tavares', 'Fonseca']
name = first_names[random.randint(0, len(first_names) - 1)]
name += f' {middle_names[random.randint(0, len(middle_names) - 1)]}'
name += f' {last_names[random.randint(0, len(last_names) - 1)]}'
lograd = ['Rua', 'Avenida', 'Praceta', 'Estrada']
ruas = ['Liberdade', 'Eugênio dos Santos', 'Argonautas', 'Fernão Lopes', 'Marginal', 'Fontes Pereira de Melo']
andar = ['R/C'] + list(range(2, 9))
fracao = ['Dto', 'Fte', 'Esq']
cpost = f'{random.randint(1200, 4500)}-{random.randint(100, 999)}'
city = ['Lisboa', 'Oeiras', 'Cascais', 'Porto', 'Setúbal', 'Faro', 'Braga', 'Viseu']
address = lograd[random.randint(0, len(lograd) - 1)]
address += f' {ruas[random.randint(0, len(ruas) - 1)]}'
address += f' {random.randint(1, 100)}'
address += f', {andar[random.randint(0, len(andar) - 1)]}'
address += f' {fracao[random.randint(0, len(fracao) - 1)]}'
address += f', {cpost}'
address += f' {city[random.randint(0, len(city) - 1)]}'
contact = {'name': name, 'address': address}
tbContacts = db.Table(data, 'tb_contacts')
tbContacts.insert(contact).exec()
print('Registo inserido com sucesso.')
elif args.action == 'search':
q = input('Indique o nome ou parte dele: ')
tbContacts = db.Table(data, 'tb_contacts')
res = tbContacts.select('id, name').whereLike({'name': q}).exec()
for i, row in enumerate(res):
record = f"{(i + 1)}. [{row['id']}] - {row['name']}"
print(record)
data.close()
if __name__ == '__main__':
main()
|
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import render
from sic_financeiro.core.globais import carregador_global
@login_required
def pagina_inicial(request):
context = carregador_global.context
context['url_contas_salvar_js'] = reverse('contas_salvar')
return render(request, '{0}/index.html'.format(carregador_global.path_home), context)
|
import re
import os
import imp
import sys
import json
import uuid
import time
import base64
import logging
import threading
import traceback
import hashlib
import functools
from io import BytesIO
from datetime import datetime
from six.moves import cStringIO as StringIO
from six.moves.urllib.parse import urlparse
from flask import Flask, Response, jsonify, request
from localstack import config
from localstack.constants import TEST_AWS_ACCOUNT_ID
from localstack.utils.aws import aws_stack, aws_responses
from localstack.services.awslambda import lambda_executors
from localstack.services.awslambda.lambda_executors import (
LAMBDA_RUNTIME_PYTHON27,
LAMBDA_RUNTIME_PYTHON36,
LAMBDA_RUNTIME_PYTHON37,
LAMBDA_RUNTIME_PYTHON38,
LAMBDA_RUNTIME_NODEJS,
LAMBDA_RUNTIME_NODEJS610,
LAMBDA_RUNTIME_NODEJS810,
LAMBDA_RUNTIME_JAVA8,
LAMBDA_RUNTIME_JAVA11,
LAMBDA_RUNTIME_DOTNETCORE2,
LAMBDA_RUNTIME_DOTNETCORE21,
LAMBDA_RUNTIME_DOTNETCORE31,
LAMBDA_RUNTIME_GOLANG,
LAMBDA_RUNTIME_RUBY,
LAMBDA_RUNTIME_RUBY25,
LAMBDA_RUNTIME_PROVIDED)
from localstack.services.awslambda.multivalue_transformer import multi_value_dict_for_list
from localstack.utils.common import (
to_str, to_bytes, load_file, save_file, TMP_FILES, ensure_readable, short_uid, long_uid, json_safe,
mkdir, unzip, is_zip_file, run, first_char_to_lower,
timestamp_millis, now_utc, safe_requests, FuncThread, isoformat_milliseconds, synchronized)
from localstack.utils.analytics import event_publisher
from localstack.utils.http_utils import parse_chunked_data
from localstack.utils.aws.aws_models import LambdaFunction, CodeSigningConfig
# logger
LOG = logging.getLogger(__name__)
APP_NAME = 'lambda_api'
PATH_ROOT = '/2015-03-31'
ARCHIVE_FILE_PATTERN = '%s/lambda.handler.*.jar' % config.TMP_FOLDER
LAMBDA_SCRIPT_PATTERN = '%s/lambda_script_*.py' % config.TMP_FOLDER
# List of Lambda runtime names. Keep them in this list, mainly to silence the linter
LAMBDA_RUNTIMES = [LAMBDA_RUNTIME_PYTHON27, LAMBDA_RUNTIME_PYTHON36, LAMBDA_RUNTIME_PYTHON37,
LAMBDA_RUNTIME_PYTHON38, LAMBDA_RUNTIME_DOTNETCORE2, LAMBDA_RUNTIME_DOTNETCORE21, LAMBDA_RUNTIME_DOTNETCORE31,
LAMBDA_RUNTIME_NODEJS, LAMBDA_RUNTIME_NODEJS610, LAMBDA_RUNTIME_NODEJS810,
LAMBDA_RUNTIME_JAVA8, LAMBDA_RUNTIME_JAVA11, LAMBDA_RUNTIME_RUBY, LAMBDA_RUNTIME_RUBY25]
DOTNET_LAMBDA_RUNTIMES = [LAMBDA_RUNTIME_DOTNETCORE2, LAMBDA_RUNTIME_DOTNETCORE21, LAMBDA_RUNTIME_DOTNETCORE31]
# default timeout in seconds
LAMBDA_DEFAULT_TIMEOUT = 3
# default handler and runtime
LAMBDA_DEFAULT_HANDLER = 'handler.handler'
LAMBDA_DEFAULT_RUNTIME = LAMBDA_RUNTIME_PYTHON38
LAMBDA_DEFAULT_STARTING_POSITION = 'LATEST'
LAMBDA_ZIP_FILE_NAME = 'original_lambda_archive.zip'
LAMBDA_JAR_FILE_NAME = 'original_lambda_archive.jar'
INVALID_PARAMETER_VALUE_EXCEPTION = 'InvalidParameterValueException'
VERSION_LATEST = '$LATEST'
FUNCTION_MAX_SIZE = 69905067
BATCH_SIZE_RANGES = {
'kinesis': (100, 10000),
'dynamodb': (100, 1000),
'sqs': (10, 10)
}
app = Flask(APP_NAME)
# map ARN strings to lambda function objects
ARN_TO_LAMBDA = {}
# map ARN strigns to CodeSigningConfig object
ARN_TO_CODE_SIGNING_CONFIG = {}
# list of event source mappings for the API
EVENT_SOURCE_MAPPINGS = []
# mutex for access to CWD and ENV
EXEC_MUTEX = threading.RLock(1)
# whether to use Docker for execution
DO_USE_DOCKER = None
# start characters indicating that a lambda result should be parsed as JSON
JSON_START_CHAR_MAP = {
list: ('[',),
tuple: ('[',),
dict: ('{',),
str: ('"',),
bytes: ('"',),
bool: ('t', 'f'),
type(None): ('n',),
int: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'),
float: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
}
POSSIBLE_JSON_TYPES = (str, bytes)
JSON_START_TYPES = tuple(set(JSON_START_CHAR_MAP.keys()) - set(POSSIBLE_JSON_TYPES))
JSON_START_CHARS = tuple(set(functools.reduce(lambda x, y: x + y, JSON_START_CHAR_MAP.values())))
# SQS listener thread settings
SQS_LISTENER_THREAD = {}
SQS_POLL_INTERVAL_SEC = 1
# lambda executor instance
LAMBDA_EXECUTOR = lambda_executors.AVAILABLE_EXECUTORS.get(config.LAMBDA_EXECUTOR, lambda_executors.DEFAULT_EXECUTOR)
# IAM policy constants
IAM_POLICY_VERSION = '2012-10-17'
POLICY_NAME_PATTERN = 'lambda_policy_%s'
# Whether to check if the handler function exists while creating lambda function
CHECK_HANDLER_ON_CREATION = False
# Marker name to indicate that a bucket represents the local file system. This is used for testing
# Serverless applications where we mount the Lambda code directly into the container from the host OS.
BUCKET_MARKER_LOCAL = '__local__'
class ClientError(Exception):
def __init__(self, msg, code=400):
super(ClientError, self).__init__(msg)
self.code = code
self.msg = msg
def get_response(self):
if isinstance(self.msg, Response):
return self.msg
return error_response(self.msg, self.code)
class LambdaContext(object):
def __init__(self, func_details, qualifier=None, context=None):
self.function_name = func_details.name()
self.function_version = func_details.get_qualifier_version(qualifier)
self.client_context = context.get('client_context')
self.invoked_function_arn = func_details.arn()
if qualifier:
self.invoked_function_arn += ':' + qualifier
self.cognito_identity = context.get('identity')
def get_remaining_time_in_millis(self):
# TODO implement!
return 1000 * 60
def cleanup():
global EVENT_SOURCE_MAPPINGS, ARN_TO_LAMBDA
ARN_TO_LAMBDA = {}
EVENT_SOURCE_MAPPINGS = []
LAMBDA_EXECUTOR.cleanup()
def func_arn(function_name):
return aws_stack.lambda_function_arn(function_name)
def func_qualifier(function_name, qualifier=None):
arn = aws_stack.lambda_function_arn(function_name)
if ARN_TO_LAMBDA.get(arn).qualifier_exists(qualifier):
return '{}:{}'.format(arn, qualifier)
return arn
def check_batch_size_range(source_arn, batch_size=None):
batch_size_entry = BATCH_SIZE_RANGES.get(source_arn.split(':')[2].lower())
if not batch_size_entry:
raise ValueError(
INVALID_PARAMETER_VALUE_EXCEPTION, 'Unsupported event source type'
)
batch_size = batch_size or batch_size_entry[0]
if batch_size > batch_size_entry[1]:
raise ValueError(
INVALID_PARAMETER_VALUE_EXCEPTION,
'BatchSize {} exceeds the max of {}'.format(batch_size, batch_size_entry[1])
)
return batch_size
def add_function_mapping(lambda_name, lambda_handler, lambda_cwd=None):
arn = func_arn(lambda_name)
ARN_TO_LAMBDA[arn].versions.get(VERSION_LATEST)['Function'] = lambda_handler
ARN_TO_LAMBDA[arn].cwd = lambda_cwd
def add_event_source(function_name, source_arn, enabled, batch_size=None):
batch_size = check_batch_size_range(source_arn, batch_size)
mapping = {
'UUID': str(uuid.uuid4()),
'StateTransitionReason': 'User action',
'LastModified': float(time.mktime(datetime.utcnow().timetuple())),
'BatchSize': batch_size,
'State': 'Enabled' if enabled in [True, None] else 'Disabled',
'FunctionArn': func_arn(function_name),
'EventSourceArn': source_arn,
'LastProcessingResult': 'OK',
'StartingPosition': LAMBDA_DEFAULT_STARTING_POSITION
}
EVENT_SOURCE_MAPPINGS.append(mapping)
return mapping
def update_event_source(uuid_value, function_name, enabled, batch_size):
for m in EVENT_SOURCE_MAPPINGS:
if uuid_value == m['UUID']:
if function_name:
m['FunctionArn'] = func_arn(function_name)
batch_size = check_batch_size_range(m['EventSourceArn'], batch_size or m['BatchSize'])
m['BatchSize'] = batch_size
m['State'] = 'Enabled' if enabled is True else 'Disabled'
m['LastModified'] = float(time.mktime(datetime.utcnow().timetuple()))
return m
return {}
def delete_event_source(uuid_value):
for i, m in enumerate(EVENT_SOURCE_MAPPINGS):
if uuid_value == m['UUID']:
return EVENT_SOURCE_MAPPINGS.pop(i)
return {}
@synchronized(lock=EXEC_MUTEX)
def use_docker():
global DO_USE_DOCKER
if DO_USE_DOCKER is None:
DO_USE_DOCKER = False
if 'docker' in config.LAMBDA_EXECUTOR:
try:
run('docker images', print_error=False)
DO_USE_DOCKER = True
except Exception:
pass
return DO_USE_DOCKER
def get_stage_variables(api_id, stage):
api_gateway_client = aws_stack.connect_to_service('apigateway')
response = api_gateway_client.get_stage(restApiId=api_id, stageName=stage)
return response.get('variables', None)
def fix_proxy_path_params(path_params):
proxy_path_param_value = path_params.get('proxy+')
if not proxy_path_param_value:
return
del path_params['proxy+']
path_params['proxy'] = proxy_path_param_value
def message_attributes_to_lower(message_attrs):
""" Convert message attribute details (first characters) to lower case (e.g., stringValue, dataType). """
message_attrs = message_attrs or {}
for _, attr in message_attrs.items():
if not isinstance(attr, dict):
continue
for key, value in dict(attr).items():
attr[first_char_to_lower(key)] = attr.pop(key)
return message_attrs
def process_apigateway_invocation(func_arn, path, payload, stage, api_id, headers={},
resource_path=None, method=None, path_params={},
query_string_params=None, request_context={}, event_context={}):
try:
resource_path = resource_path or path
path_params = dict(path_params)
fix_proxy_path_params(path_params)
event = {
'path': path,
'headers': dict(headers),
'multiValueHeaders': multi_value_dict_for_list(headers),
'pathParameters': path_params,
'body': payload,
'isBase64Encoded': False,
'resource': resource_path,
'httpMethod': method,
'queryStringParameters': query_string_params,
'multiValueQueryStringParameters': multi_value_dict_for_list(query_string_params),
'requestContext': request_context,
'stageVariables': get_stage_variables(api_id, stage),
}
LOG.debug('Running Lambda function %s from API Gateway invocation: %s %s' % (func_arn, method or 'GET', path))
return run_lambda(event=event, context=event_context, func_arn=func_arn,
asynchronous=not config.SYNCHRONOUS_API_GATEWAY_EVENTS)
except Exception as e:
LOG.warning('Unable to run Lambda function on API Gateway message: %s %s' % (e, traceback.format_exc()))
def process_sns_notification(func_arn, topic_arn, subscription_arn, message, message_id,
message_attributes, unsubscribe_url, subject='',):
event = {
'Records': [{
'EventSource': 'localstack:sns',
'EventVersion': '1.0',
'EventSubscriptionArn': subscription_arn,
'Sns': {
'Type': 'Notification',
'MessageId': message_id,
'TopicArn': topic_arn,
'Subject': subject,
'Message': message,
'Timestamp': timestamp_millis(),
'SignatureVersion': '1',
# TODO Add a more sophisticated solution with an actual signature
# Hardcoded
'Signature': 'EXAMPLEpH+..',
'SigningCertUrl': 'https://sns.us-east-1.amazonaws.com/SimpleNotificationService-000000000.pem',
'UnsubscribeUrl': unsubscribe_url,
'MessageAttributes': message_attributes
}
}]
}
return run_lambda(event=event, context={}, func_arn=func_arn, asynchronous=not config.SYNCHRONOUS_SNS_EVENTS)
def process_kinesis_records(records, stream_name):
def chunks(lst, n):
# Yield successive n-sized chunks from lst.
for i in range(0, len(lst), n):
yield lst[i:i + n]
# feed records into listening lambdas
try:
stream_arn = aws_stack.kinesis_stream_arn(stream_name)
sources = get_event_sources(source_arn=stream_arn)
for source in sources:
arn = source['FunctionArn']
for chunk in chunks(records, source['BatchSize']):
event = {
'Records': [
{
'eventID': 'shardId-000000000000:{0}'.format(rec['sequenceNumber']),
'eventSourceARN': stream_arn,
'eventSource': 'aws:kinesis',
'eventVersion': '1.0',
'eventName': 'aws:kinesis:record',
'invokeIdentityArn': 'arn:aws:iam::{0}:role/lambda-role'.format(TEST_AWS_ACCOUNT_ID),
'awsRegion': aws_stack.get_region(),
'kinesis': rec
}
for rec in chunk
]
}
run_lambda(event=event, context={}, func_arn=arn, asynchronous=not config.SYNCHRONOUS_KINESIS_EVENTS)
except Exception as e:
LOG.warning('Unable to run Lambda function on Kinesis records: %s %s' % (e, traceback.format_exc()))
def start_lambda_sqs_listener():
if SQS_LISTENER_THREAD:
return
def send_event_to_lambda(queue_arn, queue_url, lambda_arn, messages, region):
def delete_messages(result, func_arn, event, error=None, dlq_sent=None, **kwargs):
if error and not dlq_sent:
# Skip deleting messages from the queue in case of processing errors AND if
# the message has not yet been sent to a dead letter queue (DLQ).
# We'll pick them up and retry next time they become available on the queue.
return
sqs_client = aws_stack.connect_to_service('sqs')
entries = [{'Id': r['receiptHandle'], 'ReceiptHandle': r['receiptHandle']} for r in records]
sqs_client.delete_message_batch(QueueUrl=queue_url, Entries=entries)
records = []
for msg in messages:
message_attrs = message_attributes_to_lower(msg.get('MessageAttributes'))
records.append({
'body': msg['Body'],
'receiptHandle': msg['ReceiptHandle'],
'md5OfBody': msg['MD5OfBody'],
'eventSourceARN': queue_arn,
'eventSource': lambda_executors.EVENT_SOURCE_SQS,
'awsRegion': region,
'messageId': msg['MessageId'],
'attributes': msg.get('Attributes', {}),
'messageAttributes': message_attrs,
'md5OfMessageAttributes': msg.get('MD5OfMessageAttributes'),
'sqs': True,
})
event = {'Records': records}
# TODO implement retries, based on "RedrivePolicy.maxReceiveCount" in the queue settings
run_lambda(event=event, context={}, func_arn=lambda_arn, asynchronous=True, callback=delete_messages)
def listener_loop(*args):
while True:
try:
sources = get_event_sources(source_arn=r'.*:sqs:.*')
if not sources:
# Temporarily disable polling if no event sources are configured
# anymore. The loop will get restarted next time a message
# arrives and if an event source is configured.
SQS_LISTENER_THREAD.pop('_thread_')
return
sqs_client = aws_stack.connect_to_service('sqs')
for source in sources:
queue_arn = source['EventSourceArn']
lambda_arn = source['FunctionArn']
batch_size = max(min(source.get('BatchSize', 1), 10), 1)
try:
region_name = queue_arn.split(':')[3]
queue_url = aws_stack.sqs_queue_url_for_arn(queue_arn)
result = sqs_client.receive_message(
QueueUrl=queue_url,
MessageAttributeNames=['All'],
MaxNumberOfMessages=batch_size
)
messages = result.get('Messages')
if not messages:
continue
send_event_to_lambda(queue_arn, queue_url, lambda_arn, messages, region=region_name)
except Exception as e:
LOG.debug('Unable to poll SQS messages for queue %s: %s' % (queue_arn, e))
except Exception:
pass
finally:
time.sleep(SQS_POLL_INTERVAL_SEC)
LOG.debug('Starting SQS message polling thread for Lambda API')
SQS_LISTENER_THREAD['_thread_'] = FuncThread(listener_loop)
SQS_LISTENER_THREAD['_thread_'].start()
def process_sqs_message(queue_name, region_name=None):
# feed message into the first listening lambda (message should only get processed once)
try:
region_name = region_name or aws_stack.get_region()
queue_arn = aws_stack.sqs_queue_arn(queue_name, region_name=region_name)
sources = get_event_sources(source_arn=queue_arn)
arns = [s.get('FunctionArn') for s in sources]
source = (sources or [None])[0]
if not source:
return False
LOG.debug('Found %s source mappings for event from SQS queue %s: %s' % (len(arns), queue_arn, arns))
start_lambda_sqs_listener()
return True
except Exception as e:
LOG.warning('Unable to run Lambda function on SQS messages: %s %s' % (e, traceback.format_exc()))
def get_event_sources(func_name=None, source_arn=None):
result = []
for m in EVENT_SOURCE_MAPPINGS:
if not func_name or (m['FunctionArn'] in [func_name, func_arn(func_name)]):
if _arn_match(mapped=m['EventSourceArn'], searched=source_arn):
result.append(m)
return result
def _arn_match(mapped, searched):
if not searched or mapped == searched:
return True
# Some types of ARNs can end with a path separated by slashes, for
# example the ARN of a DynamoDB stream is tableARN/stream/ID. It's
# a little counterintuitive that a more specific mapped ARN can
# match a less specific ARN on the event, but some integration tests
# rely on it for things like subscribing to a stream and matching an
# event labeled with the table ARN.
if re.match(r'^%s$' % searched, mapped):
return True
if mapped.startswith(searched):
suffix = mapped[len(searched):]
return suffix[0] == '/'
return False
def get_function_version(arn, version):
func = ARN_TO_LAMBDA.get(arn)
return format_func_details(func, version=version, always_add_version=True)
def publish_new_function_version(arn):
func_details = ARN_TO_LAMBDA.get(arn)
versions = func_details.versions
max_version_number = func_details.max_version()
next_version_number = max_version_number + 1
latest_hash = versions.get(VERSION_LATEST).get('CodeSha256')
max_version = versions.get(str(max_version_number))
max_version_hash = max_version.get('CodeSha256') if max_version else ''
if latest_hash != max_version_hash:
versions[str(next_version_number)] = {
'CodeSize': versions.get(VERSION_LATEST).get('CodeSize'),
'CodeSha256': versions.get(VERSION_LATEST).get('CodeSha256'),
'Function': versions.get(VERSION_LATEST).get('Function'),
'RevisionId': str(uuid.uuid4())
}
max_version_number = next_version_number
return get_function_version(arn, str(max_version_number))
def do_list_versions(arn):
return sorted([get_function_version(arn, version) for version in
ARN_TO_LAMBDA.get(arn).versions.keys()], key=lambda k: str(k.get('Version')))
def do_update_alias(arn, alias, version, description=None):
new_alias = {
'AliasArn': arn + ':' + alias,
'FunctionVersion': version,
'Name': alias,
'Description': description or '',
'RevisionId': str(uuid.uuid4())
}
ARN_TO_LAMBDA.get(arn).aliases[alias] = new_alias
return new_alias
def run_lambda(event, context, func_arn, version=None, suppress_output=False, asynchronous=False, callback=None):
if suppress_output:
stdout_ = sys.stdout
stderr_ = sys.stderr
stream = StringIO()
sys.stdout = stream
sys.stderr = stream
try:
func_arn = aws_stack.fix_arn(func_arn)
func_details = ARN_TO_LAMBDA.get(func_arn)
if not func_details:
return not_found_error(msg='The resource specified in the request does not exist.')
context = LambdaContext(func_details, version, context)
result = LAMBDA_EXECUTOR.execute(func_arn, func_details, event, context=context,
version=version, asynchronous=asynchronous, callback=callback)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
response = {
'errorType': str(exc_type.__name__),
'errorMessage': str(e),
'stackTrace': traceback.format_tb(exc_traceback)
}
LOG.info('Error executing Lambda function %s: %s %s' % (func_arn, e, traceback.format_exc()))
return Response(json.dumps(response), status=500)
finally:
if suppress_output:
sys.stdout = stdout_
sys.stderr = stderr_
return result
def exec_lambda_code(script, handler_function='handler', lambda_cwd=None, lambda_env=None):
if lambda_cwd or lambda_env:
EXEC_MUTEX.acquire()
if lambda_cwd:
previous_cwd = os.getcwd()
os.chdir(lambda_cwd)
sys.path = [lambda_cwd] + sys.path
if lambda_env:
previous_env = dict(os.environ)
os.environ.update(lambda_env)
# generate lambda file name
lambda_id = 'l_%s' % short_uid()
lambda_file = LAMBDA_SCRIPT_PATTERN.replace('*', lambda_id)
save_file(lambda_file, script)
# delete temporary .py and .pyc files on exit
TMP_FILES.append(lambda_file)
TMP_FILES.append('%sc' % lambda_file)
try:
pre_sys_modules_keys = set(sys.modules.keys())
try:
handler_module = imp.load_source(lambda_id, lambda_file)
module_vars = handler_module.__dict__
finally:
# the above import can bring files for the function
# (eg settings.py) into the global namespace. subsequent
# calls can pick up file from another function, causing
# general issues.
post_sys_modules_keys = set(sys.modules.keys())
for key in post_sys_modules_keys:
if key not in pre_sys_modules_keys:
sys.modules.pop(key)
except Exception as e:
LOG.error('Unable to exec: %s %s' % (script, traceback.format_exc()))
raise e
finally:
if lambda_cwd or lambda_env:
if lambda_cwd:
os.chdir(previous_cwd)
sys.path.pop(0)
if lambda_env:
os.environ = previous_env
EXEC_MUTEX.release()
return module_vars[handler_function]
def get_handler_file_from_name(handler_name, runtime=LAMBDA_DEFAULT_RUNTIME):
# TODO: support Java Lambdas in the future
if runtime.startswith(LAMBDA_RUNTIME_PROVIDED):
return 'bootstrap'
delimiter = '.'
if runtime.startswith(LAMBDA_RUNTIME_NODEJS):
file_ext = '.js'
elif runtime.startswith(LAMBDA_RUNTIME_GOLANG):
file_ext = ''
elif runtime.startswith(tuple(DOTNET_LAMBDA_RUNTIMES)):
file_ext = '.dll'
delimiter = ':'
elif runtime.startswith(LAMBDA_RUNTIME_RUBY):
file_ext = '.rb'
else:
handler_name = handler_name.rpartition(delimiter)[0].replace(delimiter, os.path.sep)
file_ext = '.py'
return '%s%s' % (handler_name.split(delimiter)[0], file_ext)
def get_handler_function_from_name(handler_name, runtime=LAMBDA_DEFAULT_RUNTIME):
# TODO: support Java Lambdas in the future
if runtime.startswith(tuple(DOTNET_LAMBDA_RUNTIMES)):
return handler_name.split(':')[-1]
return handler_name.split('.')[-1]
def error_response(msg, code=500, error_type='InternalFailure'):
LOG.info(msg)
return aws_responses.flask_error_response_json(msg, code=code, error_type=error_type)
def get_zip_bytes(function_code):
"""Returns the ZIP file contents from a FunctionCode dict.
:type function_code: dict
:param function_code: https://docs.aws.amazon.com/lambda/latest/dg/API_FunctionCode.html
:returns: bytes of the Zip file.
"""
function_code = function_code or {}
if 'S3Bucket' in function_code:
s3_client = aws_stack.connect_to_service('s3')
bytes_io = BytesIO()
try:
s3_client.download_fileobj(function_code['S3Bucket'], function_code['S3Key'], bytes_io)
zip_file_content = bytes_io.getvalue()
except Exception as e:
raise ClientError('Unable to fetch Lambda archive from S3: %s' % e, 404)
elif 'ZipFile' in function_code:
zip_file_content = function_code['ZipFile']
zip_file_content = base64.b64decode(zip_file_content)
else:
raise ClientError('No valid Lambda archive specified: %s' % list(function_code.keys()))
return zip_file_content
def get_java_handler(zip_file_content, main_file, func_details=None):
"""Creates a Java handler from an uploaded ZIP or JAR.
:type zip_file_content: bytes
:param zip_file_content: ZIP file bytes.
:type handler: str
:param handler: The lambda handler path.
:type main_file: str
:param main_file: Filepath to the uploaded ZIP or JAR file.
:returns: function or flask.Response
"""
if is_zip_file(zip_file_content):
def execute(event, context):
result = lambda_executors.EXECUTOR_LOCAL.execute_java_lambda(
event, context, main_file=main_file, func_details=func_details)
return result
return execute
raise ClientError(error_response(
'Unable to extract Java Lambda handler - file is not a valid zip/jar file', 400, error_type='ValidationError'))
def set_archive_code(code, lambda_name, zip_file_content=None):
# get metadata
lambda_arn = func_arn(lambda_name)
lambda_details = ARN_TO_LAMBDA[lambda_arn]
is_local_mount = code.get('S3Bucket') == BUCKET_MARKER_LOCAL
if is_local_mount and config.LAMBDA_REMOTE_DOCKER:
msg = 'Please note that Lambda mounts (bucket name "%s") cannot be used with LAMBDA_REMOTE_DOCKER=1'
raise Exception(msg % BUCKET_MARKER_LOCAL)
# Stop/remove any containers that this arn uses.
LAMBDA_EXECUTOR.cleanup(lambda_arn)
if is_local_mount:
# Mount or use a local folder lambda executors can reference
# WARNING: this means we're pointing lambda_cwd to a local path in the user's
# file system! We must ensure that there is no data loss (i.e., we must *not* add
# this folder to TMP_FILES or similar).
return code['S3Key']
# get file content
zip_file_content = zip_file_content or get_zip_bytes(code)
# Save the zip file to a temporary file that the lambda executors can reference
code_sha_256 = base64.standard_b64encode(hashlib.sha256(zip_file_content).digest())
latest_version = lambda_details.get_version(VERSION_LATEST)
latest_version['CodeSize'] = len(zip_file_content)
latest_version['CodeSha256'] = code_sha_256.decode('utf-8')
tmp_dir = '%s/zipfile.%s' % (config.TMP_FOLDER, short_uid())
mkdir(tmp_dir)
tmp_file = '%s/%s' % (tmp_dir, LAMBDA_ZIP_FILE_NAME)
save_file(tmp_file, zip_file_content)
TMP_FILES.append(tmp_dir)
lambda_details.cwd = tmp_dir
return tmp_dir
def set_function_code(code, lambda_name, lambda_cwd=None):
def generic_handler(event, context):
raise ClientError(('Unable to find executor for Lambda function "%s". Note that ' +
'Node.js, Golang, and .Net Core Lambdas currently require LAMBDA_EXECUTOR=docker') % lambda_name)
arn = func_arn(lambda_name)
lambda_details = ARN_TO_LAMBDA[arn]
runtime = lambda_details.runtime
lambda_environment = lambda_details.envvars
handler_name = lambda_details.handler = lambda_details.handler or LAMBDA_DEFAULT_HANDLER
code_passed = code
code = code or lambda_details.code
is_local_mount = code.get('S3Bucket') == BUCKET_MARKER_LOCAL
zip_file_content = None
if code_passed:
lambda_cwd = lambda_cwd or set_archive_code(code_passed, lambda_name)
if not is_local_mount:
# Save the zip file to a temporary file that the lambda executors can reference
zip_file_content = get_zip_bytes(code_passed)
else:
lambda_cwd = lambda_cwd or lambda_details.cwd
# get local lambda working directory
tmp_file = '%s/%s' % (lambda_cwd, LAMBDA_ZIP_FILE_NAME)
if not zip_file_content:
zip_file_content = load_file(tmp_file, mode='rb')
# Set the appropriate lambda handler.
lambda_handler = generic_handler
is_java = lambda_executors.is_java_lambda(runtime)
if is_java:
# The Lambda executors for Docker subclass LambdaExecutorContainers, which
# runs Lambda in Docker by passing all *.jar files in the function working
# directory as part of the classpath. Obtain a Java handler function below.
lambda_handler = get_java_handler(zip_file_content, tmp_file, func_details=lambda_details)
if not is_local_mount:
# Lambda code must be uploaded in Zip format
if not is_zip_file(zip_file_content):
raise ClientError(
'Uploaded Lambda code for runtime ({}) is not in Zip format'.format(runtime))
# Unzip the Lambda archive contents
unzip(tmp_file, lambda_cwd)
# Obtain handler details for any non-Java Lambda function
if not is_java:
handler_file = get_handler_file_from_name(handler_name, runtime=runtime)
handler_function = get_handler_function_from_name(handler_name, runtime=runtime)
main_file = '%s/%s' % (lambda_cwd, handler_file)
if CHECK_HANDLER_ON_CREATION and not os.path.exists(main_file):
# Raise an error if (1) this is not a local mount lambda, or (2) we're
# running Lambdas locally (not in Docker), or (3) we're using remote Docker.
# -> We do *not* want to raise an error if we're using local mount in non-remote Docker
if not is_local_mount or not use_docker() or config.LAMBDA_REMOTE_DOCKER:
file_list = run('cd "%s"; du -d 3 .' % lambda_cwd)
config_debug = ('Config for local mount, docker, remote: "%s", "%s", "%s"' %
(is_local_mount, use_docker(), config.LAMBDA_REMOTE_DOCKER))
LOG.debug('Lambda archive content:\n%s' % file_list)
raise ClientError(error_response(
'Unable to find handler script (%s) in Lambda archive. %s' % (main_file, config_debug),
400, error_type='ValidationError'))
if runtime.startswith('python') and not use_docker():
try:
# make sure the file is actually readable, then read contents
ensure_readable(main_file)
zip_file_content = load_file(main_file, mode='rb')
# extract handler
lambda_handler = exec_lambda_code(
zip_file_content,
handler_function=handler_function,
lambda_cwd=lambda_cwd,
lambda_env=lambda_environment)
except Exception as e:
raise ClientError('Unable to get handler function from lambda code.', e)
add_function_mapping(lambda_name, lambda_handler, lambda_cwd)
return {'FunctionName': lambda_name}
def do_list_functions():
funcs = []
this_region = aws_stack.get_region()
for f_arn, func in ARN_TO_LAMBDA.items():
if type(func) != LambdaFunction:
continue
# filter out functions of current region
func_region = f_arn.split(':')[3]
if func_region != this_region:
continue
func_name = f_arn.split(':function:')[-1]
arn = func_arn(func_name)
func_details = ARN_TO_LAMBDA.get(arn)
if not func_details:
# this can happen if we're accessing Lambdas from a different region (ARN mismatch)
continue
details = format_func_details(func_details)
details['Tags'] = func.tags
funcs.append(details)
return funcs
def format_func_details(func_details, version=None, always_add_version=False):
version = version or VERSION_LATEST
func_version = func_details.get_version(version)
result = {
'CodeSha256': func_version.get('CodeSha256'),
'Role': func_details.role,
'KMSKeyArn': func_details.kms_key_arn,
'Version': version,
'VpcConfig': func_details.vpc_config,
'FunctionArn': func_details.arn(),
'FunctionName': func_details.name(),
'CodeSize': func_version.get('CodeSize'),
'Handler': func_details.handler,
'Runtime': func_details.runtime,
'Timeout': func_details.timeout,
'Description': func_details.description,
'MemorySize': func_details.memory_size,
'LastModified': func_details.last_modified,
'TracingConfig': {'Mode': 'PassThrough'},
'RevisionId': func_version.get('RevisionId'),
'State': 'Active',
'LastUpdateStatus': 'Successful',
'PackageType': func_details.package_type
}
if func_details.dead_letter_config:
result['DeadLetterConfig'] = func_details.dead_letter_config
if func_details.envvars:
result['Environment'] = {
'Variables': func_details.envvars
}
if (always_add_version or version != VERSION_LATEST) and len(result['FunctionArn'].split(':')) <= 7:
result['FunctionArn'] += ':%s' % version
return result
def forward_to_fallback_url(func_arn, data):
""" If LAMBDA_FALLBACK_URL is configured, forward the invocation of this non-existing
Lambda to the configured URL. """
if not config.LAMBDA_FALLBACK_URL:
return None
lambda_name = aws_stack.lambda_function_name(func_arn)
if config.LAMBDA_FALLBACK_URL.startswith('dynamodb://'):
table_name = urlparse(config.LAMBDA_FALLBACK_URL.replace('dynamodb://', 'http://')).netloc
dynamodb = aws_stack.connect_to_service('dynamodb')
item = {
'id': {'S': short_uid()},
'timestamp': {'N': str(now_utc())},
'payload': {'S': str(data)},
'function_name': {'S': lambda_name}
}
aws_stack.create_dynamodb_table(table_name, partition_key='id')
dynamodb.put_item(TableName=table_name, Item=item)
return ''
if re.match(r'^https?://.+', config.LAMBDA_FALLBACK_URL):
headers = {'lambda-function-name': lambda_name}
response = safe_requests.post(config.LAMBDA_FALLBACK_URL, data, headers=headers)
return response.content
raise ClientError('Unexpected value for LAMBDA_FALLBACK_URL: %s' % config.LAMBDA_FALLBACK_URL)
def get_lambda_policy(function, qualifier=None):
iam_client = aws_stack.connect_to_service('iam')
policies = iam_client.list_policies(Scope='Local', MaxItems=500)['Policies']
docs = []
for p in policies:
# !TODO: Cache policy documents instead of running N+1 API calls here!
versions = iam_client.list_policy_versions(PolicyArn=p['Arn'])['Versions']
default_version = [v for v in versions if v.get('IsDefaultVersion')]
versions = default_version or versions
doc = versions[0]['Document']
doc = doc if isinstance(doc, dict) else json.loads(doc)
if not isinstance(doc['Statement'], list):
doc['Statement'] = [doc['Statement']]
for stmt in doc['Statement']:
stmt['Principal'] = stmt.get('Principal') or {'AWS': TEST_AWS_ACCOUNT_ID}
doc['PolicyArn'] = p['Arn']
doc['Id'] = 'default'
docs.append(doc)
policy = [d for d in docs if d['Statement'][0]['Resource'] == func_qualifier(function, qualifier)]
return (policy or [None])[0]
def not_found_error(ref=None, msg=None):
if not msg:
msg = 'The resource you requested does not exist.'
if ref:
msg = '%s not found: %s' % ('Function' if ':function:' in ref else 'Resource', ref)
return error_response(msg, 404, error_type='ResourceNotFoundException')
# ------------
# API METHODS
# ------------
@app.before_request
def before_request():
# fix to enable chunked encoding, as this is used by some Lambda clients
transfer_encoding = request.headers.get('Transfer-Encoding', '').lower()
if transfer_encoding == 'chunked':
request.environ['wsgi.input_terminated'] = True
@app.route('%s/functions' % PATH_ROOT, methods=['POST'])
def create_function():
""" Create new function
---
operationId: 'createFunction'
parameters:
- name: 'request'
in: body
"""
arn = 'n/a'
try:
if len(request.data) > FUNCTION_MAX_SIZE:
return error_response('Request must be smaller than %s bytes for the CreateFunction operation' %
FUNCTION_MAX_SIZE, 413, error_type='RequestEntityTooLargeException')
data = json.loads(to_str(request.data))
lambda_name = data['FunctionName']
event_publisher.fire_event(event_publisher.EVENT_LAMBDA_CREATE_FUNC,
payload={'n': event_publisher.get_hash(lambda_name)})
arn = func_arn(lambda_name)
if arn in ARN_TO_LAMBDA:
return error_response('Function already exist: %s' %
lambda_name, 409, error_type='ResourceConflictException')
ARN_TO_LAMBDA[arn] = func_details = LambdaFunction(arn)
func_details.versions = {VERSION_LATEST: {'RevisionId': str(uuid.uuid4())}}
func_details.vpc_config = data.get('VpcConfig', {})
func_details.last_modified = isoformat_milliseconds(datetime.utcnow()) + '+0000'
func_details.description = data.get('Description', '')
func_details.handler = data['Handler']
func_details.runtime = data['Runtime']
func_details.envvars = data.get('Environment', {}).get('Variables', {})
func_details.tags = data.get('Tags', {})
func_details.timeout = data.get('Timeout', LAMBDA_DEFAULT_TIMEOUT)
func_details.role = data['Role']
func_details.kms_key_arn = data.get('KMSKeyArn')
func_details.memory_size = data.get('MemorySize')
func_details.code_signing_config_arn = data.get('CodeSigningConfigArn')
func_details.code = data['Code']
# TODO: support package type 'Image'
func_details.package_type = 'Zip'
func_details.set_dead_letter_config(data)
result = set_function_code(func_details.code, lambda_name)
if isinstance(result, Response):
del ARN_TO_LAMBDA[arn]
return result
# remove content from code attribute, if present
func_details.code.pop('ZipFile', None)
# prepare result
result.update(format_func_details(func_details))
if data.get('Publish'):
result['Version'] = publish_new_function_version(arn)['Version']
return jsonify(result or {})
except Exception as e:
ARN_TO_LAMBDA.pop(arn, None)
if isinstance(e, ClientError):
return e.get_response()
return error_response('Unknown error: %s %s' % (e, traceback.format_exc()))
@app.route('%s/functions/<function>' % PATH_ROOT, methods=['GET'])
def get_function(function):
""" Get details for a single function
---
operationId: 'getFunction'
parameters:
- name: 'request'
in: body
- name: 'function'
in: path
"""
funcs = do_list_functions()
for func in funcs:
if func['FunctionName'] == function:
result = {
'Configuration': func,
'Code': {
'Location': '%s/code' % request.url
},
'Tags': func['Tags']
}
lambda_details = ARN_TO_LAMBDA.get(func['FunctionArn'])
if lambda_details.concurrency is not None:
result['Concurrency'] = lambda_details.concurrency
return jsonify(result)
return not_found_error(func_arn(function))
@app.route('%s/functions/' % PATH_ROOT, methods=['GET'])
def list_functions():
""" List functions
---
operationId: 'listFunctions'
parameters:
- name: 'request'
in: body
"""
funcs = do_list_functions()
result = {
'Functions': funcs
}
return jsonify(result)
@app.route('%s/functions/<function>' % PATH_ROOT, methods=['DELETE'])
def delete_function(function):
""" Delete an existing function
---
operationId: 'deleteFunction'
parameters:
- name: 'request'
in: body
"""
arn = func_arn(function)
# Stop/remove any containers that this arn uses.
LAMBDA_EXECUTOR.cleanup(arn)
try:
ARN_TO_LAMBDA.pop(arn)
except KeyError:
return not_found_error(func_arn(function))
event_publisher.fire_event(event_publisher.EVENT_LAMBDA_DELETE_FUNC,
payload={'n': event_publisher.get_hash(function)})
i = 0
while i < len(EVENT_SOURCE_MAPPINGS):
mapping = EVENT_SOURCE_MAPPINGS[i]
if mapping['FunctionArn'] == arn:
del EVENT_SOURCE_MAPPINGS[i]
i -= 1
i += 1
result = {}
return jsonify(result)
@app.route('%s/functions/<function>/code' % PATH_ROOT, methods=['PUT'])
def update_function_code(function):
""" Update the code of an existing function
---
operationId: 'updateFunctionCode'
parameters:
- name: 'request'
in: body
"""
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return error_response('Function not found: %s' %
arn, 400, error_type='ResourceNotFoundException')
data = json.loads(to_str(request.data))
result = set_function_code(data, function)
func_details = ARN_TO_LAMBDA.get(arn)
result.update(format_func_details(func_details))
if data.get('Publish'):
result['Version'] = publish_new_function_version(arn)['Version']
if isinstance(result, Response):
return result
return jsonify(result or {})
@app.route('%s/functions/<function>/code' % PATH_ROOT, methods=['GET'])
def get_function_code(function):
""" Get the code of an existing function
---
operationId: 'getFunctionCode'
parameters:
"""
arn = func_arn(function)
lambda_cwd = ARN_TO_LAMBDA[arn].cwd
tmp_file = '%s/%s' % (lambda_cwd, LAMBDA_ZIP_FILE_NAME)
return Response(load_file(tmp_file, mode='rb'),
mimetype='application/zip',
headers={'Content-Disposition': 'attachment; filename=lambda_archive.zip'})
@app.route('%s/functions/<function>/configuration' % PATH_ROOT, methods=['GET'])
def get_function_configuration(function):
""" Get the configuration of an existing function
---
operationId: 'getFunctionConfiguration'
parameters:
"""
arn = func_arn(function)
lambda_details = ARN_TO_LAMBDA.get(arn)
if not lambda_details:
return not_found_error(arn)
result = format_func_details(lambda_details)
return jsonify(result)
@app.route('%s/functions/<function>/configuration' % PATH_ROOT, methods=['PUT'])
def update_function_configuration(function):
""" Update the configuration of an existing function
---
operationId: 'updateFunctionConfiguration'
parameters:
- name: 'request'
in: body
"""
data = json.loads(to_str(request.data))
arn = func_arn(function)
# Stop/remove any containers that this arn uses.
LAMBDA_EXECUTOR.cleanup(arn)
lambda_details = ARN_TO_LAMBDA.get(arn)
if not lambda_details:
return error_response('Unable to find Lambda function ARN "%s"' % arn,
404, error_type='ResourceNotFoundException')
if data.get('Handler'):
lambda_details.handler = data['Handler']
if data.get('Runtime'):
lambda_details.runtime = data['Runtime']
lambda_details.set_dead_letter_config(data)
env_vars = data.get('Environment', {}).get('Variables')
if env_vars is not None:
lambda_details.envvars = env_vars
if data.get('Timeout'):
lambda_details.timeout = data['Timeout']
if data.get('Role'):
lambda_details.role = data['Role']
if data.get('MemorySize'):
lambda_details.memory_size = data['MemorySize']
if data.get('Description'):
lambda_details.description = data['Description']
if data.get('VpcConfig'):
lambda_details.vpc_config = data['VpcConfig']
if data.get('KMSKeyArn'):
lambda_details.kms_key_arn = data['KMSKeyArn']
return jsonify(data)
def generate_policy_statement(sid, action, arn, sourcearn, principal):
statement = {
'Sid': sid,
'Effect': 'Allow',
'Action': action,
'Resource': arn,
}
# Adds SourceArn only if SourceArn is present
if sourcearn:
condition = {
'ArnLike': {
'AWS:SourceArn': sourcearn
}
}
statement['Condition'] = condition
# Adds Principal only if Principal is present
if principal:
principal = {
'Service': principal
}
statement['Principal'] = principal
return statement
def generate_policy(sid, action, arn, sourcearn, principal):
new_statement = generate_policy_statement(sid, action, arn, sourcearn, principal)
policy = {
'Version': IAM_POLICY_VERSION,
'Id': 'LambdaFuncAccess-%s' % sid,
'Statement': [new_statement]
}
return policy
@app.route('%s/functions/<function>/policy' % PATH_ROOT, methods=['POST'])
def add_permission(function):
data = json.loads(to_str(request.data))
iam_client = aws_stack.connect_to_service('iam')
sid = data.get('StatementId')
action = data.get('Action')
principal = data.get('Principal')
sourcearn = data.get('SourceArn')
qualifier = request.args.get('Qualifier')
arn = func_arn(function)
previous_policy = get_lambda_policy(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(func_arn(function))
if not re.match(r'lambda:[*]|lambda:[a-zA-Z]+|[*]', action):
return error_response('1 validation error detected: Value "%s" at "action" failed to satisfy '
'constraint: Member must satisfy regular expression pattern: '
'(lambda:[*]|lambda:[a-zA-Z]+|[*])' % action,
400, error_type='ValidationException')
q_arn = func_qualifier(function, qualifier)
new_policy = generate_policy(sid, action, q_arn, sourcearn, principal)
if previous_policy:
statment_with_sid = next((statement for statement in previous_policy['Statement'] if statement['Sid'] == sid),
None)
if statment_with_sid:
return error_response('The statement id (%s) provided already exists. Please provide a new statement id,'
' or remove the existing statement.' % sid, 400, error_type='ResourceConflictException')
new_policy['Statement'].extend(previous_policy['Statement'])
iam_client.delete_policy(PolicyArn=previous_policy['PolicyArn'])
iam_client.create_policy(PolicyName=POLICY_NAME_PATTERN % function,
PolicyDocument=json.dumps(new_policy),
Description='Policy for Lambda function "%s"' % function)
result = {'Statement': json.dumps(new_policy['Statement'][0])}
return jsonify(result)
@app.route('%s/functions/<function>/policy/<statement>' % PATH_ROOT, methods=['DELETE'])
def remove_permission(function, statement):
qualifier = request.args.get('Qualifier')
iam_client = aws_stack.connect_to_service('iam')
policy = get_lambda_policy(function)
if not policy:
return error_response('Unable to find policy for Lambda function "%s"' % function,
404, error_type='ResourceNotFoundException')
iam_client.delete_policy(PolicyArn=policy['PolicyArn'])
result = {
'FunctionName': function,
'Qualifier': qualifier,
'StatementId': policy['Statement'][0]['Sid'],
}
return jsonify(result)
@app.route('%s/functions/<function>/policy' % PATH_ROOT, methods=['GET'])
def get_policy(function):
qualifier = request.args.get('Qualifier')
policy = get_lambda_policy(function, qualifier)
if not policy:
return error_response('The resource you requested does not exist.',
404, error_type='ResourceNotFoundException')
return jsonify({'Policy': json.dumps(policy), 'RevisionId': 'test1234'})
@app.route('%s/functions/<function>/invocations' % PATH_ROOT, methods=['POST'])
def invoke_function(function):
""" Invoke an existing function
---
operationId: 'invokeFunction'
parameters:
- name: 'request'
in: body
"""
# function here can either be an arn or a function name
arn = func_arn(function)
# arn can also contain a qualifier, extract it from there if so
m = re.match('(arn:aws:lambda:.*:.*:function:[a-zA-Z0-9-_]+)(:.*)?', arn)
if m and m.group(2):
qualifier = m.group(2)[1:]
arn = m.group(1)
else:
qualifier = request.args.get('Qualifier')
data = request.get_data()
if data:
data = to_str(data)
try:
data = json.loads(data)
except Exception:
try:
# try to read chunked content
data = json.loads(parse_chunked_data(data))
except Exception:
return error_response('The payload is not JSON: %s' % data, 415,
error_type='UnsupportedMediaTypeException')
# Default invocation type is RequestResponse
invocation_type = request.environ.get('HTTP_X_AMZ_INVOCATION_TYPE', 'RequestResponse')
def _create_response(result, status_code=200, headers={}):
""" Create the final response for the given invocation result. """
details = {
'StatusCode': status_code,
'Payload': result,
'Headers': headers
}
if isinstance(result, Response):
details['Payload'] = to_str(result.data)
if result.status_code >= 400:
details['FunctionError'] = 'Unhandled'
elif isinstance(result, dict):
for key in ('StatusCode', 'Payload', 'FunctionError'):
if result.get(key):
details[key] = result[key]
# Try to parse parse payload as JSON
was_json = False
payload = details['Payload']
if payload and isinstance(payload, POSSIBLE_JSON_TYPES) and payload[0] in JSON_START_CHARS:
try:
details['Payload'] = json.loads(details['Payload'])
was_json = True
except Exception:
pass
# Set error headers
if details.get('FunctionError'):
details['Headers']['X-Amz-Function-Error'] = str(details['FunctionError'])
details['Headers']['X-Amz-Log-Result'] = base64.b64encode(to_bytes('')) # TODO add logs!
details['Headers']['X-Amz-Executed-Version'] = str(qualifier or VERSION_LATEST)
# Construct response object
response_obj = details['Payload']
if was_json or isinstance(response_obj, JSON_START_TYPES):
response_obj = json_safe(response_obj)
response_obj = jsonify(response_obj)
details['Headers']['Content-Type'] = 'application/json'
else:
response_obj = str(response_obj)
details['Headers']['Content-Type'] = 'text/plain'
return response_obj, details['StatusCode'], details['Headers']
# check if this lambda function exists
not_found = None
if arn not in ARN_TO_LAMBDA:
not_found = not_found_error(arn)
elif qualifier and not ARN_TO_LAMBDA.get(arn).qualifier_exists(qualifier):
not_found = not_found_error('{0}:{1}'.format(arn, qualifier))
if not_found:
forward_result = forward_to_fallback_url(arn, data)
if forward_result is not None:
return _create_response(forward_result)
return not_found
if invocation_type == 'RequestResponse':
context = {'client_context': request.headers.get('X-Amz-Client-Context')}
result = run_lambda(asynchronous=False, func_arn=arn, event=data, context=context, version=qualifier)
return _create_response(result)
elif invocation_type == 'Event':
run_lambda(asynchronous=True, func_arn=arn, event=data, context={}, version=qualifier)
return _create_response('', status_code=202)
elif invocation_type == 'DryRun':
# Assume the dry run always passes.
return _create_response('', status_code=204)
return error_response('Invocation type not one of: RequestResponse, Event or DryRun',
code=400, error_type='InvalidParameterValueException')
@app.route('%s/event-source-mappings/' % PATH_ROOT, methods=['GET'])
def list_EVENT_SOURCE_MAPPINGS():
""" List event source mappings
---
operationId: 'listEventSourceMappings'
"""
event_source_arn = request.args.get('EventSourceArn')
function_name = request.args.get('FunctionName')
mappings = EVENT_SOURCE_MAPPINGS
if event_source_arn:
mappings = [m for m in mappings if event_source_arn == m.get('EventSourceArn')]
if function_name:
function_arn = func_arn(function_name)
mappings = [m for m in mappings if function_arn == m.get('FunctionArn')]
response = {
'EventSourceMappings': mappings
}
return jsonify(response)
@app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['GET'])
def get_event_source_mapping(mapping_uuid):
""" Get an existing event source mapping
---
operationId: 'getEventSourceMapping'
parameters:
- name: 'request'
in: body
"""
mappings = EVENT_SOURCE_MAPPINGS
mappings = [m for m in mappings if mapping_uuid == m.get('UUID')]
if len(mappings) == 0:
return not_found_error()
return jsonify(mappings[0])
@app.route('%s/event-source-mappings/' % PATH_ROOT, methods=['POST'])
def create_event_source_mapping():
""" Create new event source mapping
---
operationId: 'createEventSourceMapping'
parameters:
- name: 'request'
in: body
"""
data = json.loads(to_str(request.data))
try:
mapping = add_event_source(
data['FunctionName'], data['EventSourceArn'], data.get('Enabled'), data.get('BatchSize')
)
return jsonify(mapping)
except ValueError as error:
error_type, message = error.args
return error_response(message, code=400, error_type=error_type)
@app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['PUT'])
def update_event_source_mapping(mapping_uuid):
""" Update an existing event source mapping
---
operationId: 'updateEventSourceMapping'
parameters:
- name: 'request'
in: body
"""
data = json.loads(request.data)
if not mapping_uuid:
return jsonify({})
function_name = data.get('FunctionName') or ''
enabled = data.get('Enabled', True)
batch_size = data.get('BatchSize')
try:
mapping = update_event_source(mapping_uuid, function_name, enabled, batch_size)
return jsonify(mapping)
except ValueError as error:
error_type, message = error.args
return error_response(message, code=400, error_type=error_type)
@app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['DELETE'])
def delete_event_source_mapping(mapping_uuid):
""" Delete an event source mapping
---
operationId: 'deleteEventSourceMapping'
"""
if not mapping_uuid:
return jsonify({})
mapping = delete_event_source(mapping_uuid)
return jsonify(mapping)
@app.route('%s/functions/<function>/versions' % PATH_ROOT, methods=['POST'])
def publish_version(function):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
return jsonify(publish_new_function_version(arn))
@app.route('%s/functions/<function>/versions' % PATH_ROOT, methods=['GET'])
def list_versions(function):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
return jsonify({'Versions': do_list_versions(arn)})
@app.route('%s/functions/<function>/aliases' % PATH_ROOT, methods=['POST'])
def create_alias(function):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
data = json.loads(request.data)
alias = data.get('Name')
if alias in ARN_TO_LAMBDA.get(arn).aliases:
return error_response('Alias already exists: %s' % arn + ':' + alias, 404,
error_type='ResourceConflictException')
version = data.get('FunctionVersion')
description = data.get('Description')
return jsonify(do_update_alias(arn, alias, version, description))
@app.route('%s/functions/<function>/aliases/<name>' % PATH_ROOT, methods=['PUT'])
def update_alias(function, name):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
if name not in ARN_TO_LAMBDA.get(arn).aliases:
return not_found_error(msg='Alias not found: %s:%s' % (arn, name))
current_alias = ARN_TO_LAMBDA.get(arn).aliases.get(name)
data = json.loads(request.data)
version = data.get('FunctionVersion') or current_alias.get('FunctionVersion')
description = data.get('Description') or current_alias.get('Description')
return jsonify(do_update_alias(arn, name, version, description))
@app.route('%s/functions/<function>/aliases/<name>' % PATH_ROOT, methods=['GET'])
def get_alias(function, name):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
if name not in ARN_TO_LAMBDA.get(arn).aliases:
return not_found_error(msg='Alias not found: %s:%s' % (arn, name))
return jsonify(ARN_TO_LAMBDA.get(arn).aliases.get(name))
@app.route('%s/functions/<function>/aliases' % PATH_ROOT, methods=['GET'])
def list_aliases(function):
arn = func_arn(function)
if arn not in ARN_TO_LAMBDA:
return not_found_error(arn)
return jsonify({'Aliases': sorted(ARN_TO_LAMBDA.get(arn).aliases.values(),
key=lambda x: x['Name'])})
@app.route('/<version>/functions/<function>/concurrency', methods=['GET', 'PUT', 'DELETE'])
def function_concurrency(version, function):
# the version for put_concurrency != PATH_ROOT, at the time of this
# writing it's: /2017-10-31 for this endpoint
# https://docs.aws.amazon.com/lambda/latest/dg/API_PutFunctionConcurrency.html
arn = func_arn(function)
lambda_details = ARN_TO_LAMBDA.get(arn)
if not lambda_details:
return not_found_error(arn)
if request.method == 'GET':
data = lambda_details.concurrency
if request.method == 'PUT':
data = json.loads(request.data)
lambda_details.concurrency = data
if request.method == 'DELETE':
lambda_details.concurrency = None
return Response('', status=204)
return jsonify(data)
@app.route('/<version>/tags/<arn>', methods=['GET'])
def list_tags(version, arn):
func_details = ARN_TO_LAMBDA.get(arn)
if not func_details:
return not_found_error(arn)
result = {'Tags': func_details.tags}
return jsonify(result)
@app.route('/<version>/tags/<arn>', methods=['POST'])
def tag_resource(version, arn):
data = json.loads(request.data)
tags = data.get('Tags', {})
if tags:
func_details = ARN_TO_LAMBDA.get(arn)
if not func_details:
return not_found_error(arn)
if func_details:
func_details.tags.update(tags)
return jsonify({})
@app.route('/<version>/tags/<arn>', methods=['DELETE'])
def untag_resource(version, arn):
tag_keys = request.args.getlist('tagKeys')
func_details = ARN_TO_LAMBDA.get(arn)
if not func_details:
return not_found_error(arn)
for tag_key in tag_keys:
func_details.tags.pop(tag_key, None)
return jsonify({})
@app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['PUT', 'POST'])
def put_function_event_invoke_config(function):
# TODO: resouce validation required to check if resource exists
""" Add/Updates the configuration for asynchronous invocation for a function
---
operationId: PutFunctionEventInvokeConfig | UpdateFunctionEventInvokeConfig
parameters:
- name: 'function'
in: path
- name: 'qualifier'
in: path
- name: 'request'
in: body
"""
data = json.loads(to_str(request.data))
function_arn = func_arn(function)
lambda_obj = ARN_TO_LAMBDA[function_arn]
if request.method == 'PUT':
response = lambda_obj.clear_function_event_invoke_config()
response = lambda_obj.put_function_event_invoke_config(data)
return jsonify({
'LastModified': response.last_modified,
'FunctionArn': str(function_arn),
'MaximumRetryAttempts': response.max_retry_attempts,
'MaximumEventAgeInSeconds': response.max_event_age,
'DestinationConfig': {
'OnSuccess': {
'Destination': str(response.on_successful_invocation)
},
'OnFailure': {
'Destination': str(response.dead_letter_config)
}
}
})
@app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['GET'])
def get_function_event_invoke_config(function):
""" Retrieves the configuration for asynchronous invocation for a function
---
operationId: GetFunctionEventInvokeConfig
parameters:
- name: 'function'
in: path
- name: 'qualifier'
in: path
- name: 'request'
in: body
"""
try:
function_arn = func_arn(function)
lambda_obj = ARN_TO_LAMBDA[function_arn]
except Exception as e:
return error_response(str(e), 400)
response = lambda_obj.get_function_event_invoke_config()
return jsonify(response)
@app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['DELETE'])
def delete_function_event_invoke_config(function):
try:
function_arn = func_arn(function)
lambda_obj = ARN_TO_LAMBDA[function_arn]
except Exception as e:
return error_response(str(e), 400)
lambda_obj.clear_function_event_invoke_config()
return Response('', status=204)
@app.route('/2020-06-30/functions/<function>/code-signing-config', methods=['GET'])
def get_function_code_signing_config(function):
function_arn = func_arn(function)
if function_arn not in ARN_TO_LAMBDA:
msg = 'Function not found: %s' % (function_arn)
return error_response(msg, 404, error_type='ResourceNotFoundException')
lambda_obj = ARN_TO_LAMBDA[function_arn]
if not lambda_obj.code_signing_config_arn:
arn = None
function = None
else:
arn = lambda_obj.code_signing_config_arn
result = {
'CodeSigningConfigArn': arn,
'FunctionName': function
}
return Response(json.dumps(result), status=200)
@app.route('/2020-06-30/functions/<function>/code-signing-config', methods=['PUT'])
def put_function_code_signing_config(function):
data = json.loads(request.data)
arn = data.get('CodeSigningConfigArn')
if arn not in ARN_TO_CODE_SIGNING_CONFIG:
msg = """The code signing configuration cannot be found.
Check that the provided configuration is not deleted: %s.""" % (arn)
return error_response(msg, 404, error_type='CodeSigningConfigNotFoundException')
function_arn = func_arn(function)
if function_arn not in ARN_TO_LAMBDA:
msg = 'Function not found: %s' % (function_arn)
return error_response(msg, 404, error_type='ResourceNotFoundException')
lambda_obj = ARN_TO_LAMBDA[function_arn]
if data.get('CodeSigningConfigArn'):
lambda_obj.code_signing_config_arn = arn
result = {
'CodeSigningConfigArn': arn,
'FunctionName': function
}
return Response(json.dumps(result), status=200)
@app.route('/2020-06-30/functions/<function>/code-signing-config', methods=['DELETE'])
def delete_function_code_signing_config(function):
function_arn = func_arn(function)
if function_arn not in ARN_TO_LAMBDA:
msg = 'Function not found: %s' % (function_arn)
return error_response(msg, 404, error_type='ResourceNotFoundException')
lambda_obj = ARN_TO_LAMBDA[function_arn]
lambda_obj.code_signing_config_arn = None
return Response('', status=204)
@app.route('/2020-04-22/code-signing-configs/', methods=['POST'])
def create_code_signing_config():
data = json.loads(request.data)
signing_profile_version_arns = data.get('AllowedPublishers').get('SigningProfileVersionArns')
code_signing_id = 'csc-%s' % long_uid().replace('-', '')[0:17]
arn = aws_stack.code_signing_arn(code_signing_id)
ARN_TO_CODE_SIGNING_CONFIG[arn] = CodeSigningConfig(arn, code_signing_id, signing_profile_version_arns)
code_signing_obj = ARN_TO_CODE_SIGNING_CONFIG[arn]
if data.get('Description'):
code_signing_obj.description = data['Description']
if data.get('CodeSigningPolicies', {}).get('UntrustedArtifactOnDeployment'):
code_signing_obj.untrusted_artifact_on_deployment = data['CodeSigningPolicies']['UntrustedArtifactOnDeployment']
code_signing_obj.last_modified = isoformat_milliseconds(datetime.utcnow()) + '+0000'
result = {
'CodeSigningConfig': {
'AllowedPublishers': {
'SigningProfileVersionArns': code_signing_obj.signing_profile_version_arns
},
'CodeSigningConfigArn': code_signing_obj.arn,
'CodeSigningConfigId': code_signing_obj.id,
'CodeSigningPolicies': {
'UntrustedArtifactOnDeployment': code_signing_obj.untrusted_artifact_on_deployment
},
'Description': code_signing_obj.description,
'LastModified': code_signing_obj.last_modified
}
}
return Response(json.dumps(result), status=201)
@app.route('/2020-04-22/code-signing-configs/<arn>', methods=['GET'])
def get_code_signing_config(arn):
try:
code_signing_obj = ARN_TO_CODE_SIGNING_CONFIG[arn]
except KeyError:
msg = 'The Lambda code signing configuration %s can not be found.' % arn
return error_response(msg, 404, error_type='ResourceNotFoundException')
result = {
'CodeSigningConfig': {
'AllowedPublishers': {
'SigningProfileVersionArns': code_signing_obj.signing_profile_version_arns
},
'CodeSigningConfigArn': code_signing_obj.arn,
'CodeSigningConfigId': code_signing_obj.id,
'CodeSigningPolicies': {
'UntrustedArtifactOnDeployment': code_signing_obj.untrusted_artifact_on_deployment
},
'Description': code_signing_obj.description,
'LastModified': code_signing_obj.last_modified
}
}
return Response(json.dumps(result), status=200)
@app.route('/2020-04-22/code-signing-configs/<arn>', methods=['DELETE'])
def delete_code_signing_config(arn):
try:
ARN_TO_CODE_SIGNING_CONFIG.pop(arn)
except KeyError:
msg = 'The Lambda code signing configuration %s can not be found.' % (arn)
return error_response(msg, 404, error_type='ResourceNotFoundException')
return Response('', status=204)
@app.route('/2020-04-22/code-signing-configs/<arn>', methods=['PUT'])
def update_code_signing_config(arn):
try:
code_signing_obj = ARN_TO_CODE_SIGNING_CONFIG[arn]
except KeyError:
msg = 'The Lambda code signing configuration %s can not be found.' % (arn)
return error_response(msg, 404, error_type='ResourceNotFoundException')
data = json.loads(request.data)
is_updated = False
if data.get('Description'):
code_signing_obj.description = data['Description']
is_updated = True
if data.get('AllowedPublishers', {}).get('SigningProfileVersionArns'):
code_signing_obj.signing_profile_version_arns = data['AllowedPublishers']['SigningProfileVersionArns']
is_updated = True
if data.get('CodeSigningPolicies', {}).get('UntrustedArtifactOnDeployment'):
code_signing_obj.untrusted_artifact_on_deployment = data['CodeSigningPolicies']['UntrustedArtifactOnDeployment']
is_updated = True
if is_updated:
code_signing_obj.last_modified = isoformat_milliseconds(datetime.utcnow()) + '+0000'
result = {
'CodeSigningConfig': {
'AllowedPublishers': {
'SigningProfileVersionArns': code_signing_obj.signing_profile_version_arns
},
'CodeSigningConfigArn': code_signing_obj.arn,
'CodeSigningConfigId': code_signing_obj.id,
'CodeSigningPolicies': {
'UntrustedArtifactOnDeployment': code_signing_obj.untrusted_artifact_on_deployment
},
'Description': code_signing_obj.description,
'LastModified': code_signing_obj.last_modified
}
}
return Response(json.dumps(result), status=200)
def serve(port, quiet=True):
from localstack.services import generic_proxy # moved here to fix circular import errors
# initialize the Lambda executor
LAMBDA_EXECUTOR.startup()
generic_proxy.serve_flask_app(app=app, port=port, quiet=quiet)
|
// -*-Mode: C++;-*- // technically C99
// * BeginRiceCopyright *****************************************************
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//
// Linux perf mmaped-buffer reading interface
//
/******************************************************************************
* system includes
*****************************************************************************/
#include <assert.h>
#include <errno.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
/******************************************************************************
* linux specific includes
*****************************************************************************/
#include <linux/perf_event.h>
#include <linux/version.h>
/******************************************************************************
* hpcrun includes
*****************************************************************************/
#include <hpcrun/messages/messages.h>
/******************************************************************************
* local include
*****************************************************************************/
#include "perf_mmap.h"
#include "perf-util.h"
#include "perf_barrier.h"
/******************************************************************************
* Constants
*****************************************************************************/
#define MMAP_OFFSET_0 0
#define PERF_DATA_PAGE_EXP 1 // use 2^PERF_DATA_PAGE_EXP pages
#define PERF_DATA_PAGES (1 << PERF_DATA_PAGE_EXP)
#define PERF_MMAP_SIZE(pagesz) ((pagesz) * (PERF_DATA_PAGES + 1))
#define PERF_TAIL_MASK(pagesz) (((pagesz) * PERF_DATA_PAGES) - 1)
#define BUFFER_FRONT(current_perf_mmap) ((char *) current_perf_mmap + pagesize)
#define BUFFER_SIZE (tail_mask + 1)
#define BUFFER_OFFSET(tail) ((tail) & tail_mask)
/******************************************************************************
* forward declarations
*****************************************************************************/
/******************************************************************************
* local variables
*****************************************************************************/
static int pagesize = 0;
static size_t tail_mask = 0;
/******************************************************************************
* local methods
*****************************************************************************/
//----------------------------------------------------------
// read from perf_events mmap'ed buffer
// to avoid too many memory fences, the routine requires the current
// head and tail position. Based on this info, it estimates whether
// the reading has enough bytes to read or not.
//
// If there is no enough bytes, it returns -1
// otherwise it returns 0
//----------------------------------------------------------
static int
perf_read(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
void *buf,
size_t bytes_wanted
)
{
if (current_perf_mmap == NULL)
return -1;
u64 tail_position = *data_tail;
size_t bytes_available = data_head - tail_position;
if (bytes_wanted > bytes_available) return -1;
// compute offset of tail in the circular buffer
unsigned long tail = BUFFER_OFFSET(tail_position);
long bytes_at_right = BUFFER_SIZE - tail;
// bytes to copy to the right of tail
size_t right = bytes_at_right < bytes_wanted ? bytes_at_right : bytes_wanted;
// front of the circular data buffer
char *data = BUFFER_FRONT(current_perf_mmap);
// copy bytes from tail position
memcpy(buf, data + tail, right);
// if necessary, wrap and continue copy from left edge of buffer
if (bytes_wanted > right) {
size_t left = bytes_wanted - right;
memcpy(buf + right, data, left);
}
*data_tail = tail_position + bytes_wanted;
return 0;
}
static inline int
perf_read_header(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
pe_header_t *hdr
)
{
return perf_read(data_head, data_tail, current_perf_mmap, hdr, sizeof(pe_header_t));
}
static inline int
perf_read_u32(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
u32 *val
)
{
return perf_read(data_head, data_tail, current_perf_mmap, val, sizeof(u32));
}
static inline int
perf_read_u64(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
u64 *val
)
{
return perf_read(data_head, data_tail, current_perf_mmap, val, sizeof(u64));
}
//----------------------------------------------------------
// special mmap buffer reading for PERF_SAMPLE_READ
//----------------------------------------------------------
static void
handle_struct_read_format(u64 data_head, u64 *data_tail, pe_mmap_t *perf_mmap, int read_format)
{
u64 value, id, nr, time_enabled, time_running;
if (read_format & PERF_FORMAT_GROUP) {
perf_read_u64(data_head, data_tail, perf_mmap, &nr);
} else {
perf_read_u64(data_head, data_tail, perf_mmap, &value);
}
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
perf_read_u64(data_head, data_tail, perf_mmap, &time_enabled);
}
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
perf_read_u64(data_head, data_tail, perf_mmap, &time_running);
}
if (read_format & PERF_FORMAT_GROUP) {
int i;
for(i=0;i<nr;i++) {
perf_read_u64(data_head, data_tail, perf_mmap, &value);
if (read_format & PERF_FORMAT_ID) {
perf_read_u64(data_head, data_tail, perf_mmap, &id);
}
}
}
else {
if (read_format & PERF_FORMAT_ID) {
perf_read_u64(data_head, data_tail, perf_mmap, &id);
}
}
}
//----------------------------------------------------------
// processing of kernel callchains
//----------------------------------------------------------
static int
perf_sample_callchain(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap, perf_mmap_data_t* mmap_data)
{
mmap_data->nr = 0; // initialze the number of records to be 0
u64 num_records = 0;
// determine how many frames in the call chain
if (perf_read_u64(data_head, data_tail, current_perf_mmap, &num_records) == 0) {
if (num_records > 0) {
// warning: if the number of frames is bigger than the storage (MAX_CALLCHAIN_FRAMES)
// we have to truncate them. This is not a good practice, but so far it's the only
// simplest solution I can come up.
mmap_data->nr = (num_records < MAX_CALLCHAIN_FRAMES ? num_records : MAX_CALLCHAIN_FRAMES);
// read the IPs for the frames
if (perf_read(data_head, data_tail,
current_perf_mmap, mmap_data->ips, num_records * sizeof(u64)) != 0) {
// the data seems invalid
mmap_data->nr = 0;
TMSG(LINUX_PERF, "unable to read all %d frames", num_records);
}
}
} else {
TMSG(LINUX_PERF, "unable to read the number of frames" );
}
return mmap_data->nr;
}
/**
* parse mmapped buffer and copy the values into perf_mmap_data_t mmap_info.
* we assume mmap_info is already initialized.
* returns the number of read event attributes
*/
static int
parse_record_buffer(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
struct perf_event_attr *attr,
perf_mmap_data_t *mmap_info )
{
int data_read = 0;
int sample_type = attr->sample_type;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,12,0)
if (sample_type & PERF_SAMPLE_IDENTIFIER) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->sample_id);
data_read++;
}
#endif
if (sample_type & PERF_SAMPLE_IP) {
// to be used by datacentric event
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->ip);
data_read++;
}
if (sample_type & PERF_SAMPLE_TID) {
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->pid);
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->tid);
data_read++;
}
if (sample_type & PERF_SAMPLE_TIME) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->time);
data_read++;
}
if (sample_type & PERF_SAMPLE_ADDR) {
// to be used by datacentric event
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->addr);
data_read++;
}
if (sample_type & PERF_SAMPLE_ID) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->id);
data_read++;
}
if (sample_type & PERF_SAMPLE_STREAM_ID) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->stream_id);
data_read++;
}
if (sample_type & PERF_SAMPLE_CPU) {
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->cpu);
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->res);
data_read++;
}
if (sample_type & PERF_SAMPLE_PERIOD) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->period);
data_read++;
}
if (sample_type & PERF_SAMPLE_READ) {
// to be used by datacentric event
handle_struct_read_format(data_head, data_tail, current_perf_mmap,
attr->read_format);
data_read++;
}
if (sample_type & PERF_SAMPLE_CALLCHAIN) {
// add call chain from the kernel
perf_sample_callchain(data_head, data_tail, current_perf_mmap, mmap_info);
data_read++;
}
if (sample_type & PERF_SAMPLE_RAW) {
// not supported at the moment
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->size);
mmap_info->data = alloca( sizeof(char) * mmap_info->size );
perf_read( data_head, data_tail, current_perf_mmap, mmap_info->data, mmap_info->size) ;
data_read++;
}
if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
data_read++;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,7,0)
if (sample_type & PERF_SAMPLE_REGS_USER) {
data_read++;
}
if (sample_type & PERF_SAMPLE_STACK_USER) {
data_read++;
}
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
if (sample_type & PERF_SAMPLE_WEIGHT) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->weight);
data_read++;
}
if (sample_type & PERF_SAMPLE_DATA_SRC) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->data_src);
data_read++;
}
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,13,0)
// only available since kernel 3.19
if (sample_type & PERF_SAMPLE_TRANSACTION) {
data_read++;
}
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,19,0)
// only available since kernel 3.19
if (sample_type & PERF_SAMPLE_REGS_INTR) {
data_read++;
}
#endif
return data_read;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,3,0)
// special parser for smaple_id
// any event that used sample_id_all or perf_record_misc_switch
// needs to be parsed here
static int
parse_sample_id_buffer(u64 data_head, u64 *data_tail,
pe_mmap_t *current_perf_mmap,
struct perf_event_attr *attr,
perf_mmap_data_t *mmap_info )
{
int data_read = 0;
int sample_type = attr->sample_type;
if (sample_type & PERF_SAMPLE_TID) {
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->pid);
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->tid);
data_read++;
}
if (sample_type & PERF_SAMPLE_TIME) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->time);
data_read++;
}
if (sample_type & PERF_SAMPLE_TID) {
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->pid);
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->tid);
data_read++;
}
if (sample_type & PERF_SAMPLE_STREAM_ID) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->stream_id);
data_read++;
}
if (sample_type & PERF_SAMPLE_CPU) {
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->cpu);
perf_read_u32(data_head, data_tail, current_perf_mmap, &mmap_info->res);
data_read++;
}
if (sample_type & PERF_SAMPLE_IDENTIFIER) {
perf_read_u64(data_head, data_tail, current_perf_mmap, &mmap_info->sample_id);
data_read++;
}
return data_read;
}
#endif
//----------------------------------------------------------------------
// Public Interfaces
//----------------------------------------------------------------------
//----------------------------------------------------------
// reading mmap buffer from the kernel
// in/out: mmapped data of type perf_mmap_data_t.
// return true if there are more data to be read,
// false otherwise
//----------------------------------------------------------
int
read_perf_buffer(pe_mmap_t *current_perf_mmap,
struct perf_event_attr *attr,
perf_mmap_data_t *mmap_info)
{
pe_header_t hdr;
u64 data_tail = current_perf_mmap->data_tail;
u64 data_head = current_perf_mmap->data_head;
rmb(); // memory fence after reading the data head
int read_successfully = perf_read_header(data_head, &data_tail, current_perf_mmap, &hdr);
if (read_successfully != 0 || hdr.size <= 0) {
return 0;
}
mmap_info->header_type = hdr.type;
mmap_info->header_misc = hdr.misc;
if (hdr.type == PERF_RECORD_SAMPLE) {
parse_record_buffer(data_head, &data_tail, current_perf_mmap, attr, mmap_info);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,3,0)
} else if (hdr.type == PERF_RECORD_SWITCH) {
// only available since kernel 4.3
parse_sample_id_buffer(data_head, &data_tail, current_perf_mmap, attr, mmap_info);
TMSG(LINUX_PERF, "%d context switch %d, time: %u", attr->config, hdr.misc, mmap_info->time);
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(4,2,0)
} else if (hdr.type == PERF_RECORD_LOST_SAMPLES) {
u64 lost_samples;
perf_read_u64(current_perf_mmap, &lost_samples);
TMSG(LINUX_PERF, "[%d] lost samples %d",
current->fd, lost_samples);
skip_perf_data(current_perf_mmap, hdr.size-sizeof(lost_samples))
#endif
} else {
// not a PERF_RECORD_SAMPLE nor PERF_RECORD_SWITCH
// skip it
TMSG(LINUX_PERF, "[%d] skip header %d %d : %d bytes",
attr->config,
hdr.type, hdr.misc, hdr.size);
}
// update tail after consuming a record
rmb(); // memory fence before writing data_tail
current_perf_mmap->data_tail += hdr.size;
return (data_tail-current_perf_mmap->data_tail);
}
//----------------------------------------------------------
// allocate mmap for a given file descriptor
//----------------------------------------------------------
pe_mmap_t*
set_mmap(int perf_fd)
{
if (pagesize == 0) {
perf_mmap_init();
}
void *map_result =
mmap(NULL, PERF_MMAP_SIZE(pagesize), PROT_WRITE | PROT_READ,
MAP_SHARED, perf_fd, MMAP_OFFSET_0);
if (map_result == MAP_FAILED) {
EMSG("Linux perf mmap failed: %s", strerror(errno));
return NULL;
}
pe_mmap_t *mmap = (pe_mmap_t *) map_result;
memset(mmap, 0, sizeof(pe_mmap_t));
mmap->version = 0;
mmap->compat_version = 0;
mmap->data_head = 0;
mmap->data_tail = 0;
return mmap;
}
/***
* unmap buffer. need to call this at the end of the execution
*/
void
perf_unmmap(pe_mmap_t *mmap)
{
munmap(mmap, PERF_MMAP_SIZE(pagesize));
}
/**
* initialize perf_mmap.
* caller needs to call this in the beginning before calling any API.
*/
void
perf_mmap_init()
{
pagesize = sysconf(_SC_PAGESIZE);
tail_mask = PERF_TAIL_MASK(pagesize);
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" qsiprep wrapper setup script """
from setuptools import setup, find_packages
from os import path as op
import runpy
def main():
""" Install entry-point """
this_path = op.abspath(op.dirname(__file__))
info = runpy.run_path(op.join(this_path, 'qsiprep_docker.py'))
setup(
name=info['__packagename__'],
version=info['__version__'],
description=info['__description__'],
long_description=info['__longdesc__'],
author=info['__author__'],
author_email=info['__email__'],
maintainer=info['__maintainer__'],
maintainer_email=info['__email__'],
url=info['__url__'],
license=info['__license__'],
classifiers=info['CLASSIFIERS'],
# Dependencies handling
setup_requires=[],
install_requires=[],
tests_require=[],
extras_require={},
dependency_links=[],
package_data={},
py_modules=["qsiprep_docker", "qsiprep_singularity"],
entry_points={'console_scripts': ['qsiprep-docker=qsiprep_docker:main',
'qsiprep-singularity=qsiprep_singularity:main']},
packages=find_packages(),
zip_safe=False
)
if __name__ == '__main__':
main()
|
import pandas as pd
from mlopt.problem import Problem
from mlopt import settings as stg
from mlopt.learners import LEARNER_MAP, installed_learners
from mlopt.sampling import Sampler
from mlopt.strategy import encode_strategies
from mlopt.filter import Filter
from mlopt import error as e
from mlopt.utils import n_features, accuracy, suboptimality
from mlopt import utils as u
from mlopt.kkt import create_kkt_matrix, factorize_kkt_matrix
from mlopt.utils import pandas2array
from cvxpy import Minimize, Maximize
import numpy as np
import os
from glob import glob
import tempfile
import tarfile
import pickle as pkl
from joblib import Parallel, delayed
from tqdm.auto import tqdm
from time import time
class Optimizer(object):
"""
Machine Learning Optimizer class.
"""
def __init__(self,
cvxpy_problem,
name="problem",
log_level=None,
parallel=True,
tight_constraints=True,
**solver_options):
"""
Inizialize optimizer.
Parameters
----------
problem : cvxpy.Problem
Problem in CVXPY format.
name : str
Problem name.
solver_options : dict, optional
A dict of options for the internal solver.
"""
if log_level is not None:
stg.logger.setLevel(log_level)
self._problem = Problem(cvxpy_problem,
solver=stg.DEFAULT_SOLVER,
tight_constraints=tight_constraints,
**solver_options)
self._solver_cache = None
self.name = name
self._learner = None
self.encoding = None
self.X_train = None
self.y_train = None
@property
def n_strategies(self):
"""Number of strategies."""
if self.encoding is None:
e.value_error("Model has been trained yet to " +
"return the number of strategies.")
return len(self.encoding)
def variables(self):
"""Problem variables."""
return self._problem.variables()
@property
def parameters(self):
"""Problem parameters."""
return self._problem.parameters
@property
def n_parameters(self):
"""Number of parameters."""
return self._problem.n_parameters
def samples_present(self):
"""Check if samples have been generated."""
return (self.X_train is not None) and \
(self.y_train is not None) and \
(self.encoding is not None)
def sample(self, sampling_fn, parallel=False):
"""
Sample parameters.
"""
# Create sampler
self._sampler = Sampler(self._problem, sampling_fn)
# Sample parameters
self.X_train, self.y_train, self.obj_train, self.encoding = \
self._sampler.sample(parallel=parallel)
def save_training_data(self, file_name, delete_existing=False):
"""
Save training data to file.
Avoids the need to recompute data.
Parameters
----------
file_name : string
File name of the compressed optimizer.
delete_existing : bool, optional
Delete existing file with the same name?
Defaults to False.
"""
# Check if file already exists
if os.path.isfile(file_name):
if not delete_existing:
p = None
while p not in ['y', 'n', 'N', '']:
p = input("File %s already exists. " % file_name +
"Would you like to delete it? [y/N] ")
if p == 'y':
os.remove(file_name)
else:
return
else:
os.remove(file_name)
if not self.samples_present():
e.value_error("You need to get the strategies " +
"from the data first by training the model.")
# Save to file
with open(file_name, 'wb') \
as data:
data_dict = {'X_train': self.X_train,
'y_train': self.y_train,
'obj_train': self.obj_train,
'_problem': self._problem,
'encoding': self.encoding}
# if hasattr(self, '_solver_cache'):
# data_dict['_solver_cache'] = self._solver_cache
# Store strategy filter
if hasattr(self, '_filter'):
data_dict['_filter'] = self._filter
pkl.dump(data_dict, data)
def load_training_data(self, file_name):
"""
Load pickled training data from file name.
Parameters
----------
file_name : string
File name of the data.
"""
# Check if file exists
if not os.path.isfile(file_name):
e.value_error("File %s does not exist." % file_name)
# Load optimizer
with open(file_name, "rb") as f:
data_dict = pkl.load(f)
# Store data internally
self.X_train = data_dict['X_train']
self.y_train = data_dict['y_train']
self.obj_train = data_dict['obj_train']
self._problem = data_dict['_problem']
self.encoding = data_dict['encoding']
# Set n_train in learner
if self._learner is not None:
self._learner.n_train = len(self.y_train)
stg.logger.info("Loaded %d points with %d strategies" %
(len(self.y_train), len(self.encoding)))
if ('_solver_cache' in data_dict):
self._solver_cache = data_dict['_solver_cache']
# Full strategies backup after filtering
if ('_filter' in data_dict):
self._filter = data_dict['_filter']
# Compute Good turing estimates
self._sampler = Sampler(self._problem, n_samples=len(self.X_train))
self._sampler.compute_good_turing(self.y_train)
def get_samples(self, X=None, sampling_fn=None,
parallel=True,
filter_strategies=stg.FILTER_STRATEGIES):
"""Get samples either from data or from sampling function"""
# Assert we have data to train or already trained
if X is None and sampling_fn is None and not self.samples_present():
e.value_error("Not enough arguments to train the model")
if X is not None and sampling_fn is not None:
e.value_error("You can pass only one value between X "
"and sampling_fn")
# Check if data is passed, otherwise train
# if (X is not None) and not self.samples_present():
if X is not None:
stg.logger.info("Use new data")
self.X_train = X
self.y_train = None
self.encoding = None
# Encode training strategies by solving
# the problem for all the points
results = self._problem.solve_parametric(X,
parallel=parallel,
message="Compute " +
"tight constraints " +
"for training set")
stg.logger.info("Checking for infeasible points")
not_feasible_points = {i: x for i, x in tqdm(enumerate(results))
if np.isnan(x['x']).any()}
if not_feasible_points:
e.value_error("Infeasible points found. Number of infeasible "
"points %d" % len(not_feasible_points))
stg.logger.info("No infeasible point found.")
self.obj_train = [r['cost'] for r in results]
train_strategies = [r['strategy'] for r in results]
# Check if the problems are solvable
# for r in results:
# assert r['status'] in cps.SOLUTION_PRESENT, \
# "The training points must be feasible"
# Encode strategies
self.y_train, self.encoding = \
encode_strategies(train_strategies)
# Compute Good turing estimates
self._sampler = Sampler(self._problem, n_samples=len(self.X_train))
self._sampler.compute_good_turing(self.y_train)
# Condense strategies
if filter_strategies:
self.filter_strategies(parallel=parallel)
elif sampling_fn is not None and not self.samples_present():
stg.logger.info("Use iterative sampling")
# Create X_train, y_train and encoding from
# sampling function
self.sample(sampling_fn, parallel=parallel)
# Condense strategies
if filter_strategies:
self.filter_strategies(parallel=parallel)
# Add factorization faching if
# 1. Problem is MIQP
# 2. Parameters do not enter in matrices
if self._problem.is_qp() and \
(self._solver_cache is None) and \
not self._problem.parameters_in_matrices:
self.cache_factors()
def filter_strategies(self, parallel=True, **filter_options):
# Store full non filtered strategies
self.encoding_full = self.encoding
self.y_train_full = self.y_train
# Define strategies filter (not run it yet)
self._filter = Filter(X_train=self.X_train,
y_train=self.y_train,
obj_train=self.obj_train,
encoding=self.encoding,
problem=self._problem)
self.y_train, self.encoding = \
self._filter.filter(parallel=parallel, **filter_options)
def train(self, X=None,
sampling_fn=None,
parallel=True,
learner=stg.DEFAULT_LEARNER,
filter_strategies=stg.FILTER_STRATEGIES,
**learner_options):
"""
Train optimizer using parameter X.
This function needs one argument between data points X
or sampling function sampling_fn. It will raise an error
otherwise because there is no way to sample data.
Parameters
----------
X : pandas dataframe or numpy array, optional
Data samples. Each row is a new sample points.
sampling_fn : function, optional
Function to sample data taking one argument being
the number of data points to be sampled and returning
a structure of the same type as X.
parallel : bool
Perform training in parallel.
learner : str
Learner to use. Learners are defined in :mod:`mlopt.settings`
learner_options : dict, optional
A dict of options for the learner.
"""
# Get training samples
self.get_samples(X, sampling_fn,
parallel=parallel,
filter_strategies=filter_strategies)
# Define learner
if learner not in installed_learners():
e.value_error("Learner specified not installed. "
"Available learners are: %s" % installed_learners())
self._learner = LEARNER_MAP[learner](n_input=n_features(self.X_train),
n_classes=len(self.encoding),
**learner_options)
# Train learner
self._learner.train(pandas2array(self.X_train),
self.y_train)
def cache_factors(self):
"""Cache linear system solver factorizations"""
self._solver_cache = []
stg.logger.info("Caching KKT solver factors for each strategy ")
for strategy_idx in tqdm(range(self.n_strategies)):
# Get a parameter giving that strategy
strategy = self.encoding[strategy_idx]
idx_param = np.where(self.y_train == strategy_idx)[0]
theta = self.X_train.iloc[idx_param[0]]
# Populate
self._problem.populate(theta)
# Get problem data
data, inverse_data, solving_chain = \
self._problem._get_problem_data()
# Apply strategy
strategy.apply(data, inverse_data[-1])
# Old
# self._problem.populate(theta)
#
# self._problem._relax_disc_var()
#
# reduced_problem = \
# self._problem._construct_reduced_problem(strategy)
#
# data, full_chain, inv_data = \
# reduced_problem.get_problem_data(solver=KKT)
# Get KKT matrix
KKT_mat = create_kkt_matrix(data)
solve_kkt = factorize_kkt_matrix(KKT_mat)
cache = {}
cache['factors'] = solve_kkt
# cache['inverse_data'] = inverse_data
# cache['chain'] = solving_chain
self._solver_cache += [cache]
def choose_best(self, problem_data, labels, parallel=False,
batch_size=stg.JOBLIB_BATCH_SIZE, use_cache=True):
"""
Choose best strategy between provided ones
Parameters
----------
labels : list
Strategy labels to compare.
parallel : bool, optional
Perform `n_best` strategies evaluation in parallel.
True by default.
use_cache : bool, optional
Use solver cache if available. True by default.
Returns
-------
dict
Results as a dictionary.
"""
n_best = self._learner.options['n_best']
# For each n_best classes get x, y, time and store the best one
x = []
time = []
infeas = []
cost = []
strategies = [self.encoding[label] for label in labels]
# Cache is a list of solver caches to pass
cache = [None] * n_best
if self._solver_cache and use_cache:
cache = [self._solver_cache[label] for label in labels]
n_jobs = u.get_n_processes(n_best) if parallel else 1
results = Parallel(n_jobs=n_jobs, batch_size=batch_size)(
delayed(self._problem.solve)(problem_data,
strategy=strategies[j],
cache=cache[j])
for j in range(n_best))
x = [r["x"] for r in results]
time = [r["time"] for r in results]
infeas = [r["infeasibility"] for r in results]
cost = [r["cost"] for r in results]
# Pick best class between k ones
infeas = np.array(infeas)
cost = np.array(cost)
idx_filter = np.where(infeas <= stg.INFEAS_TOL)[0]
if len(idx_filter) > 0:
# Case 1: Feasible points
# -> Get solution with best cost
# between feasible ones
if self._problem.sense() == Minimize:
idx_pick = idx_filter[np.argmin(cost[idx_filter])]
elif self._problem.sense() == Maximize:
idx_pick = idx_filter[np.argmax(cost[idx_filter])]
else:
e.value_error('Objective type not understood')
else:
# Case 2: No feasible points
# -> Get solution with minimum infeasibility
idx_pick = np.argmin(infeas)
# Store values we are interested in
result = {}
result['x'] = x[idx_pick]
result['time'] = np.sum(time)
result['strategy'] = strategies[idx_pick]
result['cost'] = cost[idx_pick]
result['infeasibility'] = infeas[idx_pick]
return result
def solve(self, X,
message="Predict optimal solution",
use_cache=True,
verbose=False,
):
"""
Predict optimal solution given the parameters X.
Parameters
----------
X : pandas DataFrame or Series
Data points.
use_cache : bool, optional
Use solver cache? Defaults to True.
Returns
-------
list
List of result dictionaries.
"""
if isinstance(X, pd.Series):
X = pd.DataFrame(X).transpose()
n_points = len(X)
if use_cache and not self._solver_cache:
e.warning("Solver cache requested but the cache has "
"not been computed for this problem. "
"Possibly parameters in proble matrices.")
# Change verbose setting
if verbose:
self._problem.verbose = True
# Define array of results to return
results = []
# Predict best n_best classes for all the points
X_pred = pandas2array(X)
t_start = time()
classes = self._learner.predict(X_pred)
t_predict = (time() - t_start) / n_points # Average predict time
if n_points > 1:
stg.logger.info(message)
ran = tqdm(range(n_points))
else:
# Do not print anything if just one point
ran = range(n_points)
for i in ran:
# Populate problem with i-th data point
self._problem.populate(X.iloc[i])
problem_data = self._problem._get_problem_data()
results.append(self.choose_best(problem_data,
classes[i, :],
use_cache=use_cache))
# Append predict time
for r in results:
r['pred_time'] = t_predict
r['solve_time'] = r['time']
r['time'] = r['pred_time'] + r['solve_time']
if len(results) == 1:
results = results[0]
return results
def save(self, file_name, delete_existing=False):
"""
Save optimizer to a specific tar.gz file.
Parameters
----------
file_name : string
File name of the compressed optimizer.
delete_existing : bool, optional
Delete existing file with the same name?
Defaults to False.
"""
if self._learner is None:
e.value_error("You cannot save the optimizer without " +
"training it before.")
# Add .tar.gz if the file has no extension
if not file_name.endswith('.tar.gz'):
file_name += ".tar.gz"
# Check if file already exists
if os.path.isfile(file_name):
if not delete_existing:
p = None
while p not in ['y', 'n', 'N', '']:
p = input("File %s already exists. " % file_name +
"Would you like to delete it? [y/N] ")
if p == 'y':
os.remove(file_name)
else:
return
else:
os.remove(file_name)
# Create temporary directory to create the archive
# and store relevant files
with tempfile.TemporaryDirectory() as tmpdir:
# Save learner
self._learner.save(os.path.join(tmpdir, "learner"))
# Save optimizer
with open(os.path.join(tmpdir, "optimizer.pkl"), 'wb') \
as optimizer:
file_dict = {'_problem': self._problem,
# '_solver_cache': self._solver_cache, # Cannot pickle
'learner_name': self._learner.name,
'learner_options': self._learner.options,
'learner_best_params': self._learner.best_params,
'encoding': self.encoding
}
pkl.dump(file_dict, optimizer)
# Create archive with the files
tar = tarfile.open(file_name, "w:gz")
for f in glob(os.path.join(tmpdir, "*")):
tar.add(f, os.path.basename(f))
tar.close()
@classmethod
def from_file(cls, file_name):
"""
Create optimizer from a specific compressed tar.gz file.
Parameters
----------
file_name : string
File name of the exported optimizer.
"""
# Add .tar.gz if the file has no extension
if not file_name.endswith('.tar.gz'):
file_name += ".tar.gz"
# Check if file exists
if not os.path.isfile(file_name):
e.value_error("File %s does not exist." % file_name)
# Extract file to temporary directory and read it
with tempfile.TemporaryDirectory() as tmpdir:
with tarfile.open(file_name) as tar:
tar.extractall(path=tmpdir)
# Load optimizer
optimizer_file_name = os.path.join(tmpdir, "optimizer.pkl")
if not optimizer_file_name:
e.value_error("Optimizer pkl file does not exist.")
with open(optimizer_file_name, "rb") as f:
optimizer_dict = pkl.load(f)
name = optimizer_dict.get('name', 'problem')
# Create optimizer using loaded dict
problem = optimizer_dict['_problem'].cvxpy_problem
optimizer = cls(problem, name=name)
# Assign strategies encoding
optimizer.encoding = optimizer_dict['encoding']
optimizer._sampler = optimizer_dict.get('_sampler', None)
# Load learner
learner_name = optimizer_dict['learner_name']
learner_options = optimizer_dict['learner_options']
learner_best_params = optimizer_dict['learner_best_params']
optimizer._learner = \
LEARNER_MAP[learner_name](n_input=optimizer.n_parameters,
n_classes=len(optimizer.encoding),
**learner_options)
optimizer._learner.best_params = learner_best_params
optimizer._learner.load(os.path.join(tmpdir, "learner"))
return optimizer
def performance(self, theta,
results_test=None,
results_heuristic=None,
parallel=False,
use_cache=True):
"""
Evaluate optimizer performance on data theta by comparing the
solution to the optimal one.
Parameters
----------
theta : DataFrame
Data to predict.
parallel : bool, optional
Solve problems in parallel? Defaults to True.
Returns
-------
dict
Results summarty.
dict
Detailed results summary.
"""
stg.logger.info("Performance evaluation")
if results_test is None:
# Get strategy for each point
results_test = self._problem.solve_parametric(
theta, parallel=parallel, message="Compute " +
"tight constraints " +
"for test set")
if results_heuristic is None:
self._problem.solver_options['MIPGap'] = 0.1 # 10% MIP Gap
# Get strategy for each point
results_heuristic = self._problem.solve_parametric(
theta, parallel=parallel, message="Compute " +
"tight constraints " +
"with heuristic MIP Gap 10 %%" +
"for test set")
self._problem.solver_options.pop('MIPGap') # Remove MIP Gap option
time_test = [r['time'] for r in results_test]
cost_test = [r['cost'] for r in results_test]
time_heuristic = [r['time'] for r in results_heuristic]
cost_heuristic = [r['cost'] for r in results_heuristic]
# Get predicted strategy for each point
results_pred = self.solve(theta,
message="Predict tight constraints for " +
"test set",
use_cache=use_cache)
time_pred = [r['time'] for r in results_pred]
solve_time_pred = [r['solve_time'] for r in results_pred]
pred_time_pred = [r['pred_time'] for r in results_pred]
cost_pred = [r['cost'] for r in results_pred]
infeas = np.array([r['infeasibility'] for r in results_pred])
n_test = len(theta)
n_train = self._learner.n_train # Number of training samples
n_theta = n_features(theta) # Number of parameters
n_strategies = len(self.encoding) # Number of strategies
# Compute comparative statistics
time_comp = np.array([time_test[i] / time_pred[i]
for i in range(n_test)])
time_comp_heuristic = np.array([time_heuristic[i] / time_pred[i]
for i in range(n_test)])
subopt = np.array([suboptimality(cost_pred[i], cost_test[i],
self._problem.sense())
for i in range(n_test)])
subopt_real = subopt[np.where(infeas <= stg.INFEAS_TOL)[0]]
if any(subopt_real):
max_subopt = np.max(subopt_real)
avg_subopt = np.mean(subopt_real)
std_subopt = np.std(subopt_real)
else:
max_subopt = np.nan
avg_subopt = np.nan
std_subopt = np.nan
subopt_heuristic = np.array([suboptimality(cost_heuristic[i],
cost_test[i],
self._problem.sense())
for i in range(n_test)])
# accuracy
test_accuracy, idx_correct = accuracy(results_pred, results_test,
self._problem.sense())
# Create dataframes to return
df = pd.Series(
{
"problem": self.name,
"learner": self._learner.name,
"n_best": self._learner.options['n_best'],
"n_var": self._problem.n_var,
"n_constr": self._problem.n_constraints,
"n_test": n_test,
"n_train": n_train,
"n_theta": n_theta,
"good_turing": self._sampler.good_turing,
"good_turing_smooth": self._sampler.good_turing_smooth,
"n_correct": np.sum(idx_correct),
"n_strategies": n_strategies,
"accuracy": 100 * test_accuracy,
"n_infeas": np.sum(infeas >= stg.INFEAS_TOL),
"avg_infeas": np.mean(infeas),
"std_infeas": np.std(infeas),
"max_infeas": np.max(infeas),
"avg_subopt": avg_subopt,
"std_subopt": std_subopt,
"max_subopt": max_subopt,
"avg_subopt_heuristic": np.mean(subopt_heuristic),
"std_subopt_heuristic": np.std(subopt_heuristic),
"max_subopt_heuristic": np.max(subopt_heuristic),
"mean_solve_time_pred": np.mean(solve_time_pred),
"std_solve_time_pred": np.std(solve_time_pred),
"mean_pred_time_pred": np.mean(pred_time_pred),
"std_pred_time_pred": np.std(pred_time_pred),
"mean_time_pred": np.mean(time_pred),
"std_time_pred": np.std(time_pred),
"max_time_pred": np.max(time_pred),
"mean_time_full": np.mean(time_test),
"std_time_full": np.std(time_test),
"max_time_full": np.max(time_test),
"mean_time_heuristic": np.mean(time_heuristic),
"std_time_heuristic": np.std(time_heuristic),
"max_time_heuristic": np.max(time_heuristic),
}
)
df_detail = pd.DataFrame(
{
"problem": [self.name] * n_test,
"learner": [self._learner.name] * n_test,
"n_best": [self._learner.options['n_best']] * n_test,
"correct": idx_correct,
"infeas": infeas,
"subopt": subopt,
"solve_time_pred": solve_time_pred,
"pred_time_pred": pred_time_pred,
"time_pred": time_pred,
"time_full": time_test,
"time_heuristic": time_heuristic,
"time_improvement": time_comp,
"time_improvement_heuristic": time_comp_heuristic,
}
)
return df, df_detail
|
const path = require('path')
module.exports = {
"verbose": false,
"rootDir": path.resolve(__dirname)
}
|
import $ from './domq.js';
import {
$D,
TOUCH_START_EVENT,
TOUCH_MOVE_EVENT,
TOUCH_END_EVENT,
NS,
EVENT_NS,
PUBLIC_VARS
} from './constants';
const ELEMS_WITH_GRABBING_CURSOR = `html, body, .${NS}-modal, .${NS}-stage, .${NS}-button, .${NS}-resizable-handle`;
export default {
/**
* --------------------------------------------------------------------------
* 1. No movable
* 2. Vertical movable
* 3. Horizontal movable
* 4. Vertical & Horizontal movable
* --------------------------------------------------------------------------
*
* Image movable
* @param {Object} $stage - The stage element of domq
* @param {Object} $image - The image element of domq
*/
movable($stage, $image) {
let isDragging = false;
let startX = 0;
let startY = 0;
let left = 0;
let top = 0;
let widthDiff = 0;
let heightDiff = 0;
let δ = 0;
const dragStart = e => {
e = e || window.event;
e.preventDefault();
const imageWidth = $image.width();
const imageHeight = $image.height();
const stageWidth = $stage.width();
const stageHeight = $stage.height();
startX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.clientX;
startY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.clientY;
// δ is the difference between image width and height
δ = !this.isRotated ? 0 : (imageWidth - imageHeight) / 2;
// Width or height difference can be use to limit image right or top position
widthDiff = !this.isRotated ? imageWidth - stageWidth : imageHeight - stageWidth;
heightDiff = !this.isRotated ? imageHeight - stageHeight : imageWidth - stageHeight;
// Modal can be dragging if image is smaller to stage
isDragging = widthDiff > 0 || heightDiff > 0 ? true : false;
PUBLIC_VARS['isMoving'] = widthDiff > 0 || heightDiff > 0 ? true : false;
// Reclac the element position when mousedown
// Fix the issue of stage with a border
left = $image.position().left - δ;
top = $image.position().top + δ;
// Add grabbing cursor
if ($stage.hasClass('is-grab')) {
$(ELEMS_WITH_GRABBING_CURSOR).addClass('is-grabbing');
}
$D.on(TOUCH_MOVE_EVENT + EVENT_NS, dragMove).on(
TOUCH_END_EVENT + EVENT_NS,
dragEnd
);
};
const dragMove = e => {
e = e || window.event;
e.preventDefault();
if (isDragging) {
const endX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.clientX;
const endY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.clientY;
const relativeX = endX - startX;
const relativeY = endY - startY;
let newLeft = relativeX + left;
let newTop = relativeY + top;
// Vertical limit
if (heightDiff > 0) {
if (relativeY + top > δ) {
newTop = δ;
} else if (relativeY + top < -heightDiff + δ) {
newTop = -heightDiff + δ;
}
} else {
newTop = top;
}
// Horizontal limit
if (widthDiff > 0) {
if (relativeX + left > -δ) {
newLeft = -δ;
} else if (relativeX + left < -widthDiff - δ) {
newLeft = -widthDiff - δ;
}
} else {
newLeft = left;
}
$image.css({
left: newLeft,
top: newTop
});
// Update image initial data
$.extend(this.imageData, {
left: newLeft,
top: newTop
});
}
};
const dragEnd = () => {
$D.off(TOUCH_MOVE_EVENT + EVENT_NS, dragMove).off(
TOUCH_END_EVENT + EVENT_NS,
dragEnd
);
isDragging = false;
PUBLIC_VARS['isMoving'] = false;
// Remove grabbing cursor
$(ELEMS_WITH_GRABBING_CURSOR).removeClass('is-grabbing');
};
$stage.on(TOUCH_START_EVENT + EVENT_NS, dragStart);
}
};
|
#!/usr/bin/env python3
import itertools
import operator
import sys
rows = [line[:-1] for line in sys.stdin]
w = len(rows[0])
tracks = ''.join(rows)
cart_moves = {'>': +1, 'v': +w, '<': -1, '^': -w}
lcurve = {+1: +w, +w: +1, -1: -w, -w: -1} # \
rcurve = {+1: -w, +w: -1, -1: +w, -w: +1} # /
left = {+1: -w, +w: +1, -1: +w, -w: -1} # +
straight = {+1: +1, +w: +w, -1: -1, -w: -w} # + | -
right = {+1: +w, +w: -1, -1: -w, -w: +1} # +
class Cart:
def __init__(self, pos, move):
self.pos = pos
self.move = move
self.turn = itertools.cycle([left, straight, right])
carts = []
bypos = {}
for pos, sym in enumerate(tracks):
if sym in cart_moves:
cart = Cart(pos, cart_moves[sym])
carts.append(cart)
bypos[pos] = cart
crash = None
while crash is None:
carts.sort(key=operator.attrgetter('pos'))
for cart in carts:
track = tracks[cart.pos]
if track == '\\':
cart.move = lcurve[cart.move]
elif track == '/':
cart.move = rcurve[cart.move]
elif track == '+':
cart.move = next(cart.turn)[cart.move]
del bypos[cart.pos]
cart.pos += cart.move
if cart.pos in bypos:
# Collision!
crash = cart.pos
break
bypos[cart.pos] = cart
x = crash % w
y = crash // w
print(str(x) + ',' + str(y))
|
'use strict';
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage();
});
/*
* Function that is called when the document is ready.
*/
function initializePage() {
$(".likeBtn").click(likeClick);
$(".likeCtr").click(likeClick);
}
function likeClick(e) {
// prevent the page from reloading
e.preventDefault();
//google analytics
ga("send","event","like","click");
} |
import './App.css';
import React, { useRef, useEffect, useState } from 'react';
import mapboxgl from '!mapbox-gl'; // eslint-disable-line import/no-webpack-loader-syntax
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import * as turf from '@turf/turf';
import {
SimpleSelectModeBezierOverride,
DirectModeBezierOverride,
DrawBezierCurve,
rawDataToBezierGroup,
customStyles,
} from 'mapbox-gl-draw-bezier-curve-mode';
import {extendDrawBar} from './utils/extendDrawBar.js';
import {demoData} from './demoData.js';
import { feature } from '@turf/turf';
// Token for demo purpose only, please replace by your own
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94LWdsLWRyYXctYmV6aWVyLWN1cnZlLWRlbW8iLCJhIjoiY2t0OXJyd2szMWV5MjJwbjlyNGtsOXVpdiJ9.Hom5aMPuxvSJUaiUynqIVA';
function App() {
const mapContainer = useRef(null);
const map = useRef(null);
const [lng, setLng] = useState(2.2972);
const [lat, setLat] = useState(48.7742);
const [zoom, setZoom] = useState(19.92);
const [drawMode, setDrawMode] = useState('simple_select');
const [selectionType, setSelectionType] = useState('');
useEffect(() => {
if (map.current) return; // initialize map only once
////////////////////////////////////////////////
// Initialize Map & Draw
////////////////////////////////////////////////
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/satellite-v9',//mapbox://styles/mapbox/streets-v11',
center: [lng, lat],
zoom: zoom
});
var draw = new MapboxDraw({
displayControlsDefault: false,
userProperties: true,
modes: {
...MapboxDraw.modes,
simple_select: SimpleSelectModeBezierOverride,
direct_select: DirectModeBezierOverride,
draw_bezier_curve: DrawBezierCurve,
},
styles: customStyles
});
////////////////////////////////////////////////
// Add DrawBar
////////////////////////////////////////////////
// const drawLineString = {on: "click", action: () => {draw.changeMode("draw_line_string")}, classes: ["mapbox-gl-draw_line"], title:'Polygon tool'};
// const drawPolygon = {on: "click", action: () => {draw.changeMode("draw_polygon")}, classes: ["mapbox-gl-draw_polygon"], title:'LineString tool'};
const drawBezierBtn = {on: "click", action: () => {draw.changeMode("draw_bezier_curve")}, classes: ["bezier-curve-icon"], title:'Bezier tool'};
const drawPointBtn = {on: "click", action: () => {draw.changeMode("draw_point")}, classes: ["mapbox-gl-draw_point"], title:'Marker tool'};
const trashBtn = {on: "click", action: () => {draw.trash()}, classes: ["mapbox-gl-draw_trash"], title:'Delete'};
const combineBtn = {on: "click", action: () => {draw.combineFeatures()}, classes: ["mapbox-gl-draw_combine"], title:'Combine'};
const unCombineBtn = {on: "click", action: () => {draw.uncombineFeatures()}, classes: ["mapbox-gl-draw_uncombine"], title:'Uncombine'};
let drawBar = new extendDrawBar({
draw: draw,
buttons: [
// drawLineString,
// drawPolygon,
drawBezierBtn,
drawPointBtn,
trashBtn,
combineBtn,
unCombineBtn],
});
map.current.addControl(drawBar);
// Fix to allow deletion with Del Key when default trash icon is not shown. See https://github.com/mapbox/mapbox-gl-draw/issues/989
draw.options.controls.trash=true;
////////////////////////////////////////////////
// Map configuration & events
////////////////////////////////////////////////
// Disable Rotation
map.current.dragRotate.disable();
map.current.touchZoomRotate.disableRotation();
// Prevent context menu from appearing on right click
window.addEventListener('contextmenu', function (e) {
// do something here... eg : Show a context menu
// console.log("show Context Menu");
e.preventDefault();
}, false);
// Prevent firefox menu from appearing on Alt key up
window.addEventListener('keyup', function (e) {
if(e.key === "Alt")
{
e.preventDefault();
}
}, false);
map.current.on('move', () => {
setLng(map.current.getCenter().lng.toFixed(4));
setLat(map.current.getCenter().lat.toFixed(4));
setZoom(map.current.getZoom().toFixed(2));
});
map.current.on('draw.modechange', (e) => {
// console.log("Mode Change : " + e.mode);
setDrawMode(e.mode);
});
map.current.on('draw.selectionchange', (e) => {
refreshSelectionType(e, setSelectionType);
});
map.current.on('draw.update', (e) => {
refreshSelectionType(e, setSelectionType);
});
///////////////////////////////////////////////////
// Import some example bezier curves from demoData
///////////////////////////////////////////////////
const bezierGroups = rawDataToBezierGroup(demoData);
let featureId;
bezierGroups.forEach(bezierGroup => {
// Draw feature
featureId = draw.add(bezierGroup.geojson)[0];
});
// Demo : Select last feature
draw.changeMode('simple_select', { featureIds: [featureId] })
});
return (
<div>
<div className="sidebar">
Longitude: {lng} | Latitude: {lat} | Zoom: {zoom}<br/>
Draw mode: {drawMode}<br/>
{(selectionType !== null && selectionType!=='') &&
<div>
Selection type : {selectionType}<br/>
</div>
}
</div>
<div className="infobar">
<b>Controls</b><br/><br/>
In draw mode : <br/>
- <b>Alt + Drag with left click</b> to create nodes with bezier handles.<br/>
- <b>Left click</b> to create nodes without handles.<br/><br/>
In edit mode : <br/>
- <b>Drag with Left click</b> on a handle to move it.<br/>
- <b>Alt + Drag with left click</b> on a handle to break handle symetry.<br/><br/>
More details : <a href="https://github.com/Jeff-Numix/mapbox-gl-draw-bezier-curve-mode">See github repo</a><br/> <br/>
</div>
<div ref={mapContainer} className="map-container" />
</div>
);
}
export default App;
function refreshSelectionType(e, setSelectionType) {
const features = e.features;
if(features.length>0){
const feature1 = features[0];
const ftype = getMultiSelectionFeatureType(e.features);
if(ftype === "Mixed") {
setSelectionType(ftype);
}
else if(feature1.properties.bezierGroup){
const bezierGroup = feature1.properties.bezierGroup;// without functions
let typeString = (bezierGroup.bezierCurves.length>1 ? `${ftype}(${bezierGroup.bezierCurves.length})` : `${ftype}`);
typeString += " Length: " + getBezierLength(features);
setSelectionType(typeString);
}
else if(feature.geometry){
setSelectionType(feature.geometry.type);
}
}
else {
setSelectionType(null);
}
}
function getBezierLength(features){
let distKm=0
features.forEach(feature => {
if(feature.geometry){
distKm += turf.length(feature.geometry, 'kilometers');
}
});
if(distKm <0.001) return `${(distKm*100000).toLocaleString(undefined, { maximumFractionDigits: 2 })} cm`;
if(distKm <1) return `${(distKm*1000).toLocaleString(undefined, { maximumFractionDigits: 2 })} m`;
return `${(distKm).toLocaleString(undefined, { maximumFractionDigits: 2 })} km`;
}
function getFeatureType(feature){
if(feature.properties.bezierGroup){
const bezierGroup = feature.properties.bezierGroup;
if(bezierGroup.bezierCurves.length>1){
return "MultiBezierCurve";
}
else {
return "BezierCurve";
}
}
else {
return feature.geometry.type;
}
}
function getMultiSelectionFeatureType(features) {
if(features.length>0){
const feature1Type = getFeatureType(features[0]);
for (let i = 1; i < features.length; i++) {
const featureType = getFeatureType(features[i]);
if(feature1Type!==featureType){return "Mixed"};
}
return feature1Type;
}
else {
return "None";
}
} |
import base64
import calendar
import hashlib
import hmac
import time
from datetime import datetime
import requests
from .exceptions import (
KucoinAPIException, KucoinRequestException, MarketOrderException, LimitOrderException
)
from .utils import compact_json_dict, flat_uuid
class Client(object):
REST_API_URL = 'https://openapi-v2.kucoin.com'
SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com'
API_VERSION = 'v1'
API_VERSION2 = 'v2'
API_VERSION3 = 'v3'
SIDE_BUY = 'buy'
SIDE_SELL = 'sell'
ACCOUNT_MAIN = 'main'
ACCOUNT_TRADE = 'trade'
ORDER_LIMIT = 'limit'
ORDER_MARKET = 'market'
ORDER_LIMIT_STOP = 'limit_stop'
ORDER_MARKET_STOP = 'market_stop'
STOP_LOSS = 'loss'
STOP_ENTRY = 'entry'
STP_CANCEL_NEWEST = 'CN'
STP_CANCEL_OLDEST = 'CO'
STP_DECREASE_AND_CANCEL = 'DC'
STP_CANCEL_BOTH = 'CB'
TIMEINFORCE_GOOD_TILL_CANCELLED = 'GTC'
TIMEINFORCE_GOOD_TILL_TIME = 'GTT'
TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC'
TIMEINFORCE_FILL_OR_KILL = 'FOK'
def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_params=None):
"""Kucoin API Client constructor
https://docs.kucoin.com/
:param api_key: Api Token Id
:type api_key: string
:param api_secret: Api Secret
:type api_secret: string
:param passphrase: Api Passphrase used to create API
:type passphrase: string
:param sandbox: (optional) Use the sandbox endpoint or not (default False)
:type sandbox: bool
:param requests_params: (optional) Dictionary of requests params to use for all calls
:type requests_params: dict.
.. code:: python
client = Client(api_key, api_secret, api_passphrase)
"""
self.API_KEY = api_key
self.API_SECRET = api_secret
self.API_PASSPHRASE = passphrase
if sandbox:
self.API_URL = self.SANDBOX_API_URL
else:
self.API_URL = self.REST_API_URL
self._requests_params = requests_params
self.session = self._init_session()
def _init_session(self):
session = requests.session()
headers = {'Accept': 'application/json',
'User-Agent': 'python-kucoin',
'Content-Type': 'application/json',
'KC-API-KEY': self.API_KEY,
'KC-API-PASSPHRASE': self.API_PASSPHRASE}
session.headers.update(headers)
return session
@staticmethod
def _get_params_for_sig(data):
"""Convert params to ordered string for signature
:param data:
:return: ordered parameters like amount=10&price=1.1&type=BUY
"""
return '&'.join(["{}={}".format(key, data[key]) for key in data])
def _generate_signature(self, nonce, method, path, data):
"""Generate the call signature
:param path:
:param data:
:param nonce:
:return: signature string
"""
data_json = ""
endpoint = path
if method == "get":
if data:
query_string = self._get_params_for_sig(data)
endpoint = "{}?{}".format(path, query_string)
elif data:
data_json = compact_json_dict(data)
sig_str = ("{}{}{}{}".format(nonce, method.upper(), endpoint, data_json)).encode('utf-8')
m = hmac.new(self.API_SECRET.encode('utf-8'), sig_str, hashlib.sha256)
return base64.b64encode(m.digest())
def _create_path(self, path, api_version=None):
api_version = api_version or self.API_VERSION
return '/api/{}/{}'.format(api_version, path)
def _create_uri(self, path):
return '{}{}'.format(self.API_URL, path)
def _request(self, method, path, signed, api_version=None, **kwargs):
# set default requests timeout
kwargs['timeout'] = 10
# add our global requests params
if self._requests_params:
kwargs.update(self._requests_params)
kwargs['data'] = kwargs.get('data', {})
kwargs['headers'] = kwargs.get('headers', {})
full_path = self._create_path(path, api_version)
uri = self._create_uri(full_path)
if signed:
# generate signature
nonce = int(time.time() * 1000)
kwargs['headers']['KC-API-TIMESTAMP'] = str(nonce)
kwargs['headers']['KC-API-SIGN'] = self._generate_signature(nonce, method, full_path, kwargs['data'])
if kwargs['data'] and method == 'get':
kwargs['params'] = kwargs['data']
del kwargs['data']
if signed and method != 'get' and kwargs['data']:
kwargs['data'] = compact_json_dict(kwargs['data'])
response = getattr(self.session, method)(uri, **kwargs)
return self._handle_response(response)
@staticmethod
def _handle_response(response):
"""Internal helper for handling API responses from the Kucoin server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
if not str(response.status_code).startswith('2'):
raise KucoinAPIException(response)
try:
res = response.json()
if 'code' in res and res['code'] != "200000":
raise KucoinAPIException(response)
if 'success' in res and not res['success']:
raise KucoinAPIException(response)
# by default return full response
# if it's a normal response we have a data attribute, return that
if 'data' in res:
res = res['data']
return res
except ValueError:
raise KucoinRequestException('Invalid Response: %s' % response.text)
def _get(self, path, signed=False, api_version=None, **kwargs):
return self._request('get', path, signed, api_version, **kwargs)
def _post(self, path, signed=False, api_version=None, **kwargs):
return self._request('post', path, signed, api_version, **kwargs)
def _put(self, path, signed=False, api_version=None, **kwargs):
return self._request('put', path, signed, api_version, **kwargs)
def _delete(self, path, signed=False, api_version=None, **kwargs):
return self._request('delete', path, signed, api_version, **kwargs)
def get_timestamp(self):
"""Get the server timestamp
https://docs.kucoin.com/#time
:return: response timestamp in ms
"""
return self._get("timestamp")
def get_status(self):
"""Get the service status
https://docs.kucoin.com/#service-status
.. code:: python
currencies = client.get_status()
:returns: API Response
.. code-block:: python
{
"status": "open", //open, close, cancelonly
"msg": "upgrade match engine" //remark for operation
}
"""
return self._get("status")
# Currency Endpoints
def get_currencies(self):
"""List known currencies
https://docs.kucoin.com/#get-currencies
.. code:: python
currencies = client.get_currencies()
:returns: API Response
.. code-block:: python
[
{
"currency": "BTC",
"name": "BTC",
"fullName": "Bitcoin",
"precision": 8
},
{
"currency": "ETH",
"name": "ETH",
"fullName": "Ethereum",
"precision": 7
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('currencies', False)
def get_currency(self, currency):
"""Get single currency detail
https://docs.kucoin.com/#get-currency-detail
.. code:: python
# call with no coins
currency = client.get_currency('BTC')
:returns: API Response
.. code-block:: python
{
"currency": "BTC",
"name": "BTC",
"fullName": "Bitcoin",
"precision": 8,
"withdrawalMinSize": "0.002",
"withdrawalMinFee": "0.0005",
"isWithdrawEnabled": true,
"isDepositEnabled": true
}
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('currencies/{}'.format(currency), False)
# User Account Endpoints
def get_accounts(self, currency=None, account_type=None):
"""Get a list of accounts
https://docs.kucoin.com/#accounts
:param currency: optional Currency code
:type currency: string
:param account_type: optional Account type - main, trade, margin or pool
:type account_type: string
.. code:: python
accounts = client.get_accounts()
accounts = client.get_accounts('BTC')
accounts = client.get_accounts('BTC', 'trade)
:returns: API Response
.. code-block:: python
[
{
"id": "5bd6e9286d99522a52e458de",
"currency": "BTC",
"type": "main",
"balance": "237582.04299",
"available": "237582.032",
"holds": "0.01099"
},
{
"id": "5bd6e9216d99522a52e458d6",
"currency": "BTC",
"type": "trade",
"balance": "1234356",
"available": "1234356",
"holds": "0"
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if account_type:
data['type'] = account_type
return self._get('accounts', True, data=data)
def get_account(self, account_id):
"""Get an individual account
https://docs.kucoin.com/#get-an-account
:param account_id: ID for account - from list_accounts()
:type account_id: string
.. code:: python
account = client.get_account('5bd6e9216d99522a52e458d6')
:returns: API Response
.. code-block:: python
{
"currency": "KCS",
"balance": "1000000060.6299",
"available": "1000000060.6299",
"holds": "0"
}
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('accounts/{}'.format(account_id), True)
def create_account(self, account_type, currency):
"""Create an account
https://docs.kucoin.com/#create-an-account
:param account_type: Account type - main, trade, margin
:type account_type: string
:param currency: Currency code
:type currency: string
.. code:: python
account = client.create_account('trade', 'BTC')
:returns: API Response
.. code-block:: python
{
"id": "5bd6e9286d99522a52e458de"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'type': account_type,
'currency': currency
}
return self._post('accounts', True, data=data)
def get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, page=None,
limit=None):
"""Get list of account activity
https://docs.kucoin.com/#get-account-history
:param currency: (optional) currency name
:type currency: string
:param direction: (optional) Side: in - Receive, out - Send
:type direction: string
:param biz_type: (optional) Business type: DEPOSIT, WITHDRAW, TRANSFER, SUB_TRANSFER,TRADE_EXCHANGE, MARGIN_EXCHANGE, KUCOIN_BONUS.
:type biz_type: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Current page - default 1
:type page: int
:param limit: (optional) Number of results to return - default 50
:type limit: int
.. code:: python
history = client.get_account_activity('5bd6e9216d99522a52e458d6')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10)
:returns: API Response
.. code-block:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 2,
"totalPage": 1,
"items": [
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.040596",
"bizType": "withdraw",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8a",
"currency": "BTC"
}
},
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.140396",
"bizType": "trade exchange",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8e",
"tradeId": "5bc7f080b3949c03286eef8a",
"symbol": "BTC-USD"
}
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if direction:
data['direction'] = direction
if biz_type:
data['bizType'] = biz_type
if start:
data['startAt'] = start
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
return self._get('accounts/ledgers', True, data=data)
def get_transferable(self, currency, account_type):
"""Get the transferable balance of a specified account
https://docs.kucoin.com/#get-the-transferable
:param currency: Currency code
:type currency: string
:param account_type: Account type - main, trade, margin or pool
:type account_type: string
.. code:: python
accounts = client.get_transferable('BTC', 'trade')
:returns: API Response
.. code-block:: python
{
"currency": "BTC",
"balance": "0",
"available": "0",
"holds": "0",
"transferable": "0"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency,
'type': account_type.upper(),
}
return self._get('accounts/transferable', True, data=data)
def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None):
"""Transfer fund among accounts on the platform
https://docs.kucoin.com/#inner-transfer
:param currency: currency name
:type currency: str
:param from_type: Account type of payer: main, trade, margin or pool
:type from_type: str
:param to_type: Account type of payee: main, trade, margin , contract or pool
:type to_type: str
:param amount: Amount to transfer
:type amount: int
:param order_id: (optional) Request ID (default flat_uuid())
:type order_id: string
.. code:: python
transfer = client.create_inner_transfer('BTC', 'main', 'trade', 1)
:returns: API Response
.. code-block:: python
{
"orderId": "5bd6e9286d99522a52e458de"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'from': from_type,
'to': to_type,
'amount': amount,
'currency': currency,
'clientOid': order_id or flat_uuid(),
}
return self._post('accounts/inner-transfer', True, api_version=self.API_VERSION2, data=data)
# Deposit Endpoints
def create_deposit_address(self, currency, chain=None):
"""Create deposit address of currency for deposit. You can just create one deposit address.
https://docs.kucoin.com/#create-deposit-address
:param currency: Name of currency
:param chain: The chain name of currency
:type currency: string
:type chain: string
.. code:: python
address = client.create_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
if chain is not None:
data['chain'] = chain
return self._post('deposit-addresses', True, data=data)
def get_deposit_address(self, currency, chain=None):
"""Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:param chain: chain name of currency
:type currency: string
:type chain: string
.. code:: python
address = client.get_deposit_address('USDT','TRC20')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d",
"chain": "OMNI"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
if chain is not None:
data['chain'] = chain
return self._get('deposit-addresses', True, data=data)
def get_deposits(self, currency=None, status=None, start=None, end=None, page=None, limit=None):
"""Get deposit records for a currency
https://docs.kucoin.com/#get-deposit-list
:param currency: Name of currency (optional)
:type currency: string
:param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
:type status: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of transactions
:type limit: int
.. code:: python
deposits = client.get_deposits('NEO')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 5,
"totalNum": 2,
"totalPage": 1,
"items": [
{
"address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
"memo": "5c247c8a03aa677cea2a251d",
"amount": 1,
"fee": 0.0001,
"currency": "KCS",
"isInner": false,
"walletTxId": "5bbb57386d99522d9f954c5a@test004",
"status": "SUCCESS",
"createdAt": 1544178843000,
"updatedAt": 1544178891000
}, {
"address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
"memo": "5c247c8a03aa677cea2a251d",
"amount": 1,
"fee": 0.0001,
"currency": "KCS",
"isInner": false,
"walletTxId": "5bbb57386d99522d9f954c5a@test003",
"status": "SUCCESS",
"createdAt": 1544177654000,
"updatedAt": 1544178733000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if status:
data['status'] = status
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if limit:
data['pageSize'] = limit
if page:
data['currentPage'] = page
return self._get('deposits', True, data=data)
# Withdraw Endpoints
def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None):
"""Get deposit records for a currency
https://docs.kucoin.com/#get-withdrawals-list
:param currency: Name of currency (optional)
:type currency: string
:param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
:type status: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of transactions
:type limit: int
.. code:: python
withdrawals = client.get_withdrawals('NEO')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"id": "5c2dc64e03aa675aa263f1ac",
"address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
"memo": "",
"currency": "ETH",
"amount": 1.0000000,
"fee": 0.0100000,
"walletTxId": "3e2414d82acce78d38be7fe9",
"isInner": false,
"status": "FAILURE",
"createdAt": 1546503758000,
"updatedAt": 1546504603000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if status:
data['status'] = status
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if limit:
data['pageSize'] = limit
if page:
data['currentPage'] = page
return self._get('withdrawals', True, data=data)
def get_withdrawal_quotas(self, currency, chain=None):
"""Get withdrawal quotas for a currency
https://docs.kucoin.com/#get-withdrawal-quotas
:param currency: Name of currency
:type currency: string
:param chain: The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20, default is ERC20. This only apply for multi-chain currency, and there is no need for single chain currency.
:type chain: string
.. code:: python
quotas = client.get_withdrawal_quotas('ETH')
:returns: ApiResponse
.. code:: python
{
"currency": "ETH",
"availableAmount": 2.9719999,
"remainAmount": 2.9719999,
"withdrawMinSize": 0.1000000,
"limitBTCAmount": 2.0,
"innerWithdrawMinFee": 0.00001,
"isWithdrawEnabled": true,
"withdrawMinFee": 0.0100000,
"precision": 7
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
if chain:
data['chain'] = chain
return self._get('withdrawals/quotas', True, data=data)
def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False, remark=None, chain=None):
"""Process a withdrawal
https://docs.kucoin.com/#apply-withdraw
:param currency: Name of currency
:type currency: string
:param amount: Amount to withdraw
:type amount: number
:param address: Address to withdraw to
:type address: string
:param memo: (optional) Remark to the withdrawal address
:type memo: string
:param is_inner: (optional) Internal withdrawal or not
:type is_inner: bool
:param remark: (optional) Remark
:type remark: string
:param chain: (optional) The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20, default is ERC20. This only apply for multi-chain currency, and there is no need for single chain currency.
:type chain: string
.. code:: python
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
:returns: ApiResponse
.. code:: python
{
"withdrawalId": "5bffb63303aa675e8bbe18f9"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency,
'amount': amount,
'address': address
}
if memo:
data['memo'] = memo
if is_inner:
data['isInner'] = is_inner
if remark:
data['remark'] = remark
if chain:
data['chain'] = chain
return self._post('withdrawals', True, data=data)
def cancel_withdrawal(self, withdrawal_id):
"""Cancel a withdrawal
https://docs.kucoin.com/#cancel-withdrawal
:param withdrawal_id: ID of withdrawal
:type withdrawal_id: string
.. code:: python
client.cancel_withdrawal('5bffb63303aa675e8bbe18f9')
:returns: None
:raises: KucoinResponseException, KucoinAPIException
"""
return self._delete('withdrawals/{}'.format(withdrawal_id), True)
# Order Endpoints
def create_market_order(
self, symbol, side, size=None, funds=None,
client_oid=None, remark=None, stop=None, stop_price=None,
stp=None, trade_type=None):
"""Create a market order
One of size or funds must be set
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param size: (optional) Desired amount in base currency
:type size: string
:param funds: (optional) Desired amount of quote currency to use
:type funds: string
:param client_oid: (optional) Unique order id (default flat_uuid())
:type client_oid: string
:param remark: (optional) remark for the order, max 100 utf8 characters
:type remark: string
:param stop: (optional) stop type loss or entry - requires stop_price
:type stop: string
:param stop_price: (optional) trigger price for stop order
:type stop_price: string
:param stp: (optional) self trade protection CN, CO, CB or DC (default is None)
:type stp: string
:param trade_type: (optional) The type of trading : TRADE(Spot Trade), MARGIN_TRADE (Margin Trade). Default is TRADE
:type trade_type: string
.. code:: python
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, MarketOrderException
"""
if not size and not funds:
raise MarketOrderException('Need size or fund parameter')
if size and funds:
raise MarketOrderException('Need size or fund parameter not both')
if stop and not stop_price:
raise LimitOrderException('Stop order needs stop_price')
if stop_price and not stop:
raise LimitOrderException('Stop order type required with stop_price')
data = {
'side': side,
'symbol': symbol,
'type': self.ORDER_MARKET
}
if size:
data['size'] = size
if funds:
data['funds'] = funds
if client_oid:
data['clientOid'] = client_oid
else:
data['clientOid'] = flat_uuid()
if remark:
data['remark'] = remark
if stop:
data['stop'] = stop
data['stopPrice'] = stop_price
if stp:
data['stp'] = stp
if trade_type:
data['tradeType'] = trade_type
return self._post('orders', True, data=data)
def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None,
time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None,
cancel_after=None, post_only=None,
hidden=None, iceberg=None, visible_size=None):
"""Create an order
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param price: Name of coin
:type price: string
:param size: Amount of base currency to buy or sell
:type size: string
:param client_oid: (optional) Unique order_id default flat_uuid()
:type client_oid: string
:param remark: (optional) remark for the order, max 100 utf8 characters
:type remark: string
:param stp: (optional) self trade protection CN, CO, CB or DC (default is None)
:type stp: string
:param trade_type: (optional) The type of trading : TRADE(Spot Trade), MARGIN_TRADE (Margin Trade). Default is TRADE
:type trade_type: string
:param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC)
:type time_in_force: string
:param stop: (optional) stop type loss or entry - requires stop_price
:type stop: string
:param stop_price: (optional) trigger price for stop order
:type stop_price: string
:param cancel_after: (optional) number of seconds to cancel the order if not filled
required time_in_force to be GTT
:type cancel_after: string
:param post_only: (optional) indicates that the order should only make liquidity. If any part of
the order results in taking liquidity, the order will be rejected and no part of it will execute.
:type post_only: bool
:param hidden: (optional) Orders not displayed in order book
:type hidden: bool
:param iceberg: (optional) Only visible portion of the order is displayed in the order book
:type iceberg: bool
:param visible_size: (optional) The maximum visible size of an iceberg order
:type visible_size: bool
.. code:: python
order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000')
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, LimitOrderException
"""
if stop and not stop_price:
raise LimitOrderException('Stop order needs stop_price')
if stop_price and not stop:
raise LimitOrderException('Stop order type required with stop_price')
if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME:
raise LimitOrderException('Cancel after only works with time_in_force = "GTT"')
if hidden and iceberg:
raise LimitOrderException('Order can be either "hidden" or "iceberg"')
if iceberg and not visible_size:
raise LimitOrderException('Iceberg order requires visible_size')
data = {
'symbol': symbol,
'side': side,
'type': self.ORDER_LIMIT,
'price': price,
'size': size
}
if client_oid:
data['clientOid'] = client_oid
else:
data['clientOid'] = flat_uuid()
if remark:
data['remark'] = remark
if stp:
data['stp'] = stp
if trade_type:
data['tradeType'] = trade_type
if time_in_force:
data['timeInForce'] = time_in_force
if cancel_after:
data['cancelAfter'] = cancel_after
if post_only:
data['postOnly'] = post_only
if stop:
data['stop'] = stop
data['stopPrice'] = stop_price
if hidden:
data['hidden'] = hidden
if iceberg:
data['iceberg'] = iceberg
data['visible_size'] = visible_size
return self._post('orders', True, data=data)
def cancel_order(self, order_id):
"""Cancel an order
https://docs.kucoin.com/#cancel-an-order
:param order_id: Order id
:type order_id: string
.. code:: python
res = client.cancel_order('5bd6e9286d99522a52e458de)
:returns: ApiResponse
.. code:: python
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de"
]
}
:raises: KucoinResponseException, KucoinAPIException
KucoinAPIException If order_id is not found
"""
return self._delete('orders/{}'.format(order_id), True)
def cancel_order_by_client_oid(self, client_oid):
"""Cancel an order by the clientOid
https://docs.kucoin.com/#cancel-single-order-by-clientoid
:param client_oid: ClientOid
:type client_oid: string
.. code:: python
res = client.cancel_order_by_client_oid('6d539dc614db3)
:returns: ApiResponse
.. code:: python
{
"cancelledOrderId": "5f311183c9b6d539dc614db3",
"clientOid": "6d539dc614db3"
}
:raises: KucoinResponseException, KucoinAPIException
KucoinAPIException If order_id is not found
"""
return self._delete('order/client-order/{}'.format(client_oid), True)
def cancel_all_orders(self, symbol=None):
"""Cancel all orders
https://docs.kucoin.com/#cancel-all-orders
.. code:: python
res = client.cancel_all_orders()
:returns: ApiResponse
.. code:: python
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de"
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol is not None:
data['symbol'] = symbol
return self._delete('orders', True, data=data)
def get_orders(self, symbol=None, status=None, side=None, order_type=None,
start=None, end=None, page=None, limit=None, trade_type='TRADE'):
"""Get list of orders
https://docs.kucoin.com/#list-orders
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param status: (optional) Specify status active or done (default done)
:type status: string
:param side: (optional) buy or sell
:type side: string
:param order_type: (optional) limit, market, limit_stop or market_stop
:type order_type: string
:param trade_type: The type of trading : TRADE(Spot Trading), MARGIN_TRADE (Margin Trading).
:type trade_type: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_orders(symbol='KCS-BTC', status='active')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberge": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": null,
"remark": null,
"tags": null,
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if status:
data['status'] = status
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
if trade_type:
data['tradeType'] = trade_type
return self._get('orders', True, data=data)
def get_historical_orders(self, symbol=None, side=None,
start=None, end=None, page=None, limit=None):
"""List of KuCoin V1 historical orders.
https://docs.kucoin.com/#get-v1-historical-orders-list
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_historical_orders(symbol='KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 50,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"symbol": "SNOV-ETH",
"dealPrice": "0.0000246",
"dealValue": "0.018942",
"amount": "770",
"fee": "0.00001137",
"side": "sell",
"createdAt": 1540080199
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
return self._get('hist-orders', True, data=data)
def get_order(self, order_id):
"""Get order details
https://docs.kucoin.com/#get-an-order
:param order_id: orderOid value
:type order_id: str
.. code:: python
order = client.get_order('5c35c02703aa673ceec2a168')
:returns: ApiResponse
.. code:: python
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberge": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": null,
"remark": null,
"tags": null,
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000
}
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('orders/{}'.format(order_id), True)
def get_order_by_client_oid(self, client_oid):
"""Get order details by clientOid
https://docs.kucoin.com/#get-an-order
:param client_oid: clientOid value
:type client_oid: str
.. code:: python
order = client.get_order_by_client_oid('6d539dc614db312')
:returns: ApiResponse
.. code:: python
{
"id": "5f3113a1c9b6d539dc614dc6",
"symbol": "KCS-BTC",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "0.00001",
"size": "1",
"funds": "0",
"dealFunds": "0",
"dealSize": "0",
"fee": "0",
"feeCurrency": "BTC",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "API",
"clientOid": "6d539dc614db312",
"remark": "",
"tags": "",
"isActive": true,
"cancelExist": false,
"createdAt": 1597051810000,
"tradeType": "TRADE"
}
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('order/client-order/{}'.format(client_oid), True)
# Fill Endpoints
def get_fills(self, order_id=None, symbol=None, side=None, order_type=None,
start=None, end=None, page=None, limit=None, trade_type=None):
"""Get a list of recent fills.
https://docs.kucoin.com/#list-fills
:param order_id: (optional) generated order id
:type order_id: string
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: string
:param order_type: (optional) limit, market, limit_stop or market_stop
:type order_type: string
:param start: Start time as unix timestamp (optional)
:type start: string
:param end: End time as unix timestamp (optional)
:type end: string
:param trade_type: The type of trading : TRADE(Spot Trading), MARGIN_TRADE (Margin Trading).
:type trade_type: string
:param page: optional - Page to fetch
:type page: int
:param limit: optional - Number of orders
:type limit: int
.. code:: python
fills = client.get_fills()
:returns: ApiResponse
.. code:: python
{
"currentPage":1,
"pageSize":1,
"totalNum":251915,
"totalPage":251915,
"items":[
{
"symbol":"BTC-USDT",
"tradeId":"5c35c02709e4f67d5266954e",
"orderId":"5c35c02703aa673ceec2a168",
"counterOrderId":"5c1ab46003aa676e487fa8e3",
"side":"buy",
"liquidity":"taker",
"forceTaker":true,
"price":"0.083",
"size":"0.8424304",
"funds":"0.0699217232",
"fee":"0",
"feeRate":"0",
"feeCurrency":"USDT",
"stop":"",
"type":"limit",
"createdAt":1547026472000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if order_id:
data['orderId'] = order_id
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
if trade_type:
data['tradeType'] = trade_type
return self._get('fills', True, data=data)
# Market Endpoints
def get_symbols(self):
"""Get a list of available currency pairs for trading.
https://docs.kucoin.com/#symbols-amp-ticker
.. code:: python
symbols = client.get_symbols()
:returns: ApiResponse
.. code:: python
[
{
"symbol": "BTC-USDT",
"name": "BTC-USDT",
"baseCurrency": "BTC",
"quoteCurrency": "USDT",
"baseMinSize": "0.00000001",
"quoteMinSize": "0.01",
"baseMaxSize": "10000",
"quoteMaxSize": "100000",
"baseIncrement": "0.00000001",
"quoteIncrement": "0.01",
"priceIncrement": "0.00000001",
"enableTrading": true
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('symbols', False)
def get_ticker(self, symbol=None):
"""Get symbol tick
https://docs.kucoin.com/#get-ticker
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
all_ticks = client.get_ticker()
ticker = client.get_ticker('ETH-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545825031840", # now sequence
"price": "3494.367783", # last trade price
"size": "0.05027185", # last trade size
"bestBid": "3494.367783", # best bid price
"bestBidSize": "2.60323254", # size at best bid price
"bestAsk": "3499.12", # best ask price
"bestAskSize": "0.01474011" # size at best ask price
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
tick_path = 'market/allTickers'
if symbol is not None:
tick_path = 'market/orderbook/level1'
data = {
'symbol': symbol
}
return self._get(tick_path, False, data=data)
def get_fiat_prices(self, base=None, symbol=None):
"""Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with
comma one by one. default is all
:type symbol: string
.. code:: python
prices = client.get_fiat_prices()
:returns: ApiResponse
.. code:: python
{
"BTC": "3911.28000000",
"ETH": "144.55492453",
"LTC": "48.45888179",
"KCS": "0.45546856"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if base is not None:
data['base'] = base
if symbol is not None:
data['currencies'] = symbol
return self._get('prices', False, data=data)
def get_24hr_stats(self, symbol):
"""Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
stats = client.get_24hr_stats('ETH-BTC')
:returns: ApiResponse
Without a symbol param
.. code:: python
{
"symbol": "BTC-USDT",
"changeRate": "0.0128", # 24h change rate
"changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number,
# the price rises; if the change rate is a positive number, the price falls.)
"open": 61, # Opening price
"close": 63.6, # Closing price
"high": "63.6", # Highest price filled
"low": "61", # Lowest price filled
"vol": "244.78", # Transaction quantity
"volValue": "15252.0127" # Transaction amount
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/stats', False, data=data)
def get_markets(self):
"""Get supported market list
https://docs.kucoin.com/#get-market-list
.. code:: python
markets = client.get_markets()
:returns: ApiResponse
.. code:: python
{
"data": [
"BTC",
"ETH",
"USDT"
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
return self._get('markets', False)
def get_order_book(self, symbol, depth_20=False):
"""Get a list of bids and asks aggregated by price for a symbol.
Returns up to 20 or 100 depth each side. Fastest Order book API
https://docs.kucoin.com/#get-part-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param depth_20: If to return only 20 depth
:type depth_20: bool
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price, size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
path = 'market/orderbook/level2_'
if depth_20:
path += '20'
else:
path += '100'
return self._get(path, False, data=data)
def get_full_order_book(self, symbol):
"""Get a list of all bids and asks aggregated by price for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2', True, api_version=self.API_VERSION3, data=data)
def get_full_order_book_level3(self, symbol):
"""Get a list of all bids and asks non-aggregated for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-atomic
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545896707028",
"bids": [
[
"5c2477e503aa671a745c4057", # orderId
"6", # price
"0.999" # size
],
[
"5c2477e103aa671a745c4054",
"5",
"0.999"
]
],
"asks": [
[
"5c24736703aa671a745c401e",
"200",
"1"
],
[
"5c2475c903aa671a745c4033",
"201",
"1"
]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level3', False, data=data)
def get_trade_histories(self, symbol):
"""List the latest trades for a symbol
https://docs.kucoin.com/#get-trade-histories
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_trade_histories('KCS-BTC')
:returns: ApiResponse
.. code:: python
[
{
"sequence": "1545896668571",
"price": "0.07", # Filled price
"size": "0.004", # Filled amount
"side": "buy", # Filled side. The filled side is set to the taker by default.
"time": 1545904567062140823 # Transaction time
},
{
"sequence": "1545896668578",
"price": "0.054",
"size": "0.066",
"side": "buy",
"time": 1545904581619888405
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/histories', False, data=data)
def get_kline_data(self, symbol, kline_type='5min', start=None, end=None):
"""Get kline data
For each query, the system would return at most 1500 pieces of data.
To obtain more data, please page the data by time.
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour,
4hour, 6hour, 8hour, 12hour, 1day, 1week
:type kline_type: string
:param start: Start time as unix timestamp (optional) default start of day in UTC
:type start: int
:param end: End time as unix timestamp (optional) default now in UTC
:type end: int
https://docs.kucoin.com/#get-historic-rates
.. code:: python
klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
:returns: ApiResponse
.. code:: python
[
[
"1545904980", //Start time of the candle cycle
"0.058", //opening price
"0.049", //closing price
"0.058", //highest price
"0.049", //lowest price
"0.018", //Transaction amount
"0.000945" //Transaction volume
],
[
"1545904920",
"0.058",
"0.072",
"0.072",
"0.058",
"0.103",
"0.006986"
]
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
if kline_type is not None:
data['type'] = kline_type
if start is not None:
data['startAt'] = start
else:
data['startAt'] = calendar.timegm(datetime.utcnow().date().timetuple())
if end is not None:
data['endAt'] = end
else:
data['endAt'] = int(time.time())
return self._get('market/candles', False, data=data)
# Websocket Endpoints
def get_ws_endpoint(self, private=False):
"""Get websocket channel details
:param private: Name of symbol e.g. KCS-BTC
:type private: bool
https://docs.kucoin.com/#websocket-feed
.. code:: python
ws_details = client.get_ws_endpoint(private=True)
:returns: ApiResponse
.. code:: python
{
"code": "200000",
"data": {
"instanceServers": [
{
"pingInterval": 50000,
"endpoint": "wss://push1-v2.kucoin.net/endpoint",
"protocol": "websocket",
"encrypt": true,
"pingTimeout": 10000
}
],
"token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE"
}
}
:raises: KucoinResponseException, KucoinAPIException
"""
path = 'bullet-public'
signed = private
if private:
path = 'bullet-private'
return self._post(path, signed)
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/home/ubuntu/workspace/project/dist";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _flickity = __webpack_require__(3);
var _flickity2 = _interopRequireDefault(_flickity);
var _Fixed = __webpack_require__(21);
var _Fixed2 = _interopRequireDefault(_Fixed);
var _Posts = __webpack_require__(22);
var _Posts2 = _interopRequireDefault(_Posts);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _Posts2.default)("http://miaucore.azurewebsites.net/api/News", function (data) {
var mainCarrousel = new _flickity2.default('[data-id="main-carrousel"]', { pageDots: false, wrapAround: true });
});
var rank = new _Fixed2.default('#ranking');
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*eslint-disable no-unused-vars*/
/*!
* jQuery JavaScript Library v3.1.0
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2016-07-07T21:44Z
*/
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
/* global Symbol */
// Defining this global in .eslintrc would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var
version = "3.1.0",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
DOMEval( code );
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.0
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-04
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true;
},
{ dir: "parentNode", next: "legend" }
);
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives:
// IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset)
// not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Check form elements and option elements for explicit disabling
return "label" in elem && elem.disabled === disabled ||
"form" in elem && elem.disabled === disabled ||
// Check non-disabled form elements for fieldset[disabled] ancestors
"form" in elem && elem.disabled === false && (
// Support: IE6-11+
// Ancestry is covered for us
elem.isDisabled === disabled ||
// Otherwise, assume any non-<option> under fieldset[disabled] is disabled
/* jshint -W018 */
elem.isDisabled !== !disabled &&
("label" in elem || !disabledAncestor( elem )) !== disabled
);
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
return m ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( true ),
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( el ) {
return el.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnotwhite = ( /\S+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
resolve.call( undefined, value );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.call( undefined, value );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( jQuery.isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList
.then( fn )
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch( function( error ) {
jQuery.readyException( error );
} );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
( ( key && typeof key === "string" ) && value === undefined ) ) {
return this.get( owner, key );
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnotwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? JSON.parse( data ) :
data;
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) ),
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== "undefined" ?
context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, selector );
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support: IE <=9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox <=42
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push( { elem: cur, handlers: matches } );
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
function manipulationTarget( elem, content ) {
if ( jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
div.style.cssText =
"box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
container.appendChild( div );
jQuery.extend( support, {
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE <=9 only
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// At this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// At this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val,
valueIsBorderBox = true,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
if ( elem.getClientRects().length ) {
val = elem.getBoundingClientRect()[ name ];
}
// Some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// Use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
}
} );
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function raf() {
if ( timerId ) {
window.requestAnimationFrame( raf );
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// Ensure the complete handler is called before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* eslint-disable no-loop-func */
anim.done( function() {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3 only
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ] );
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
} ),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length; index++ ) {
result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnotwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
// Go to the end state if fx are off or if document is hidden
if ( jQuery.fx.off || document.hidden ) {
opt.duration = 0;
} else {
opt.duration = typeof opt.duration === "number" ?
opt.duration : opt.duration in jQuery.fx.speeds ?
jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
}
// Normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// Show any hidden elements after setting opacity to 0
return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
// Animate to the value specified
.end().animate( { opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = window.requestAnimationFrame ?
window.requestAnimationFrame( raf ) :
window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
if ( window.cancelAnimationFrame ) {
window.cancelAnimationFrame( timerId );
} else {
window.clearInterval( timerId );
}
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
} )();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
var rclass = /[\t\r\n\f]/g;
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnotwhite ) || [];
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + getClass( elem ) + " " ).replace( rclass, " " )
.indexOf( className ) > -1
) {
return true;
}
}
return false;
}
} );
var rreturn = /\r/g,
rspaces = /[\x20\t\r\n\f]+/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// Handle most common string cases
ret.replace( rreturn, "" ) :
// Handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType[ 0 ] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR );
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( completed ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available, append data to url
if ( s.data ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in uncached url if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rts, "" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend &&
( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( jQuery.isFunction( html ) ) {
html = html.call( this[ 0 ] );
}
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// Force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none)
if ( rect.width || rect.height ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
// Return zeros for disconnected and hidden elements (gh-2310)
return rect;
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset = {
top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
};
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable );
};
} );
} );
jQuery.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
jQuery.parseJSON = JSON.parse;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( true ) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return jQuery;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} );
/***/ },
/* 2 */,
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* Flickity v2.0.3
* Touch, responsive, flickable carousels
*
* Licensed GPLv3 for open source use
* or Flickity Commercial License for commercial use
*
* http://flickity.metafizzy.co
* Copyright 2016 Metafizzy
*/
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(12),
__webpack_require__(15),
__webpack_require__(17),
__webpack_require__(18),
__webpack_require__(19),
__webpack_require__(20)
], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
require('./flickity'),
require('./drag'),
require('./prev-next-button'),
require('./page-dots'),
require('./player'),
require('./add-remove-cell'),
require('./lazyload')
);
}
})( window, function factory( Flickity ) {
/*jshint strict: false*/
return Flickity;
});
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Flickity main
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(5),
__webpack_require__(6),
__webpack_require__(7),
__webpack_require__(9),
__webpack_require__(10),
__webpack_require__(11)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( EvEmitter, getSize, utils, Cell, Slide, animatePrototype ) {
return factory( window, EvEmitter, getSize, utils, Cell, Slide, animatePrototype );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('ev-emitter'),
require('get-size'),
require('fizzy-ui-utils'),
require('./cell'),
require('./slide'),
require('./animate')
);
} else {
// browser global
var _Flickity = window.Flickity;
window.Flickity = factory(
window,
window.EvEmitter,
window.getSize,
window.fizzyUIUtils,
_Flickity.Cell,
_Flickity.Slide,
_Flickity.animatePrototype
);
}
}( window, function factory( window, EvEmitter, getSize,
utils, Cell, Slide, animatePrototype ) {
'use strict';
// vars
var jQuery = window.jQuery;
var getComputedStyle = window.getComputedStyle;
var console = window.console;
function moveElements( elems, toElem ) {
elems = utils.makeArray( elems );
while ( elems.length ) {
toElem.appendChild( elems.shift() );
}
}
// -------------------------- Flickity -------------------------- //
// globally unique identifiers
var GUID = 0;
// internal store of all Flickity intances
var instances = {};
function Flickity( element, options ) {
var queryElement = utils.getQueryElement( element );
if ( !queryElement ) {
if ( console ) {
console.error( 'Bad element for Flickity: ' + ( queryElement || element ) );
}
return;
}
this.element = queryElement;
// do not initialize twice on same element
if ( this.element.flickityGUID ) {
var instance = instances[ this.element.flickityGUID ];
instance.option( options );
return instance;
}
// add jQuery
if ( jQuery ) {
this.$element = jQuery( this.element );
}
// options
this.options = utils.extend( {}, this.constructor.defaults );
this.option( options );
// kick things off
this._create();
}
Flickity.defaults = {
accessibility: true,
// adaptiveHeight: false,
cellAlign: 'center',
// cellSelector: undefined,
// contain: false,
freeScrollFriction: 0.075, // friction when free-scrolling
friction: 0.28, // friction when selecting
namespaceJQueryEvents: true,
// initialIndex: 0,
percentPosition: true,
resize: true,
selectedAttraction: 0.025,
setGallerySize: true
// watchCSS: false,
// wrapAround: false
};
// hash of methods triggered on _create()
Flickity.createMethods = [];
var proto = Flickity.prototype;
// inherit EventEmitter
utils.extend( proto, EvEmitter.prototype );
proto._create = function() {
// add id for Flickity.data
var id = this.guid = ++GUID;
this.element.flickityGUID = id; // expando
instances[ id ] = this; // associate via id
// initial properties
this.selectedIndex = 0;
// how many frames slider has been in same position
this.restingFrames = 0;
// initial physics properties
this.x = 0;
this.velocity = 0;
this.originSide = this.options.rightToLeft ? 'right' : 'left';
// create viewport & slider
this.viewport = document.createElement('div');
this.viewport.className = 'flickity-viewport';
this._createSlider();
if ( this.options.resize || this.options.watchCSS ) {
window.addEventListener( 'resize', this );
}
Flickity.createMethods.forEach( function( method ) {
this[ method ]();
}, this );
if ( this.options.watchCSS ) {
this.watchCSS();
} else {
this.activate();
}
};
/**
* set options
* @param {Object} opts
*/
proto.option = function( opts ) {
utils.extend( this.options, opts );
};
proto.activate = function() {
if ( this.isActive ) {
return;
}
this.isActive = true;
this.element.classList.add('flickity-enabled');
if ( this.options.rightToLeft ) {
this.element.classList.add('flickity-rtl');
}
this.getSize();
// move initial cell elements so they can be loaded as cells
var cellElems = this._filterFindCellElements( this.element.children );
moveElements( cellElems, this.slider );
this.viewport.appendChild( this.slider );
this.element.appendChild( this.viewport );
// get cells from children
this.reloadCells();
if ( this.options.accessibility ) {
// allow element to focusable
this.element.tabIndex = 0;
// listen for key presses
this.element.addEventListener( 'keydown', this );
}
this.emitEvent('activate');
var index;
var initialIndex = this.options.initialIndex;
if ( this.isInitActivated ) {
index = this.selectedIndex;
} else if ( initialIndex !== undefined ) {
index = this.cells[ initialIndex ] ? initialIndex : 0;
} else {
index = 0;
}
// select instantly
this.select( index, false, true );
// flag for initial activation, for using initialIndex
this.isInitActivated = true;
};
// slider positions the cells
proto._createSlider = function() {
// slider element does all the positioning
var slider = document.createElement('div');
slider.className = 'flickity-slider';
slider.style[ this.originSide ] = 0;
this.slider = slider;
};
proto._filterFindCellElements = function( elems ) {
return utils.filterFindElements( elems, this.options.cellSelector );
};
// goes through all children
proto.reloadCells = function() {
// collection of item elements
this.cells = this._makeCells( this.slider.children );
this.positionCells();
this._getWrapShiftCells();
this.setGallerySize();
};
/**
* turn elements into Flickity.Cells
* @param {Array or NodeList or HTMLElement} elems
* @returns {Array} items - collection of new Flickity Cells
*/
proto._makeCells = function( elems ) {
var cellElems = this._filterFindCellElements( elems );
// create new Flickity for collection
var cells = cellElems.map( function( cellElem ) {
return new Cell( cellElem, this );
}, this );
return cells;
};
proto.getLastCell = function() {
return this.cells[ this.cells.length - 1 ];
};
proto.getLastSlide = function() {
return this.slides[ this.slides.length - 1 ];
};
// positions all cells
proto.positionCells = function() {
// size all cells
this._sizeCells( this.cells );
// position all cells
this._positionCells( 0 );
};
/**
* position certain cells
* @param {Integer} index - which cell to start with
*/
proto._positionCells = function( index ) {
index = index || 0;
// also measure maxCellHeight
// start 0 if positioning all cells
this.maxCellHeight = index ? this.maxCellHeight || 0 : 0;
var cellX = 0;
// get cellX
if ( index > 0 ) {
var startCell = this.cells[ index - 1 ];
cellX = startCell.x + startCell.size.outerWidth;
}
var len = this.cells.length;
for ( var i=index; i < len; i++ ) {
var cell = this.cells[i];
cell.setPosition( cellX );
cellX += cell.size.outerWidth;
this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight );
}
// keep track of cellX for wrap-around
this.slideableWidth = cellX;
// slides
this.updateSlides();
// contain slides target
this._containSlides();
// update slidesWidth
this.slidesWidth = len ? this.getLastSlide().target - this.slides[0].target : 0;
};
/**
* cell.getSize() on multiple cells
* @param {Array} cells
*/
proto._sizeCells = function( cells ) {
cells.forEach( function( cell ) {
cell.getSize();
});
};
// -------------------------- -------------------------- //
proto.updateSlides = function() {
this.slides = [];
if ( !this.cells.length ) {
return;
}
var slide = new Slide( this );
this.slides.push( slide );
var isOriginLeft = this.originSide == 'left';
var nextMargin = isOriginLeft ? 'marginRight' : 'marginLeft';
var canCellFit = this._getCanCellFit();
this.cells.forEach( function( cell, i ) {
// just add cell if first cell in slide
if ( !slide.cells.length ) {
slide.addCell( cell );
return;
}
var slideWidth = ( slide.outerWidth - slide.firstMargin ) +
( cell.size.outerWidth - cell.size[ nextMargin ] );
if ( canCellFit.call( this, i, slideWidth ) ) {
slide.addCell( cell );
} else {
// doesn't fit, new slide
slide.updateTarget();
slide = new Slide( this );
this.slides.push( slide );
slide.addCell( cell );
}
}, this );
// last slide
slide.updateTarget();
// update .selectedSlide
this.updateSelectedSlide();
};
proto._getCanCellFit = function() {
var groupCells = this.options.groupCells;
if ( !groupCells ) {
return function() {
return false;
};
} else if ( typeof groupCells == 'number' ) {
// group by number. 3 -> [0,1,2], [3,4,5], ...
var number = parseInt( groupCells, 10 );
return function( i ) {
return ( i % number ) !== 0;
};
}
// default, group by width of slide
// parse '75%
var percentMatch = typeof groupCells == 'string' &&
groupCells.match(/^(\d+)%$/);
var percent = percentMatch ? parseInt( percentMatch[1], 10 ) / 100 : 1;
return function( i, slideWidth ) {
return slideWidth <= ( this.size.innerWidth + 1 ) * percent;
};
};
// alias _init for jQuery plugin .flickity()
proto._init =
proto.reposition = function() {
this.positionCells();
this.positionSliderAtSelected();
};
proto.getSize = function() {
this.size = getSize( this.element );
this.setCellAlign();
this.cursorPosition = this.size.innerWidth * this.cellAlign;
};
var cellAlignShorthands = {
// cell align, then based on origin side
center: {
left: 0.5,
right: 0.5
},
left: {
left: 0,
right: 1
},
right: {
right: 0,
left: 1
}
};
proto.setCellAlign = function() {
var shorthand = cellAlignShorthands[ this.options.cellAlign ];
this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign;
};
proto.setGallerySize = function() {
if ( this.options.setGallerySize ) {
var height = this.options.adaptiveHeight && this.selectedSlide ?
this.selectedSlide.height : this.maxCellHeight;
this.viewport.style.height = height + 'px';
}
};
proto._getWrapShiftCells = function() {
// only for wrap-around
if ( !this.options.wrapAround ) {
return;
}
// unshift previous cells
this._unshiftCells( this.beforeShiftCells );
this._unshiftCells( this.afterShiftCells );
// get before cells
// initial gap
var gapX = this.cursorPosition;
var cellIndex = this.cells.length - 1;
this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 );
// get after cells
// ending gap between last cell and end of gallery viewport
gapX = this.size.innerWidth - this.cursorPosition;
// start cloning at first cell, working forwards
this.afterShiftCells = this._getGapCells( gapX, 0, 1 );
};
proto._getGapCells = function( gapX, cellIndex, increment ) {
// keep adding cells until the cover the initial gap
var cells = [];
while ( gapX > 0 ) {
var cell = this.cells[ cellIndex ];
if ( !cell ) {
break;
}
cells.push( cell );
cellIndex += increment;
gapX -= cell.size.outerWidth;
}
return cells;
};
// ----- contain ----- //
// contain cell targets so no excess sliding
proto._containSlides = function() {
if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) {
return;
}
var isRightToLeft = this.options.rightToLeft;
var beginMargin = isRightToLeft ? 'marginRight' : 'marginLeft';
var endMargin = isRightToLeft ? 'marginLeft' : 'marginRight';
var contentWidth = this.slideableWidth - this.getLastCell().size[ endMargin ];
// content is less than gallery size
var isContentSmaller = contentWidth < this.size.innerWidth;
// bounds
var beginBound = this.cursorPosition + this.cells[0].size[ beginMargin ];
var endBound = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign );
// contain each cell target
this.slides.forEach( function( slide ) {
if ( isContentSmaller ) {
// all cells fit inside gallery
slide.target = contentWidth * this.cellAlign;
} else {
// contain to bounds
slide.target = Math.max( slide.target, beginBound );
slide.target = Math.min( slide.target, endBound );
}
}, this );
};
// ----- ----- //
/**
* emits events via eventEmitter and jQuery events
* @param {String} type - name of event
* @param {Event} event - original event
* @param {Array} args - extra arguments
*/
proto.dispatchEvent = function( type, event, args ) {
var emitArgs = event ? [ event ].concat( args ) : args;
this.emitEvent( type, emitArgs );
if ( jQuery && this.$element ) {
// default trigger with type if no event
type += this.options.namespaceJQueryEvents ? '.flickity' : '';
var $event = type;
if ( event ) {
// create jQuery event
var jQEvent = jQuery.Event( event );
jQEvent.type = type;
$event = jQEvent;
}
this.$element.trigger( $event, args );
}
};
// -------------------------- select -------------------------- //
/**
* @param {Integer} index - index of the slide
* @param {Boolean} isWrap - will wrap-around to last/first if at the end
* @param {Boolean} isInstant - will immediately set position at selected cell
*/
proto.select = function( index, isWrap, isInstant ) {
if ( !this.isActive ) {
return;
}
index = parseInt( index, 10 );
this._wrapSelect( index );
if ( this.options.wrapAround || isWrap ) {
index = utils.modulo( index, this.slides.length );
}
// bail if invalid index
if ( !this.slides[ index ] ) {
return;
}
this.selectedIndex = index;
this.updateSelectedSlide();
if ( isInstant ) {
this.positionSliderAtSelected();
} else {
this.startAnimation();
}
if ( this.options.adaptiveHeight ) {
this.setGallerySize();
}
this.dispatchEvent('select');
// old v1 event name, remove in v3
this.dispatchEvent('cellSelect');
};
// wraps position for wrapAround, to move to closest slide. #113
proto._wrapSelect = function( index ) {
var len = this.slides.length;
var isWrapping = this.options.wrapAround && len > 1;
if ( !isWrapping ) {
return index;
}
var wrapIndex = utils.modulo( index, len );
// go to shortest
var delta = Math.abs( wrapIndex - this.selectedIndex );
var backWrapDelta = Math.abs( ( wrapIndex + len ) - this.selectedIndex );
var forewardWrapDelta = Math.abs( ( wrapIndex - len ) - this.selectedIndex );
if ( !this.isDragSelect && backWrapDelta < delta ) {
index += len;
} else if ( !this.isDragSelect && forewardWrapDelta < delta ) {
index -= len;
}
// wrap position so slider is within normal area
if ( index < 0 ) {
this.x -= this.slideableWidth;
} else if ( index >= len ) {
this.x += this.slideableWidth;
}
};
proto.previous = function( isWrap, isInstant ) {
this.select( this.selectedIndex - 1, isWrap, isInstant );
};
proto.next = function( isWrap, isInstant ) {
this.select( this.selectedIndex + 1, isWrap, isInstant );
};
proto.updateSelectedSlide = function() {
var slide = this.slides[ this.selectedIndex ];
// selectedIndex could be outside of slides, if triggered before resize()
if ( !slide ) {
return;
}
// unselect previous selected slide
this.unselectSelectedSlide();
// update new selected slide
this.selectedSlide = slide;
slide.select();
this.selectedCells = slide.cells;
this.selectedElements = slide.getCellElements();
// HACK: selectedCell & selectedElement is first cell in slide, backwards compatibility
// Remove in v3?
this.selectedCell = slide.cells[0];
this.selectedElement = this.selectedElements[0];
};
proto.unselectSelectedSlide = function() {
if ( this.selectedSlide ) {
this.selectedSlide.unselect();
}
};
/**
* select slide from number or cell element
* @param {Element or Number} elem
*/
proto.selectCell = function( value, isWrap, isInstant ) {
// get cell
var cell;
if ( typeof value == 'number' ) {
cell = this.cells[ value ];
} else {
// use string as selector
if ( typeof value == 'string' ) {
value = this.element.querySelector( value );
}
// get cell from element
cell = this.getCell( value );
}
// select slide that has cell
for ( var i=0; cell && i < this.slides.length; i++ ) {
var slide = this.slides[i];
var index = slide.cells.indexOf( cell );
if ( index != -1 ) {
this.select( i, isWrap, isInstant );
return;
}
}
};
// -------------------------- get cells -------------------------- //
/**
* get Flickity.Cell, given an Element
* @param {Element} elem
* @returns {Flickity.Cell} item
*/
proto.getCell = function( elem ) {
// loop through cells to get the one that matches
for ( var i=0; i < this.cells.length; i++ ) {
var cell = this.cells[i];
if ( cell.element == elem ) {
return cell;
}
}
};
/**
* get collection of Flickity.Cells, given Elements
* @param {Element, Array, NodeList} elems
* @returns {Array} cells - Flickity.Cells
*/
proto.getCells = function( elems ) {
elems = utils.makeArray( elems );
var cells = [];
elems.forEach( function( elem ) {
var cell = this.getCell( elem );
if ( cell ) {
cells.push( cell );
}
}, this );
return cells;
};
/**
* get cell elements
* @returns {Array} cellElems
*/
proto.getCellElements = function() {
return this.cells.map( function( cell ) {
return cell.element;
});
};
/**
* get parent cell from an element
* @param {Element} elem
* @returns {Flickit.Cell} cell
*/
proto.getParentCell = function( elem ) {
// first check if elem is cell
var cell = this.getCell( elem );
if ( cell ) {
return cell;
}
// try to get parent cell elem
elem = utils.getParent( elem, '.flickity-slider > *' );
return this.getCell( elem );
};
/**
* get cells adjacent to a slide
* @param {Integer} adjCount - number of adjacent slides
* @param {Integer} index - index of slide to start
* @returns {Array} cells - array of Flickity.Cells
*/
proto.getAdjacentCellElements = function( adjCount, index ) {
if ( !adjCount ) {
return this.selectedSlide.getCellElements();
}
index = index === undefined ? this.selectedIndex : index;
var len = this.slides.length;
if ( 1 + ( adjCount * 2 ) >= len ) {
return this.getCellElements();
}
var cellElems = [];
for ( var i = index - adjCount; i <= index + adjCount ; i++ ) {
var slideIndex = this.options.wrapAround ? utils.modulo( i, len ) : i;
var slide = this.slides[ slideIndex ];
if ( slide ) {
cellElems = cellElems.concat( slide.getCellElements() );
}
}
return cellElems;
};
// -------------------------- events -------------------------- //
proto.uiChange = function() {
this.emitEvent('uiChange');
};
proto.childUIPointerDown = function( event ) {
this.emitEvent( 'childUIPointerDown', [ event ] );
};
// ----- resize ----- //
proto.onresize = function() {
this.watchCSS();
this.resize();
};
utils.debounceMethod( Flickity, 'onresize', 150 );
proto.resize = function() {
if ( !this.isActive ) {
return;
}
this.getSize();
// wrap values
if ( this.options.wrapAround ) {
this.x = utils.modulo( this.x, this.slideableWidth );
}
this.positionCells();
this._getWrapShiftCells();
this.setGallerySize();
this.emitEvent('resize');
// update selected index for group slides, instant
// TODO: position can be lost between groups of various numbers
var selectedElement = this.selectedElements && this.selectedElements[0];
this.selectCell( selectedElement, false, true );
};
// watches the :after property, activates/deactivates
proto.watchCSS = function() {
var watchOption = this.options.watchCSS;
if ( !watchOption ) {
return;
}
var afterContent = getComputedStyle( this.element, ':after' ).content;
// activate if :after { content: 'flickity' }
if ( afterContent.indexOf('flickity') != -1 ) {
this.activate();
} else {
this.deactivate();
}
};
// ----- keydown ----- //
// go previous/next if left/right keys pressed
proto.onkeydown = function( event ) {
// only work if element is in focus
if ( !this.options.accessibility ||
( document.activeElement && document.activeElement != this.element ) ) {
return;
}
if ( event.keyCode == 37 ) {
// go left
var leftMethod = this.options.rightToLeft ? 'next' : 'previous';
this.uiChange();
this[ leftMethod ]();
} else if ( event.keyCode == 39 ) {
// go right
var rightMethod = this.options.rightToLeft ? 'previous' : 'next';
this.uiChange();
this[ rightMethod ]();
}
};
// -------------------------- destroy -------------------------- //
// deactivate all Flickity functionality, but keep stuff available
proto.deactivate = function() {
if ( !this.isActive ) {
return;
}
this.element.classList.remove('flickity-enabled');
this.element.classList.remove('flickity-rtl');
// destroy cells
this.cells.forEach( function( cell ) {
cell.destroy();
});
this.unselectSelectedSlide();
this.element.removeChild( this.viewport );
// move child elements back into element
moveElements( this.slider.children, this.element );
if ( this.options.accessibility ) {
this.element.removeAttribute('tabIndex');
this.element.removeEventListener( 'keydown', this );
}
// set flags
this.isActive = false;
this.emitEvent('deactivate');
};
proto.destroy = function() {
this.deactivate();
window.removeEventListener( 'resize', this );
this.emitEvent('destroy');
if ( jQuery && this.$element ) {
jQuery.removeData( this.element, 'flickity' );
}
delete this.element.flickityGUID;
delete instances[ this.guid ];
};
// -------------------------- prototype -------------------------- //
utils.extend( proto, animatePrototype );
// -------------------------- extras -------------------------- //
/**
* get Flickity instance from element
* @param {Element} elem
* @returns {Flickity}
*/
Flickity.data = function( elem ) {
elem = utils.getQueryElement( elem );
var id = elem && elem.flickityGUID;
return id && instances[ id ];
};
utils.htmlInit( Flickity, 'flickity' );
if ( jQuery && jQuery.bridget ) {
jQuery.bridget( 'flickity', Flickity );
}
Flickity.Cell = Cell;
return Flickity;
}));
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* EvEmitter v1.0.3
* Lil' event emitter
* MIT License
*/
/* jshint unused: true, undef: true, strict: true */
( function( global, factory ) {
// universal module definition
/* jshint strict: false */ /* globals define, module, window */
if ( true ) {
// AMD - RequireJS
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS - Browserify, Webpack
module.exports = factory();
} else {
// Browser globals
global.EvEmitter = factory();
}
}( typeof window != 'undefined' ? window : this, function() {
"use strict";
function EvEmitter() {}
var proto = EvEmitter.prototype;
proto.on = function( eventName, listener ) {
if ( !eventName || !listener ) {
return;
}
// set events hash
var events = this._events = this._events || {};
// set listeners array
var listeners = events[ eventName ] = events[ eventName ] || [];
// only add once
if ( listeners.indexOf( listener ) == -1 ) {
listeners.push( listener );
}
return this;
};
proto.once = function( eventName, listener ) {
if ( !eventName || !listener ) {
return;
}
// add event
this.on( eventName, listener );
// set once flag
// set onceEvents hash
var onceEvents = this._onceEvents = this._onceEvents || {};
// set onceListeners object
var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
// set flag
onceListeners[ listener ] = true;
return this;
};
proto.off = function( eventName, listener ) {
var listeners = this._events && this._events[ eventName ];
if ( !listeners || !listeners.length ) {
return;
}
var index = listeners.indexOf( listener );
if ( index != -1 ) {
listeners.splice( index, 1 );
}
return this;
};
proto.emitEvent = function( eventName, args ) {
var listeners = this._events && this._events[ eventName ];
if ( !listeners || !listeners.length ) {
return;
}
var i = 0;
var listener = listeners[i];
args = args || [];
// once stuff
var onceListeners = this._onceEvents && this._onceEvents[ eventName ];
while ( listener ) {
var isOnce = onceListeners && onceListeners[ listener ];
if ( isOnce ) {
// remove listener
// remove before trigger to prevent recursion
this.off( eventName, listener );
// unset once flag
delete onceListeners[ listener ];
}
// trigger listener
listener.apply( this, args );
// get next listener
i += isOnce ? 0 : 1;
listener = listeners[i];
}
return this;
};
return EvEmitter;
}));
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* getSize v2.0.2
* measure size of elements
* MIT license
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false, module: false, console: false */
( function( window, factory ) {
'use strict';
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return factory();
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
window.getSize = factory();
}
})( window, function factory() {
'use strict';
// -------------------------- helpers -------------------------- //
// get a number from a string, not a percentage
function getStyleSize( value ) {
var num = parseFloat( value );
// not a percent like '100%', and a number
var isValid = value.indexOf('%') == -1 && !isNaN( num );
return isValid && num;
}
function noop() {}
var logError = typeof console == 'undefined' ? noop :
function( message ) {
console.error( message );
};
// -------------------------- measurements -------------------------- //
var measurements = [
'paddingLeft',
'paddingRight',
'paddingTop',
'paddingBottom',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'borderLeftWidth',
'borderRightWidth',
'borderTopWidth',
'borderBottomWidth'
];
var measurementsLength = measurements.length;
function getZeroSize() {
var size = {
width: 0,
height: 0,
innerWidth: 0,
innerHeight: 0,
outerWidth: 0,
outerHeight: 0
};
for ( var i=0; i < measurementsLength; i++ ) {
var measurement = measurements[i];
size[ measurement ] = 0;
}
return size;
}
// -------------------------- getStyle -------------------------- //
/**
* getStyle, get style of element, check for Firefox bug
* https://bugzilla.mozilla.org/show_bug.cgi?id=548397
*/
function getStyle( elem ) {
var style = getComputedStyle( elem );
if ( !style ) {
logError( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See http://bit.ly/getsizebug1' );
}
return style;
}
// -------------------------- setup -------------------------- //
var isSetup = false;
var isBoxSizeOuter;
/**
* setup
* check isBoxSizerOuter
* do on first getSize() rather than on page load for Firefox bug
*/
function setup() {
// setup once
if ( isSetup ) {
return;
}
isSetup = true;
// -------------------------- box sizing -------------------------- //
/**
* WebKit measures the outer-width on style.width on border-box elems
* IE & Firefox<29 measures the inner-width
*/
var div = document.createElement('div');
div.style.width = '200px';
div.style.padding = '1px 2px 3px 4px';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px 2px 3px 4px';
div.style.boxSizing = 'border-box';
var body = document.body || document.documentElement;
body.appendChild( div );
var style = getStyle( div );
getSize.isBoxSizeOuter = isBoxSizeOuter = getStyleSize( style.width ) == 200;
body.removeChild( div );
}
// -------------------------- getSize -------------------------- //
function getSize( elem ) {
setup();
// use querySeletor if elem is string
if ( typeof elem == 'string' ) {
elem = document.querySelector( elem );
}
// do not proceed on non-objects
if ( !elem || typeof elem != 'object' || !elem.nodeType ) {
return;
}
var style = getStyle( elem );
// if hidden, everything is 0
if ( style.display == 'none' ) {
return getZeroSize();
}
var size = {};
size.width = elem.offsetWidth;
size.height = elem.offsetHeight;
var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';
// get all measurements
for ( var i=0; i < measurementsLength; i++ ) {
var measurement = measurements[i];
var value = style[ measurement ];
var num = parseFloat( value );
// any 'auto', 'medium' value will be 0
size[ measurement ] = !isNaN( num ) ? num : 0;
}
var paddingWidth = size.paddingLeft + size.paddingRight;
var paddingHeight = size.paddingTop + size.paddingBottom;
var marginWidth = size.marginLeft + size.marginRight;
var marginHeight = size.marginTop + size.marginBottom;
var borderWidth = size.borderLeftWidth + size.borderRightWidth;
var borderHeight = size.borderTopWidth + size.borderBottomWidth;
var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
// overwrite width and height if we can get it from style
var styleWidth = getStyleSize( style.width );
if ( styleWidth !== false ) {
size.width = styleWidth +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
}
var styleHeight = getStyleSize( style.height );
if ( styleHeight !== false ) {
size.height = styleHeight +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
}
size.innerWidth = size.width - ( paddingWidth + borderWidth );
size.innerHeight = size.height - ( paddingHeight + borderHeight );
size.outerWidth = size.width + marginWidth;
size.outerHeight = size.height + marginHeight;
return size;
}
return getSize;
});
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* Fizzy UI utils v2.0.3
* MIT license
*/
/*jshint browser: true, undef: true, unused: true, strict: true */
( function( window, factory ) {
// universal module definition
/*jshint strict: false */ /*globals define, module, require */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(8)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( matchesSelector ) {
return factory( window, matchesSelector );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('desandro-matches-selector')
);
} else {
// browser global
window.fizzyUIUtils = factory(
window,
window.matchesSelector
);
}
}( window, function factory( window, matchesSelector ) {
'use strict';
var utils = {};
// ----- extend ----- //
// extends objects
utils.extend = function( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
};
// ----- modulo ----- //
utils.modulo = function( num, div ) {
return ( ( num % div ) + div ) % div;
};
// ----- makeArray ----- //
// turn element or nodeList into an array
utils.makeArray = function( obj ) {
var ary = [];
if ( Array.isArray( obj ) ) {
// use object if already an array
ary = obj;
} else if ( obj && typeof obj.length == 'number' ) {
// convert nodeList to array
for ( var i=0; i < obj.length; i++ ) {
ary.push( obj[i] );
}
} else {
// array of single index
ary.push( obj );
}
return ary;
};
// ----- removeFrom ----- //
utils.removeFrom = function( ary, obj ) {
var index = ary.indexOf( obj );
if ( index != -1 ) {
ary.splice( index, 1 );
}
};
// ----- getParent ----- //
utils.getParent = function( elem, selector ) {
while ( elem != document.body ) {
elem = elem.parentNode;
if ( matchesSelector( elem, selector ) ) {
return elem;
}
}
};
// ----- getQueryElement ----- //
// use element as selector string
utils.getQueryElement = function( elem ) {
if ( typeof elem == 'string' ) {
return document.querySelector( elem );
}
return elem;
};
// ----- handleEvent ----- //
// enable .ontype to trigger from .addEventListener( elem, 'type' )
utils.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
// ----- filterFindElements ----- //
utils.filterFindElements = function( elems, selector ) {
// make array of elems
elems = utils.makeArray( elems );
var ffElems = [];
elems.forEach( function( elem ) {
// check that elem is an actual element
if ( !( elem instanceof HTMLElement ) ) {
return;
}
// add elem if no selector
if ( !selector ) {
ffElems.push( elem );
return;
}
// filter & find items if we have a selector
// filter
if ( matchesSelector( elem, selector ) ) {
ffElems.push( elem );
}
// find children
var childElems = elem.querySelectorAll( selector );
// concat childElems to filterFound array
for ( var i=0; i < childElems.length; i++ ) {
ffElems.push( childElems[i] );
}
});
return ffElems;
};
// ----- debounceMethod ----- //
utils.debounceMethod = function( _class, methodName, threshold ) {
// original method
var method = _class.prototype[ methodName ];
var timeoutName = methodName + 'Timeout';
_class.prototype[ methodName ] = function() {
var timeout = this[ timeoutName ];
if ( timeout ) {
clearTimeout( timeout );
}
var args = arguments;
var _this = this;
this[ timeoutName ] = setTimeout( function() {
method.apply( _this, args );
delete _this[ timeoutName ];
}, threshold || 100 );
};
};
// ----- docReady ----- //
utils.docReady = function( callback ) {
var readyState = document.readyState;
if ( readyState == 'complete' || readyState == 'interactive' ) {
// do async to allow for other scripts to run. metafizzy/flickity#441
setTimeout( callback );
} else {
document.addEventListener( 'DOMContentLoaded', callback );
}
};
// ----- htmlInit ----- //
// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
utils.toDashed = function( str ) {
return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
return $1 + '-' + $2;
}).toLowerCase();
};
var console = window.console;
/**
* allow user to initialize classes via [data-namespace] or .js-namespace class
* htmlInit( Widget, 'widgetName' )
* options are parsed from data-namespace-options
*/
utils.htmlInit = function( WidgetClass, namespace ) {
utils.docReady( function() {
var dashedNamespace = utils.toDashed( namespace );
var dataAttr = 'data-' + dashedNamespace;
var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );
var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );
var elems = utils.makeArray( dataAttrElems )
.concat( utils.makeArray( jsDashElems ) );
var dataOptionsAttr = dataAttr + '-options';
var jQuery = window.jQuery;
elems.forEach( function( elem ) {
var attr = elem.getAttribute( dataAttr ) ||
elem.getAttribute( dataOptionsAttr );
var options;
try {
options = attr && JSON.parse( attr );
} catch ( error ) {
// log error, do not initialize
if ( console ) {
console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +
': ' + error );
}
return;
}
// initialize
var instance = new WidgetClass( elem, options );
// make available via $().data('namespace')
if ( jQuery ) {
jQuery.data( elem, namespace, instance );
}
});
});
};
// ----- ----- //
return utils;
}));
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* matchesSelector v2.0.1
* matchesSelector( element, '.selector' )
* MIT license
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
( function( window, factory ) {
/*global define: false, module: false */
'use strict';
// universal module definition
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
window.matchesSelector = factory();
}
}( window, function factory() {
'use strict';
var matchesMethod = ( function() {
var ElemProto = Element.prototype;
// check for the standard method name first
if ( ElemProto.matches ) {
return 'matches';
}
// check un-prefixed
if ( ElemProto.matchesSelector ) {
return 'matchesSelector';
}
// check vendor prefixes
var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];
for ( var i=0; i < prefixes.length; i++ ) {
var prefix = prefixes[i];
var method = prefix + 'MatchesSelector';
if ( ElemProto[ method ] ) {
return method;
}
}
})();
return function matchesSelector( elem, selector ) {
return elem[ matchesMethod ]( selector );
};
}));
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Flickity.Cell
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(6)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( getSize ) {
return factory( window, getSize );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('get-size')
);
} else {
// browser global
window.Flickity = window.Flickity || {};
window.Flickity.Cell = factory(
window,
window.getSize
);
}
}( window, function factory( window, getSize ) {
'use strict';
function Cell( elem, parent ) {
this.element = elem;
this.parent = parent;
this.create();
}
var proto = Cell.prototype;
proto.create = function() {
this.element.style.position = 'absolute';
this.x = 0;
this.shift = 0;
};
proto.destroy = function() {
// reset style
this.element.style.position = '';
var side = this.parent.originSide;
this.element.style[ side ] = '';
};
proto.getSize = function() {
this.size = getSize( this.element );
};
proto.setPosition = function( x ) {
this.x = x;
this.updateTarget();
this.renderPosition( x );
};
// setDefaultTarget v1 method, backwards compatibility, remove in v3
proto.updateTarget = proto.setDefaultTarget = function() {
var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight';
this.target = this.x + this.size[ marginProperty ] +
this.size.width * this.parent.cellAlign;
};
proto.renderPosition = function( x ) {
// render position of cell with in slider
var side = this.parent.originSide;
this.element.style[ side ] = this.parent.getPositionValue( x );
};
/**
* @param {Integer} factor - 0, 1, or -1
**/
proto.wrapShift = function( shift ) {
this.shift = shift;
this.renderPosition( this.x + this.parent.slideableWidth * shift );
};
proto.remove = function() {
this.element.parentNode.removeChild( this.element );
};
return Cell;
}));
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// slide
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
window.Flickity = window.Flickity || {};
window.Flickity.Slide = factory();
}
}( window, function factory() {
'use strict';
function Slide( parent ) {
this.parent = parent;
this.isOriginLeft = parent.originSide == 'left';
this.cells = [];
this.outerWidth = 0;
this.height = 0;
}
var proto = Slide.prototype;
proto.addCell = function( cell ) {
this.cells.push( cell );
this.outerWidth += cell.size.outerWidth;
this.height = Math.max( cell.size.outerHeight, this.height );
// first cell stuff
if ( this.cells.length == 1 ) {
this.x = cell.x; // x comes from first cell
var beginMargin = this.isOriginLeft ? 'marginLeft' : 'marginRight';
this.firstMargin = cell.size[ beginMargin ];
}
};
proto.updateTarget = function() {
var endMargin = this.isOriginLeft ? 'marginRight' : 'marginLeft';
var lastCell = this.getLastCell();
var lastMargin = lastCell ? lastCell.size[ endMargin ] : 0;
var slideWidth = this.outerWidth - ( this.firstMargin + lastMargin );
this.target = this.x + this.firstMargin + slideWidth * this.parent.cellAlign;
};
proto.getLastCell = function() {
return this.cells[ this.cells.length - 1 ];
};
proto.select = function() {
this.changeSelectedClass('add');
};
proto.unselect = function() {
this.changeSelectedClass('remove');
};
proto.changeSelectedClass = function( method ) {
this.cells.forEach( function( cell ) {
cell.element.classList[ method ]('is-selected');
});
};
proto.getCellElements = function() {
return this.cells.map( function( cell ) {
return cell.element;
});
};
return Slide;
}));
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// animate
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( utils ) {
return factory( window, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('fizzy-ui-utils')
);
} else {
// browser global
window.Flickity = window.Flickity || {};
window.Flickity.animatePrototype = factory(
window,
window.fizzyUIUtils
);
}
}( window, function factory( window, utils ) {
'use strict';
// -------------------------- requestAnimationFrame -------------------------- //
// get rAF, prefixed, if present
var requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame;
// fallback to setTimeout
var lastTime = 0;
if ( !requestAnimationFrame ) {
requestAnimationFrame = function( callback ) {
var currTime = new Date().getTime();
var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
var id = setTimeout( callback, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
}
// -------------------------- animate -------------------------- //
var proto = {};
proto.startAnimation = function() {
if ( this.isAnimating ) {
return;
}
this.isAnimating = true;
this.restingFrames = 0;
this.animate();
};
proto.animate = function() {
this.applyDragForce();
this.applySelectedAttraction();
var previousX = this.x;
this.integratePhysics();
this.positionSlider();
this.settle( previousX );
// animate next frame
if ( this.isAnimating ) {
var _this = this;
requestAnimationFrame( function animateFrame() {
_this.animate();
});
}
};
var transformProperty = ( function () {
var style = document.documentElement.style;
if ( typeof style.transform == 'string' ) {
return 'transform';
}
return 'WebkitTransform';
})();
proto.positionSlider = function() {
var x = this.x;
// wrap position around
if ( this.options.wrapAround && this.cells.length > 1 ) {
x = utils.modulo( x, this.slideableWidth );
x = x - this.slideableWidth;
this.shiftWrapCells( x );
}
x = x + this.cursorPosition;
// reverse if right-to-left and using transform
x = this.options.rightToLeft && transformProperty ? -x : x;
var value = this.getPositionValue( x );
// use 3D tranforms for hardware acceleration on iOS
// but use 2D when settled, for better font-rendering
this.slider.style[ transformProperty ] = this.isAnimating ?
'translate3d(' + value + ',0,0)' : 'translateX(' + value + ')';
// scroll event
var firstSlide = this.slides[0];
if ( firstSlide ) {
var positionX = -this.x - firstSlide.target;
var progress = positionX / this.slidesWidth;
this.dispatchEvent( 'scroll', null, [ progress, positionX ] );
}
};
proto.positionSliderAtSelected = function() {
if ( !this.cells.length ) {
return;
}
this.x = -this.selectedSlide.target;
this.positionSlider();
};
proto.getPositionValue = function( position ) {
if ( this.options.percentPosition ) {
// percent position, round to 2 digits, like 12.34%
return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 )+ '%';
} else {
// pixel positioning
return Math.round( position ) + 'px';
}
};
proto.settle = function( previousX ) {
// keep track of frames where x hasn't moved
if ( !this.isPointerDown && Math.round( this.x * 100 ) == Math.round( previousX * 100 ) ) {
this.restingFrames++;
}
// stop animating if resting for 3 or more frames
if ( this.restingFrames > 2 ) {
this.isAnimating = false;
delete this.isFreeScrolling;
// render position with translateX when settled
this.positionSlider();
this.dispatchEvent('settle');
}
};
proto.shiftWrapCells = function( x ) {
// shift before cells
var beforeGap = this.cursorPosition + x;
this._shiftCells( this.beforeShiftCells, beforeGap, -1 );
// shift after cells
var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition );
this._shiftCells( this.afterShiftCells, afterGap, 1 );
};
proto._shiftCells = function( cells, gap, shift ) {
for ( var i=0; i < cells.length; i++ ) {
var cell = cells[i];
var cellShift = gap > 0 ? shift : 0;
cell.wrapShift( cellShift );
gap -= cell.size.outerWidth;
}
};
proto._unshiftCells = function( cells ) {
if ( !cells || !cells.length ) {
return;
}
for ( var i=0; i < cells.length; i++ ) {
cells[i].wrapShift( 0 );
}
};
// -------------------------- physics -------------------------- //
proto.integratePhysics = function() {
this.x += this.velocity;
this.velocity *= this.getFrictionFactor();
};
proto.applyForce = function( force ) {
this.velocity += force;
};
proto.getFrictionFactor = function() {
return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ];
};
proto.getRestingPosition = function() {
// my thanks to Steven Wittens, who simplified this math greatly
return this.x + this.velocity / ( 1 - this.getFrictionFactor() );
};
proto.applyDragForce = function() {
if ( !this.isPointerDown ) {
return;
}
// change the position to drag position by applying force
var dragVelocity = this.dragX - this.x;
var dragForce = dragVelocity - this.velocity;
this.applyForce( dragForce );
};
proto.applySelectedAttraction = function() {
// do not attract if pointer down or no cells
if ( this.isPointerDown || this.isFreeScrolling || !this.cells.length ) {
return;
}
var distance = this.selectedSlide.target * -1 - this.x;
var force = distance * this.options.selectedAttraction;
this.applyForce( force );
};
return proto;
}));
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// drag
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(13),
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Flickity, Unidragger, utils ) {
return factory( window, Flickity, Unidragger, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('./flickity'),
require('unidragger'),
require('fizzy-ui-utils')
);
} else {
// browser global
window.Flickity = factory(
window,
window.Flickity,
window.Unidragger,
window.fizzyUIUtils
);
}
}( window, function factory( window, Flickity, Unidragger, utils ) {
'use strict';
// ----- defaults ----- //
utils.extend( Flickity.defaults, {
draggable: true,
dragThreshold: 3,
});
// ----- create ----- //
Flickity.createMethods.push('_createDrag');
// -------------------------- drag prototype -------------------------- //
var proto = Flickity.prototype;
utils.extend( proto, Unidragger.prototype );
// -------------------------- -------------------------- //
proto._createDrag = function() {
this.on( 'activate', this.bindDrag );
this.on( 'uiChange', this._uiChangeDrag );
this.on( 'childUIPointerDown', this._childUIPointerDownDrag );
this.on( 'deactivate', this.unbindDrag );
};
proto.bindDrag = function() {
if ( !this.options.draggable || this.isDragBound ) {
return;
}
this.element.classList.add('is-draggable');
this.handles = [ this.viewport ];
this.bindHandles();
this.isDragBound = true;
};
proto.unbindDrag = function() {
if ( !this.isDragBound ) {
return;
}
this.element.classList.remove('is-draggable');
this.unbindHandles();
delete this.isDragBound;
};
proto._uiChangeDrag = function() {
delete this.isFreeScrolling;
};
proto._childUIPointerDownDrag = function( event ) {
event.preventDefault();
this.pointerDownFocus( event );
};
// -------------------------- pointer events -------------------------- //
// nodes that have text fields
var cursorNodes = {
TEXTAREA: true,
INPUT: true,
OPTION: true,
};
// input types that do not have text fields
var clickTypes = {
radio: true,
checkbox: true,
button: true,
submit: true,
image: true,
file: true,
};
proto.pointerDown = function( event, pointer ) {
// dismiss inputs with text fields. #403, #404
var isCursorInput = cursorNodes[ event.target.nodeName ] &&
!clickTypes[ event.target.type ];
if ( isCursorInput ) {
// reset pointerDown logic
this.isPointerDown = false;
delete this.pointerIdentifier;
return;
}
this._dragPointerDown( event, pointer );
// kludge to blur focused inputs in dragger
var focused = document.activeElement;
if ( focused && focused.blur && focused != this.element &&
// do not blur body for IE9 & 10, #117
focused != document.body ) {
focused.blur();
}
this.pointerDownFocus( event );
// stop if it was moving
this.dragX = this.x;
this.viewport.classList.add('is-pointer-down');
// bind move and end events
this._bindPostStartEvents( event );
// track scrolling
this.pointerDownScroll = getScrollPosition();
window.addEventListener( 'scroll', this );
this.dispatchEvent( 'pointerDown', event, [ pointer ] );
};
var touchStartEvents = {
touchstart: true,
MSPointerDown: true
};
var focusNodes = {
INPUT: true,
SELECT: true
};
proto.pointerDownFocus = function( event ) {
// focus element, if not touch, and its not an input or select
if ( !this.options.accessibility || touchStartEvents[ event.type ] ||
focusNodes[ event.target.nodeName ] ) {
return;
}
var prevScrollY = window.pageYOffset;
this.element.focus();
// hack to fix scroll jump after focus, #76
if ( window.pageYOffset != prevScrollY ) {
window.scrollTo( window.pageXOffset, prevScrollY );
}
};
proto.canPreventDefaultOnPointerDown = function( event ) {
// prevent default, unless touchstart or <select>
var isTouchstart = event.type == 'touchstart';
var targetNodeName = event.target.nodeName;
return !isTouchstart && targetNodeName != 'SELECT';
};
// ----- move ----- //
proto.hasDragStarted = function( moveVector ) {
return Math.abs( moveVector.x ) > this.options.dragThreshold;
};
// ----- up ----- //
proto.pointerUp = function( event, pointer ) {
delete this.isTouchScrolling;
this.viewport.classList.remove('is-pointer-down');
this.dispatchEvent( 'pointerUp', event, [ pointer ] );
this._dragPointerUp( event, pointer );
};
proto.pointerDone = function() {
window.removeEventListener( 'scroll', this );
delete this.pointerDownScroll;
};
// -------------------------- dragging -------------------------- //
proto.dragStart = function( event, pointer ) {
this.dragStartPosition = this.x;
this.startAnimation();
this.dispatchEvent( 'dragStart', event, [ pointer ] );
};
proto.pointerMove = function( event, pointer ) {
var moveVector = this._dragPointerMove( event, pointer );
this.dispatchEvent( 'pointerMove', event, [ pointer, moveVector ] );
this._dragMove( event, pointer, moveVector );
};
proto.dragMove = function( event, pointer, moveVector ) {
event.preventDefault();
this.previousDragX = this.dragX;
// reverse if right-to-left
var direction = this.options.rightToLeft ? -1 : 1;
var dragX = this.dragStartPosition + moveVector.x * direction;
if ( !this.options.wrapAround && this.slides.length ) {
// slow drag
var originBound = Math.max( -this.slides[0].target, this.dragStartPosition );
dragX = dragX > originBound ? ( dragX + originBound ) * 0.5 : dragX;
var endBound = Math.min( -this.getLastSlide().target, this.dragStartPosition );
dragX = dragX < endBound ? ( dragX + endBound ) * 0.5 : dragX;
}
this.dragX = dragX;
this.dragMoveTime = new Date();
this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] );
};
proto.dragEnd = function( event, pointer ) {
if ( this.options.freeScroll ) {
this.isFreeScrolling = true;
}
// set selectedIndex based on where flick will end up
var index = this.dragEndRestingSelect();
if ( this.options.freeScroll && !this.options.wrapAround ) {
// if free-scroll & not wrap around
// do not free-scroll if going outside of bounding slides
// so bounding slides can attract slider, and keep it in bounds
var restingX = this.getRestingPosition();
this.isFreeScrolling = -restingX > this.slides[0].target &&
-restingX < this.getLastSlide().target;
} else if ( !this.options.freeScroll && index == this.selectedIndex ) {
// boost selection if selected index has not changed
index += this.dragEndBoostSelect();
}
delete this.previousDragX;
// apply selection
// TODO refactor this, selecting here feels weird
// HACK, set flag so dragging stays in correct direction
this.isDragSelect = this.options.wrapAround;
this.select( index );
delete this.isDragSelect;
this.dispatchEvent( 'dragEnd', event, [ pointer ] );
};
proto.dragEndRestingSelect = function() {
var restingX = this.getRestingPosition();
// how far away from selected slide
var distance = Math.abs( this.getSlideDistance( -restingX, this.selectedIndex ) );
// get closet resting going up and going down
var positiveResting = this._getClosestResting( restingX, distance, 1 );
var negativeResting = this._getClosestResting( restingX, distance, -1 );
// use closer resting for wrap-around
var index = positiveResting.distance < negativeResting.distance ?
positiveResting.index : negativeResting.index;
return index;
};
/**
* given resting X and distance to selected cell
* get the distance and index of the closest cell
* @param {Number} restingX - estimated post-flick resting position
* @param {Number} distance - distance to selected cell
* @param {Integer} increment - +1 or -1, going up or down
* @returns {Object} - { distance: {Number}, index: {Integer} }
*/
proto._getClosestResting = function( restingX, distance, increment ) {
var index = this.selectedIndex;
var minDistance = Infinity;
var condition = this.options.contain && !this.options.wrapAround ?
// if contain, keep going if distance is equal to minDistance
function( d, md ) { return d <= md; } : function( d, md ) { return d < md; };
while ( condition( distance, minDistance ) ) {
// measure distance to next cell
index += increment;
minDistance = distance;
distance = this.getSlideDistance( -restingX, index );
if ( distance === null ) {
break;
}
distance = Math.abs( distance );
}
return {
distance: minDistance,
// selected was previous index
index: index - increment
};
};
/**
* measure distance between x and a slide target
* @param {Number} x
* @param {Integer} index - slide index
*/
proto.getSlideDistance = function( x, index ) {
var len = this.slides.length;
// wrap around if at least 2 slides
var isWrapAround = this.options.wrapAround && len > 1;
var slideIndex = isWrapAround ? utils.modulo( index, len ) : index;
var slide = this.slides[ slideIndex ];
if ( !slide ) {
return null;
}
// add distance for wrap-around slides
var wrap = isWrapAround ? this.slideableWidth * Math.floor( index / len ) : 0;
return x - ( slide.target + wrap );
};
proto.dragEndBoostSelect = function() {
// do not boost if no previousDragX or dragMoveTime
if ( this.previousDragX === undefined || !this.dragMoveTime ||
// or if drag was held for 100 ms
new Date() - this.dragMoveTime > 100 ) {
return 0;
}
var distance = this.getSlideDistance( -this.dragX, this.selectedIndex );
var delta = this.previousDragX - this.dragX;
if ( distance > 0 && delta > 0 ) {
// boost to next if moving towards the right, and positive velocity
return 1;
} else if ( distance < 0 && delta < 0 ) {
// boost to previous if moving towards the left, and negative velocity
return -1;
}
return 0;
};
// ----- staticClick ----- //
proto.staticClick = function( event, pointer ) {
// get clickedCell, if cell was clicked
var clickedCell = this.getParentCell( event.target );
var cellElem = clickedCell && clickedCell.element;
var cellIndex = clickedCell && this.cells.indexOf( clickedCell );
this.dispatchEvent( 'staticClick', event, [ pointer, cellElem, cellIndex ] );
};
// ----- scroll ----- //
proto.onscroll = function() {
var scroll = getScrollPosition();
var scrollMoveX = this.pointerDownScroll.x - scroll.x;
var scrollMoveY = this.pointerDownScroll.y - scroll.y;
// cancel click/tap if scroll is too much
if ( Math.abs( scrollMoveX ) > 3 || Math.abs( scrollMoveY ) > 3 ) {
this._pointerDone();
}
};
// ----- utils ----- //
function getScrollPosition() {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
}
// ----- ----- //
return Flickity;
}));
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* Unidragger v2.1.0
* Draggable base class
* MIT license
*/
/*jshint browser: true, unused: true, undef: true, strict: true */
( function( window, factory ) {
// universal module definition
/*jshint strict: false */ /*globals define, module, require */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(14)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Unipointer ) {
return factory( window, Unipointer );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('unipointer')
);
} else {
// browser global
window.Unidragger = factory(
window,
window.Unipointer
);
}
}( window, function factory( window, Unipointer ) {
'use strict';
// ----- ----- //
function noop() {}
// -------------------------- Unidragger -------------------------- //
function Unidragger() {}
// inherit Unipointer & EvEmitter
var proto = Unidragger.prototype = Object.create( Unipointer.prototype );
// ----- bind start ----- //
proto.bindHandles = function() {
this._bindHandles( true );
};
proto.unbindHandles = function() {
this._bindHandles( false );
};
var navigator = window.navigator;
/**
* works as unbinder, as you can .bindHandles( false ) to unbind
* @param {Boolean} isBind - will unbind if falsey
*/
proto._bindHandles = function( isBind ) {
// munge isBind, default to true
isBind = isBind === undefined ? true : !!isBind;
// extra bind logic
var binderExtra;
if ( navigator.pointerEnabled ) {
binderExtra = function( handle ) {
// disable scrolling on the element
handle.style.touchAction = isBind ? 'none' : '';
};
} else if ( navigator.msPointerEnabled ) {
binderExtra = function( handle ) {
// disable scrolling on the element
handle.style.msTouchAction = isBind ? 'none' : '';
};
} else {
binderExtra = noop;
}
// bind each handle
var bindMethod = isBind ? 'addEventListener' : 'removeEventListener';
for ( var i=0; i < this.handles.length; i++ ) {
var handle = this.handles[i];
this._bindStartEvent( handle, isBind );
binderExtra( handle );
handle[ bindMethod ]( 'click', this );
}
};
// ----- start event ----- //
/**
* pointer start
* @param {Event} event
* @param {Event or Touch} pointer
*/
proto.pointerDown = function( event, pointer ) {
// dismiss range sliders
if ( event.target.nodeName == 'INPUT' && event.target.type == 'range' ) {
// reset pointerDown logic
this.isPointerDown = false;
delete this.pointerIdentifier;
return;
}
this._dragPointerDown( event, pointer );
// kludge to blur focused inputs in dragger
var focused = document.activeElement;
if ( focused && focused.blur ) {
focused.blur();
}
// bind move and end events
this._bindPostStartEvents( event );
this.emitEvent( 'pointerDown', [ event, pointer ] );
};
// base pointer down logic
proto._dragPointerDown = function( event, pointer ) {
// track to see when dragging starts
this.pointerDownPoint = Unipointer.getPointerPoint( pointer );
var canPreventDefault = this.canPreventDefaultOnPointerDown( event, pointer );
if ( canPreventDefault ) {
event.preventDefault();
}
};
// overwriteable method so Flickity can prevent for scrolling
proto.canPreventDefaultOnPointerDown = function( event ) {
// prevent default, unless touchstart or <select>
return event.target.nodeName != 'SELECT';
};
// ----- move event ----- //
/**
* drag move
* @param {Event} event
* @param {Event or Touch} pointer
*/
proto.pointerMove = function( event, pointer ) {
var moveVector = this._dragPointerMove( event, pointer );
this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] );
this._dragMove( event, pointer, moveVector );
};
// base pointer move logic
proto._dragPointerMove = function( event, pointer ) {
var movePoint = Unipointer.getPointerPoint( pointer );
var moveVector = {
x: movePoint.x - this.pointerDownPoint.x,
y: movePoint.y - this.pointerDownPoint.y
};
// start drag if pointer has moved far enough to start drag
if ( !this.isDragging && this.hasDragStarted( moveVector ) ) {
this._dragStart( event, pointer );
}
return moveVector;
};
// condition if pointer has moved far enough to start drag
proto.hasDragStarted = function( moveVector ) {
return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3;
};
// ----- end event ----- //
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
*/
proto.pointerUp = function( event, pointer ) {
this.emitEvent( 'pointerUp', [ event, pointer ] );
this._dragPointerUp( event, pointer );
};
proto._dragPointerUp = function( event, pointer ) {
if ( this.isDragging ) {
this._dragEnd( event, pointer );
} else {
// pointer didn't move enough for drag to start
this._staticClick( event, pointer );
}
};
// -------------------------- drag -------------------------- //
// dragStart
proto._dragStart = function( event, pointer ) {
this.isDragging = true;
this.dragStartPoint = Unipointer.getPointerPoint( pointer );
// prevent clicks
this.isPreventingClicks = true;
this.dragStart( event, pointer );
};
proto.dragStart = function( event, pointer ) {
this.emitEvent( 'dragStart', [ event, pointer ] );
};
// dragMove
proto._dragMove = function( event, pointer, moveVector ) {
// do not drag if not dragging yet
if ( !this.isDragging ) {
return;
}
this.dragMove( event, pointer, moveVector );
};
proto.dragMove = function( event, pointer, moveVector ) {
event.preventDefault();
this.emitEvent( 'dragMove', [ event, pointer, moveVector ] );
};
// dragEnd
proto._dragEnd = function( event, pointer ) {
// set flags
this.isDragging = false;
// re-enable clicking async
setTimeout( function() {
delete this.isPreventingClicks;
}.bind( this ) );
this.dragEnd( event, pointer );
};
proto.dragEnd = function( event, pointer ) {
this.emitEvent( 'dragEnd', [ event, pointer ] );
};
// ----- onclick ----- //
// handle all clicks and prevent clicks when dragging
proto.onclick = function( event ) {
if ( this.isPreventingClicks ) {
event.preventDefault();
}
};
// ----- staticClick ----- //
// triggered after pointer down & up with no/tiny movement
proto._staticClick = function( event, pointer ) {
// ignore emulated mouse up clicks
if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {
return;
}
// allow click in <input>s and <textarea>s
var nodeName = event.target.nodeName;
if ( nodeName == 'INPUT' || nodeName == 'TEXTAREA' ) {
event.target.focus();
}
this.staticClick( event, pointer );
// set flag for emulated clicks 300ms after touchend
if ( event.type != 'mouseup' ) {
this.isIgnoringMouseUp = true;
// reset flag after 300ms
setTimeout( function() {
delete this.isIgnoringMouseUp;
}.bind( this ), 400 );
}
};
proto.staticClick = function( event, pointer ) {
this.emitEvent( 'staticClick', [ event, pointer ] );
};
// ----- utils ----- //
Unidragger.getPointerPoint = Unipointer.getPointerPoint;
// ----- ----- //
return Unidragger;
}));
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* Unipointer v2.1.0
* base class for doing one thing with pointer event
* MIT license
*/
/*jshint browser: true, undef: true, unused: true, strict: true */
( function( window, factory ) {
// universal module definition
/* jshint strict: false */ /*global define, module, require */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(5)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( EvEmitter ) {
return factory( window, EvEmitter );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('ev-emitter')
);
} else {
// browser global
window.Unipointer = factory(
window,
window.EvEmitter
);
}
}( window, function factory( window, EvEmitter ) {
'use strict';
function noop() {}
function Unipointer() {}
// inherit EvEmitter
var proto = Unipointer.prototype = Object.create( EvEmitter.prototype );
proto.bindStartEvent = function( elem ) {
this._bindStartEvent( elem, true );
};
proto.unbindStartEvent = function( elem ) {
this._bindStartEvent( elem, false );
};
/**
* works as unbinder, as you can ._bindStart( false ) to unbind
* @param {Boolean} isBind - will unbind if falsey
*/
proto._bindStartEvent = function( elem, isBind ) {
// munge isBind, default to true
isBind = isBind === undefined ? true : !!isBind;
var bindMethod = isBind ? 'addEventListener' : 'removeEventListener';
if ( window.navigator.pointerEnabled ) {
// W3C Pointer Events, IE11. See https://coderwall.com/p/mfreca
elem[ bindMethod ]( 'pointerdown', this );
} else if ( window.navigator.msPointerEnabled ) {
// IE10 Pointer Events
elem[ bindMethod ]( 'MSPointerDown', this );
} else {
// listen for both, for devices like Chrome Pixel
elem[ bindMethod ]( 'mousedown', this );
elem[ bindMethod ]( 'touchstart', this );
}
};
// trigger handler methods for events
proto.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
// returns the touch that we're keeping track of
proto.getTouch = function( touches ) {
for ( var i=0; i < touches.length; i++ ) {
var touch = touches[i];
if ( touch.identifier == this.pointerIdentifier ) {
return touch;
}
}
};
// ----- start event ----- //
proto.onmousedown = function( event ) {
// dismiss clicks from right or middle buttons
var button = event.button;
if ( button && ( button !== 0 && button !== 1 ) ) {
return;
}
this._pointerDown( event, event );
};
proto.ontouchstart = function( event ) {
this._pointerDown( event, event.changedTouches[0] );
};
proto.onMSPointerDown =
proto.onpointerdown = function( event ) {
this._pointerDown( event, event );
};
/**
* pointer start
* @param {Event} event
* @param {Event or Touch} pointer
*/
proto._pointerDown = function( event, pointer ) {
// dismiss other pointers
if ( this.isPointerDown ) {
return;
}
this.isPointerDown = true;
// save pointer identifier to match up touch events
this.pointerIdentifier = pointer.pointerId !== undefined ?
// pointerId for pointer events, touch.indentifier for touch events
pointer.pointerId : pointer.identifier;
this.pointerDown( event, pointer );
};
proto.pointerDown = function( event, pointer ) {
this._bindPostStartEvents( event );
this.emitEvent( 'pointerDown', [ event, pointer ] );
};
// hash of events to be bound after start event
var postStartEvents = {
mousedown: [ 'mousemove', 'mouseup' ],
touchstart: [ 'touchmove', 'touchend', 'touchcancel' ],
pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ],
MSPointerDown: [ 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel' ]
};
proto._bindPostStartEvents = function( event ) {
if ( !event ) {
return;
}
// get proper events to match start event
var events = postStartEvents[ event.type ];
// bind events to node
events.forEach( function( eventName ) {
window.addEventListener( eventName, this );
}, this );
// save these arguments
this._boundPointerEvents = events;
};
proto._unbindPostStartEvents = function() {
// check for _boundEvents, in case dragEnd triggered twice (old IE8 bug)
if ( !this._boundPointerEvents ) {
return;
}
this._boundPointerEvents.forEach( function( eventName ) {
window.removeEventListener( eventName, this );
}, this );
delete this._boundPointerEvents;
};
// ----- move event ----- //
proto.onmousemove = function( event ) {
this._pointerMove( event, event );
};
proto.onMSPointerMove =
proto.onpointermove = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerMove( event, event );
}
};
proto.ontouchmove = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerMove( event, touch );
}
};
/**
* pointer move
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
proto._pointerMove = function( event, pointer ) {
this.pointerMove( event, pointer );
};
// public
proto.pointerMove = function( event, pointer ) {
this.emitEvent( 'pointerMove', [ event, pointer ] );
};
// ----- end event ----- //
proto.onmouseup = function( event ) {
this._pointerUp( event, event );
};
proto.onMSPointerUp =
proto.onpointerup = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerUp( event, event );
}
};
proto.ontouchend = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerUp( event, touch );
}
};
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
proto._pointerUp = function( event, pointer ) {
this._pointerDone();
this.pointerUp( event, pointer );
};
// public
proto.pointerUp = function( event, pointer ) {
this.emitEvent( 'pointerUp', [ event, pointer ] );
};
// ----- pointer done ----- //
// triggered on pointer up & pointer cancel
proto._pointerDone = function() {
// reset properties
this.isPointerDown = false;
delete this.pointerIdentifier;
// remove events
this._unbindPostStartEvents();
this.pointerDone();
};
proto.pointerDone = noop;
// ----- pointer cancel ----- //
proto.onMSPointerCancel =
proto.onpointercancel = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerCancel( event, event );
}
};
proto.ontouchcancel = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerCancel( event, touch );
}
};
/**
* pointer cancel
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
proto._pointerCancel = function( event, pointer ) {
this._pointerDone();
this.pointerCancel( event, pointer );
};
// public
proto.pointerCancel = function( event, pointer ) {
this.emitEvent( 'pointerCancel', [ event, pointer ] );
};
// ----- ----- //
// utility function for getting x/y coords from event
Unipointer.getPointerPoint = function( pointer ) {
return {
x: pointer.pageX,
y: pointer.pageY
};
};
// ----- ----- //
return Unipointer;
}));
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// prev/next buttons
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(16),
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Flickity, TapListener, utils ) {
return factory( window, Flickity, TapListener, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('./flickity'),
require('tap-listener'),
require('fizzy-ui-utils')
);
} else {
// browser global
factory(
window,
window.Flickity,
window.TapListener,
window.fizzyUIUtils
);
}
}( window, function factory( window, Flickity, TapListener, utils ) {
'use strict';
var svgURI = 'http://www.w3.org/2000/svg';
// -------------------------- PrevNextButton -------------------------- //
function PrevNextButton( direction, parent ) {
this.direction = direction;
this.parent = parent;
this._create();
}
PrevNextButton.prototype = new TapListener();
PrevNextButton.prototype._create = function() {
// properties
this.isEnabled = true;
this.isPrevious = this.direction == -1;
var leftDirection = this.parent.options.rightToLeft ? 1 : -1;
this.isLeft = this.direction == leftDirection;
var element = this.element = document.createElement('button');
element.className = 'flickity-prev-next-button';
element.className += this.isPrevious ? ' previous' : ' next';
// prevent button from submitting form http://stackoverflow.com/a/10836076/182183
element.setAttribute( 'type', 'button' );
// init as disabled
this.disable();
element.setAttribute( 'aria-label', this.isPrevious ? 'previous' : 'next' );
// create arrow
var svg = this.createSVG();
element.appendChild( svg );
// update on select
this.parent.on( 'select', function() {
this.update();
}.bind( this ));
// tap
this.on( 'tap', this.onTap );
// pointerDown
this.on( 'pointerDown', function onPointerDown( button, event ) {
this.parent.childUIPointerDown( event );
}.bind( this ));
};
PrevNextButton.prototype.activate = function() {
this.bindTap( this.element );
// click events from keyboard
this.element.addEventListener( 'click', this );
// add to DOM
this.parent.element.appendChild( this.element );
};
PrevNextButton.prototype.deactivate = function() {
// remove from DOM
this.parent.element.removeChild( this.element );
// do regular TapListener destroy
TapListener.prototype.destroy.call( this );
// click events from keyboard
this.element.removeEventListener( 'click', this );
};
PrevNextButton.prototype.createSVG = function() {
var svg = document.createElementNS( svgURI, 'svg');
svg.setAttribute( 'viewBox', '0 0 100 100' );
var path = document.createElementNS( svgURI, 'path');
var pathMovements = getArrowMovements( this.parent.options.arrowShape );
path.setAttribute( 'd', pathMovements );
path.setAttribute( 'class', 'arrow' );
// rotate arrow
if ( !this.isLeft ) {
path.setAttribute( 'transform', 'translate(100, 100) rotate(180) ' );
}
svg.appendChild( path );
return svg;
};
// get SVG path movmement
function getArrowMovements( shape ) {
// use shape as movement if string
if ( typeof shape == 'string' ) {
return shape;
}
// create movement string
return 'M ' + shape.x0 + ',50' +
' L ' + shape.x1 + ',' + ( shape.y1 + 50 ) +
' L ' + shape.x2 + ',' + ( shape.y2 + 50 ) +
' L ' + shape.x3 + ',50 ' +
' L ' + shape.x2 + ',' + ( 50 - shape.y2 ) +
' L ' + shape.x1 + ',' + ( 50 - shape.y1 ) +
' Z';
}
PrevNextButton.prototype.onTap = function() {
if ( !this.isEnabled ) {
return;
}
this.parent.uiChange();
var method = this.isPrevious ? 'previous' : 'next';
this.parent[ method ]();
};
PrevNextButton.prototype.handleEvent = utils.handleEvent;
PrevNextButton.prototype.onclick = function() {
// only allow clicks from keyboard
var focused = document.activeElement;
if ( focused && focused == this.element ) {
this.onTap();
}
};
// ----- ----- //
PrevNextButton.prototype.enable = function() {
if ( this.isEnabled ) {
return;
}
this.element.disabled = false;
this.isEnabled = true;
};
PrevNextButton.prototype.disable = function() {
if ( !this.isEnabled ) {
return;
}
this.element.disabled = true;
this.isEnabled = false;
};
PrevNextButton.prototype.update = function() {
// index of first or last slide, if previous or next
var slides = this.parent.slides;
// enable is wrapAround and at least 2 slides
if ( this.parent.options.wrapAround && slides.length > 1 ) {
this.enable();
return;
}
var lastIndex = slides.length ? slides.length - 1 : 0;
var boundIndex = this.isPrevious ? 0 : lastIndex;
var method = this.parent.selectedIndex == boundIndex ? 'disable' : 'enable';
this[ method ]();
};
PrevNextButton.prototype.destroy = function() {
this.deactivate();
};
// -------------------------- Flickity prototype -------------------------- //
utils.extend( Flickity.defaults, {
prevNextButtons: true,
arrowShape: {
x0: 10,
x1: 60, y1: 50,
x2: 70, y2: 40,
x3: 30
}
});
Flickity.createMethods.push('_createPrevNextButtons');
var proto = Flickity.prototype;
proto._createPrevNextButtons = function() {
if ( !this.options.prevNextButtons ) {
return;
}
this.prevButton = new PrevNextButton( -1, this );
this.nextButton = new PrevNextButton( 1, this );
this.on( 'activate', this.activatePrevNextButtons );
};
proto.activatePrevNextButtons = function() {
this.prevButton.activate();
this.nextButton.activate();
this.on( 'deactivate', this.deactivatePrevNextButtons );
};
proto.deactivatePrevNextButtons = function() {
this.prevButton.deactivate();
this.nextButton.deactivate();
this.off( 'deactivate', this.deactivatePrevNextButtons );
};
// -------------------------- -------------------------- //
Flickity.PrevNextButton = PrevNextButton;
return Flickity;
}));
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* Tap listener v2.0.0
* listens to taps
* MIT license
*/
/*jshint browser: true, unused: true, undef: true, strict: true */
( function( window, factory ) {
// universal module definition
/*jshint strict: false*/ /*globals define, module, require */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(14)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Unipointer ) {
return factory( window, Unipointer );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('unipointer')
);
} else {
// browser global
window.TapListener = factory(
window,
window.Unipointer
);
}
}( window, function factory( window, Unipointer ) {
'use strict';
// -------------------------- TapListener -------------------------- //
function TapListener( elem ) {
this.bindTap( elem );
}
// inherit Unipointer & EventEmitter
var proto = TapListener.prototype = Object.create( Unipointer.prototype );
/**
* bind tap event to element
* @param {Element} elem
*/
proto.bindTap = function( elem ) {
if ( !elem ) {
return;
}
this.unbindTap();
this.tapElement = elem;
this._bindStartEvent( elem, true );
};
proto.unbindTap = function() {
if ( !this.tapElement ) {
return;
}
this._bindStartEvent( this.tapElement, true );
delete this.tapElement;
};
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
*/
proto.pointerUp = function( event, pointer ) {
// ignore emulated mouse up clicks
if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {
return;
}
var pointerPoint = Unipointer.getPointerPoint( pointer );
var boundingRect = this.tapElement.getBoundingClientRect();
var scrollX = window.pageXOffset;
var scrollY = window.pageYOffset;
// calculate if pointer is inside tapElement
var isInside = pointerPoint.x >= boundingRect.left + scrollX &&
pointerPoint.x <= boundingRect.right + scrollX &&
pointerPoint.y >= boundingRect.top + scrollY &&
pointerPoint.y <= boundingRect.bottom + scrollY;
// trigger callback if pointer is inside element
if ( isInside ) {
this.emitEvent( 'tap', [ event, pointer ] );
}
// set flag for emulated clicks 300ms after touchend
if ( event.type != 'mouseup' ) {
this.isIgnoringMouseUp = true;
// reset flag after 300ms
var _this = this;
setTimeout( function() {
delete _this.isIgnoringMouseUp;
}, 400 );
}
};
proto.destroy = function() {
this.pointerDone();
this.unbindTap();
};
// ----- ----- //
return TapListener;
}));
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// page dots
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(16),
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Flickity, TapListener, utils ) {
return factory( window, Flickity, TapListener, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('./flickity'),
require('tap-listener'),
require('fizzy-ui-utils')
);
} else {
// browser global
factory(
window,
window.Flickity,
window.TapListener,
window.fizzyUIUtils
);
}
}( window, function factory( window, Flickity, TapListener, utils ) {
// -------------------------- PageDots -------------------------- //
'use strict';
function PageDots( parent ) {
this.parent = parent;
this._create();
}
PageDots.prototype = new TapListener();
PageDots.prototype._create = function() {
// create holder element
this.holder = document.createElement('ol');
this.holder.className = 'flickity-page-dots';
// create dots, array of elements
this.dots = [];
// tap
this.on( 'tap', this.onTap );
};
PageDots.prototype.activate = function() {
this.setDots();
this.bindTap( this.holder );
// add to DOM
this.parent.element.appendChild( this.holder );
};
PageDots.prototype.deactivate = function() {
// remove from DOM
this.parent.element.removeChild( this.holder );
TapListener.prototype.destroy.call( this );
};
PageDots.prototype.setDots = function() {
// get difference between number of slides and number of dots
var delta = this.parent.slides.length - this.dots.length;
if ( delta > 0 ) {
this.addDots( delta );
} else if ( delta < 0 ) {
this.removeDots( -delta );
}
};
PageDots.prototype.addDots = function( count ) {
var fragment = document.createDocumentFragment();
var newDots = [];
while ( count ) {
var dot = document.createElement('li');
dot.className = 'dot';
fragment.appendChild( dot );
newDots.push( dot );
count--;
}
this.holder.appendChild( fragment );
this.dots = this.dots.concat( newDots );
};
PageDots.prototype.removeDots = function( count ) {
// remove from this.dots collection
var removeDots = this.dots.splice( this.dots.length - count, count );
// remove from DOM
removeDots.forEach( function( dot ) {
this.holder.removeChild( dot );
}, this );
};
PageDots.prototype.updateSelected = function() {
// remove selected class on previous
if ( this.selectedDot ) {
this.selectedDot.className = 'dot';
}
// don't proceed if no dots
if ( !this.dots.length ) {
return;
}
this.selectedDot = this.dots[ this.parent.selectedIndex ];
this.selectedDot.className = 'dot is-selected';
};
PageDots.prototype.onTap = function( event ) {
var target = event.target;
// only care about dot clicks
if ( target.nodeName != 'LI' ) {
return;
}
this.parent.uiChange();
var index = this.dots.indexOf( target );
this.parent.select( index );
};
PageDots.prototype.destroy = function() {
this.deactivate();
};
Flickity.PageDots = PageDots;
// -------------------------- Flickity -------------------------- //
utils.extend( Flickity.defaults, {
pageDots: true
});
Flickity.createMethods.push('_createPageDots');
var proto = Flickity.prototype;
proto._createPageDots = function() {
if ( !this.options.pageDots ) {
return;
}
this.pageDots = new PageDots( this );
// events
this.on( 'activate', this.activatePageDots );
this.on( 'select', this.updateSelectedPageDots );
this.on( 'cellChange', this.updatePageDots );
this.on( 'resize', this.updatePageDots );
this.on( 'deactivate', this.deactivatePageDots );
this.pageDots.on( 'pointerDown', function( event ) {
this.childUIPointerDown( event );
}.bind( this ));
};
proto.activatePageDots = function() {
this.pageDots.activate();
};
proto.updateSelectedPageDots = function() {
this.pageDots.updateSelected();
};
proto.updatePageDots = function() {
this.pageDots.setDots();
};
proto.deactivatePageDots = function() {
this.pageDots.deactivate();
};
// ----- ----- //
Flickity.PageDots = PageDots;
return Flickity;
}));
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// player & autoPlay
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(5),
__webpack_require__(7),
__webpack_require__(4)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( EvEmitter, utils, Flickity ) {
return factory( EvEmitter, utils, Flickity );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
require('ev-emitter'),
require('fizzy-ui-utils'),
require('./flickity')
);
} else {
// browser global
factory(
window.EvEmitter,
window.fizzyUIUtils,
window.Flickity
);
}
}( window, function factory( EvEmitter, utils, Flickity ) {
'use strict';
// -------------------------- Page Visibility -------------------------- //
// https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API
var hiddenProperty, visibilityEvent;
if ( 'hidden' in document ) {
hiddenProperty = 'hidden';
visibilityEvent = 'visibilitychange';
} else if ( 'webkitHidden' in document ) {
hiddenProperty = 'webkitHidden';
visibilityEvent = 'webkitvisibilitychange';
}
// -------------------------- Player -------------------------- //
function Player( parent ) {
this.parent = parent;
this.state = 'stopped';
// visibility change event handler
if ( visibilityEvent ) {
this.onVisibilityChange = function() {
this.visibilityChange();
}.bind( this );
this.onVisibilityPlay = function() {
this.visibilityPlay();
}.bind( this );
}
}
Player.prototype = Object.create( EvEmitter.prototype );
// start play
Player.prototype.play = function() {
if ( this.state == 'playing' ) {
return;
}
// do not play if page is hidden, start playing when page is visible
var isPageHidden = document[ hiddenProperty ];
if ( visibilityEvent && isPageHidden ) {
document.addEventListener( visibilityEvent, this.onVisibilityPlay );
return;
}
this.state = 'playing';
// listen to visibility change
if ( visibilityEvent ) {
document.addEventListener( visibilityEvent, this.onVisibilityChange );
}
// start ticking
this.tick();
};
Player.prototype.tick = function() {
// do not tick if not playing
if ( this.state != 'playing' ) {
return;
}
var time = this.parent.options.autoPlay;
// default to 3 seconds
time = typeof time == 'number' ? time : 3000;
var _this = this;
// HACK: reset ticks if stopped and started within interval
this.clear();
this.timeout = setTimeout( function() {
_this.parent.next( true );
_this.tick();
}, time );
};
Player.prototype.stop = function() {
this.state = 'stopped';
this.clear();
// remove visibility change event
if ( visibilityEvent ) {
document.removeEventListener( visibilityEvent, this.onVisibilityChange );
}
};
Player.prototype.clear = function() {
clearTimeout( this.timeout );
};
Player.prototype.pause = function() {
if ( this.state == 'playing' ) {
this.state = 'paused';
this.clear();
}
};
Player.prototype.unpause = function() {
// re-start play if paused
if ( this.state == 'paused' ) {
this.play();
}
};
// pause if page visibility is hidden, unpause if visible
Player.prototype.visibilityChange = function() {
var isPageHidden = document[ hiddenProperty ];
this[ isPageHidden ? 'pause' : 'unpause' ]();
};
Player.prototype.visibilityPlay = function() {
this.play();
document.removeEventListener( visibilityEvent, this.onVisibilityPlay );
};
// -------------------------- Flickity -------------------------- //
utils.extend( Flickity.defaults, {
pauseAutoPlayOnHover: true
});
Flickity.createMethods.push('_createPlayer');
var proto = Flickity.prototype;
proto._createPlayer = function() {
this.player = new Player( this );
this.on( 'activate', this.activatePlayer );
this.on( 'uiChange', this.stopPlayer );
this.on( 'pointerDown', this.stopPlayer );
this.on( 'deactivate', this.deactivatePlayer );
};
proto.activatePlayer = function() {
if ( !this.options.autoPlay ) {
return;
}
this.player.play();
this.element.addEventListener( 'mouseenter', this );
};
// Player API, don't hate the ... thanks I know where the door is
proto.playPlayer = function() {
this.player.play();
};
proto.stopPlayer = function() {
this.player.stop();
};
proto.pausePlayer = function() {
this.player.pause();
};
proto.unpausePlayer = function() {
this.player.unpause();
};
proto.deactivatePlayer = function() {
this.player.stop();
this.element.removeEventListener( 'mouseenter', this );
};
// ----- mouseenter/leave ----- //
// pause auto-play on hover
proto.onmouseenter = function() {
if ( !this.options.pauseAutoPlayOnHover ) {
return;
}
this.player.pause();
this.element.addEventListener( 'mouseleave', this );
};
// resume auto-play on hover off
proto.onmouseleave = function() {
this.player.unpause();
this.element.removeEventListener( 'mouseleave', this );
};
// ----- ----- //
Flickity.Player = Player;
return Flickity;
}));
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// add, remove cell
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Flickity, utils ) {
return factory( window, Flickity, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('./flickity'),
require('fizzy-ui-utils')
);
} else {
// browser global
factory(
window,
window.Flickity,
window.fizzyUIUtils
);
}
}( window, function factory( window, Flickity, utils ) {
'use strict';
// append cells to a document fragment
function getCellsFragment( cells ) {
var fragment = document.createDocumentFragment();
cells.forEach( function( cell ) {
fragment.appendChild( cell.element );
});
return fragment;
}
// -------------------------- add/remove cell prototype -------------------------- //
var proto = Flickity.prototype;
/**
* Insert, prepend, or append cells
* @param {Element, Array, NodeList} elems
* @param {Integer} index
*/
proto.insert = function( elems, index ) {
var cells = this._makeCells( elems );
if ( !cells || !cells.length ) {
return;
}
var len = this.cells.length;
// default to append
index = index === undefined ? len : index;
// add cells with document fragment
var fragment = getCellsFragment( cells );
// append to slider
var isAppend = index == len;
if ( isAppend ) {
this.slider.appendChild( fragment );
} else {
var insertCellElement = this.cells[ index ].element;
this.slider.insertBefore( fragment, insertCellElement );
}
// add to this.cells
if ( index === 0 ) {
// prepend, add to start
this.cells = cells.concat( this.cells );
} else if ( isAppend ) {
// append, add to end
this.cells = this.cells.concat( cells );
} else {
// insert in this.cells
var endCells = this.cells.splice( index, len - index );
this.cells = this.cells.concat( cells ).concat( endCells );
}
this._sizeCells( cells );
var selectedIndexDelta = index > this.selectedIndex ? 0 : cells.length;
this._cellAddedRemoved( index, selectedIndexDelta );
};
proto.append = function( elems ) {
this.insert( elems, this.cells.length );
};
proto.prepend = function( elems ) {
this.insert( elems, 0 );
};
/**
* Remove cells
* @param {Element, Array, NodeList} elems
*/
proto.remove = function( elems ) {
var cells = this.getCells( elems );
var selectedIndexDelta = 0;
var len = cells.length;
var i, cell;
// calculate selectedIndexDelta, easier if done in seperate loop
for ( i=0; i < len; i++ ) {
cell = cells[i];
var wasBefore = this.cells.indexOf( cell ) < this.selectedIndex;
selectedIndexDelta -= wasBefore ? 1 : 0;
}
for ( i=0; i < len; i++ ) {
cell = cells[i];
cell.remove();
// remove item from collection
utils.removeFrom( this.cells, cell );
}
if ( cells.length ) {
// update stuff
this._cellAddedRemoved( 0, selectedIndexDelta );
}
};
// updates when cells are added or removed
proto._cellAddedRemoved = function( changedCellIndex, selectedIndexDelta ) {
// TODO this math isn't perfect with grouped slides
selectedIndexDelta = selectedIndexDelta || 0;
this.selectedIndex += selectedIndexDelta;
this.selectedIndex = Math.max( 0, Math.min( this.slides.length - 1, this.selectedIndex ) );
this.cellChange( changedCellIndex, true );
// backwards compatibility
this.emitEvent( 'cellAddedRemoved', [ changedCellIndex, selectedIndexDelta ] );
};
/**
* logic to be run after a cell's size changes
* @param {Element} elem - cell's element
*/
proto.cellSizeChange = function( elem ) {
var cell = this.getCell( elem );
if ( !cell ) {
return;
}
cell.getSize();
var index = this.cells.indexOf( cell );
this.cellChange( index );
};
/**
* logic any time a cell is changed: added, removed, or size changed
* @param {Integer} changedCellIndex - index of the changed cell, optional
*/
proto.cellChange = function( changedCellIndex, isPositioningSlider ) {
var prevSlideableWidth = this.slideableWidth;
this._positionCells( changedCellIndex );
this._getWrapShiftCells();
this.setGallerySize();
this.emitEvent( 'cellChange', [ changedCellIndex ] );
// position slider
if ( this.options.freeScroll ) {
// shift x by change in slideableWidth
// TODO fix position shifts when prepending w/ freeScroll
var deltaX = prevSlideableWidth - this.slideableWidth;
this.x += deltaX * this.cellAlign;
this.positionSlider();
} else {
// do not position slider after lazy load
if ( isPositioningSlider ) {
this.positionSliderAtSelected();
}
this.select( this.selectedIndex );
}
};
// ----- ----- //
return Flickity;
}));
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// lazyload
( function( window, factory ) {
// universal module definition
/* jshint strict: false */
if ( true ) {
// AMD
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
__webpack_require__(4),
__webpack_require__(7)
], __WEBPACK_AMD_DEFINE_RESULT__ = function( Flickity, utils ) {
return factory( window, Flickity, utils );
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('./flickity'),
require('fizzy-ui-utils')
);
} else {
// browser global
factory(
window,
window.Flickity,
window.fizzyUIUtils
);
}
}( window, function factory( window, Flickity, utils ) {
'use strict';
Flickity.createMethods.push('_createLazyload');
var proto = Flickity.prototype;
proto._createLazyload = function() {
this.on( 'select', this.lazyLoad );
};
proto.lazyLoad = function() {
var lazyLoad = this.options.lazyLoad;
if ( !lazyLoad ) {
return;
}
// get adjacent cells, use lazyLoad option for adjacent count
var adjCount = typeof lazyLoad == 'number' ? lazyLoad : 0;
var cellElems = this.getAdjacentCellElements( adjCount );
// get lazy images in those cells
var lazyImages = [];
cellElems.forEach( function( cellElem ) {
var lazyCellImages = getCellLazyImages( cellElem );
lazyImages = lazyImages.concat( lazyCellImages );
});
// load lazy images
lazyImages.forEach( function( img ) {
new LazyLoader( img, this );
}, this );
};
function getCellLazyImages( cellElem ) {
// check if cell element is lazy image
if ( cellElem.nodeName == 'IMG' &&
cellElem.getAttribute('data-flickity-lazyload') ) {
return [ cellElem ];
}
// select lazy images in cell
var imgs = cellElem.querySelectorAll('img[data-flickity-lazyload]');
return utils.makeArray( imgs );
}
// -------------------------- LazyLoader -------------------------- //
/**
* class to handle loading images
*/
function LazyLoader( img, flickity ) {
this.img = img;
this.flickity = flickity;
this.load();
}
LazyLoader.prototype.handleEvent = utils.handleEvent;
LazyLoader.prototype.load = function() {
this.img.addEventListener( 'load', this );
this.img.addEventListener( 'error', this );
// load image
this.img.src = this.img.getAttribute('data-flickity-lazyload');
// remove attr
this.img.removeAttribute('data-flickity-lazyload');
};
LazyLoader.prototype.onload = function( event ) {
this.complete( event, 'flickity-lazyloaded' );
};
LazyLoader.prototype.onerror = function( event ) {
this.complete( event, 'flickity-lazyerror' );
};
LazyLoader.prototype.complete = function( event, className ) {
// unbind events
this.img.removeEventListener( 'load', this );
this.img.removeEventListener( 'error', this );
var cell = this.flickity.getParentCell( this.img );
var cellElem = cell && cell.element;
this.flickity.cellSizeChange( cellElem );
this.img.classList.add( className );
this.flickity.dispatchEvent( 'lazyLoad', event, cellElem );
};
// ----- ----- //
Flickity.LazyLoader = LazyLoader;
return Flickity;
}));
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _jquery = __webpack_require__(1);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Fixed = function () {
function Fixed(selector) {
_classCallCheck(this, Fixed);
this.element = (0, _jquery2.default)(selector);
this.win = (0, _jquery2.default)(window);
this.eltop = this.element.offset().top;
}
_createClass(Fixed, [{
key: 'init',
value: function init() {
this.bindEvents();
}
}, {
key: 'bindEvents',
value: function bindEvents() {
var _this = this;
this.win.on('scroll', function (e) {
_this.handleScroll(e);
});
}
}, {
key: 'handleScroll',
value: function handleScroll(e) {
var wintop = this.win.scrollTop();
if (wintop >= this.eltop) {
var position = wintop - this.eltop;
this.setPosition(position);
} else {
this.setPosition(0);
}
}
}, {
key: 'setPosition',
value: function setPosition(top) {
this.element.css({ transform: 'translateY(' + top + 'px)' });
}
}]);
return Fixed;
}();
exports.default = Fixed;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = load;
var _jquery = __webpack_require__(1);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var $newsWrapper = (0, _jquery2.default)('#timeline');
var $newsTamplate = ' <article class="new">\n <div class="banner">\n <img src="{{bannerImage}}"></img>\n </div>\n <h1 class="title">{{title}}</h1>\n <p class="content">\n {{content}}\n </p>\n <div class="actions">\n <a href="/project/readmore.html?id={{id}}" class="btn -compact readmore">Read more.</a>\n </div>\n </article>';
var $featuredNewsWrapper = (0, _jquery2.default)('[data-id="main-carrousel"]');
var $featuredNewsTemplate = ' <figure class="new">\n <img src="{{bannerImage}}">\n <figcaption>{{content}}<a href="/project/readmore.html?id={{id}}"> Read more.</a></figcaption>\n \n </figure>';
function render($wrapper, $template, data) {
var $news = data.map(function (val) {
var keys = Object.keys(val);
var html = $template;
keys.forEach(function (key) {
html = html.replace('{{' + key + '}}', val[key]);
});
return html;
});
$wrapper.html($news);
}
function getFeaturedNews(news) {
return news.slice(0, 2);
}
function getNews(news) {
return news.slice(2, news.length);
}
function load(url, cb) {
_jquery2.default.get(url).then(function (data) {
if (typeof data === "string") {
data = JSON.parse(data);
}
var feterednews = getFeaturedNews(data);
var news = getNews(data);
render($featuredNewsWrapper, $featuredNewsTemplate, feterednews);
render($newsWrapper, $newsTamplate, news);
cb(data);
});
}
/***/ }
/******/ ]);
//# sourceMappingURL=bundle.main.js.map |
import resolve from 'rollup-plugin-node-resolve';
export default {
input: './src/index.js',
output: {
file: 'public/game.js',
format: 'iife',
},
plugins: [
resolve(),
],
};
|
#pragma once
/*
The MIT License (MIT)
Copyright (c) 2015 Dennis Wandschura
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.
*/
struct EntityActor;
#include "Steering.h"
struct Seek : public Steering
{
EntityActor* m_entity;
vx::float3 m_targetPosition;
f32 m_maxAcceleration;
Seek(EntityActor* entity, const vx::float3 &target, f32 maxAccel);
void setTarget(const vx::float3 &target);
bool getSteering(SteeringOutput* output) override;
}; |
#!/usr/bin/env python
class Base_check:
sender_data = dict()
def _get_conf(self):
'''Run config parser'''
from mon_conf import Get_conf
self.conf = Get_conf(self.args).run()
def _send(self):
'''Run zabbix sender'''
from mon_sender import Mon_sender
Mon_sender(self.args, self.sender_data).run()
def _discovery(self):
'''Run discovery'''
from mon_discovery import Mon_discovery
Mon_discovery(self.args, self.sender_data).run()
|
# Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Experimental `dataset` API for parsing example."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import structure
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import gen_experimental_dataset_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.python.util.tf_export import tf_export
class _ParseExampleDataset(dataset_ops.UnaryDataset):
"""A `Dataset` that parses `example` dataset into a `dict` dataset."""
def __init__(self, input_dataset, features, num_parallel_calls):
super(_ParseExampleDataset, self).__init__(input_dataset)
self._input_dataset = input_dataset
if not input_dataset._element_structure.is_compatible_with( # pylint: disable=protected-access
structure.TensorStructure(dtypes.string, [None])):
raise TypeError("Input dataset should be a dataset of vectors of strings")
self._num_parallel_calls = num_parallel_calls
# pylint: disable=protected-access
self._features = parsing_ops._prepend_none_dimension(features)
# sparse_keys and dense_keys come back sorted here.
(sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,
dense_shapes) = parsing_ops._features_to_raw_params(
self._features, [
parsing_ops.VarLenFeature, parsing_ops.SparseFeature,
parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature
])
# TODO(b/112859642): Pass sparse_index and sparse_values for SparseFeature.
(_, dense_defaults_vec, sparse_keys, sparse_types, dense_keys, dense_shapes,
dense_shape_as_shape) = parsing_ops._process_raw_parameters(
None, dense_defaults, sparse_keys, sparse_types, dense_keys,
dense_types, dense_shapes)
# pylint: enable=protected-access
self._sparse_keys = sparse_keys
self._sparse_types = sparse_types
self._dense_keys = dense_keys
self._dense_defaults = dense_defaults_vec
self._dense_shapes = dense_shapes
self._dense_types = dense_types
dense_output_shapes = [
self._input_dataset.output_shapes.concatenate(shape)
for shape in dense_shape_as_shape
]
sparse_output_shapes = [
self._input_dataset.output_shapes.concatenate([None])
for _ in range(len(sparse_keys))
]
output_shapes = dict(
zip(self._dense_keys + self._sparse_keys,
dense_output_shapes + sparse_output_shapes))
output_types = dict(
zip(self._dense_keys + self._sparse_keys,
self._dense_types + self._sparse_types))
output_classes = dict(
zip(self._dense_keys + self._sparse_keys,
[ops.Tensor for _ in range(len(self._dense_defaults))] +
[sparse_tensor.SparseTensor for _ in range(len(self._sparse_keys))
]))
self._structure = structure.convert_legacy_structure(
output_types, output_shapes, output_classes)
def _as_variant_tensor(self):
return gen_experimental_dataset_ops.experimental_parse_example_dataset(
self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access
self._num_parallel_calls,
self._dense_defaults,
self._sparse_keys,
self._dense_keys,
self._sparse_types,
self._dense_shapes,
**dataset_ops.flat_structure(self))
@property
def _element_structure(self):
return self._structure
# TODO(b/111553342): add arguments names and example names as well.
@tf_export("data.experimental.parse_example_dataset")
def parse_example_dataset(features, num_parallel_calls=1):
"""A transformation that parses `Example` protos into a `dict` of tensors.
Parses a number of serialized `Example` protos given in `serialized`. We refer
to `serialized` as a batch with `batch_size` many entries of individual
`Example` protos.
This op parses serialized examples into a dictionary mapping keys to `Tensor`
and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature`,
`SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature`
and `SparseFeature` is mapped to a `SparseTensor`, and each
`FixedLenFeature` is mapped to a `Tensor`. See `tf.parse_example` for more
details about feature dictionaries.
Args:
features: A `dict` mapping feature keys to `FixedLenFeature`,
`VarLenFeature`, and `SparseFeature` values.
num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,
representing the number of parsing processes to call in parallel.
Returns:
A dataset transformation function, which can be passed to
`tf.data.Dataset.apply`.
Raises:
ValueError: if features argument is None.
"""
if features is None:
raise ValueError("Missing: features was %s." % features)
def _apply_fn(dataset):
"""Function from `Dataset` to `Dataset` that applies the transformation."""
out_dataset = _ParseExampleDataset(dataset, features, num_parallel_calls)
if any(
isinstance(feature, parsing_ops.SparseFeature)
for _, feature in features.items()
):
# pylint: disable=protected-access
# pylint: disable=g-long-lambda
out_dataset = out_dataset.map(
lambda x: parsing_ops._construct_sparse_tensors_for_sparse_features(
features, x), num_parallel_calls=num_parallel_calls)
return out_dataset
return _apply_fn
|
/* jshint browser: true */
/* jshint unused: false */
/* global describe, beforeEach, afterEach, it, spyOn, expect*/
/* global $, jasmine*/
(function () {
'use strict';
describe('foxx Model', function () {
it('is sorted by mount', function () {
expect(window.Foxx.prototype.idAttribute).toEqual('mount');
});
it("can return it's mount url-encoded", function () {
var testMount = '/this/is_/a/test/mount';
var expected = encodeURIComponent(testMount);
var myFoxx = new window.Foxx({
mount: testMount
});
expect(myFoxx.encodedMount()).toEqual(expected);
});
it('verifies defaults', function () {
var myFoxx = new window.Foxx();
expect(myFoxx.get('name')).toEqual('');
expect(myFoxx.get('version')).toEqual('Unknown Version');
expect(myFoxx.get('description')).toEqual('No description');
expect(myFoxx.get('git')).toEqual('');
expect(myFoxx.get('isSystem')).toBeFalsy();
expect(myFoxx.get('development')).toBeFalsy();
});
it('is always considered new', function () {
var myFoxx = new window.Foxx();
expect(myFoxx.isNew()).toBeFalsy();
});
it('system apps should know it', function () {
var myFoxx = new window.Foxx({
system: true
});
expect(myFoxx.isSystem()).toBeTruthy();
});
it('non system apps should know it', function () {
var myFoxx = new window.Foxx({
system: false
});
expect(myFoxx.isSystem()).toBeFalsy();
});
describe('mode chages', function () {
var myFoxx, expected, call;
beforeEach(function () {
var testMount = '/this/is_/a/test/mount';
myFoxx = new window.Foxx({
mount: testMount
});
expected = {
value: false
};
call = {
back: function () {
throw new Error('Should be a spy');
}
};
spyOn($, 'ajax').andCallFake(function (opts) {
expect(opts.url).toEqual('/_admin/aardvark/foxxes/devel?mount=' + myFoxx.encodedMount());
expect(opts.type).toEqual('PATCH');
expect(opts.success).toEqual(jasmine.any(Function));
expect(opts.error).toEqual(jasmine.any(Function));
expect(opts.data).toEqual(JSON.stringify(expected.value));
opts.success();
});
spyOn(call, 'back');
});
it('should activate production mode', function () {
myFoxx.set('development', true);
expected.value = false;
myFoxx.toggleDevelopment(false, call.back);
expect($.ajax).toHaveBeenCalled();
expect(call.back).toHaveBeenCalled();
expect(myFoxx.get('development')).toEqual(false);
});
it('should activate development mode', function () {
myFoxx.set('development', false);
expected.value = true;
myFoxx.toggleDevelopment(true, call.back);
expect($.ajax).toHaveBeenCalled();
expect(call.back).toHaveBeenCalled();
expect(myFoxx.get('development')).toEqual(true);
});
});
describe('configuration', function () {
var myFoxx;
beforeEach(function () {
var testMount = '/this/is_/a/test/mount';
myFoxx = new window.Foxx({
mount: testMount
});
});
it('can be read', function () {
var data = {
opt1: {
type: 'string',
description: 'Option description',
default: 'empty',
current: 'empty'
}
};
spyOn($, 'ajax').andCallFake(function (opts) {
expect(opts.url).toEqual('/_admin/aardvark/foxxes/config?mount=' + myFoxx.encodedMount());
expect(opts.type).toEqual('GET');
expect(opts.success).toEqual(jasmine.any(Function));
expect(opts.error).toEqual(jasmine.any(Function));
opts.success(data);
});
myFoxx.getConfiguration(function (result) {
expect(result).toEqual(data);
});
expect($.ajax).toHaveBeenCalled();
});
it('can be saved', function () {
var data = {
opt1: 'empty'
};
var call = {
back: function () {
throw new Error('Should be a spy.');
}
};
spyOn($, 'ajax').andCallFake(function (opts) {
expect(opts.url).toEqual('/_admin/aardvark/foxxes/config?mount=' + myFoxx.encodedMount());
expect(opts.type).toEqual('PATCH');
expect(opts.data).toEqual(JSON.stringify(data));
expect(opts.success).toEqual(jasmine.any(Function));
expect(opts.error).toEqual(jasmine.any(Function));
opts.success(data);
});
spyOn(call, 'back');
myFoxx.setConfiguration(data, call.back);
expect($.ajax).toHaveBeenCalled();
expect(call.back).toHaveBeenCalled();
});
});
it('should be able to trigger setup', function () {
var testMount = '/this/is_/a/test/mount';
var data = true;
var myFoxx = new window.Foxx({
mount: testMount
});
spyOn($, 'ajax').andCallFake(function (opts) {
expect(opts.url).toEqual('/_admin/aardvark/foxxes/setup?mount=' + myFoxx.encodedMount());
expect(opts.type).toEqual('PATCH');
expect(opts.success).toEqual(jasmine.any(Function));
expect(opts.error).toEqual(jasmine.any(Function));
opts.success(data);
});
myFoxx.setup(function (result) {
expect(result).toEqual(data);
});
expect($.ajax).toHaveBeenCalled();
});
it('should be able to trigger teardown', function () {
var testMount = '/this/is_/a/test/mount';
var data = true;
var myFoxx = new window.Foxx({
mount: testMount
});
spyOn($, 'ajax').andCallFake(function (opts) {
expect(opts.url).toEqual('/_admin/aardvark/foxxes/teardown?mount=' + myFoxx.encodedMount());
expect(opts.type).toEqual('PATCH');
expect(opts.success).toEqual(jasmine.any(Function));
expect(opts.error).toEqual(jasmine.any(Function));
opts.success(data);
});
myFoxx.teardown(function (result) {
expect(result).toEqual(data);
});
expect($.ajax).toHaveBeenCalled();
});
it('should be able to download', function () {
var testMount = '/this/is/a/test/mount';
spyOn(window, 'open');
var dbName = 'foxx';
spyOn(window.arango, 'getDatabaseName').andReturn(dbName);
var myFoxx = new window.Foxx({
mount: testMount
});
myFoxx.download();
expect(window.open).toHaveBeenCalledWith(
'/_db/' + dbName + '/_admin/aardvark/foxxes/download/zip?mount=' + myFoxx.encodedMount()
);
});
});
}());
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.34/esri/copyright.txt for details.
//>>built
define("esri/dijit/analysis/nls/nl/BuildMultiVariablesList",{chooseInputLayer:"Kies een invoerlaag",addAVar:"Voeg een variabele toe",distToNearest:"Afstand tot het dichtstbijzijnde",attrOfInterest:"Attribuut van het dichtstbijzijnde",summaryNearby:"Samenvatting van dichtbij",summaryIntersecting:"Samenvatting van de intersectie",distToNearestLabel:"De afstand van het centrum van de bin naar het dichtstbijzijnde object in de invoerlaag",attrOfInterestLabel:"De waarde van een gespecificeerd veld van het dichtstbijzijnde object van de invoerlaag",
summaryNearbyLabel:"Een statistiek die berekend is van alle objecten die gevonden zijn binnen de gespecificeerde afstand van het centrum van de bin",summaryIntersectingLabel:"Een statistiek berekend op basis van alle objecten die de bin kruisen",maxDistancefromCtr:"Maximumafstand van het centrum van de bin",fieldToIncude:"Veld dat inbegrepen moet worden",statstoCalculate:"Statistiek om te berekenen",summFeatuesWithin:"Maak een samenvatting van de objecten binnen",layerChangeWarnMsg:"De toegevoegde variabelen voor deze invoerlaag zullen worden verwijderd als de invoerlaag veranderd wordt",
validationErrorMsg:"Herstel de validatiefouten voordat u een nieuwe variabele toevoegt",atleastOneVarMsg:"Voeg ten minste een variabele toe aan deze geselecteerde laag"}); |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_WEBSTORE_WEBSTORE_RESULT_H_
#define CHROME_BROWSER_UI_APP_LIST_SEARCH_WEBSTORE_WEBSTORE_RESULT_H_
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/extensions/install_observer.h"
#include "chrome/common/extensions/webstore_install_result.h"
#include "extensions/browser/extension_registry_observer.h"
#include "extensions/common/manifest.h"
#include "ui/app_list/search_result.h"
#include "url/gurl.h"
class AppListControllerDelegate;
class Profile;
namespace extensions {
class ExtensionRegistry;
class InstallTracker;
}
namespace app_list {
class WebstoreResult : public SearchResult,
public extensions::InstallObserver,
public extensions::ExtensionRegistryObserver {
public:
WebstoreResult(Profile* profile,
const std::string& app_id,
const GURL& icon_url,
bool is_paid,
extensions::Manifest::Type item_type,
AppListControllerDelegate* controller);
~WebstoreResult() override;
const std::string& app_id() const { return app_id_; }
const GURL& icon_url() const { return icon_url_; }
extensions::Manifest::Type item_type() const { return item_type_; }
bool is_paid() const { return is_paid_; }
// SearchResult overrides:
void Open(int event_flags) override;
void InvokeAction(int action_index, int event_flags) override;
scoped_ptr<SearchResult> Duplicate() const override;
private:
// Set the initial state and start observing both InstallObserver and
// ExtensionRegistryObserver.
void InitAndStartObserving();
void UpdateActions();
void SetDefaultDetails();
void OnIconLoaded();
void StartInstall();
void InstallCallback(bool success,
const std::string& error,
extensions::webstore_install::Result result);
void LaunchCallback(extensions::webstore_install::Result result,
const std::string& error);
void StopObservingInstall();
void StopObservingRegistry();
// extensions::InstallObserver overrides:
void OnDownloadProgress(const std::string& extension_id,
int percent_downloaded) override;
void OnShutdown() override;
// extensions::ExtensionRegistryObserver overides:
void OnExtensionInstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
bool is_update) override;
void OnShutdown(extensions::ExtensionRegistry* registry) override;
Profile* profile_;
const std::string app_id_;
const GURL icon_url_;
const bool is_paid_;
extensions::Manifest::Type item_type_;
gfx::ImageSkia icon_;
AppListControllerDelegate* controller_;
extensions::InstallTracker* install_tracker_; // Not owned.
extensions::ExtensionRegistry* extension_registry_; // Not owned.
base::WeakPtrFactory<WebstoreResult> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WebstoreResult);
};
} // namespace app_list
#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_WEBSTORE_WEBSTORE_RESULT_H_
|
from abc import ABC, abstractmethod
from collections import Counter
from itertools import combinations
from typing import List
from model.chord_formulas import (DOM7Chord, DOM9Chord, DOM11Chord, DOM13Chord,
MAJChord, MINChord)
from model.dt_def import Transition, TransitionContext
from model.satb_elements import AbstractNote, Note
from model.solver_config import get_config
class AbstractRule(ABC):
@classmethod
@abstractmethod
def validate(cls, *args, **kwargs):
raise NotImplementedError
class AllNotesMatchedRule(AbstractRule):
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that all voices are matched
return len(matchings) == get_config()['voice_count']
class ValidParallelIntervalRule(AbstractRule):
VALID_PARALLEL_INTERVALS = {3, 4, 8, 9}
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that the solution does not contain any illegal parallel intervals
for trans_pair in combinations(matchings, 2):
lower_trans, upper_trans = trans_pair[0], trans_pair[1]
if (
(
(upper_trans.next_abs_pos - lower_trans.next_abs_pos) % 12 ==
(upper_trans.cur_abs_pos - lower_trans.cur_abs_pos) % 12
) &
(
(upper_trans.next_abs_pos - lower_trans.next_abs_pos)
not in cls.VALID_PARALLEL_INTERVALS
) & lower_trans.abs_pos_changed
):
return False
return True
class VoicesNotExceedingOctaveNorCrossingRule(AbstractRule):
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that the voices do not exceed an octave apart nor have perfect unisons
# nor cross each other
for i in range(1, len(matchings)):
lower_trans = matchings[i - 1]
upper_trans = matchings[i]
if (
(upper_trans.next_abs_pos - lower_trans.next_abs_pos <= 0) |
(upper_trans.next_abs_pos - lower_trans.next_abs_pos > 12)
):
return False
return True
class VoicesWithinRangeRule(AbstractRule):
SOP_RANGE = (Note(AbstractNote('C'), 4), Note(AbstractNote('C'), 6)) # Soprano
MS_RANGE = (Note(AbstractNote('A'), 3), Note(AbstractNote('G'), 5)) # Mezzo Soprano
ALT_RANGE = (Note(AbstractNote('F'), 3), Note(AbstractNote('D'), 5)) # Alto
TEN_RANGE = (Note(AbstractNote('C'), 3), Note(AbstractNote('A'), 4)) # Tenor
BAR_RANGE = (Note(AbstractNote('G'), 2), Note(AbstractNote('F'), 4)) # Baritone
BASS_RANGE = (Note(AbstractNote('E'), 2), Note(AbstractNote('E'), 4)) # Bass
FOUR_VOICES = [BASS_RANGE, TEN_RANGE, ALT_RANGE, SOP_RANGE]
FIVE_VOICES = [BASS_RANGE, BAR_RANGE, TEN_RANGE, ALT_RANGE, SOP_RANGE]
SIX_VOICES = [BASS_RANGE, BAR_RANGE, TEN_RANGE, ALT_RANGE, MS_RANGE, SOP_RANGE]
@classmethod
def _is_within_range(cls, pos, voice_range):
return (pos >= voice_range[0].abs_pos & pos <= voice_range[1].abs_pos)
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that each voice is within range
voices = None
if len(matchings) == 4:
voices = cls.FOUR_VOICES
elif len(matchings) == 5:
voices = cls.FIVE_VOICES
elif len(matchings) == 6:
voices = cls.SIX_VOICES
for trans, voice_range in zip(matchings, voices):
if not cls._is_within_range(trans.next_abs_pos, voice_range):
return False
return True
class DominantNotesResolvingRule(AbstractRule):
DOM_TOL = {
3: {*range(0, 2)},
7: {*range(0, -3, -1)},
9: {*range(0, -3, -1)},
11: {0},
13: {*range(0, -5, -1)}
}
SUS_TOL = {
2: {*range(1, 3)},
4: {*range(-1, -3, -1)}
}
@classmethod
def _is_within_tolerance(cls, trans, tolerance_set):
if trans.cur_scale_pos in tolerance_set:
if (
(trans.next_abs_pos - trans.cur_abs_pos)
not in tolerance_set[trans.cur_scale_pos]
):
return False
return True
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that dominant and sustained notes in specific chords resolve properly
cur_chord = transition_context.cur_satb_chord
if any(type(cur_chord.chord_formula) is chord_type
for chord_type in (DOM7Chord, DOM9Chord, DOM11Chord, DOM13Chord)):
for trans in matchings:
if not cls._is_within_tolerance(trans, cls.DOM_TOL):
return False
for trans in matchings:
if not cls._is_within_tolerance(trans, cls.SUS_TOL):
return False
return True
class AcceptableNoteFrequenciesRule(AbstractRule):
@classmethod
def validate(cls, matchings: List[Transition], transition_context: TransitionContext):
# Ensure that the chord has proper note frequencies
pos_counter = Counter()
for trans in matchings:
pos_counter[trans.next_scale_pos] += 1
# This is an exception reserved for when DOM7 resolves to tonic
exc = (
(
any(
type(transition_context.cur_chord_formula) is chord_type
for chord_type in (DOM7Chord, DOM11Chord, DOM13Chord)
)
) &
(
any(
type(transition_context.next_chord_formula) is chord_type
for chord_type in (MAJChord, MINChord)
)
)
)
freq_tol = transition_context.next_satb_chord.chord_formula.get_note_freqs(exc)
for pos, freq_range in freq_tol.items():
if (
(pos_counter.get(pos, 0) < freq_range.min_freq) |
(pos_counter.get(pos, 0) > freq_range.max_freq)
):
return False
return True
|
/* $NetBSD: uhci.c,v 1.24 1999/02/20 23:26:16 augustss Exp $ */
/* $FreeBSD: src/sys/dev/usb/uhci.c,v 1.7.2.2 1999/05/08 23:04:46 n_hibma Exp $ */
/*
* Copyright (c) 1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Lennart Augustsson ([email protected]) at
* Carlstedt Research & Technology.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* USB Universal Host Controller driver.
* Handles PIIX3 and PIIX4.
*
* Data sheets: ftp://download.intel.com/design/intarch/datashts/29055002.pdf
* ftp://download.intel.com/design/intarch/datashts/29056201.pdf
* UHCI spec: http://www.intel.com/design/usb/uhci11d.pdf
* USB spec: http://www.usb.org/cgi-usb/mailmerge.cgi/home/usb/docs/developers/
cgiform.tpl
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#if defined(__NetBSD__)
#include <sys/device.h>
#elif defined(__FreeBSD__)
#include <sys/module.h>
#include <sys/bus.h>
#endif
#include <sys/proc.h>
#include <sys/queue.h>
#include <sys/select.h>
#include <machine/bus.h>
#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>
#include <dev/usb/usbdivar.h>
#include <dev/usb/usb_mem.h>
#include <dev/usb/usb_quirks.h>
#include <dev/usb/uhcireg.h>
#include <dev/usb/uhcivar.h>
#if defined(__FreeBSD__)
#include <machine/clock.h>
#define delay(d) DELAY(d)
#endif
#ifdef UHCI_DEBUG
#define DPRINTF(x) if (uhcidebug) logprintf x
#define DPRINTFN(n,x) if (uhcidebug>(n)) logprintf x
int uhcidebug = 1;
#else
#define DPRINTF(x)
#define DPRINTFN(n,x)
#endif
#define MS_TO_TICKS(ms) ((ms) * hz / 1000)
struct uhci_pipe {
struct usbd_pipe pipe;
uhci_intr_info_t *iinfo;
int newtoggle;
/* Info needed for different pipe kinds. */
union {
/* Control pipe */
struct {
uhci_soft_qh_t *sqh;
usb_dma_t reqdma;
usb_dma_t datadma;
uhci_soft_td_t *setup, *stat;
u_int length;
} ctl;
/* Interrupt pipe */
struct {
usb_dma_t datadma;
int npoll;
uhci_soft_qh_t **qhs;
} intr;
/* Bulk pipe */
struct {
uhci_soft_qh_t *sqh;
usb_dma_t datadma;
u_int length;
int isread;
} bulk;
/* Iso pipe */
struct iso {
u_int bufsize;
u_int nbuf;
usb_dma_t *bufs;
uhci_soft_td_t **stds;
} iso;
} u;
};
/*
* The uhci_intr_info free list can be global since they contain
* no dma specific data. The other free lists do.
*/
LIST_HEAD(, uhci_intr_info) uhci_ii_free;
void uhci_busreset __P((uhci_softc_t *));
usbd_status uhci_run __P((uhci_softc_t *, int run));
uhci_soft_td_t *uhci_alloc_std __P((uhci_softc_t *));
void uhci_free_std __P((uhci_softc_t *, uhci_soft_td_t *));
uhci_soft_qh_t *uhci_alloc_sqh __P((uhci_softc_t *));
void uhci_free_sqh __P((uhci_softc_t *, uhci_soft_qh_t *));
uhci_intr_info_t *uhci_alloc_intr_info __P((uhci_softc_t *));
void uhci_free_intr_info __P((uhci_intr_info_t *ii));
#if 0
void uhci_enter_ctl_q __P((uhci_softc_t *, uhci_soft_qh_t *,
uhci_intr_info_t *));
void uhci_exit_ctl_q __P((uhci_softc_t *, uhci_soft_qh_t *));
#endif
void uhci_free_std_chain __P((uhci_softc_t *,
uhci_soft_td_t *, uhci_soft_td_t *));
usbd_status uhci_alloc_std_chain __P((struct uhci_pipe *, uhci_softc_t *,
int, int, int, usb_dma_t *,
uhci_soft_td_t **,
uhci_soft_td_t **));
void uhci_timo __P((void *));
void uhci_waitintr __P((uhci_softc_t *, usbd_request_handle));
void uhci_check_intr __P((uhci_softc_t *, uhci_intr_info_t *));
void uhci_ii_done __P((uhci_intr_info_t *, int));
void uhci_timeout __P((void *));
void uhci_wakeup_ctrl __P((void *, int, int, void *, int));
void uhci_lock_frames __P((uhci_softc_t *));
void uhci_unlock_frames __P((uhci_softc_t *));
void uhci_add_ctrl __P((uhci_softc_t *, uhci_soft_qh_t *));
void uhci_add_bulk __P((uhci_softc_t *, uhci_soft_qh_t *));
void uhci_remove_ctrl __P((uhci_softc_t *, uhci_soft_qh_t *));
void uhci_remove_bulk __P((uhci_softc_t *, uhci_soft_qh_t *));
int uhci_str __P((usb_string_descriptor_t *, int, char *));
void uhci_wakeup_cb __P((usbd_request_handle reqh));
usbd_status uhci_device_ctrl_transfer __P((usbd_request_handle));
usbd_status uhci_device_ctrl_start __P((usbd_request_handle));
void uhci_device_ctrl_abort __P((usbd_request_handle));
void uhci_device_ctrl_close __P((usbd_pipe_handle));
usbd_status uhci_device_intr_transfer __P((usbd_request_handle));
usbd_status uhci_device_intr_start __P((usbd_request_handle));
void uhci_device_intr_abort __P((usbd_request_handle));
void uhci_device_intr_close __P((usbd_pipe_handle));
usbd_status uhci_device_bulk_transfer __P((usbd_request_handle));
usbd_status uhci_device_bulk_start __P((usbd_request_handle));
void uhci_device_bulk_abort __P((usbd_request_handle));
void uhci_device_bulk_close __P((usbd_pipe_handle));
usbd_status uhci_device_isoc_transfer __P((usbd_request_handle));
usbd_status uhci_device_isoc_start __P((usbd_request_handle));
void uhci_device_isoc_abort __P((usbd_request_handle));
void uhci_device_isoc_close __P((usbd_pipe_handle));
usbd_status uhci_device_isoc_setbuf __P((usbd_pipe_handle, u_int, u_int));
usbd_status uhci_root_ctrl_transfer __P((usbd_request_handle));
usbd_status uhci_root_ctrl_start __P((usbd_request_handle));
void uhci_root_ctrl_abort __P((usbd_request_handle));
void uhci_root_ctrl_close __P((usbd_pipe_handle));
usbd_status uhci_root_intr_transfer __P((usbd_request_handle));
usbd_status uhci_root_intr_start __P((usbd_request_handle));
void uhci_root_intr_abort __P((usbd_request_handle));
void uhci_root_intr_close __P((usbd_pipe_handle));
usbd_status uhci_open __P((usbd_pipe_handle));
void uhci_poll __P((struct usbd_bus *));
usbd_status uhci_device_request __P((usbd_request_handle reqh));
void uhci_ctrl_done __P((uhci_intr_info_t *ii));
void uhci_bulk_done __P((uhci_intr_info_t *ii));
void uhci_add_intr __P((uhci_softc_t *, int, uhci_soft_qh_t *));
void uhci_remove_intr __P((uhci_softc_t *, int, uhci_soft_qh_t *));
usbd_status uhci_device_setintr __P((uhci_softc_t *sc,
struct uhci_pipe *pipe, int ival));
void uhci_intr_done __P((uhci_intr_info_t *ii));
void uhci_isoc_done __P((uhci_intr_info_t *ii));
#ifdef UHCI_DEBUG
static void uhci_dumpregs __P((uhci_softc_t *));
void uhci_dump_tds __P((uhci_soft_td_t *));
void uhci_dump_qh __P((uhci_soft_qh_t *));
void uhci_dump __P((void));
void uhci_dump_td __P((uhci_soft_td_t *));
#endif
#if defined(__NetBSD__)
#define UWRITE2(sc, r, x) bus_space_write_2((sc)->iot, (sc)->ioh, (r), (x))
#define UWRITE4(sc, r, x) bus_space_write_4((sc)->iot, (sc)->ioh, (r), (x))
#define UREAD2(sc, r) bus_space_read_2((sc)->iot, (sc)->ioh, (r))
#define UREAD4(sc, r) bus_space_read_4((sc)->iot, (sc)->ioh, (r))
#elif defined(__FreeBSD__)
#define UWRITE2(sc,r,x) outw((sc)->sc_iobase + (r), (x))
#define UWRITE4(sc,r,x) outl((sc)->sc_iobase + (r), (x))
#define UREAD2(sc,r) inw((sc)->sc_iobase + (r))
#define UREAD4(sc,r) inl((sc)->sc_iobase + (r))
#endif
#define UHCICMD(sc, cmd) UWRITE2(sc, UHCI_CMD, cmd)
#define UHCISTS(sc) UREAD2(sc, UHCI_STS)
#define UHCI_RESET_TIMEOUT 100 /* reset timeout */
#define UHCI_CURFRAME(sc) (UREAD2(sc, UHCI_FRNUM) & UHCI_FRNUM_MASK)
#define UHCI_INTR_ENDPT 1
struct usbd_methods uhci_root_ctrl_methods = {
uhci_root_ctrl_transfer,
uhci_root_ctrl_start,
uhci_root_ctrl_abort,
uhci_root_ctrl_close,
0,
};
struct usbd_methods uhci_root_intr_methods = {
uhci_root_intr_transfer,
uhci_root_intr_start,
uhci_root_intr_abort,
uhci_root_intr_close,
0,
};
struct usbd_methods uhci_device_ctrl_methods = {
uhci_device_ctrl_transfer,
uhci_device_ctrl_start,
uhci_device_ctrl_abort,
uhci_device_ctrl_close,
0,
};
struct usbd_methods uhci_device_intr_methods = {
uhci_device_intr_transfer,
uhci_device_intr_start,
uhci_device_intr_abort,
uhci_device_intr_close,
0,
};
struct usbd_methods uhci_device_bulk_methods = {
uhci_device_bulk_transfer,
uhci_device_bulk_start,
uhci_device_bulk_abort,
uhci_device_bulk_close,
0,
};
struct usbd_methods uhci_device_isoc_methods = {
uhci_device_isoc_transfer,
uhci_device_isoc_start,
uhci_device_isoc_abort,
uhci_device_isoc_close,
uhci_device_isoc_setbuf,
};
void
uhci_busreset(sc)
uhci_softc_t *sc;
{
UHCICMD(sc, UHCI_CMD_GRESET); /* global reset */
usb_delay_ms(&sc->sc_bus, USB_BUS_RESET_DELAY); /* wait a little */
UHCICMD(sc, 0); /* do nothing */
}
usbd_status
uhci_init(sc)
uhci_softc_t *sc;
{
usbd_status r;
int i, j;
uhci_soft_qh_t *csqh, *bsqh, *sqh;
uhci_soft_td_t *std;
usb_dma_t dma;
static int uhci_global_init_done = 0;
DPRINTFN(1,("uhci_init: start\n"));
if (!uhci_global_init_done) {
uhci_global_init_done = 1;
LIST_INIT(&uhci_ii_free);
}
uhci_run(sc, 0); /* stop the controller */
UWRITE2(sc, UHCI_INTR, 0); /* disable interrupts */
uhci_busreset(sc);
/* Allocate and initialize real frame array. */
r = usb_allocmem(sc->sc_dmatag,
UHCI_FRAMELIST_COUNT * sizeof(uhci_physaddr_t),
UHCI_FRAMELIST_ALIGN, &dma);
if (r != USBD_NORMAL_COMPLETION)
return (r);
sc->sc_pframes = KERNADDR(&dma);
UWRITE2(sc, UHCI_FRNUM, 0); /* set frame number to 0 */
UWRITE4(sc, UHCI_FLBASEADDR, DMAADDR(&dma)); /* set frame list */
/* Allocate the dummy QH where bulk traffic will be queued. */
bsqh = uhci_alloc_sqh(sc);
if (!bsqh)
return (USBD_NOMEM);
bsqh->qh->qh_hlink = UHCI_PTR_T; /* end of QH chain */
bsqh->qh->qh_elink = UHCI_PTR_T;
sc->sc_bulk_start = sc->sc_bulk_end = bsqh;
/* Allocate the dummy QH where control traffic will be queued. */
csqh = uhci_alloc_sqh(sc);
if (!csqh)
return (USBD_NOMEM);
csqh->qh->hlink = bsqh;
csqh->qh->qh_hlink = bsqh->physaddr | UHCI_PTR_Q;
csqh->qh->qh_elink = UHCI_PTR_T;
sc->sc_ctl_start = sc->sc_ctl_end = csqh;
/*
* Make all (virtual) frame list pointers point to the interrupt
* queue heads and the interrupt queue heads at the control
* queue head and point the physical frame list to the virtual.
*/
for(i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
std = uhci_alloc_std(sc);
sqh = uhci_alloc_sqh(sc);
if (!std || !sqh)
return (USBD_NOMEM);
std->td->link.sqh = sqh;
std->td->td_link = sqh->physaddr | UHCI_PTR_Q;
std->td->td_status = UHCI_TD_IOS; /* iso, inactive */
std->td->td_token = 0;
std->td->td_buffer = 0;
sqh->qh->hlink = csqh;
sqh->qh->qh_hlink = csqh->physaddr | UHCI_PTR_Q;
sqh->qh->elink = 0;
sqh->qh->qh_elink = UHCI_PTR_T;
sc->sc_vframes[i].htd = std;
sc->sc_vframes[i].etd = std;
sc->sc_vframes[i].hqh = sqh;
sc->sc_vframes[i].eqh = sqh;
for (j = i;
j < UHCI_FRAMELIST_COUNT;
j += UHCI_VFRAMELIST_COUNT)
sc->sc_pframes[j] = std->physaddr;
}
LIST_INIT(&sc->sc_intrhead);
/* Set up the bus struct. */
sc->sc_bus.open_pipe = uhci_open;
sc->sc_bus.pipe_size = sizeof(struct uhci_pipe);
sc->sc_bus.do_poll = uhci_poll;
DPRINTFN(1,("uhci_init: enabling\n"));
UWRITE2(sc, UHCI_INTR, UHCI_INTR_TOCRCIE | UHCI_INTR_RIE |
UHCI_INTR_IOCE | UHCI_INTR_SPIE); /* enable interrupts */
return (uhci_run(sc, 1)); /* and here we go... */
}
#ifdef UHCI_DEBUG
static void
uhci_dumpregs(sc)
uhci_softc_t *sc;
{
printf("%s: regs: cmd=%04x, sts=%04x, intr=%04x, frnum=%04x, "
"flbase=%08x, sof=%02x, portsc1=%04x, portsc2=%04x, ",
USBDEVNAME(sc->sc_bus.bdev),
UREAD2(sc, UHCI_CMD),
UREAD2(sc, UHCI_STS),
UREAD2(sc, UHCI_INTR),
UREAD2(sc, UHCI_FRNUM),
UREAD4(sc, UHCI_FLBASEADDR),
UREAD1(sc, UHCI_SOF),
UREAD2(sc, UHCI_PORTSC1),
UREAD2(sc, UHCI_PORTSC2));
}
int uhci_longtd = 1;
void
uhci_dump_td(p)
uhci_soft_td_t *p;
{
printf("TD(%p) at %08lx link=0x%08lx st=0x%08lx tok=0x%08lx buf=0x%08lx\n",
p, (long)p->physaddr,
(long)p->td->td_link,
(long)p->td->td_status,
(long)p->td->td_token,
(long)p->td->td_buffer);
if (uhci_longtd)
printf(" %b %b,errcnt=%d,actlen=%d pid=%02x,addr=%d,endpt=%d,"
"D=%d,maxlen=%d\n",
(int)p->td->td_link,
"\20\1T\2Q\3VF",
(int)p->td->td_status,
"\20\22BITSTUFF\23CRCTO\24NAK\25BABBLE\26DBUFFER\27"
"STALLED\30ACTIVE\31IOC\32ISO\33LS\36SPD",
UHCI_TD_GET_ERRCNT(p->td->td_status),
UHCI_TD_GET_ACTLEN(p->td->td_status),
UHCI_TD_GET_PID(p->td->td_token),
UHCI_TD_GET_DEVADDR(p->td->td_token),
UHCI_TD_GET_ENDPT(p->td->td_token),
UHCI_TD_GET_DT(p->td->td_token),
UHCI_TD_GET_MAXLEN(p->td->td_token));
}
void
uhci_dump_qh(p)
uhci_soft_qh_t *p;
{
printf("QH(%p) at %08x: hlink=%08x elink=%08x\n", p, (int)p->physaddr,
p->qh->qh_hlink, p->qh->qh_elink);
}
#if 0
void
uhci_dump()
{
uhci_softc_t *sc = uhci;
uhci_dumpregs(sc);
printf("intrs=%d\n", sc->sc_intrs);
printf("framelist[i].link = %08x\n", sc->sc_framelist[0].link);
uhci_dump_qh(sc->sc_ctl_start->qh->hlink);
}
#endif
void
uhci_dump_tds(std)
uhci_soft_td_t *std;
{
uhci_soft_td_t *p;
for(p = std; p; p = p->td->link.std)
uhci_dump_td(p);
}
#endif
/*
* This routine is executed periodically and simulates interrupts
* from the root controller interrupt pipe for port status change.
*/
void
uhci_timo(addr)
void *addr;
{
usbd_request_handle reqh = addr;
usbd_pipe_handle pipe = reqh->pipe;
uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
int s;
u_char *p;
DPRINTFN(15, ("uhci_timo\n"));
p = KERNADDR(&upipe->u.intr.datadma);
p[0] = 0;
if (UREAD2(sc, UHCI_PORTSC1) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
p[0] |= 1<<1;
if (UREAD2(sc, UHCI_PORTSC2) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
p[0] |= 1<<2;
s = splusb();
if (p[0] != 0) {
reqh->actlen = 1;
reqh->status = USBD_NORMAL_COMPLETION;
reqh->xfercb(reqh);
}
if (reqh->pipe->intrreqh == reqh) {
usb_timeout(uhci_timo, reqh, sc->sc_ival, reqh->timo_handle);
} else {
usb_freemem(sc->sc_dmatag, &upipe->u.intr.datadma);
usb_start_next(reqh->pipe);
}
splx(s);
}
void
uhci_lock_frames(sc)
uhci_softc_t *sc;
{
int s = splusb();
while (sc->sc_vflock) {
sc->sc_vflock |= UHCI_WANT_LOCK;
tsleep(&sc->sc_vflock, PRIBIO, "uhcqhl", 0);
}
sc->sc_vflock = UHCI_HAS_LOCK;
splx(s);
}
void
uhci_unlock_frames(sc)
uhci_softc_t *sc;
{
int s = splusb();
sc->sc_vflock &= ~UHCI_HAS_LOCK;
if (sc->sc_vflock & UHCI_WANT_LOCK)
wakeup(&sc->sc_vflock);
splx(s);
}
/*
* Allocate an interrupt information struct. A free list is kept
* for fast allocation.
*/
uhci_intr_info_t *
uhci_alloc_intr_info(sc)
uhci_softc_t *sc;
{
uhci_intr_info_t *ii;
ii = LIST_FIRST(&uhci_ii_free);
if (ii)
LIST_REMOVE(ii, list);
else {
ii = malloc(sizeof(uhci_intr_info_t), M_USBDEV, M_NOWAIT);
}
ii->sc = sc;
#if defined(__FreeBSD__)
callout_handle_init(&ii->timeout_handle);
#endif
return ii;
}
void
uhci_free_intr_info(ii)
uhci_intr_info_t *ii;
{
LIST_INSERT_HEAD(&uhci_ii_free, ii, list); /* and put on free list */
}
/* Add control QH, called at splusb(). */
void
uhci_add_ctrl(sc, sqh)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
{
uhci_qh_t *eqh;
DPRINTFN(10, ("uhci_add_ctrl: sqh=%p\n", sqh));
eqh = sc->sc_ctl_end->qh;
sqh->qh->hlink = eqh->hlink;
sqh->qh->qh_hlink = eqh->qh_hlink;
eqh->hlink = sqh;
eqh->qh_hlink = sqh->physaddr | UHCI_PTR_Q;
sc->sc_ctl_end = sqh;
}
/* Remove control QH, called at splusb(). */
void
uhci_remove_ctrl(sc, sqh)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
{
uhci_soft_qh_t *pqh;
DPRINTFN(10, ("uhci_remove_ctrl: sqh=%p\n", sqh));
for (pqh = sc->sc_ctl_start; pqh->qh->hlink != sqh; pqh=pqh->qh->hlink)
#if defined(DIAGNOSTIC) || defined(UHCI_DEBUG)
if (pqh->qh->qh_hlink & UHCI_PTR_T) {
printf("uhci_remove_ctrl: QH not found\n");
return;
}
#else
;
#endif
pqh->qh->hlink = sqh->qh->hlink;
pqh->qh->qh_hlink = sqh->qh->qh_hlink;
if (sc->sc_ctl_end == sqh)
sc->sc_ctl_end = pqh;
}
/* Add bulk QH, called at splusb(). */
void
uhci_add_bulk(sc, sqh)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
{
uhci_qh_t *eqh;
DPRINTFN(10, ("uhci_add_bulk: sqh=%p\n", sqh));
eqh = sc->sc_bulk_end->qh;
sqh->qh->hlink = eqh->hlink;
sqh->qh->qh_hlink = eqh->qh_hlink;
eqh->hlink = sqh;
eqh->qh_hlink = sqh->physaddr | UHCI_PTR_Q;
sc->sc_bulk_end = sqh;
}
/* Remove bulk QH, called at splusb(). */
void
uhci_remove_bulk(sc, sqh)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
{
uhci_soft_qh_t *pqh;
DPRINTFN(10, ("uhci_remove_bulk: sqh=%p\n", sqh));
for (pqh = sc->sc_bulk_start;
pqh->qh->hlink != sqh;
pqh = pqh->qh->hlink)
#if defined(DIAGNOSTIC) || defined(UHCI_DEBUG)
if (pqh->qh->qh_hlink & UHCI_PTR_T) {
printf("uhci_remove_bulk: QH not found\n");
return;
}
#else
;
#endif
pqh->qh->hlink = sqh->qh->hlink;
pqh->qh->qh_hlink = sqh->qh->qh_hlink;
if (sc->sc_bulk_end == sqh)
sc->sc_bulk_end = pqh;
}
int
uhci_intr(priv)
void *priv;
{
uhci_softc_t *sc = priv;
int status;
int ack = 0;
uhci_intr_info_t *ii;
sc->sc_intrs++;
#if defined(UHCI_DEBUG)
if (uhcidebug > 9) {
printf("%s: uhci_intr\n", USBDEVNAME(sc->sc_bus.bdev));
uhci_dumpregs(sc);
}
#endif
status = UREAD2(sc, UHCI_STS);
if (status & UHCI_STS_USBINT)
ack |= UHCI_STS_USBINT;
if (status & UHCI_STS_USBEI)
ack |= UHCI_STS_USBEI;
if (status & UHCI_STS_RD) {
ack |= UHCI_STS_RD;
printf("%s: resume detect\n", USBDEVNAME(sc->sc_bus.bdev));
}
if (status & UHCI_STS_HSE) {
ack |= UHCI_STS_HSE;
printf("%s: Host Controller Process Error\n", USBDEVNAME(sc->sc_bus.bdev));
}
if (status & UHCI_STS_HCPE) {
ack |= UHCI_STS_HCPE;
printf("%s: Host System Error\n", USBDEVNAME(sc->sc_bus.bdev));
}
if (status & UHCI_STS_HCH) {
/* no acknowledge needed */
printf("%s: controller halted\n", USBDEVNAME(sc->sc_bus.bdev));
}
if (ack) /* acknowledge the ints */
UWRITE2(sc, UHCI_STS, ack);
else /* nothing to acknowledge */
return 0;
/*
* Interrupts on UHCI really suck. When the host controller
* interrupts because a transfer is completed there is no
* way of knowing which transfer it was. You can scan down
* the TDs and QHs of the previous frame to limit the search,
* but that assumes that the interrupt was not delayed by more
* than 1 ms, which may not always be true (e.g. after debug
* output on a slow console).
* We scan all interrupt descriptors to see if any have
* completed.
*/
for (ii = LIST_FIRST(&sc->sc_intrhead); ii; ii = LIST_NEXT(ii, list))
uhci_check_intr(sc, ii);
DPRINTFN(10, ("uhci_intr: exit\n"));
return 1;
}
/* Check for an interrupt. */
void
uhci_check_intr(sc, ii)
uhci_softc_t *sc;
uhci_intr_info_t *ii;
{
struct uhci_pipe *upipe;
uhci_soft_td_t *std;
u_int32_t status;
DPRINTFN(15, ("uhci_check_intr: ii=%p\n", ii));
#ifdef DIAGNOSTIC
if (!ii) {
printf("uhci_check_intr: no ii? %p\n", ii);
return;
}
if (!ii->stdend) {
printf("uhci_check_intr: ii->stdend==0\n");
return;
}
#endif
if (!ii->stdstart)
return;
/* If the last TD is still active we need to check whether there
* is a an error somewhere in the middle, or whether there was a
* short packet (SPD and not ACTIVE).
*/
if (ii->stdend->td->td_status & UHCI_TD_ACTIVE) {
for (std = ii->stdstart; std != ii->stdend; std = std->td->link.std){
status = std->td->td_status;
DPRINTF(("status=0x%04x\n", status));
if ((status & UHCI_TD_STALLED) ||
(status & (UHCI_TD_SPD | UHCI_TD_ACTIVE)) == UHCI_TD_SPD)
goto done;
}
return;
}
done:
usb_untimeout(uhci_timeout, ii, ii->timeout_handle);
upipe = (struct uhci_pipe *)ii->reqh->pipe;
upipe->pipe.endpoint->toggle = upipe->newtoggle;
uhci_ii_done(ii, 0);
}
void
uhci_ii_done(ii, timo)
uhci_intr_info_t *ii;
int timo; /* timeout that triggered function call? */
{
usbd_request_handle reqh = ii->reqh;
uhci_soft_td_t *std;
int actlen = 0; /* accumulated actual length for queue */
int err = 0; /* error status of last inactive transfer */
DPRINTFN(10, ("uhci_ii_done: ii=%p ready %d\n", ii, timo));
#ifdef DIAGNOSTIC
{
/* avoid finishing a transfer more than once */
int s = splhigh();
if (ii->isdone) {
splx(s);
printf("uhci_ii_done: is done!\n");
return;
}
ii->isdone = 1;
splx(s);
}
#endif
/* The transfer is done; compute actual length and status */
/* XXX Is this correct for control xfers? */
for (std = ii->stdstart; std; std = std->td->link.std) {
if (std->td->td_status & UHCI_TD_ACTIVE)
break;
/* error status of last TD for error handling below */
err = std->td->td_status & UHCI_TD_ERROR;
if (UHCI_TD_GET_PID(std->td->td_token) != UHCI_TD_PID_SETUP)
actlen += UHCI_TD_GET_ACTLEN(std->td->td_status);
}
DPRINTFN(10, ("uhci_ii_done: actlen=%d, err=0x%x\n", actlen, err));
if (err != 0) {
DPRINTFN(-1+((err & ~UHCI_TD_STALLED) != 0),
("uhci_ii_done: error, addr=%d, endpt=0x%02x, "
"err=0x%b\n",
reqh->pipe->device->address,
reqh->pipe->endpoint->edesc->bEndpointAddress,
(int)err,
"\20\22BITSTUFF\23CRCTO\24NAK\25BABBLE\26DBUFFER\27"
"STALLED\30ACTIVE"));
if (err & ~UHCI_TD_STALLED) {
/* more then STALLED, like +BABBLE or +CRC/TIMEOUT */
reqh->status = USBD_IOERROR; /* more info XXX */
} else {
reqh->status = USBD_STALLED;
}
} else {
reqh->status = USBD_NORMAL_COMPLETION;
}
reqh->actlen = actlen;
if (timo) {
/* We got a timeout. Make sure transaction is not active. */
for (std = ii->stdstart; std != 0; std = std->td->link.std)
std->td->td_status &= ~UHCI_TD_ACTIVE;
/* XXX should we wait 1 ms */
reqh->status = USBD_TIMEOUT;
}
DPRINTFN(5, ("uhci_ii_done: calling handler ii=%p\n", ii));
/* select the proper type termination of the transfer
* based on the transfer type for the queue
*/
switch (reqh->pipe->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
case UE_CONTROL:
uhci_ctrl_done(ii);
usb_start_next(reqh->pipe);
break;
case UE_ISOCHRONOUS:
uhci_isoc_done(ii);
usb_start_next(reqh->pipe);
break;
case UE_BULK:
uhci_bulk_done(ii);
usb_start_next(reqh->pipe);
break;
case UE_INTERRUPT:
uhci_intr_done(ii);
break;
}
/* And finally execute callback. */
reqh->xfercb(reqh);
}
/*
* Called when a request does not complete.
*/
void
uhci_timeout(addr)
void *addr;
{
uhci_intr_info_t *ii = addr;
int s;
DPRINTF(("uhci_timeout: ii=%p\n", ii));
s = splusb();
uhci_ii_done(ii, 1);
splx(s);
}
/*
* Wait here until controller claims to have an interrupt.
* Then call uhci_intr and return. Use timeout to avoid waiting
* too long.
* Only used during boot when interrupts are not enabled yet.
*/
void
uhci_waitintr(sc, reqh)
uhci_softc_t *sc;
usbd_request_handle reqh;
{
int timo = reqh->timeout;
int usecs;
uhci_intr_info_t *ii;
DPRINTFN(15,("uhci_waitintr: timeout = %ds\n", timo));
reqh->status = USBD_IN_PROGRESS;
for (usecs = timo * 1000000 / hz; usecs > 0; usecs -= 1000) {
usb_delay_ms(&sc->sc_bus, 1);
DPRINTFN(10,("uhci_waitintr: 0x%04x\n", UREAD2(sc, UHCI_STS)));
if (UREAD2(sc, UHCI_STS) & UHCI_STS_USBINT) {
uhci_intr(sc);
if (reqh->status != USBD_IN_PROGRESS)
return;
}
}
/* Timeout */
DPRINTF(("uhci_waitintr: timeout\n"));
for (ii = LIST_FIRST(&sc->sc_intrhead);
ii && ii->reqh != reqh;
ii = LIST_NEXT(ii, list))
;
if (ii)
uhci_ii_done(ii, 1);
else
panic("uhci_waitintr: lost intr_info\n");
}
void
uhci_poll(bus)
struct usbd_bus *bus;
{
uhci_softc_t *sc = (uhci_softc_t *)bus;
if (UREAD2(sc, UHCI_STS) & UHCI_STS_USBINT)
uhci_intr(sc);
}
#if 0
void
uhci_reset(p)
void *p;
{
uhci_softc_t *sc = p;
int n;
UHCICMD(sc, UHCI_CMD_HCRESET);
/* The reset bit goes low when the controller is done. */
for (n = 0; n < UHCI_RESET_TIMEOUT &&
(UREAD2(sc, UHCI_CMD) & UHCI_CMD_HCRESET); n++)
delay(100);
if (n >= UHCI_RESET_TIMEOUT)
printf("%s: controller did not reset\n",
USBDEVNAME(sc->sc_bus.bdev));
}
#endif
usbd_status
uhci_run(sc, run)
uhci_softc_t *sc;
int run;
{
int s, n, running;
s = splusb();
running = ((UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) == 0);
if (run == running) {
splx(s);
return (USBD_NORMAL_COMPLETION);
}
UWRITE2(sc, UHCI_CMD, run ? UHCI_CMD_RS : 0);
for(n = 0; n < 10; n++) {
running = ((UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) == 0);
/* return when we've entered the state we want */
if (run == running) {
splx(s);
return (USBD_NORMAL_COMPLETION);
}
usb_delay_ms(&sc->sc_bus, 1);
}
splx(s);
printf("%s: cannot %s\n", USBDEVNAME(sc->sc_bus.bdev),
run ? "start" : "stop");
return (USBD_IOERROR);
}
/*
* Memory management routines.
* uhci_alloc_std allocates TDs
* uhci_alloc_sqh allocates QHs
* These two routines do their own free list management,
* partly for speed, partly because allocating DMAable memory
* has page size granularaity so much memory would be wasted if
* only one TD/QH (32 bytes) was placed in each allocated chunk.
*/
uhci_soft_td_t *
uhci_alloc_std(sc)
uhci_softc_t *sc;
{
uhci_soft_td_t *std;
usbd_status r;
int i;
usb_dma_t dma;
if (!sc->sc_freetds) {
DPRINTFN(2,("uhci_alloc_std: allocating chunk\n"));
std = malloc(sizeof(uhci_soft_td_t) * UHCI_TD_CHUNK,
M_USBDEV, M_NOWAIT);
if (!std)
return (0);
r = usb_allocmem(sc->sc_dmatag, UHCI_TD_SIZE * UHCI_TD_CHUNK,
UHCI_TD_ALIGN, &dma);
if (r != USBD_NORMAL_COMPLETION) {
free(std, M_USBDEV);
return (0);
}
for(i = 0; i < UHCI_TD_CHUNK; i++, std++) {
std->physaddr = DMAADDR(&dma) + i * UHCI_TD_SIZE;
std->td = (uhci_td_t *)
((char *)KERNADDR(&dma) + i * UHCI_TD_SIZE);
std->td->link.std = sc->sc_freetds;
sc->sc_freetds = std;
}
}
std = sc->sc_freetds;
sc->sc_freetds = std->td->link.std;
memset(std->td, 0, UHCI_TD_SIZE);
return std;
}
void
uhci_free_std(sc, std)
uhci_softc_t *sc;
uhci_soft_td_t *std;
{
#ifdef DIAGNOSTIC
#define TD_IS_FREE 0x12345678
if (std->td->td_token == TD_IS_FREE) {
printf("uhci_free_std: freeing free TD %p\n", std);
return;
}
std->td->td_token = TD_IS_FREE;
#endif
std->td->link.std = sc->sc_freetds;
sc->sc_freetds = std;
}
uhci_soft_qh_t *
uhci_alloc_sqh(sc)
uhci_softc_t *sc;
{
uhci_soft_qh_t *sqh;
usbd_status r;
int i, offs;
usb_dma_t dma;
if (!sc->sc_freeqhs) {
DPRINTFN(2, ("uhci_alloc_sqh: allocating chunk\n"));
sqh = malloc(sizeof(uhci_soft_qh_t) * UHCI_QH_CHUNK,
M_USBDEV, M_NOWAIT);
if (!sqh)
return 0;
r = usb_allocmem(sc->sc_dmatag, UHCI_QH_SIZE * UHCI_QH_CHUNK,
UHCI_QH_ALIGN, &dma);
if (r != USBD_NORMAL_COMPLETION) {
free(sqh, M_USBDEV);
return 0;
}
for(i = 0; i < UHCI_QH_CHUNK; i++, sqh++) {
offs = i * UHCI_QH_SIZE;
sqh->physaddr = DMAADDR(&dma) + offs;
sqh->qh = (uhci_qh_t *)
((char *)KERNADDR(&dma) + offs);
sqh->qh->hlink = sc->sc_freeqhs;
sc->sc_freeqhs = sqh;
}
}
sqh = sc->sc_freeqhs;
sc->sc_freeqhs = sqh->qh->hlink;
memset(sqh->qh, 0, UHCI_QH_SIZE);
return (sqh);
}
void
uhci_free_sqh(sc, sqh)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
{
sqh->qh->hlink = sc->sc_freeqhs;
sc->sc_freeqhs = sqh;
}
#if 0
/*
* Enter a list of transfers onto a control queue.
* Called at splusb()
*/
void
uhci_enter_ctl_q(sc, sqh, ii)
uhci_softc_t *sc;
uhci_soft_qh_t *sqh;
uhci_intr_info_t *ii;
{
DPRINTFN(5, ("uhci_enter_ctl_q: sqh=%p\n", sqh));
}
#endif
void
uhci_free_std_chain(sc, std, stdend)
uhci_softc_t *sc;
uhci_soft_td_t *std;
uhci_soft_td_t *stdend;
{
uhci_soft_td_t *p;
for (; std != stdend; std = p) {
p = std->td->link.std;
uhci_free_std(sc, std);
}
}
usbd_status
uhci_alloc_std_chain(upipe, sc, len, rd, spd, dma, sp, ep)
struct uhci_pipe *upipe;
uhci_softc_t *sc;
int len, rd, spd;
usb_dma_t *dma;
uhci_soft_td_t **sp, **ep;
{
uhci_soft_td_t *p, *lastp;
uhci_physaddr_t lastlink;
int i, ntd, l, tog, maxp;
u_int32_t status;
int addr = upipe->pipe.device->address;
int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
DPRINTFN(15, ("uhci_alloc_std_chain: addr=%d endpt=%d len=%d ls=%d "
"spd=%d\n", addr, endpt, len,
upipe->pipe.device->lowspeed, spd));
if (len == 0) {
*sp = *ep = 0;
DPRINTFN(-1,("uhci_alloc_std_chain: len=0\n"));
return (USBD_NORMAL_COMPLETION);
}
maxp = UGETW(upipe->pipe.endpoint->edesc->wMaxPacketSize);
if (maxp == 0) {
printf("uhci_alloc_std_chain: maxp=0\n");
return (USBD_INVAL);
}
ntd = (len + maxp - 1) / maxp;
tog = upipe->pipe.endpoint->toggle;
if (ntd % 2 == 0)
tog ^= 1;
upipe->newtoggle = tog ^ 1;
lastp = 0;
lastlink = UHCI_PTR_T;
ntd--;
status = UHCI_TD_SET_ERRCNT(3) | UHCI_TD_ACTIVE;
if (upipe->pipe.device->lowspeed)
status |= UHCI_TD_LOWSPEED;
if (spd)
status |= UHCI_TD_SPD;
for (i = ntd; i >= 0; i--) {
p = uhci_alloc_std(sc);
if (!p) {
uhci_free_std_chain(sc, lastp, 0);
return (USBD_NOMEM);
}
p->td->link.std = lastp;
p->td->td_link = lastlink;
lastp = p;
lastlink = p->physaddr;
p->td->td_status = status;
if (i == ntd) {
/* last TD */
l = len % maxp;
if (l == 0) l = maxp;
*ep = p;
} else
l = maxp;
p->td->td_token =
rd ? UHCI_TD_IN (l, endpt, addr, tog) :
UHCI_TD_OUT(l, endpt, addr, tog);
p->td->td_buffer = DMAADDR(dma) + i * maxp;
tog ^= 1;
}
*sp = lastp;
/*upipe->pipe.endpoint->toggle = tog;*/
DPRINTFN(10, ("uhci_alloc_std_chain: oldtog=%d newtog=%d\n",
upipe->pipe.endpoint->toggle, upipe->newtoggle));
return (USBD_NORMAL_COMPLETION);
}
usbd_status
uhci_device_bulk_transfer(reqh)
usbd_request_handle reqh;
{
int s;
usbd_status r;
s = splusb();
r = usb_insert_transfer(reqh);
splx(s);
if (r != USBD_NORMAL_COMPLETION)
return (r);
else
return (uhci_device_bulk_start(reqh));
}
usbd_status
uhci_device_bulk_start(reqh)
usbd_request_handle reqh;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
uhci_intr_info_t *ii = upipe->iinfo;
uhci_soft_td_t *xfer, *xferend;
uhci_soft_qh_t *sqh;
usb_dma_t *dmap;
usbd_status r;
int len, isread;
int s;
DPRINTFN(3, ("uhci_device_bulk_transfer: reqh=%p buf=%p len=%d "
"flags=%d\n",
reqh, reqh->buffer, reqh->length, reqh->flags));
if (reqh->isreq)
panic("uhci_device_bulk_transfer: a request\n");
len = reqh->length;
dmap = &upipe->u.bulk.datadma;
isread = reqh->pipe->endpoint->edesc->bEndpointAddress & UE_IN;
sqh = upipe->u.bulk.sqh;
upipe->u.bulk.isread = isread;
upipe->u.bulk.length = len;
r = usb_allocmem(sc->sc_dmatag, len, 0, dmap);
if (r != USBD_NORMAL_COMPLETION)
goto ret1;
r = uhci_alloc_std_chain(upipe, sc, len, isread,
reqh->flags & USBD_SHORT_XFER_OK,
dmap, &xfer, &xferend);
if (r != USBD_NORMAL_COMPLETION)
goto ret2;
xferend->td->td_status |= UHCI_TD_IOC;
if (!isread && len != 0)
memcpy(KERNADDR(dmap), reqh->buffer, len);
#ifdef UHCI_DEBUG
if (uhcidebug > 10) {
printf("uhci_device_bulk_transfer: xfer(1)\n");
uhci_dump_tds(xfer);
}
#endif
/* Set up interrupt info. */
ii->reqh = reqh;
ii->stdstart = xfer;
ii->stdend = xferend;
#if defined(__FreeBSD__)
callout_handle_init(&ii->timeout_handle);
#endif
#ifdef DIAGNOSTIC
ii->isdone = 0;
#endif
sqh->qh->elink = xfer;
sqh->qh->qh_elink = xfer->physaddr;
sqh->intr_info = ii;
s = splusb();
uhci_add_bulk(sc, sqh);
LIST_INSERT_HEAD(&sc->sc_intrhead, ii, list);
if (reqh->timeout && !sc->sc_bus.use_polling) {
usb_timeout(uhci_timeout, ii,
MS_TO_TICKS(reqh->timeout), ii->timeout_handle);
}
splx(s);
#ifdef UHCI_DEBUG
if (uhcidebug > 10) {
printf("uhci_device_bulk_transfer: xfer(2)\n");
uhci_dump_tds(xfer);
}
#endif
return (USBD_IN_PROGRESS);
ret2:
if (len != 0)
usb_freemem(sc->sc_dmatag, dmap);
ret1:
return (r);
}
/* Abort a device bulk request. */
void
uhci_device_bulk_abort(reqh)
usbd_request_handle reqh;
{
/* XXX inactivate */
usb_delay_ms(reqh->pipe->device->bus, 1);/* make sure it is done */
/* XXX call done */
}
/* Close a device bulk pipe. */
void
uhci_device_bulk_close(pipe)
usbd_pipe_handle pipe;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
uhci_free_sqh(sc, upipe->u.bulk.sqh);
uhci_free_intr_info(upipe->iinfo);
/* XXX free other resources */
}
usbd_status
uhci_device_ctrl_transfer(reqh)
usbd_request_handle reqh;
{
int s;
usbd_status r;
s = splusb();
r = usb_insert_transfer(reqh);
splx(s);
if (r != USBD_NORMAL_COMPLETION)
return (r);
else
return (uhci_device_ctrl_start(reqh));
}
usbd_status
uhci_device_ctrl_start(reqh)
usbd_request_handle reqh;
{
uhci_softc_t *sc = (uhci_softc_t *)reqh->pipe->device->bus;
usbd_status r;
if (!reqh->isreq)
panic("uhci_device_ctrl_transfer: not a request\n");
r = uhci_device_request(reqh);
if (r != USBD_NORMAL_COMPLETION)
return (r);
if (sc->sc_bus.use_polling)
uhci_waitintr(sc, reqh);
return (USBD_IN_PROGRESS);
}
usbd_status
uhci_device_intr_transfer(reqh)
usbd_request_handle reqh;
{
int s;
usbd_status r;
s = splusb();
r = usb_insert_transfer(reqh);
splx(s);
if (r != USBD_NORMAL_COMPLETION)
return (r);
else
return (uhci_device_intr_start(reqh));
}
usbd_status
uhci_device_intr_start(reqh)
usbd_request_handle reqh;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
uhci_intr_info_t *ii = upipe->iinfo;
uhci_soft_td_t *xfer, *xferend;
uhci_soft_qh_t *sqh;
usb_dma_t *dmap;
usbd_status r;
int len, i;
int s;
DPRINTFN(3, ("uhci_device_intr_transfer: reqh=%p buf=%p len=%d "
"flags=%d\n",
reqh, reqh->buffer, reqh->length, reqh->flags));
if (reqh->isreq)
panic("uhci_device_intr_transfer: a request\n");
len = reqh->length;
dmap = &upipe->u.intr.datadma;
if (len == 0)
return (USBD_INVAL); /* XXX should it be? */
r = usb_allocmem(sc->sc_dmatag, len, 0, dmap);
if (r != USBD_NORMAL_COMPLETION)
goto ret1;
r = uhci_alloc_std_chain(upipe, sc, len, 1,
reqh->flags & USBD_SHORT_XFER_OK,
dmap, &xfer, &xferend);
if (r != USBD_NORMAL_COMPLETION)
goto ret2;
xferend->td->td_status |= UHCI_TD_IOC;
#ifdef UHCI_DEBUG
if (uhcidebug > 10) {
printf("uhci_device_intr_transfer: xfer(1)\n");
uhci_dump_tds(xfer);
uhci_dump_qh(upipe->u.intr.qhs[0]);
}
#endif
s = splusb();
/* Set up interrupt info. */
ii->reqh = reqh;
ii->stdstart = xfer;
ii->stdend = xferend;
#ifdef DIAGNOSTIC
ii->isdone = 0;
#endif
DPRINTFN(10,("uhci_device_intr_transfer: qhs[0]=%p\n",
upipe->u.intr.qhs[0]));
for (i = 0; i < upipe->u.intr.npoll; i++) {
sqh = upipe->u.intr.qhs[i];
sqh->qh->elink = xfer;
sqh->qh->qh_elink = xfer->physaddr;
}
splx(s);
#ifdef UHCI_DEBUG
if (uhcidebug > 10) {
printf("uhci_device_intr_transfer: xfer(2)\n");
uhci_dump_tds(xfer);
uhci_dump_qh(upipe->u.intr.qhs[0]);
}
#endif
return (USBD_IN_PROGRESS);
ret2:
if (len != 0)
usb_freemem(sc->sc_dmatag, dmap);
ret1:
return (r);
}
/* Abort a device control request. */
void
uhci_device_ctrl_abort(reqh)
usbd_request_handle reqh;
{
/* XXX inactivate */
usb_delay_ms(reqh->pipe->device->bus, 1); /* make sure it is done */
/* XXX call done */
}
/* Close a device control pipe. */
void
uhci_device_ctrl_close(pipe)
usbd_pipe_handle pipe;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
uhci_free_intr_info(upipe->iinfo);
/* XXX free other resources */
}
/* Abort a device interrupt request. */
void
uhci_device_intr_abort(reqh)
usbd_request_handle reqh;
{
struct uhci_pipe *upipe;
DPRINTFN(1, ("uhci_device_intr_abort: reqh=%p\n", reqh));
/* XXX inactivate */
usb_delay_ms(reqh->pipe->device->bus, 2); /* make sure it is done */
if (reqh->pipe->intrreqh == reqh) {
DPRINTF(("uhci_device_intr_abort: remove\n"));
reqh->pipe->intrreqh = 0;
upipe = (struct uhci_pipe *)reqh->pipe;
uhci_intr_done(upipe->u.intr.qhs[0]->intr_info);
}
}
/* Close a device interrupt pipe. */
void
uhci_device_intr_close(pipe)
usbd_pipe_handle pipe;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
int i, s, npoll;
upipe->iinfo->stdstart = 0; /* inactive */
/* Unlink descriptors from controller data structures. */
npoll = upipe->u.intr.npoll;
uhci_lock_frames(sc);
for (i = 0; i < npoll; i++)
uhci_remove_intr(sc, upipe->u.intr.qhs[i]->pos,
upipe->u.intr.qhs[i]);
uhci_unlock_frames(sc);
/*
* We now have to wait for any activity on the physical
* descriptors to stop.
*/
usb_delay_ms(&sc->sc_bus, 2);
for(i = 0; i < npoll; i++)
uhci_free_sqh(sc, upipe->u.intr.qhs[i]);
free(upipe->u.intr.qhs, M_USB);
s = splusb();
LIST_REMOVE(upipe->iinfo, list); /* remove from active list */
splx(s);
uhci_free_intr_info(upipe->iinfo);
/* XXX free other resources */
}
usbd_status
uhci_device_request(reqh)
usbd_request_handle reqh;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
usb_device_request_t *req = &reqh->request;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
int addr = dev->address;
int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
uhci_intr_info_t *ii = upipe->iinfo;
uhci_soft_td_t *setup, *xfer, *stat, *next, *xferend;
uhci_soft_qh_t *sqh;
usb_dma_t *dmap;
int len;
u_int32_t ls;
usbd_status r;
int isread;
int s;
DPRINTFN(3,("uhci_device_control type=0x%02x, request=0x%02x, "
"wValue=0x%04x, wIndex=0x%04x len=%d, addr=%d, endpt=%d\n",
req->bmRequestType, req->bRequest, UGETW(req->wValue),
UGETW(req->wIndex), UGETW(req->wLength),
addr, endpt));
ls = dev->lowspeed ? UHCI_TD_LOWSPEED : 0;
isread = req->bmRequestType & UT_READ;
len = UGETW(req->wLength);
setup = upipe->u.ctl.setup;
stat = upipe->u.ctl.stat;
sqh = upipe->u.ctl.sqh;
dmap = &upipe->u.ctl.datadma;
/* Set up data transaction */
if (len != 0) {
r = usb_allocmem(sc->sc_dmatag, len, 0, dmap);
if (r != USBD_NORMAL_COMPLETION)
goto ret1;
upipe->pipe.endpoint->toggle = 1;
r = uhci_alloc_std_chain(upipe, sc, len, isread,
reqh->flags & USBD_SHORT_XFER_OK,
dmap, &xfer, &xferend);
if (r != USBD_NORMAL_COMPLETION)
goto ret2;
next = xfer;
xferend->td->link.std = stat;
xferend->td->td_link = stat->physaddr;
} else {
next = stat;
}
upipe->u.ctl.length = len;
memcpy(KERNADDR(&upipe->u.ctl.reqdma), req, sizeof *req);
if (!isread && len != 0)
memcpy(KERNADDR(dmap), reqh->buffer, len);
setup->td->link.std = next;
setup->td->td_link = next->physaddr;
setup->td->td_status = UHCI_TD_SET_ERRCNT(3) | ls | UHCI_TD_ACTIVE;
setup->td->td_token = UHCI_TD_SETUP(sizeof *req, endpt, addr);
setup->td->td_buffer = DMAADDR(&upipe->u.ctl.reqdma);
stat->td->link.std = 0;
stat->td->td_link = UHCI_PTR_T;
stat->td->td_status = UHCI_TD_SET_ERRCNT(3) | ls |
UHCI_TD_ACTIVE | UHCI_TD_IOC;
stat->td->td_token =
isread ? UHCI_TD_OUT(0, endpt, addr, 1) :
UHCI_TD_IN (0, endpt, addr, 1);
stat->td->td_buffer = 0;
#ifdef UHCI_DEBUG
if (uhcidebug > 20) {
printf("uhci_device_request: setup\n");
uhci_dump_td(setup);
printf("uhci_device_request: stat\n");
uhci_dump_td(stat);
}
#endif
/* Set up interrupt info. */
ii->reqh = reqh;
ii->stdstart = setup;
ii->stdend = stat;
#if defined(__FreeBSD__)
callout_handle_init(&ii->timeout_handle);
#endif
#ifdef DIAGNOSTIC
ii->isdone = 0;
#endif
sqh->qh->elink = setup;
sqh->qh->qh_elink = setup->physaddr;
sqh->intr_info = ii;
s = splusb();
uhci_add_ctrl(sc, sqh);
LIST_INSERT_HEAD(&sc->sc_intrhead, ii, list);
#ifdef UHCI_DEBUG
if (uhcidebug > 12) {
uhci_soft_td_t *std;
uhci_soft_qh_t *xqh;
uhci_soft_qh_t *sxqh;
int maxqh = 0;
uhci_physaddr_t link;
printf("uhci_enter_ctl_q: follow from [0]\n");
for (std = sc->sc_vframes[0].htd, link = 0;
(link & UHCI_PTR_Q) == 0;
std = std->td->link.std) {
link = std->td->td_link;
uhci_dump_td(std);
}
for (sxqh = xqh = (uhci_soft_qh_t *)std;
xqh;
xqh = (maxqh++ == 5 || xqh->qh->hlink==sxqh ||
xqh->qh->hlink==xqh ? NULL : xqh->qh->hlink)) {
uhci_dump_qh(xqh);
uhci_dump_qh(sxqh);
}
printf("Enqueued QH:\n");
uhci_dump_qh(sqh);
uhci_dump_tds(sqh->qh->elink);
}
#endif
if (reqh->timeout && !sc->sc_bus.use_polling) {
usb_timeout(uhci_timeout, ii,
MS_TO_TICKS(reqh->timeout), ii->timeout_handle);
}
splx(s);
return (USBD_NORMAL_COMPLETION);
ret2:
if (len != 0)
usb_freemem(sc->sc_dmatag, dmap);
ret1:
return (r);
}
usbd_status
uhci_device_isoc_transfer(reqh)
usbd_request_handle reqh;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
#ifdef UHCI_DEBUG
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
#endif
DPRINTFN(1,("uhci_device_isoc_transfer: sc=%p\n", sc));
if (upipe->u.iso.bufsize == 0)
return (USBD_INVAL);
/* XXX copy data */
return (USBD_XXX);
}
usbd_status
uhci_device_isoc_start(reqh)
usbd_request_handle reqh;
{
return (USBD_XXX);
}
void
uhci_device_isoc_abort(reqh)
usbd_request_handle reqh;
{
/* XXX Can't abort a single request. */
}
void
uhci_device_isoc_close(pipe)
usbd_pipe_handle pipe;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
struct iso *iso;
int i;
/*
* Make sure all TDs are marked as inactive.
* Wait for completion.
* Unschedule.
* Deallocate.
*/
iso = &upipe->u.iso;
for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++)
iso->stds[i]->td->td_status &= ~UHCI_TD_ACTIVE;
usb_delay_ms(&sc->sc_bus, 2); /* wait for completion */
uhci_lock_frames(sc);
for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
uhci_soft_td_t *std, *vstd;
std = iso->stds[i];
for (vstd = sc->sc_vframes[i % UHCI_VFRAMELIST_COUNT].htd;
vstd && vstd->td->link.std != std;
vstd = vstd->td->link.std)
;
if (!vstd) {
/*panic*/
printf("uhci_device_isoc_close: %p not found\n", std);
uhci_unlock_frames(sc);
return;
}
vstd->td->link = std->td->link;
vstd->td->td_link = std->td->td_link;
uhci_free_std(sc, std);
}
uhci_unlock_frames(sc);
for (i = 0; i < iso->nbuf; i++)
usb_freemem(sc->sc_dmatag, &iso->bufs[i]);
free(iso->stds, M_USB);
free(iso->bufs, M_USB);
/* XXX what else? */
}
usbd_status
uhci_device_isoc_setbuf(pipe, bufsize, nbuf)
usbd_pipe_handle pipe;
u_int bufsize;
u_int nbuf;
{
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
usbd_device_handle dev = upipe->pipe.device;
uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
int addr = upipe->pipe.device->address;
int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
int rd = upipe->pipe.endpoint->edesc->bEndpointAddress & UE_IN;
struct iso *iso;
int i;
usbd_status r;
/*
* For simplicity the number of buffers must fit nicely in the frame
* list.
*/
if (UHCI_VFRAMELIST_COUNT % nbuf != 0)
return (USBD_INVAL);
iso = &upipe->u.iso;
iso->bufsize = bufsize;
iso->nbuf = nbuf;
/* Allocate memory for buffers. */
iso->bufs = malloc(nbuf * sizeof(usb_dma_t), M_USB, M_WAITOK);
iso->stds = malloc(UHCI_VFRAMELIST_COUNT * sizeof (uhci_soft_td_t *),
M_USB, M_WAITOK);
for (i = 0; i < nbuf; i++) {
r = usb_allocmem(sc->sc_dmatag, bufsize, 0, &iso->bufs[i]);
if (r != USBD_NORMAL_COMPLETION) {
nbuf = i;
goto bad1;
}
}
/* Allocate the TDs. */
for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
iso->stds[i] = uhci_alloc_std(sc);
if (iso->stds[i] == 0)
goto bad2;
}
/* XXX check schedule */
/* XXX interrupts */
/* Insert TDs into schedule, all marked inactive. */
uhci_lock_frames(sc);
for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
uhci_soft_td_t *std, *vstd;
std = iso->stds[i];
std->td->td_status = UHCI_TD_IOS; /* iso, inactive */
std->td->td_token =
rd ? UHCI_TD_IN (0, endpt, addr, 0) :
UHCI_TD_OUT(0, endpt, addr, 0);
std->td->td_buffer = DMAADDR(&iso->bufs[i % nbuf]);
vstd = sc->sc_vframes[i % UHCI_VFRAMELIST_COUNT].htd;
std->td->link = vstd->td->link;
std->td->td_link = vstd->td->td_link;
vstd->td->link.std = std;
vstd->td->td_link = std->physaddr;
}
uhci_unlock_frames(sc);
return (USBD_NORMAL_COMPLETION);
bad2:
while (--i >= 0)
uhci_free_std(sc, iso->stds[i]);
bad1:
for (i = 0; i < nbuf; i++)
usb_freemem(sc->sc_dmatag, &iso->bufs[i]);
free(iso->stds, M_USB);
free(iso->bufs, M_USB);
return (USBD_NOMEM);
}
void
uhci_isoc_done(ii)
uhci_intr_info_t *ii;
{
}
void
uhci_intr_done(ii)
uhci_intr_info_t *ii;
{
uhci_softc_t *sc = ii->sc;
usbd_request_handle reqh = ii->reqh;
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
usb_dma_t *dma;
uhci_soft_qh_t *sqh;
int i, npoll;
DPRINTFN(5, ("uhci_intr_done: length=%d\n", reqh->actlen));
dma = &upipe->u.intr.datadma;
memcpy(reqh->buffer, KERNADDR(dma), reqh->actlen);
npoll = upipe->u.intr.npoll;
for(i = 0; i < npoll; i++) {
sqh = upipe->u.intr.qhs[i];
sqh->qh->elink = 0;
sqh->qh->qh_elink = UHCI_PTR_T;
}
uhci_free_std_chain(sc, ii->stdstart, 0);
/* XXX Wasteful. */
if (reqh->pipe->intrreqh == reqh) {
uhci_soft_td_t *xfer, *xferend;
/* This alloc cannot fail since we freed the chain above. */
uhci_alloc_std_chain(upipe, sc, reqh->length, 1,
reqh->flags & USBD_SHORT_XFER_OK,
dma, &xfer, &xferend);
xferend->td->td_status |= UHCI_TD_IOC;
#ifdef UHCI_DEBUG
if (uhcidebug > 10) {
printf("uhci_device_intr_done: xfer(1)\n");
uhci_dump_tds(xfer);
uhci_dump_qh(upipe->u.intr.qhs[0]);
}
#endif
ii->stdstart = xfer;
ii->stdend = xferend;
#ifdef DIAGNOSTIC
ii->isdone = 0;
#endif
for (i = 0; i < npoll; i++) {
sqh = upipe->u.intr.qhs[i];
sqh->qh->elink = xfer;
sqh->qh->qh_elink = xfer->physaddr;
}
} else {
usb_freemem(sc->sc_dmatag, dma);
ii->stdstart = 0; /* mark as inactive */
usb_start_next(reqh->pipe);
}
}
/* Deallocate request data structures */
void
uhci_ctrl_done(ii)
uhci_intr_info_t *ii;
{
uhci_softc_t *sc = ii->sc;
usbd_request_handle reqh = ii->reqh;
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
u_int len = upipe->u.ctl.length;
usb_dma_t *dma;
uhci_td_t *htd = ii->stdstart->td;
#ifdef DIAGNOSTIC
if (!reqh->isreq)
panic("uhci_ctrl_done: not a request\n");
#endif
LIST_REMOVE(ii, list); /* remove from active list */
uhci_remove_ctrl(sc, upipe->u.ctl.sqh);
if (len != 0) {
dma = &upipe->u.ctl.datadma;
if (reqh->request.bmRequestType & UT_READ)
memcpy(reqh->buffer, KERNADDR(dma), len);
uhci_free_std_chain(sc, htd->link.std, ii->stdend);
usb_freemem(sc->sc_dmatag, dma);
}
DPRINTFN(5, ("uhci_ctrl_done: length=%d\n", reqh->actlen));
}
/* Deallocate request data structures */
void
uhci_bulk_done(ii)
uhci_intr_info_t *ii;
{
uhci_softc_t *sc = ii->sc;
usbd_request_handle reqh = ii->reqh;
struct uhci_pipe *upipe = (struct uhci_pipe *)reqh->pipe;
u_int len = upipe->u.bulk.length;
usb_dma_t *dma;
uhci_td_t *htd = ii->stdstart->td;
LIST_REMOVE(ii, list); /* remove from active list */
uhci_remove_bulk(sc, upipe->u.bulk.sqh);
if (len != 0) {
dma = &upipe->u.bulk.datadma;
if (upipe->u.bulk.isread && len != 0)
memcpy(reqh->buffer, KERNADDR(dma), len);
uhci_free_std_chain(sc, htd->link.std, 0);
usb_freemem(sc->sc_dmatag, dma);
}
DPRINTFN(4, ("uhci_bulk_done: length=%d\n", reqh->actlen));
/* XXX compute new toggle */
}
/* Add interrupt QH, called with vflock. */
void
uhci_add_intr(sc, n, sqh)
uhci_softc_t *sc;
int n;
uhci_soft_qh_t *sqh;
{
struct uhci_vframe *vf = &sc->sc_vframes[n];
uhci_qh_t *eqh;
DPRINTFN(4, ("uhci_add_intr: n=%d sqh=%p\n", n, sqh));
eqh = vf->eqh->qh;
sqh->qh->hlink = eqh->hlink;
sqh->qh->qh_hlink = eqh->qh_hlink;
eqh->hlink = sqh;
eqh->qh_hlink = sqh->physaddr | UHCI_PTR_Q;
vf->eqh = sqh;
vf->bandwidth++;
}
/* Remove interrupt QH, called with vflock. */
void
uhci_remove_intr(sc, n, sqh)
uhci_softc_t *sc;
int n;
uhci_soft_qh_t *sqh;
{
struct uhci_vframe *vf = &sc->sc_vframes[n];
uhci_soft_qh_t *pqh;
DPRINTFN(4, ("uhci_remove_intr: n=%d sqh=%p\n", n, sqh));
for (pqh = vf->hqh; pqh->qh->hlink != sqh; pqh = pqh->qh->hlink)
#if defined(DIAGNOSTIC) || defined(UHCI_DEBUG)
if (pqh->qh->qh_hlink & UHCI_PTR_T) {
printf("uhci_remove_intr: QH not found\n");
return;
}
#else
;
#endif
pqh->qh->hlink = sqh->qh->hlink;
pqh->qh->qh_hlink = sqh->qh->qh_hlink;
if (vf->eqh == sqh)
vf->eqh = pqh;
vf->bandwidth--;
}
usbd_status
uhci_device_setintr(sc, upipe, ival)
uhci_softc_t *sc;
struct uhci_pipe *upipe;
int ival;
{
uhci_soft_qh_t *sqh;
int i, npoll, s;
u_int bestbw, bw, bestoffs, offs;
DPRINTFN(2, ("uhci_setintr: pipe=%p\n", upipe));
if (ival == 0) {
printf("uhci_setintr: 0 interval\n");
return (USBD_INVAL);
}
if (ival > UHCI_VFRAMELIST_COUNT)
ival = UHCI_VFRAMELIST_COUNT;
npoll = (UHCI_VFRAMELIST_COUNT + ival - 1) / ival;
DPRINTFN(2, ("uhci_setintr: ival=%d npoll=%d\n", ival, npoll));
upipe->u.intr.npoll = npoll;
upipe->u.intr.qhs =
malloc(npoll * sizeof(uhci_soft_qh_t *), M_USB, M_WAITOK);
/*
* Figure out which offset in the schedule that has most
* bandwidth left over.
*/
#define MOD(i) ((i) & (UHCI_VFRAMELIST_COUNT-1))
for (bestoffs = offs = 0, bestbw = ~0; offs < ival; offs++) {
for (bw = i = 0; i < npoll; i++)
bw += sc->sc_vframes[MOD(i * ival + offs)].bandwidth;
if (bw < bestbw) {
bestbw = bw;
bestoffs = offs;
}
}
DPRINTFN(1, ("uhci_setintr: bw=%d offs=%d\n", bestbw, bestoffs));
upipe->iinfo->stdstart = 0;
for(i = 0; i < npoll; i++) {
upipe->u.intr.qhs[i] = sqh = uhci_alloc_sqh(sc);
sqh->qh->elink = 0;
sqh->qh->qh_elink = UHCI_PTR_T;
sqh->pos = MOD(i * ival + bestoffs);
sqh->intr_info = upipe->iinfo;
}
#undef MOD
s = splusb();
LIST_INSERT_HEAD(&sc->sc_intrhead, upipe->iinfo, list);
splx(s);
uhci_lock_frames(sc);
/* Enter QHs into the controller data structures. */
for(i = 0; i < npoll; i++)
uhci_add_intr(sc, upipe->u.intr.qhs[i]->pos,
upipe->u.intr.qhs[i]);
uhci_unlock_frames(sc);
DPRINTFN(5, ("uhci_setintr: returns %p\n", upipe));
return (USBD_NORMAL_COMPLETION);
}
/* Open a new pipe. */
usbd_status
uhci_open(pipe)
usbd_pipe_handle pipe;
{
uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
usbd_status r;
DPRINTFN(1, ("uhci_open: pipe=%p, addr=%d, endpt=%d (%d)\n",
pipe, pipe->device->address,
ed->bEndpointAddress, sc->sc_addr));
if (pipe->device->address == sc->sc_addr) {
switch (ed->bEndpointAddress) {
case USB_CONTROL_ENDPOINT:
pipe->methods = &uhci_root_ctrl_methods;
break;
case UE_IN | UHCI_INTR_ENDPT:
pipe->methods = &uhci_root_intr_methods;
break;
default:
return (USBD_INVAL);
}
} else {
upipe->iinfo = uhci_alloc_intr_info(sc);
if (upipe->iinfo == 0)
return (USBD_NOMEM);
switch (ed->bmAttributes & UE_XFERTYPE) {
case UE_CONTROL:
pipe->methods = &uhci_device_ctrl_methods;
upipe->u.ctl.sqh = uhci_alloc_sqh(sc);
if (upipe->u.ctl.sqh == 0)
goto bad;
upipe->u.ctl.setup = uhci_alloc_std(sc);
if (upipe->u.ctl.setup == 0) {
uhci_free_sqh(sc, upipe->u.ctl.sqh);
goto bad;
}
upipe->u.ctl.stat = uhci_alloc_std(sc);
if (upipe->u.ctl.stat == 0) {
uhci_free_sqh(sc, upipe->u.ctl.sqh);
uhci_free_std(sc, upipe->u.ctl.setup);
goto bad;
}
r = usb_allocmem(sc->sc_dmatag,
sizeof(usb_device_request_t),
0, &upipe->u.ctl.reqdma);
if (r != USBD_NORMAL_COMPLETION) {
uhci_free_sqh(sc, upipe->u.ctl.sqh);
uhci_free_std(sc, upipe->u.ctl.setup);
uhci_free_std(sc, upipe->u.ctl.stat);
goto bad;
}
break;
case UE_INTERRUPT:
pipe->methods = &uhci_device_intr_methods;
return (uhci_device_setintr(sc, upipe, ed->bInterval));
case UE_ISOCHRONOUS:
pipe->methods = &uhci_device_isoc_methods;
upipe->u.iso.nbuf = 0;
return (USBD_NORMAL_COMPLETION);
case UE_BULK:
pipe->methods = &uhci_device_bulk_methods;
upipe->u.bulk.sqh = uhci_alloc_sqh(sc);
if (upipe->u.bulk.sqh == 0)
goto bad;
break;
}
}
return (USBD_NORMAL_COMPLETION);
bad:
uhci_free_intr_info(upipe->iinfo);
return (USBD_NOMEM);
}
/*
* Data structures and routines to emulate the root hub.
*/
usb_device_descriptor_t uhci_devd = {
USB_DEVICE_DESCRIPTOR_SIZE,
UDESC_DEVICE, /* type */
{0x00, 0x01}, /* USB version */
UCLASS_HUB, /* class */
USUBCLASS_HUB, /* subclass */
0, /* protocol */
64, /* max packet */
{0},{0},{0x00,0x01}, /* device id */
1,2,0, /* string indicies */
1 /* # of configurations */
};
usb_config_descriptor_t uhci_confd = {
USB_CONFIG_DESCRIPTOR_SIZE,
UDESC_CONFIG,
{USB_CONFIG_DESCRIPTOR_SIZE +
USB_INTERFACE_DESCRIPTOR_SIZE +
USB_ENDPOINT_DESCRIPTOR_SIZE},
1,
1,
0,
UC_SELF_POWERED,
0 /* max power */
};
usb_interface_descriptor_t uhci_ifcd = {
USB_INTERFACE_DESCRIPTOR_SIZE,
UDESC_INTERFACE,
0,
0,
1,
UCLASS_HUB,
USUBCLASS_HUB,
0,
0
};
usb_endpoint_descriptor_t uhci_endpd = {
USB_ENDPOINT_DESCRIPTOR_SIZE,
UDESC_ENDPOINT,
UE_IN | UHCI_INTR_ENDPT,
UE_INTERRUPT,
{8},
255
};
usb_hub_descriptor_t uhci_hubd_piix = {
USB_HUB_DESCRIPTOR_SIZE,
UDESC_HUB,
2,
{ UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0 },
50, /* power on to power good */
0,
{ 0x00 }, /* both ports are removable */
};
int
uhci_str(p, l, s)
usb_string_descriptor_t *p;
int l;
char *s;
{
int i;
if (l == 0)
return (0);
p->bLength = 2 * strlen(s) + 2;
if (l == 1)
return (1);
p->bDescriptorType = UDESC_STRING;
l -= 2;
for (i = 0; s[i] && l > 1; i++, l -= 2)
USETW2(p->bString[i], 0, s[i]);
return (2*i+2);
}
/*
* Simulate a hardware hub by handling all the necessary requests.
*/
usbd_status
uhci_root_ctrl_transfer(reqh)
usbd_request_handle reqh;
{
int s;
usbd_status r;
s = splusb();
r = usb_insert_transfer(reqh);
splx(s);
if (r != USBD_NORMAL_COMPLETION)
return (r);
else
return (uhci_root_ctrl_start(reqh));
}
usbd_status
uhci_root_ctrl_start(reqh)
usbd_request_handle reqh;
{
uhci_softc_t *sc = (uhci_softc_t *)reqh->pipe->device->bus;
usb_device_request_t *req;
void *buf;
int port, x;
int len, value, index, status, change, l, totlen = 0;
usb_port_status_t ps;
usbd_status r;
if (!reqh->isreq)
panic("uhci_root_ctrl_transfer: not a request\n");
req = &reqh->request;
buf = reqh->buffer;
DPRINTFN(10,("uhci_root_ctrl_control type=0x%02x request=%02x\n",
req->bmRequestType, req->bRequest));
len = UGETW(req->wLength);
value = UGETW(req->wValue);
index = UGETW(req->wIndex);
#define C(x,y) ((x) | ((y) << 8))
switch(C(req->bRequest, req->bmRequestType)) {
case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
/*
* DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
* for the integrated root hub.
*/
break;
case C(UR_GET_CONFIG, UT_READ_DEVICE):
if (len > 0) {
*(u_int8_t *)buf = sc->sc_conf;
totlen = 1;
}
break;
case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
DPRINTFN(2,("uhci_root_ctrl_control wValue=0x%04x\n", value));
switch(value >> 8) {
case UDESC_DEVICE:
if ((value & 0xff) != 0) {
r = USBD_IOERROR;
goto ret;
}
totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
memcpy(buf, &uhci_devd, l);
break;
case UDESC_CONFIG:
if ((value & 0xff) != 0) {
r = USBD_IOERROR;
goto ret;
}
totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
memcpy(buf, &uhci_confd, l);
buf = (char *)buf + l;
len -= l;
l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
totlen += l;
memcpy(buf, &uhci_ifcd, l);
buf = (char *)buf + l;
len -= l;
l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
totlen += l;
memcpy(buf, &uhci_endpd, l);
break;
case UDESC_STRING:
if (len == 0)
break;
*(u_int8_t *)buf = 0;
totlen = 1;
switch (value & 0xff) {
case 1: /* Vendor */
totlen = uhci_str(buf, len, sc->sc_vendor);
break;
case 2: /* Product */
totlen = uhci_str(buf, len, "UHCI root hub");
break;
}
break;
default:
r = USBD_IOERROR;
goto ret;
}
break;
case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
if (len > 0) {
*(u_int8_t *)buf = 0;
totlen = 1;
}
break;
case C(UR_GET_STATUS, UT_READ_DEVICE):
if (len > 1) {
USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
totlen = 2;
}
break;
case C(UR_GET_STATUS, UT_READ_INTERFACE):
case C(UR_GET_STATUS, UT_READ_ENDPOINT):
if (len > 1) {
USETW(((usb_status_t *)buf)->wStatus, 0);
totlen = 2;
}
break;
case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
if (value >= USB_MAX_DEVICES) {
r = USBD_IOERROR;
goto ret;
}
sc->sc_addr = value;
break;
case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
if (value != 0 && value != 1) {
r = USBD_IOERROR;
goto ret;
}
sc->sc_conf = value;
break;
case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
break;
case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
r = USBD_IOERROR;
goto ret;
case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
break;
case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
break;
/* Hub requests */
case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
break;
case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
DPRINTFN(3, ("uhci_root_ctrl_control: UR_CLEAR_PORT_FEATURE "
"port=%d feature=%d\n",
index, value));
if (index == 1)
port = UHCI_PORTSC1;
else if (index == 2)
port = UHCI_PORTSC2;
else {
r = USBD_IOERROR;
goto ret;
}
switch(value) {
case UHF_PORT_ENABLE:
x = UREAD2(sc, port);
UWRITE2(sc, port, x & ~UHCI_PORTSC_PE);
break;
case UHF_PORT_SUSPEND:
x = UREAD2(sc, port);
UWRITE2(sc, port, x & ~UHCI_PORTSC_SUSP);
break;
case UHF_PORT_RESET:
x = UREAD2(sc, port);
UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
break;
case UHF_C_PORT_CONNECTION:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_CSC);
break;
case UHF_C_PORT_ENABLE:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_POEDC);
break;
case UHF_C_PORT_OVER_CURRENT:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_OCIC);
break;
case UHF_C_PORT_RESET:
sc->sc_isreset = 0;
r = USBD_NORMAL_COMPLETION;
goto ret;
case UHF_PORT_CONNECTION:
case UHF_PORT_OVER_CURRENT:
case UHF_PORT_POWER:
case UHF_PORT_LOW_SPEED:
case UHF_C_PORT_SUSPEND:
default:
r = USBD_IOERROR;
goto ret;
}
break;
case C(UR_GET_BUS_STATE, UT_READ_CLASS_OTHER):
if (index == 1)
port = UHCI_PORTSC1;
else if (index == 2)
port = UHCI_PORTSC2;
else {
r = USBD_IOERROR;
goto ret;
}
if (len > 0) {
*(u_int8_t *)buf =
(UREAD2(sc, port) & UHCI_PORTSC_LS) >>
UHCI_PORTSC_LS_SHIFT;
totlen = 1;
}
break;
case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
if (value != 0) {
r = USBD_IOERROR;
goto ret;
}
l = min(len, USB_HUB_DESCRIPTOR_SIZE);
totlen = l;
memcpy(buf, &uhci_hubd_piix, l);
break;
case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
if (len != 4) {
r = USBD_IOERROR;
goto ret;
}
memset(buf, 0, len);
totlen = len;
break;
case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
if (index == 1)
port = UHCI_PORTSC1;
else if (index == 2)
port = UHCI_PORTSC2;
else {
r = USBD_IOERROR;
goto ret;
}
if (len != 4) {
r = USBD_IOERROR;
goto ret;
}
x = UREAD2(sc, port);
status = change = 0;
if (x & UHCI_PORTSC_CCS )
status |= UPS_CURRENT_CONNECT_STATUS;
if (x & UHCI_PORTSC_CSC )
change |= UPS_C_CONNECT_STATUS;
if (x & UHCI_PORTSC_PE )
status |= UPS_PORT_ENABLED;
if (x & UHCI_PORTSC_POEDC)
change |= UPS_C_PORT_ENABLED;
if (x & UHCI_PORTSC_OCI )
status |= UPS_OVERCURRENT_INDICATOR;
if (x & UHCI_PORTSC_OCIC )
change |= UPS_C_OVERCURRENT_INDICATOR;
if (x & UHCI_PORTSC_SUSP )
status |= UPS_SUSPEND;
if (x & UHCI_PORTSC_LSDA )
status |= UPS_LOW_SPEED;
status |= UPS_PORT_POWER;
if (sc->sc_isreset)
change |= UPS_C_PORT_RESET;
USETW(ps.wPortStatus, status);
USETW(ps.wPortChange, change);
l = min(len, sizeof ps);
memcpy(buf, &ps, l);
totlen = l;
break;
case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
r = USBD_IOERROR;
goto ret;
case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
break;
case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
if (index == 1)
port = UHCI_PORTSC1;
else if (index == 2)
port = UHCI_PORTSC2;
else {
r = USBD_IOERROR;
goto ret;
}
switch(value) {
case UHF_PORT_ENABLE:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_PE);
break;
case UHF_PORT_SUSPEND:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_SUSP);
break;
case UHF_PORT_RESET:
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_PR);
usb_delay_ms(&sc->sc_bus, 10);
UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
delay(100);
x = UREAD2(sc, port);
UWRITE2(sc, port, x | UHCI_PORTSC_PE);
delay(100);
DPRINTFN(3,("uhci port %d reset, status = 0x%04x\n",
index, UREAD2(sc, port)));
sc->sc_isreset = 1;
break;
case UHF_C_PORT_CONNECTION:
case UHF_C_PORT_ENABLE:
case UHF_C_PORT_OVER_CURRENT:
case UHF_PORT_CONNECTION:
case UHF_PORT_OVER_CURRENT:
case UHF_PORT_POWER:
case UHF_PORT_LOW_SPEED:
case UHF_C_PORT_SUSPEND:
case UHF_C_PORT_RESET:
default:
r = USBD_IOERROR;
goto ret;
}
break;
default:
r = USBD_IOERROR;
goto ret;
}
reqh->actlen = totlen;
r = USBD_NORMAL_COMPLETION;
ret:
reqh->status = r;
reqh->xfercb(reqh);
usb_start_next(reqh->pipe);
return (USBD_IN_PROGRESS);
}
/* Abort a root control request. */
void
uhci_root_ctrl_abort(reqh)
usbd_request_handle reqh;
{
/* Nothing to do, all transfers are syncronous. */
}
/* Close the root pipe. */
void
uhci_root_ctrl_close(pipe)
usbd_pipe_handle pipe;
{
usb_untimeout(uhci_timo, pipe->intrreqh, pipe->intrreqh->timo_handle);
DPRINTF(("uhci_root_ctrl_close\n"));
}
/* Abort a root interrupt request. */
void
uhci_root_intr_abort(reqh)
usbd_request_handle reqh;
{
usb_untimeout(uhci_timo, reqh, reqh->timo_handle);
}
usbd_status
uhci_root_intr_transfer(reqh)
usbd_request_handle reqh;
{
int s;
usbd_status r;
s = splusb();
r = usb_insert_transfer(reqh);
splx(s);
if (r != USBD_NORMAL_COMPLETION)
return (r);
else
return (uhci_root_intr_start(reqh));
}
/* Start a transfer on the root interrupt pipe */
usbd_status
uhci_root_intr_start(reqh)
usbd_request_handle reqh;
{
usbd_pipe_handle pipe = reqh->pipe;
uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
usb_dma_t *dmap;
usbd_status r;
int len;
DPRINTFN(3, ("uhci_root_intr_transfer: reqh=%p buf=%p len=%d "
"flags=%d\n",
reqh, reqh->buffer, reqh->length, reqh->flags));
len = reqh->length;
dmap = &upipe->u.intr.datadma;
if (len == 0)
return (USBD_INVAL); /* XXX should it be? */
r = usb_allocmem(sc->sc_dmatag, len, 0, dmap);
if (r != USBD_NORMAL_COMPLETION)
return (r);
sc->sc_ival = MS_TO_TICKS(reqh->pipe->endpoint->edesc->bInterval);
usb_timeout(uhci_timo, reqh, sc->sc_ival, reqh->timo_handle);
return (USBD_IN_PROGRESS);
}
/* Close the root interrupt pipe. */
void
uhci_root_intr_close(pipe)
usbd_pipe_handle pipe;
{
usb_untimeout(uhci_timo, pipe->intrreqh, pipe->intrreqh->timo_handle);
DPRINTF(("uhci_root_intr_close\n"));
}
|
import{r as t,e,h as i,H as n,g as r}from"./p-8dbe4215.js";function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var o;const a=s((function(t){
/*! bkkr-choices v10.0.1-beta.18 | © 2021 Josh Johnson | https://github.com/bkkr-team/bkkr-choices#readme */
var e;window,e=function(){return function(t){var e={};function i(n){if(e[n])return e[n].exports;var r=e[n]={i:n,l:!1,exports:{}};return t[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(n,r,function(e){return t[e]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="/public/assets/scripts/",i(i.s=7)}([function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(1);e.DEFAULT_CLASSNAMES={containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",selectedState:"is-selected",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"},e.DEFAULT_CONFIG={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,duplicateItemsAllowed:!0,inline:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:n.sortByAlpha,placeholder:!0,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:"auto",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",uniqueItemText:"Only unique values can be added",customAddItemText:"Only values matching specific conditions can be added",addItemText:function(t){return'Press Enter to add <b>"'+n.sanitise(t)+'"</b>'},maxItemText:function(t){return"Only "+t+" values can be added"},valueComparer:function(t,e){return t===e},fuseOptions:{includeScore:!0},callbackOnInit:null,callbackOnCreateTemplates:null,classNames:e.DEFAULT_CLASSNAMES},e.EVENTS={showDropdown:"showDropdown",hideDropdown:"hideDropdown",change:"change",choice:"choice",search:"search",addItem:"addItem",removeItem:"removeItem",highlightItem:"highlightItem",highlightChoice:"highlightChoice",unhighlightItem:"unhighlightItem"},e.ACTION_TYPES={ADD_CHOICE:"ADD_CHOICE",FILTER_CHOICES:"FILTER_CHOICES",ACTIVATE_CHOICES:"ACTIVATE_CHOICES",CLEAR_CHOICES:"CLEAR_CHOICES",ADD_GROUP:"ADD_GROUP",ADD_ITEM:"ADD_ITEM",REMOVE_ITEM:"REMOVE_ITEM",HIGHLIGHT_ITEM:"HIGHLIGHT_ITEM",CLEAR_ALL:"CLEAR_ALL",RESET_TO:"RESET_TO",SET_IS_LOADING:"SET_IS_LOADING"},e.KEY_CODES={BACK_KEY:"Backspace",DELETE_KEY:"Delete",ENTER_KEY:"Enter",A_KEY:"KeyA",ESC_KEY:"Escape",UP_KEY:"ArrowUp",DOWN_KEY:"ArrowDown",LEFT_KEY:"ArrowLeft",RIGHT_KEY:"ArrowRight",PAGE_UP_KEY:"PageUp",PAGE_DOWN_KEY:"PageDown"},e.TEXT_TYPE="text",e.SELECT_ONE_TYPE="select-one",e.SELECT_MULTIPLE_TYPE="select-multiple",e.SCROLLING_SPEED=4},function(t,e){var i;Object.defineProperty(e,"__esModule",{value:!0}),e.getRandomNumber=function(t,e){return Math.floor(Math.random()*(e-t)+t)},e.generateChars=function(t){return Array.from({length:t},(function(){return e.getRandomNumber(0,36).toString(36)})).join("")},e.generateId=function(t,i){var n=t.id||t.name&&t.name+"-"+e.generateChars(2)||e.generateChars(4);return i+"-"+n.replace(/(:|\.|\[|\]|,)/g,"")},e.getType=function(t){return Object.prototype.toString.call(t).slice(8,-1)},e.isType=function(t,i){return null!=i&&e.getType(i)===t},e.wrap=function(t,e){return void 0===e&&(e=document.createElement("div")),t.nextSibling?t.parentNode&&t.parentNode.insertBefore(e,t.nextSibling):t.parentNode&&t.parentNode.appendChild(e),e.appendChild(t)},e.getAdjacentEl=function(t,e,i){void 0===i&&(i=1);for(var n=(i>0?"next":"previous")+"ElementSibling",r=t[n];r;){if(r.matches(e))return r;r=r[n]}return r},e.isScrolledIntoView=function(t,e,i){return void 0===i&&(i=1),!!t&&(i>0?e.scrollTop+e.offsetHeight>=t.offsetTop+t.offsetHeight:t.offsetTop>=e.scrollTop)},e.sanitise=function(t){return"string"!=typeof t?t:t.replace(/&/g,"&").replace(/>/g,"&rt;").replace(/</g,"<").replace(/"/g,""")},e.strToEl=(i=document.createElement("div"),function(t){var e=t.trim();i.innerHTML=e;for(var n=i.children[0];i.firstChild;)i.removeChild(i.firstChild);return n}),e.sortByAlpha=function(t,e){var i=t.label,n=e.label;return(void 0===i?t.value:i).localeCompare(void 0===n?e.value:n,[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},e.sortByScore=function(t,e){var i=t.score,n=e.score;return(void 0===i?0:i)-(void 0===n?0:n)},e.dispatchEvent=function(t,e,i){void 0===i&&(i=null);var n=new CustomEvent(e,{detail:i,bubbles:!0,cancelable:!0});return t.dispatchEvent(n)},e.existsInArray=function(t,e,i){return void 0===i&&(i="value"),t.some((function(t){return"string"==typeof e?t[i]===e.trim():t[i]===e}))},e.cloneObject=function(t){return JSON.parse(JSON.stringify(t))},e.diff=function(t,e){var i=Object.keys(t).sort(),n=Object.keys(e).sort();return i.filter((function(t){return n.indexOf(t)<0}))}},function(t,e,i){(function(t,n){var r,s=i(6);r="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==t?t:n;var o=Object(s.a)(r);e.a=o}).call(this,i(12),i(13)(t))},function(t,e,i){i.r(e),i.d(e,"__DO_NOT_USE__ActionTypes",(function(){return s})),i.d(e,"applyMiddleware",(function(){return b})),i.d(e,"bindActionCreators",(function(){return l})),i.d(e,"combineReducers",(function(){return h})),i.d(e,"compose",(function(){return p})),i.d(e,"createStore",(function(){return a}));var n=i(2),r=function(){return Math.random().toString(36).substring(7).split("").join(".")},s={INIT:"@@redux/INIT"+r(),REPLACE:"@@redux/REPLACE"+r(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+r()}};function o(t){if("object"!=typeof t||null===t)return!1;for(var e=t;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function a(t,e,i){var r;if("function"==typeof e&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.");if("function"==typeof e&&void 0===i&&(i=e,e=void 0),void 0!==i){if("function"!=typeof i)throw new Error("Expected the enhancer to be a function.");return i(a)(t,e)}if("function"!=typeof t)throw new Error("Expected the reducer to be a function.");var c=t,h=e,u=[],l=u,f=!1;function d(){l===u&&(l=u.slice())}function v(){if(f)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return h}function p(t){if("function"!=typeof t)throw new Error("Expected the listener to be a function.");if(f)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api-reference/store#subscribe(listener) for more details.");var e=!0;return d(),l.push(t),function(){if(e){if(f)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api-reference/store#subscribe(listener) for more details.");e=!1,d();var i=l.indexOf(t);l.splice(i,1)}}}function b(t){if(!o(t))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===t.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(f)throw new Error("Reducers may not dispatch actions.");try{f=!0,h=c(h,t)}finally{f=!1}for(var e=u=l,i=0;i<e.length;i++)(0,e[i])();return t}function m(t){if("function"!=typeof t)throw new Error("Expected the nextReducer to be a function.");c=t,b({type:s.REPLACE})}function g(){var t,e=p;return(t={subscribe:function(t){if("object"!=typeof t||null===t)throw new TypeError("Expected the observer to be an object.");function i(){t.next&&t.next(v())}return i(),{unsubscribe:e(i)}}})[n.a]=function(){return this},t}return b({type:s.INIT}),(r={dispatch:b,subscribe:p,getState:v,replaceReducer:m})[n.a]=g,r}function c(t,e){var i=e&&e.type;return"Given "+(i&&'action "'+String(i)+'"'||"an action")+', reducer "'+t+'" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.'}function h(t){for(var e=Object.keys(t),i={},n=0;n<e.length;n++){var r=e[n];"function"==typeof t[r]&&(i[r]=t[r])}var o,a=Object.keys(i);try{!function(t){Object.keys(t).forEach((function(e){var i=t[e];if(void 0===i(void 0,{type:s.INIT}))throw new Error('Reducer "'+e+"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.");if(void 0===i(void 0,{type:s.PROBE_UNKNOWN_ACTION()}))throw new Error('Reducer "'+e+"\" returned undefined when probed with a random type. Don't try to handle "+s.INIT+' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.')}))}(i)}catch(t){o=t}return function(t,e){if(void 0===t&&(t={}),o)throw o;for(var n=!1,r={},s=0;s<a.length;s++){var h=a[s],u=t[h],l=(0,i[h])(u,e);if(void 0===l){var f=c(h,e);throw new Error(f)}r[h]=l,n=n||l!==u}return n?r:t}}function u(t,e){return function(){return e(t.apply(this,arguments))}}function l(t,e){if("function"==typeof t)return u(t,e);if("object"!=typeof t||null===t)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===t?"null":typeof t)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');var i={};for(var n in t){var r=t[n];"function"==typeof r&&(i[n]=u(r,e))}return i}function f(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function d(t,e){var i=Object.keys(t);return Object.getOwnPropertySymbols&&i.push.apply(i,Object.getOwnPropertySymbols(t)),e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i}function v(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?d(i,!0).forEach((function(e){f(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):d(i).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function p(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return 0===e.length?function(t){return t}:1===e.length?e[0]:e.reduce((function(t,e){return function(){return t(e.apply(void 0,arguments))}}))}function b(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return function(t){return function(){var i=t.apply(void 0,arguments),n=function(){throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},r={getState:i.getState,dispatch:function(){return n.apply(void 0,arguments)}},s=e.map((function(t){return t(r)}));return v({},i,{dispatch:n=p.apply(void 0,s)(i.dispatch)})}}}},function(t,e,i){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var r=i(3),s=n(i(14)),o=n(i(15)),a=n(i(16)),c=n(i(17)),h=i(1);e.defaultState={groups:[],items:[],choices:[],loading:!1};var u=r.combineReducers({items:s.default,groups:o.default,choices:a.default,loading:c.default});e.default=function(t,i){var n=t;if("CLEAR_ALL"===i.type)n=e.defaultState;else if("RESET_TO"===i.type)return h.cloneObject(i.state);return u(n,i)}},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),r=function(){function t(t){var e=t.element,i=t.classNames;if(this.element=e,this.classNames=i,!(e instanceof HTMLInputElement||e instanceof HTMLSelectElement))throw new TypeError("Invalid element passed");this.isDisabled=!1}return Object.defineProperty(t.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dir",{get:function(){return this.element.dir},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){return this.element.value},set:function(t){this.element.value=t},enumerable:!0,configurable:!0}),t.prototype.conceal=function(){this.element.classList.add(this.classNames.input),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},t.prototype.reveal=function(){this.element.classList.remove(this.classNames.input),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},t.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},t.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},t.prototype.triggerEvent=function(t,e){n.dispatchEvent(this.element,t,e)},t}();e.default=r},function(t,e,i){function n(t){var e,i=t.Symbol;return"function"==typeof i?i.observable?e=i.observable:(e=i("observable"),i.observable=e):e="@@observable",e}i.d(e,"a",(function(){return n}))},function(t,e,i){t.exports=i(8)},function(t,e,i){var n=this&&this.__spreadArrays||function(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;var n=Array(t),r=0;for(e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n},r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var s=r(i(9)),o=r(i(10)),a=r(i(11)),c=i(18),h=i(0),u=r(i(25)),l=i(26),f=i(27),d=i(28),v=i(29),p=i(1),b=i(4),m="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,g={},y=function(){function t(e,i){var r=this;void 0===e&&(e="[data-choice]"),void 0===i&&(i={}),this.config=o.default.all([h.DEFAULT_CONFIG,t.defaults.options,i],{arrayMerge:function(t,e){return n(e)}});var s=p.diff(this.config,h.DEFAULT_CONFIG);s.length&&console.warn("Unknown config option(s) passed",s.join(", "));var u="string"==typeof e?document.querySelector(e):e;if(!(u instanceof HTMLInputElement||u instanceof HTMLSelectElement))throw TypeError("Expected one of the following types text|select-one|select-multiple");if(this._isTextElement=u.type===h.TEXT_TYPE,this._isSelectOneElement=u.type===h.SELECT_ONE_TYPE,this._isSelectMultipleElement=u.type===h.SELECT_MULTIPLE_TYPE,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this.config.searchEnabled=this._isSelectMultipleElement||this.config.searchEnabled,["auto","always"].includes(""+this.config.renderSelectedChoices)||(this.config.renderSelectedChoices="auto"),i.addItemFilter&&"function"!=typeof i.addItemFilter){var l=i.addItemFilter instanceof RegExp?i.addItemFilter:new RegExp(i.addItemFilter);this.config.addItemFilter=l.test.bind(l)}if(this.passedElement=this._isTextElement?new c.WrappedInput({element:u,classNames:this.config.classNames,delimiter:this.config.delimiter}):new c.WrappedSelect({element:u,classNames:this.config.classNames,template:function(t){return r._templates.option(t)}}),this.initialised=!1,this._store=new a.default,this._initialState=b.defaultState,this._currentState=b.defaultState,this._prevState=b.defaultState,this._currentValue="",this._canSearch=!!this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=p.generateId(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var f=window.getComputedStyle(this.passedElement.element).direction;f!==window.getComputedStyle(document.documentElement).direction&&(this._direction=f)}if(this._idNames={itemChoice:"item-choice"},this._isSelectElement&&(this._presetGroups=this.passedElement.optionGroups,this._presetOptions=this.passedElement.options),this._presetChoices=this.config.choices,this._presetItems=this.config.items,this.passedElement.value&&this._isTextElement){var d=this.passedElement.value.split(this.config.delimiter);this._presetItems=this._presetItems.concat(d)}if(this.passedElement.options&&this.passedElement.options.forEach((function(t){r._presetChoices.push({value:t.value,label:t.innerHTML,selected:!!t.selected,disabled:t.disabled||t.parentNode.disabled,placeholder:""===t.value||t.hasAttribute("placeholder"),customProperties:t.dataset["custom-properties"]})})),this._render=this._render.bind(this),this._onFocus=this._onFocus.bind(this),this._onBlur=this._onBlur.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onClick=this._onClick.bind(this),this._onTouchMove=this._onTouchMove.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onMouseDown=this._onMouseDown.bind(this),this._onMouseOver=this._onMouseOver.bind(this),this._onFormReset=this._onFormReset.bind(this),this._onSelectKey=this._onSelectKey.bind(this),this._onEnterKey=this._onEnterKey.bind(this),this._onEscapeKey=this._onEscapeKey.bind(this),this._onDirectionKey=this._onDirectionKey.bind(this),this._onDeleteKey=this._onDeleteKey.bind(this),this.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:e}),void(this.initialised=!0);this.init()}return Object.defineProperty(t,"defaults",{get:function(){return Object.preventExtensions({get options(){return g},get templates(){return u.default}})},enumerable:!0,configurable:!0}),t.prototype.init=function(){if(!this.initialised){this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(!this.config.addItems||this.passedElement.element.hasAttribute("disabled"))&&this.disable(),this.initialised=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},t.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._isSelectElement&&(this.passedElement.options=this._presetOptions),this._templates=u.default,this.initialised=!1)},t.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},t.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},t.prototype.highlightItem=function(t,e){if(void 0===e&&(e=!0),!t||!t.id)return this;var i=t.id,n=t.groupId,r=void 0===n?-1:n,s=t.value,o=void 0===s?"":s,a=t.label,c=void 0===a?"":a,u=r>=0?this._store.getGroupById(r):null;return this._store.dispatch(f.highlightItem(i,!0)),e&&this.passedElement.triggerEvent(h.EVENTS.highlightItem,{id:i,value:o,label:c,groupValue:u&&u.value?u.value:null}),this},t.prototype.unhighlightItem=function(t){if(!t||!t.id)return this;var e=t.id,i=t.groupId,n=void 0===i?-1:i,r=t.value,s=void 0===r?"":r,o=t.label,a=void 0===o?"":o,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch(f.highlightItem(e,!1)),this.passedElement.triggerEvent(h.EVENTS.highlightItem,{id:e,value:s,label:a,groupValue:c&&c.value?c.value:null}),this},t.prototype.highlightAll=function(){var t=this;return this._store.items.forEach((function(e){return t.highlightItem(e)})),this},t.prototype.unhighlightAll=function(){var t=this;return this._store.items.forEach((function(e){return t.unhighlightItem(e)})),this},t.prototype.removeActiveItemsByValue=function(t){var e=this;return this._store.activeItems.filter((function(e){return e.value===t})).forEach((function(t){return e._removeItem(t)})),this},t.prototype.removeActiveItems=function(t){var e=this;return this._store.activeItems.filter((function(e){return e.id!==t})).forEach((function(t){return e._removeItem(t)})),this},t.prototype.removeHighlightedItems=function(t){var e=this;return void 0===t&&(t=!1),this._store.highlightedActiveItems.forEach((function(i){e._removeItem(i),t&&e._triggerChange(i.value)})),this},t.prototype.showDropdown=function(t){var e=this;return this.dropdown.isActive||this.config.inline||requestAnimationFrame((function(){e.dropdown.show(),e.containerOuter.open(e.dropdown.distanceFromTopWindow),!t&&e._canSearch&&e.input.focus(),e.passedElement.triggerEvent(h.EVENTS.showDropdown,{})})),this},t.prototype.hideDropdown=function(t){var e=this;return this.dropdown.isActive?(requestAnimationFrame((function(){e.dropdown.hide(),e.containerOuter.close(),!t&&e._canSearch&&(e.input.removeActiveDescendant(),e.input.blur()),e.passedElement.triggerEvent(h.EVENTS.hideDropdown,{})})),this):this},t.prototype.getValue=function(t){void 0===t&&(t=!1);var e=this._store.activeItems.reduce((function(e,i){return e.push(t?i.value:i),e}),[]);return this._isSelectOneElement?e[0]:e},t.prototype.setValue=function(t){var e=this;return this.initialised?(t.forEach((function(t){return e._setChoiceOrItem(t)})),this):this},t.prototype.setChoiceByValue=function(t){var e=this;return!this.initialised||this._isTextElement||(Array.isArray(t)?t:[t]).forEach((function(t){return e._findAndSelectChoiceByValue(t)})),this},t.prototype.setChoices=function(t,e,i,n){var r=this;if(void 0===t&&(t=[]),void 0===e&&(e="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof e||!e)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof t){var s=t(this);if("function"==typeof Promise&&s instanceof Promise)return new Promise((function(t){return requestAnimationFrame(t)})).then((function(){return r._handleLoadingState(!0)})).then((function(){return s})).then((function(t){return r.setChoices(t,e,i,n)})).catch((function(t){r.config.silent||console.error(t)})).then((function(){return r._handleLoadingState(!1)})).then((function(){return r}));if(!Array.isArray(s))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: "+typeof s);return this.setChoices(s,e,i,!1)}if(!Array.isArray(t))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._startLoading(),t.forEach((function(t){t.choices?r._addGroup({id:t.id?parseInt(""+t.id,10):null,group:t,valueKey:e,labelKey:i}):r._addChoice({value:t[e],label:t[i],isSelected:!!t.selected,isDisabled:!!t.disabled,placeholder:!!t.placeholder,customProperties:t.customProperties})})),this._stopLoading(),this},t.prototype.clearChoices=function(){return this._store.dispatch(l.clearChoices()),this},t.prototype.clearStore=function(){return this._store.dispatch(v.clearAll()),this},t.prototype.clearInput=function(){return this.input.clear(!this._isSelectElement),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch(l.activateChoices(!0))),this},t.prototype._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var t=this._currentState.items!==this._prevState.items;(this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems(),this._prevState=this._currentState)}},t.prototype._renderChoices=function(){var t=this,e=this._store,i=e.activeGroups,n=e.activeChoices,r=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return t.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var s=n.filter((function(t){return!0===t.placeholder&&-1===t.groupId}));s.length>=1&&(r=this._createChoicesFragment(s,r)),r=this._createGroupsFragment(i,n,r)}else n.length>=1&&(r=this._createChoicesFragment(n,r));if(r.childNodes&&r.childNodes.length>0){var o=this._canAddItem(this._store.activeItems,this.input.value);if(o.response)this.choiceList.append(r),this._highlightChoice();else{var a=this._getTemplate("notice",o.notice);this.choiceList.append(a)}}else{var c=void 0;a=void 0,this._isSearching?(a="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,c=this._getTemplate("notice",a,"no-results")):(a="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,c=this._getTemplate("notice",a,"no-choices")),this.choiceList.append(c)}},t.prototype._renderItems=function(){var t=this._store.activeItems||[];this.itemList.clear();var e=this._createItemsFragment(t);e.childNodes&&this.itemList.append(e)},t.prototype._createGroupsFragment=function(t,e,i){var n=this;return void 0===i&&(i=document.createDocumentFragment()),this.config.shouldSort&&t.sort(this.config.sorter),t.forEach((function(t){var r=function(t){return e.filter((function(e){return n._isSelectOneElement?e.groupId===t.id:e.groupId===t.id&&("always"===n.config.renderSelectedChoices||!e.selected)}))}(t);if(r.length>=1){var s=n._getTemplate("choiceGroup",t);i.appendChild(s),n._createChoicesFragment(r,i,!0)}})),i},t.prototype._createChoicesFragment=function(t,e,i){var r=this;void 0===e&&(e=document.createDocumentFragment()),void 0===i&&(i=!1);var s=this.config,o=s.renderSelectedChoices,a=s.searchResultLimit,c=s.renderChoiceLimit,h=this._isSearching?p.sortByScore:this.config.sorter,u=function(t){if("auto"!==o||r._isSelectOneElement||!t.selected){var i=r._getTemplate("choice",t,r.config.itemSelectText,r.config.inline);e.appendChild(i)}},l=t;"auto"!==o||this._isSelectOneElement||(l=t.filter((function(t){return!t.selected})));var f=l.reduce((function(t,e){return e.placeholder?t.placeholderChoices.push(e):t.normalChoices.push(e),t}),{placeholderChoices:[],normalChoices:[]}),d=f.placeholderChoices,v=f.normalChoices;(this.config.shouldSort||this._isSearching)&&v.sort(h);var b=l.length,m=this._isSelectOneElement?n(d,v):v;this._isSearching?b=a:c&&c>0&&!i&&(b=c);for(var g=0;g<b;g+=1)m[g]&&u(m[g]);return e},t.prototype._createItemsFragment=function(t,e){var i=this;void 0===e&&(e=document.createDocumentFragment());var n=this.config,r=n.removeItemButton;return n.shouldSortItems&&!this._isSelectOneElement&&t.sort(n.sorter),this._isTextElement?this.passedElement.value=t.map((function(t){return t.value})).join(this.config.delimiter):this.passedElement.options=t,t.forEach((function(t){var n=i._getTemplate("item",t,r);e.appendChild(n)})),e},t.prototype._triggerChange=function(t){null!=t&&this.passedElement.triggerEvent(h.EVENTS.change,{value:t})},t.prototype._selectPlaceholderChoice=function(t){this._addItem({value:t.value,label:t.label,choiceId:t.id,groupId:t.groupId,placeholder:t.placeholder}),this._triggerChange(t.value)},t.prototype._handleButtonAction=function(t,e){if(t&&e&&this.config.removeItems&&this.config.removeItemButton){var i=e.parentNode&&e.parentNode.dataset.id,n=i&&t.find((function(t){return t.id===parseInt(i,10)}));n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectElement&&this._store.placeholderChoice&&this._selectPlaceholderChoice(this._store.placeholderChoice))}},t.prototype._handleItemAction=function(t,e,i){var n=this;if(void 0===i&&(i=!1),t&&e&&this.config.removeItems&&!this._isSelectElement){var r=e.dataset.id;t.forEach((function(t){t.id!==parseInt(""+r,10)||t.highlighted?!i&&t.highlighted&&n.unhighlightItem(t):n.highlightItem(t)})),this.input.focus()}},t.prototype._handleChoiceAction=function(t,e){var i=this;if(t&&e){var n=e.dataset.id,r=n&&this._store.getChoiceById(n);if(r&&!r.disabled){var s=this.dropdown.isActive;r.keyCode=t[0]&&t[0].keyCode?t[0].keyCode:void 0,this.passedElement.triggerEvent(h.EVENTS.choice,{choice:r}),r.selected?(this._store.activeItems.filter((function(t){return t.choiceId===r.id})).forEach((function(t){return i._removeItem(t)})),this._triggerChange(r.value)):this._canAddItem(t,r.value).response&&(this._addItem({value:r.value,label:r.label,choiceId:r.id,groupId:r.groupId,customProperties:r.customProperties,placeholder:r.placeholder,keyCode:r.keyCode}),this._triggerChange(r.value)),this.clearInput(),s&&this._isSelectOneElement&&(this.hideDropdown(!0),this.containerOuter.focus())}}},t.prototype._handleBackspace=function(t){if(this.config.removeItems&&t){var e=t[t.length-1],i=t.some((function(t){return t.highlighted}));this.config.editItems&&!i&&e?(this.input.value=e.value,this.input.setWidth(),this._removeItem(e),this._triggerChange(e.value)):(i||this.highlightItem(e,!1),this.removeHighlightedItems(!0))}},t.prototype._startLoading=function(){this._store.dispatch(v.setIsLoading(!0))},t.prototype._stopLoading=function(){this._store.dispatch(v.setIsLoading(!1))},t.prototype._handleLoadingState=function(t){void 0===t&&(t=!0);var e=this.itemList.getChild("."+this.config.classNames.placeholder);t?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?e?e.innerHTML=this.config.loadingText:(e=this._getTemplate("placeholder",this.config.loadingText))&&this.itemList.append(e):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?e&&(e.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},t.prototype._handleSearch=function(t){if(t&&this.input.isFocussed){var e=this.config,i=e.searchFloor,n=e.searchChoices,r=this._store.choices.some((function(t){return!t.active}));if(t&&t.length>=i){var s=n?this._searchChoices(t):0;this.passedElement.triggerEvent(h.EVENTS.search,{value:t,resultCount:s})}else r&&(this._isSearching=!1,this._store.dispatch(l.activateChoices(!0)))}},t.prototype._canAddItem=function(t,e){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(e):this.config.addItemText;if(!this._isSelectOneElement){var r=p.existsInArray(t,e);this.config.maxItemCount>0&&this.config.maxItemCount<=t.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&r&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(e):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(e)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(e):this.config.customAddItemText)}return{response:i,notice:n}},t.prototype._searchChoices=function(t){var e="string"==typeof t?t.trim():t,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(e.length<1&&e===i+" ")return 0;var r=this._store.searchableChoices,o=e,a=n(this.config.searchFields),c=Object.assign(this.config.fuseOptions,{keys:a,includeMatches:!0}),h=new s.default(r,c).search(o);return this._currentValue=e,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(l.filterChoices(h)),h.length},t.prototype._addEventListeners=function(){var t=document.documentElement;t.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),t.addEventListener("click",this._onClick,{passive:!0}),t.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},t.prototype._removeEventListeners=function(){var t=document.documentElement;t.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),t.removeEventListener("click",this._onClick),t.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},t.prototype._onKeyDown=function(t){var e=t.code,i=t.key,n=this._store.activeItems,r=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),a=/[a-zA-Z0-9-_ ]/.test(i),c=h.KEY_CODES.BACK_KEY,u=h.KEY_CODES.DELETE_KEY,l=h.KEY_CODES.ENTER_KEY,f=h.KEY_CODES.A_KEY,d=h.KEY_CODES.ESC_KEY,v=h.KEY_CODES.UP_KEY,p=h.KEY_CODES.DOWN_KEY,b=h.KEY_CODES.PAGE_UP_KEY,m=h.KEY_CODES.PAGE_DOWN_KEY,g=e===c||e===u||e===v||e===p||e===h.KEY_CODES.LEFT_KEY||e===h.KEY_CODES.RIGHT_KEY||e===b||e===m||e===d;switch(this._isTextElement||s||!a||(this.showDropdown(),this.input.isFocussed||g||(this.input.value+=i.toLowerCase())),e){case f:return this._onSelectKey(t,o);case l:return this._onEnterKey(t,n,s);case d:return this._onEscapeKey(s);case v:case b:case p:case m:return this._onDirectionKey(t,s);case u:case c:return this._onDeleteKey(t,n,r)}},t.prototype._onKeyUp=function(t){var e=t.target,i=t.code,n=this.input.value,r=this._canAddItem(this._store.activeItems,n),s=h.KEY_CODES.BACK_KEY,o=h.KEY_CODES.DELETE_KEY,a=h.KEY_CODES.ESC_KEY,c=h.KEY_CODES.UP_KEY,u=h.KEY_CODES.DOWN_KEY,f=h.KEY_CODES.LEFT_KEY,d=h.KEY_CODES.RIGHT_KEY,v=h.KEY_CODES.PAGE_UP_KEY,p=h.KEY_CODES.PAGE_DOWN_KEY;if(this._isTextElement)if(r.notice&&n){var b=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=b.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0);else{var m=i===s||i===o,g=m||i===c||i===u||i===f||i===d||i===v||i===p||i===a,y=this._canSearch&&r.response;m&&e&&!e.value&&!this._isTextElement&&this._isSearching?(this._isSearching=!1,this._store.dispatch(l.activateChoices(!0))):y&&!g&&this._handleSearch(this.input.value)}this._canSearch=this.config.searchEnabled},t.prototype._onSelectKey=function(t,e){(t.ctrlKey||t.metaKey)&&e&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},t.prototype._onEnterKey=function(t,e,i){var n=t.target,r=h.KEY_CODES.ENTER_KEY,s=n&&n.hasAttribute("data-button");if(this._isTextElement&&n&&n.value){var o=this.input.value;this._canAddItem(e,o).response&&(this.hideDropdown(!0),this._addItem({value:o}),this._triggerChange(o),this.clearInput())}if(s&&(this._handleButtonAction(e,n),t.preventDefault()),i){var a=this.dropdown.getChild("."+this.config.classNames.highlightedState);a&&(e[0]&&(e[0].keyCode=r),this._handleChoiceAction(e,a)),t.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),t.preventDefault())},t.prototype._onEscapeKey=function(t){t&&(this.hideDropdown(!0),this.containerOuter.focus())},t.prototype._onDirectionKey=function(t,e){var i=t.code,n=t.metaKey,r=h.KEY_CODES.DOWN_KEY,s=h.KEY_CODES.PAGE_UP_KEY,o=h.KEY_CODES.PAGE_DOWN_KEY;if(e||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=i===r||i===o?1:-1,c="[data-choice-selectable]",u=void 0;if(n||i===o||i===s)u=this.dropdown.element.querySelector(a>0?"[data-choice-selectable]:last-of-type":c);else{var l=this.dropdown.element.querySelector("."+this.config.classNames.highlightedState);u=l?p.getAdjacentEl(l,c,a):this.dropdown.element.querySelector(c)}u&&(p.isScrolledIntoView(u,this.choiceList.element,a)||this.choiceList.scrollToChildElement(u,a),this._highlightChoice(u)),t.preventDefault()}},t.prototype._onDeleteKey=function(t,e,i){this._isSelectOneElement||t.target.value||!i||(this._handleBackspace(e),t.preventDefault())},t.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},t.prototype._onTouchEnd=function(t){var e=(t||t.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(e)&&((e===this.containerOuter.element||e===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),t.stopPropagation()),this._wasTap=!0},t.prototype._onMouseDown=function(t){var e=t.target;if(e instanceof HTMLElement){if(m&&this.choiceList.element.contains(e)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?t.offsetX>=i.offsetWidth:t.offsetX<i.offsetLeft}if(e!==this.input.element){var n=e.closest("[data-button],[data-item],[data-choice]");if(n instanceof HTMLElement){var r=t.shiftKey,s=this._store.activeItems,o=n.dataset;"button"in o?this._handleButtonAction(s,n):"item"in o?this._handleItemAction(s,n,r):"choice"in o&&this._handleChoiceAction(s,n)}t.preventDefault()}}},t.prototype._onMouseOver=function(t){var e=t.target;e instanceof HTMLElement&&"choice"in e.dataset&&this._highlightChoice(e)},t.prototype._onClick=function(t){var e=t.target;this.containerOuter.element.contains(e)?this.dropdown.isActive||this.containerOuter.isDisabled?this._isSelectOneElement&&e!==this.input.element&&!this.dropdown.element.contains(e)&&this.hideDropdown():this._isTextElement?document.activeElement!==this.input.element&&this.input.focus():(this.showDropdown(),this.containerOuter.focus()):(this._store.highlightedActiveItems.length>0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},t.prototype._onFocus=function(t){var e,i=this,n=t.target;n&&this.containerOuter.element.contains(n)&&((e={})[h.TEXT_TYPE]=function(){n===i.input.element&&i.containerOuter.addFocusState()},e[h.SELECT_ONE_TYPE]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},e[h.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},e)[this.passedElement.element.type]()},t.prototype._onBlur=function(t){var e,i=this,n=t.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var r=this._store.activeItems.some((function(t){return t.highlighted}));((e={})[h.TEXT_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),r&&i.unhighlightAll(),i.hideDropdown(!0))},e[h.SELECT_ONE_TYPE]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},e[h.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),r&&i.unhighlightAll())},e)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},t.prototype._onFormReset=function(){this._store.dispatch(v.resetTo(this._initialState))},t.prototype._highlightChoice=function(t){var e=this;void 0===t&&(t=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=t;Array.from(this.dropdown.element.querySelectorAll("."+this.config.classNames.highlightedState)).forEach((function(t){t.classList.remove(e.config.classNames.highlightedState),t.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(h.EVENTS.highlightChoice,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},t.prototype._addItem=function(t){var e=t.value,i=t.label,n=void 0===i?null:i,r=t.choiceId,s=void 0===r?-1:r,o=t.groupId,a=void 0===o?-1:o,c=t.customProperties,u=void 0===c?{}:c,l=t.placeholder,d=void 0!==l&&l,v=t.keyCode,p=void 0===v?"":v,b="string"==typeof e?e.trim():e,m=this._store.items,g=n||b,y=s||-1,w=a>=0?this._store.getGroupById(a):null,O=m?m.length+1:1;this.config.prependValue&&(b=this.config.prependValue+b.toString()),this.config.appendValue&&(b+=this.config.appendValue.toString()),this._store.dispatch(f.addItem({value:b,label:g,id:O,choiceId:y,groupId:a,customProperties:u,placeholder:d,keyCode:p})),this._isSelectOneElement&&this.removeActiveItems(O),this.passedElement.triggerEvent(h.EVENTS.addItem,{id:O,value:b,label:g,customProperties:u,groupValue:w&&w.value?w.value:null,keyCode:p})},t.prototype._removeItem=function(t){var e=t.id,i=t.value,n=t.label,r=t.customProperties,s=t.choiceId,o=t.groupId,a=o&&o>=0?this._store.getGroupById(o):null;e&&s&&(this._store.dispatch(f.removeItem(e,s)),this.passedElement.triggerEvent(h.EVENTS.removeItem,{id:e,value:i,label:n,customProperties:r,groupValue:a&&a.value?a.value:null}))},t.prototype._addChoice=function(t){var e=t.value,i=t.label,n=t.isSelected,r=void 0!==n&&n,s=t.isDisabled,o=t.groupId,a=t.customProperties,c=void 0===a?{}:a,h=t.placeholder,u=void 0!==h&&h,f=t.keyCode,d=void 0===f?"":f;if(null!=e){var v=this._store.choices,p=(void 0===i?null:i)||e,b=v?v.length+1:1;this._store.dispatch(l.addChoice({id:b,groupId:void 0===o?-1:o,elementId:this._baseId+"-"+this._idNames.itemChoice+"-"+b,value:e,label:p,disabled:void 0!==s&&s,customProperties:c,placeholder:u,keyCode:d})),r&&this._addItem({value:e,label:p,choiceId:b,customProperties:c,placeholder:u,keyCode:d})}},t.prototype._addGroup=function(t){var e=this,i=t.group,n=t.id,r=t.valueKey,s=void 0===r?"value":r,o=t.labelKey,a=void 0===o?"label":o,c=p.isType("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),h=n||Math.floor((new Date).valueOf()*Math.random());c?(this._store.dispatch(d.addGroup({value:i.label,id:h,active:!0,disabled:!!i.disabled&&i.disabled})),c.forEach((function(t){var i=t.disabled||t.parentNode&&t.parentNode.disabled;e._addChoice({value:t[s],label:p.isType("Object",t)?t[a]:t.innerHTML,isSelected:t.selected,isDisabled:i,groupId:h,customProperties:t.customProperties,placeholder:t.placeholder})}))):this._store.dispatch(d.addGroup({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},t.prototype._getTemplate=function(t){for(var e,i=[],r=1;r<arguments.length;r++)i[r-1]=arguments[r];var s=this.config.classNames;return(e=this._templates[t]).call.apply(e,n([this,s],i))},t.prototype._createTemplates=function(){var t=this.config.callbackOnCreateTemplates,e={};t&&"function"==typeof t&&(e=t.call(this,p.strToEl)),this._templates=o.default(u.default,e)},t.prototype._createElements=function(){this.containerOuter=new c.Container({element:this._getTemplate("containerOuter",this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this.passedElement.element.type),classNames:this.config.classNames,type:this.passedElement.element.type,position:this.config.position,inline:this.config.inline}),this.containerInner=new c.Container({element:this._getTemplate("containerInner"),classNames:this.config.classNames,type:this.passedElement.element.type,position:this.config.position,inline:this.config.inline}),this.input=new c.Input({element:this._getTemplate("input",this._placeholderValue),classNames:this.config.classNames,type:this.passedElement.element.type,preventPaste:!this.config.paste}),this.choiceList=new c.List({element:this._getTemplate("choiceList",this._isSelectOneElement)}),this.itemList=new c.List({element:this._getTemplate("itemList",this._isSelectOneElement)}),this.dropdown=new c.Dropdown({element:this._getTemplate("dropdown"),classNames:this.config.classNames,type:this.passedElement.element.type,inline:this.config.inline})},t.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectElement?this.input.placeholder=this.config.searchPlaceholderValue||"":this._placeholderValue&&(this.input.placeholder=this._placeholderValue,this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this._isTextElement||this.dropdown.element.appendChild(this.choiceList.element),this._isSelectElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._isSelectElement&&(this._highlightPosition=0,this._isSearching=!1,this._startLoading(),this._presetGroups.length?this._addPredefinedGroups(this._presetGroups):this._addPredefinedChoices(this._presetChoices),this._stopLoading()),this._isTextElement&&this._addPredefinedItems(this._presetItems)},t.prototype._addPredefinedGroups=function(t){var e=this,i=this.passedElement.placeholderOption;i&&i.parentNode&&"SELECT"===i.parentNode.tagName&&this._addChoice({value:i.value,label:i.innerHTML,isSelected:i.selected,isDisabled:i.disabled,placeholder:!0}),t.forEach((function(t){return e._addGroup({group:t,id:t.id||null})}))},t.prototype._addPredefinedChoices=function(t){var e=this;this.config.shouldSort&&t.sort(this.config.sorter);var i=t.some((function(t){return t.selected}));t.forEach((function(t){var n=t.value,r=void 0===n?"":n,s=t.label,o=t.customProperties,a=t.placeholder;e._isSelectElement?t.choices?e._addGroup({group:t,id:t.id||null}):e._addChoice({value:r,label:s,isSelected:!!(e._isSelectOneElement&&!i||t.selected),isDisabled:!!t.disabled,placeholder:!!a,customProperties:o}):e._addChoice({value:r,label:s,isSelected:!!t.selected,isDisabled:!!t.disabled,placeholder:!!t.placeholder,customProperties:o})}))},t.prototype._addPredefinedItems=function(t){var e=this;t.forEach((function(t){"object"==typeof t&&t.value&&e._addItem({value:t.value,label:t.label,choiceId:t.id,customProperties:t.customProperties,placeholder:t.placeholder}),"string"==typeof t&&e._addItem({value:t})}))},t.prototype._setChoiceOrItem=function(t){var e=this;({object:function(){t.value&&(e._isTextElement?e._addItem({value:t.value,label:t.label,choiceId:t.id,customProperties:t.customProperties,placeholder:t.placeholder}):e._addChoice({value:t.value,label:t.label,isSelected:!0,isDisabled:!1,customProperties:t.customProperties,placeholder:t.placeholder}))},string:function(){e._isTextElement?e._addItem({value:t}):e._addChoice({value:t,label:t,isSelected:!0,isDisabled:!1})}})[p.getType(t).toLowerCase()]()},t.prototype._findAndSelectChoiceByValue=function(t){var e=this,i=this._store.choices.find((function(i){return e.config.valueComparer(i.value,t)}));i&&!i.selected&&this._addItem({value:i.value,label:i.label,choiceId:i.id,groupId:i.groupId,customProperties:i.customProperties,placeholder:i.placeholder,keyCode:i.keyCode})},t.prototype._generatePlaceholderValue=function(){if(this._isSelectElement&&this.passedElement.placeholderOption){var t=this.passedElement.placeholderOption;return t?t.text:null}var e=this.config,i=e.placeholderValue,n=this.passedElement.element.dataset;if(e.placeholder){if(i)return i;if(n.placeholder)return n.placeholder}return null},t}();e.default=y},function(t){
/*!
* Fuse.js v3.4.6 - Lightweight fuzzy-search (http://fusejs.io)
*
* Copyright (c) 2012-2017 Kirollos Risk (http://kiro.me)
* All Rights Reserved. Apache Software License 2.0
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
t.exports=function(t){var e={};function i(n){if(e[n])return e[n].exports;var r=e[n]={i:n,l:!1,exports:{}};return t[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(n,r,function(e){return t[e]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=1)}([function(t){t.exports=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===Object.prototype.toString.call(t)}},function(t,e,i){function n(t){return(n="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})(t)}var r=i(2),s=i(8),o=i(0),a=function(){function t(e,i){var n=i.location,r=void 0===n?0:n,o=i.distance,a=void 0===o?100:o,c=i.threshold,h=void 0===c?.6:c,u=i.maxPatternLength,l=void 0===u?32:u,f=i.caseSensitive,d=void 0!==f&&f,v=i.tokenSeparator,p=void 0===v?/ +/g:v,b=i.findAllMatches,m=void 0!==b&&b,g=i.minMatchCharLength,y=void 0===g?1:g,w=i.id,O=void 0===w?null:w,k=i.keys,_=void 0===k?[]:k,x=i.shouldSort,I=void 0===x||x,j=i.getFn,E=void 0===j?s:j,C=i.sortFn,S=void 0===C?function(t,e){return t.score-e.score}:C,A=i.tokenize,T=void 0!==A&&A,M=i.matchAllTokens,P=void 0!==M&&M,L=i.includeMatches,D=void 0!==L&&L,N=i.includeScore,R=void 0!==N&&N,H=i.verbose,z=void 0!==H&&H;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options={location:r,distance:a,threshold:h,maxPatternLength:l,isCaseSensitive:d,tokenSeparator:p,findAllMatches:m,minMatchCharLength:y,id:O,keys:_,includeMatches:D,includeScore:R,shouldSort:I,getFn:E,sortFn:S,verbose:z,tokenize:T,matchAllTokens:P},this.setCollection(e)}var e;return(e=[{key:"setCollection",value:function(t){return this.list=t,t}},{key:"search",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(t,'"'));var i=this._prepareSearchers(t),n=this._search(i.tokenSearchers,i.fullSearcher),r=n.results;return this._computeScore(n.weights,r),this.options.shouldSort&&this._sort(r),e.limit&&"number"==typeof e.limit&&(r=r.slice(0,e.limit)),this._format(r)}},{key:"_prepareSearchers",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=[];if(this.options.tokenize)for(var i=t.split(this.options.tokenSeparator),n=0,s=i.length;n<s;n+=1)e.push(new r(i[n],this.options));return{tokenSearchers:e,fullSearcher:new r(t,this.options)}}},{key:"_search",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1?arguments[1]:void 0,i=this.list,n={},r=[];if("string"==typeof i[0]){for(var s=0,o=i.length;s<o;s+=1)this._analyze({key:"",value:i[s],record:s,index:s},{resultMap:n,results:r,tokenSearchers:t,fullSearcher:e});return{weights:null,results:r}}for(var a={},c=0,h=i.length;c<h;c+=1)for(var u=i[c],l=0,f=this.options.keys.length;l<f;l+=1){var d=this.options.keys[l];if("string"!=typeof d){if(a[d.name]={weight:1-d.weight||1},d.weight<=0||d.weight>1)throw new Error("Key weight has to be > 0 and <= 1");d=d.name}else a[d]={weight:1};this._analyze({key:d,value:this.options.getFn(u,d),record:u,index:c},{resultMap:n,results:r,tokenSearchers:t,fullSearcher:e})}return{weights:a,results:r}}},{key:"_analyze",value:function(t,e){var i=t.key,n=t.arrayIndex,r=void 0===n?-1:n,s=t.value,a=t.record,c=t.index,h=e.tokenSearchers,u=void 0===h?[]:h,l=e.fullSearcher,f=void 0===l?[]:l,d=e.resultMap,v=void 0===d?{}:d,p=e.results,b=void 0===p?[]:p;if(null!=s){var m=!1,g=-1,y=0;if("string"==typeof s){this._log("\nKey: ".concat(""===i?"-":i));var w=f.search(s);if(this._log('Full text: "'.concat(s,'", score: ').concat(w.score)),this.options.tokenize){for(var O=s.split(this.options.tokenSeparator),k=[],_=0;_<u.length;_+=1){var x=u[_];this._log('\nPattern: "'.concat(x.pattern,'"'));for(var I=!1,j=0;j<O.length;j+=1){var E=O[j],C=x.search(E),S={};C.isMatch?(S[E]=C.score,m=!0,I=!0,k.push(C.score)):(S[E]=1,this.options.matchAllTokens||k.push(1)),this._log('Token: "'.concat(E,'", score: ').concat(S[E]))}I&&(y+=1)}g=k[0];for(var A=k.length,T=1;T<A;T+=1)g+=k[T];this._log("Token score average:",g/=A)}var M=w.score;g>-1&&(M=(M+g)/2),this._log("Score average:",M);var P=!this.options.tokenize||!this.options.matchAllTokens||y>=u.length;if(this._log("\nCheck Matches: ".concat(P)),(m||w.isMatch)&&P){var L=v[c];L?L.output.push({key:i,arrayIndex:r,value:s,score:M,matchedIndices:w.matchedIndices}):(v[c]={item:a,output:[{key:i,arrayIndex:r,value:s,score:M,matchedIndices:w.matchedIndices}]},b.push(v[c]))}}else if(o(s))for(var D=0,N=s.length;D<N;D+=1)this._analyze({key:i,arrayIndex:D,value:s[D],record:a,index:c},{resultMap:v,results:b,tokenSearchers:u,fullSearcher:f})}}},{key:"_computeScore",value:function(t,e){this._log("\n\nComputing score:\n");for(var i=0,n=e.length;i<n;i+=1){for(var r=e[i].output,s=r.length,o=1,a=1,c=0;c<s;c+=1){var h=t?t[r[c].key].weight:1,u=(1===h?r[c].score:r[c].score||.001)*h;1!==h?a=Math.min(a,u):(r[c].nScore=u,o*=u)}e[i].score=1===a?o:a,this._log(e[i])}}},{key:"_sort",value:function(t){this._log("\n\nSorting...."),t.sort(this.options.sortFn)}},{key:"_format",value:function(t){var e=[];if(this.options.verbose){var i=[];this._log("\n\nOutput:\n\n",JSON.stringify(t,(function(t,e){if("object"===n(e)&&null!==e){if(-1!==i.indexOf(e))return;i.push(e)}return e}))),i=null}var r=[];this.options.includeMatches&&r.push((function(t,e){var i=t.output;e.matches=[];for(var n=0,r=i.length;n<r;n+=1){var s=i[n];if(0!==s.matchedIndices.length){var o={indices:s.matchedIndices,value:s.value};s.key&&(o.key=s.key),s.hasOwnProperty("arrayIndex")&&s.arrayIndex>-1&&(o.arrayIndex=s.arrayIndex),e.matches.push(o)}}})),this.options.includeScore&&r.push((function(t,e){e.score=t.score}));for(var s=0,o=t.length;s<o;s+=1){var a=t[s];if(this.options.id&&(a.item=this.options.getFn(a.item,this.options.id)[0]),r.length){for(var c={item:a.item},h=0,u=r.length;h<u;h+=1)r[h](a,c);e.push(c)}else e.push(a.item)}return e}},{key:"_log",value:function(){var t;this.options.verbose&&(t=console).log.apply(t,arguments)}}])&&function(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}(t.prototype,e),t}();t.exports=a},function(t,e,i){var n=i(3),r=i(4),s=i(7),o=function(){function t(e,i){var n=i.location,r=void 0===n?0:n,o=i.distance,a=void 0===o?100:o,c=i.threshold,h=void 0===c?.6:c,u=i.maxPatternLength,l=void 0===u?32:u,f=i.isCaseSensitive,d=void 0!==f&&f,v=i.tokenSeparator,p=void 0===v?/ +/g:v,b=i.findAllMatches,m=void 0!==b&&b,g=i.minMatchCharLength,y=void 0===g?1:g;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options={location:r,distance:a,threshold:h,maxPatternLength:l,isCaseSensitive:d,tokenSeparator:p,findAllMatches:m,minMatchCharLength:y},this.pattern=this.options.isCaseSensitive?e:e.toLowerCase(),this.pattern.length<=l&&(this.patternAlphabet=s(this.pattern))}var e;return(e=[{key:"search",value:function(t){if(this.options.isCaseSensitive||(t=t.toLowerCase()),this.pattern===t)return{isMatch:!0,score:0,matchedIndices:[[0,t.length-1]]};var e=this.options;if(this.pattern.length>e.maxPatternLength)return n(t,this.pattern,e.tokenSeparator);var i=this.options;return r(t,this.pattern,this.patternAlphabet,{location:i.location,distance:i.distance,threshold:i.threshold,findAllMatches:i.findAllMatches,minMatchCharLength:i.minMatchCharLength})}}])&&function(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}(t.prototype,e),t}();t.exports=o},function(t){var e=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;t.exports=function(t,i){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,r=new RegExp(i.replace(e,"\\$&").replace(n,"|")),s=t.match(r),o=!!s,a=[];if(o)for(var c=0,h=s.length;c<h;c+=1){var u=s[c];a.push([t.indexOf(u),u.length-1])}return{score:o?.5:1,isMatch:o,matchedIndices:a}}},function(t,e,i){var n=i(5),r=i(6);t.exports=function(t,e,i,s){for(var o=s.location,a=s.distance,c=void 0===a?100:a,h=s.threshold,u=s.findAllMatches,l=void 0!==u&&u,f=s.minMatchCharLength,d=void 0===f?1:f,v=void 0===o?0:o,p=t.length,b=void 0===h?.6:h,m=t.indexOf(e,v),g=e.length,y=[],w=0;w<p;w+=1)y[w]=0;if(-1!==m){var O=n(e,{errors:0,currentLocation:m,expectedLocation:v,distance:c});if(b=Math.min(O,b),-1!==(m=t.lastIndexOf(e,v+g))){var k=n(e,{errors:0,currentLocation:m,expectedLocation:v,distance:c});b=Math.min(k,b)}}m=-1;for(var _=[],x=1,I=g+p,j=1<<(g<=31?g-1:30),E=0;E<g;E+=1){for(var C=0,S=I;C<S;)n(e,{errors:E,currentLocation:v+S,expectedLocation:v,distance:c})<=b?C=S:I=S,S=Math.floor((I-C)/2+C);I=S;var A=Math.max(1,v-S+1),T=l?p:Math.min(v+S,p)+g,M=Array(T+2);M[T+1]=(1<<E)-1;for(var P=T;P>=A;P-=1){var L=P-1,D=i[t.charAt(L)];if(D&&(y[L]=1),M[P]=(M[P+1]<<1|1)&D,0!==E&&(M[P]|=(_[P+1]|_[P])<<1|1|_[P+1]),M[P]&j&&(x=n(e,{errors:E,currentLocation:L,expectedLocation:v,distance:c}))<=b){if(b=x,(m=L)<=v)break;A=Math.max(1,2*v-m)}}if(n(e,{errors:E+1,currentLocation:v,expectedLocation:v,distance:c})>b)break;_=M}return{isMatch:m>=0,score:0===x?.001:x,matchedIndices:r(y,d)}}},function(t){t.exports=function(t,e){var i=e.errors,n=e.currentLocation,r=e.expectedLocation,s=e.distance,o=void 0===s?100:s,a=(void 0===i?0:i)/t.length,c=Math.abs((void 0===r?0:r)-(void 0===n?0:n));return o?a+c/o:c?1:a}},function(t){t.exports=function(){for(var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=[],n=-1,r=-1,s=0,o=t.length;s<o;s+=1){var a=t[s];a&&-1===n?n=s:a||-1===n||((r=s-1)-n+1>=e&&i.push([n,r]),n=-1)}return t[s-1]&&s-n>=e&&i.push([n,s-1]),i}},function(t){t.exports=function(t){for(var e={},i=t.length,n=0;n<i;n+=1)e[t.charAt(n)]=0;for(var r=0;r<i;r+=1)e[t.charAt(r)]|=1<<i-r-1;return e}},function(t,e,i){var n=i(0);t.exports=function(t,e){return function t(e,i,r){if(i){var s=i.indexOf("."),o=i,a=null;-1!==s&&(o=i.slice(0,s),a=i.slice(s+1));var c=e[o];if(null!=c)if(a||"string"!=typeof c&&"number"!=typeof c)if(n(c))for(var h=0,u=c.length;h<u;h+=1)t(c[h],a,r);else a&&t(c,a,r);else r.push(c.toString())}else r.push(e);return r}(t,e,[])}}])},function(t){var e=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||function(t){return t.$$typeof===i}(t)}(t)},i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(t,e){return!1!==e.clone&&e.isMergeableObject(t)?o(Array.isArray(t)?[]:{},t,e):t}function r(t,e,i){return t.concat(e).map((function(t){return n(t,i)}))}function s(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return t.propertyIsEnumerable(e)})):[]}(t))}function o(t,i,a){(a=a||{}).arrayMerge=a.arrayMerge||r,a.isMergeableObject=a.isMergeableObject||e,a.cloneUnlessOtherwiseSpecified=n;var c=Array.isArray(i);return c===Array.isArray(t)?c?a.arrayMerge(t,i,a):function(t,e,i){var r={};return i.isMergeableObject(t)&&s(t).forEach((function(e){r[e]=n(t[e],i)})),s(e).forEach((function(s){(function(t,e){try{return e in t&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))}catch(t){return!1}})(t,s)||(r[s]=i.isMergeableObject(e[s])&&t[s]?function(t,e){if(!e.customMerge)return o;var i=e.customMerge(t);return"function"==typeof i?i:o}(s,i)(t[s],e[s],i):n(e[s],i))})),r}(t,i,a):n(i,a)}o.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,i){return o(t,i,e)}),{})},t.exports=o},function(t,e,i){var n=this&&this.__spreadArrays||function(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;var n=Array(t),r=0;for(e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n},r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var s=i(3),o=r(i(4)),a=function(){function t(){this._store=s.createStore(o.default,window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__())}return t.prototype.subscribe=function(t){this._store.subscribe(t)},t.prototype.dispatch=function(t){this._store.dispatch(t)},Object.defineProperty(t.prototype,"state",{get:function(){return this._store.getState()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"items",{get:function(){return this.state.items},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeItems",{get:function(){return this.items.filter((function(t){return!0===t.active}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"highlightedActiveItems",{get:function(){return this.items.filter((function(t){return t.active&&t.highlighted}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choices",{get:function(){return this.state.choices},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeChoices",{get:function(){return this.choices.filter((function(t){return!0===t.active}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"selectableChoices",{get:function(){return this.choices.filter((function(t){return!0!==t.disabled}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"searchableChoices",{get:function(){return this.selectableChoices.filter((function(t){return!0!==t.placeholder}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"placeholderChoice",{get:function(){return n(this.choices).reverse().find((function(t){return!0===t.placeholder}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"groups",{get:function(){return this.state.groups},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeGroups",{get:function(){var t=this.choices;return this.groups.filter((function(e){var i=!0===e.active&&!1===e.disabled,n=t.some((function(t){return!0===t.active&&!1===t.disabled}));return i&&n}),[])},enumerable:!0,configurable:!0}),t.prototype.isLoading=function(){return this.state.loading},t.prototype.getChoiceById=function(t){return this.activeChoices.find((function(e){return e.id===parseInt(t,10)}))},t.prototype.getGroupById=function(t){return this.groups.find((function(e){return e.id===t}))},t}();e.default=a},function(t){var e;e=function(){return this}();try{e=e||new Function("return this")()}catch(t){"object"==typeof window&&(e=window)}t.exports=e},function(t){t.exports=function(t){if(!t.webpackPolyfill){var e=Object.create(t);e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),Object.defineProperty(e,"exports",{enumerable:!0}),e.webpackPolyfill=1}return e}},function(t,e){var i=this&&this.__spreadArrays||function(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;var n=Array(t),r=0;for(e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultState=[],e.default=function(t,n){switch(void 0===t&&(t=e.defaultState),n.type){case"ADD_ITEM":return i(t,[{id:n.id,choiceId:n.choiceId,groupId:n.groupId,value:n.value,label:n.label,active:!0,highlighted:!1,customProperties:n.customProperties,placeholder:n.placeholder||!1,keyCode:null}]).map((function(t){var e=t;return e.highlighted=!1,e}));case"REMOVE_ITEM":return t.map((function(t){var e=t;return e.id===n.id&&(e.active=!1),e}));case"HIGHLIGHT_ITEM":var r=n;return t.map((function(t){var e=t;return e.id===r.id&&(e.highlighted=r.highlighted),e}));default:return t}}},function(t,e){var i=this&&this.__spreadArrays||function(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;var n=Array(t),r=0;for(e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultState=[],e.default=function(t,n){switch(void 0===t&&(t=e.defaultState),n.type){case"ADD_GROUP":return i(t,[{id:n.id,value:n.value,active:n.active,disabled:n.disabled}]);case"CLEAR_CHOICES":return[];default:return t}}},function(t,e){var i=this&&this.__spreadArrays||function(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;var n=Array(t),r=0;for(e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultState=[],e.default=function(t,n){switch(void 0===t&&(t=e.defaultState),n.type){case"ADD_CHOICE":return i(t,[{id:n.id,elementId:n.elementId,groupId:n.groupId,value:n.value,label:n.label||n.value,disabled:n.disabled||!1,selected:!1,active:!0,score:9999,customProperties:n.customProperties,placeholder:n.placeholder||!1}]);case"ADD_ITEM":var r=n;return r.choiceId>-1?t.map((function(t){var e=t;return e.id===parseInt(""+r.choiceId,10)&&(e.selected=!0),e})):t;case"REMOVE_ITEM":var s=n;return s.choiceId&&s.choiceId>-1?t.map((function(t){var e=t;return e.id===parseInt(""+s.choiceId,10)&&(e.selected=!1),e})):t;case"FILTER_CHOICES":var o=n;return t.map((function(t){var e=t;return e.active=o.results.some((function(t){return t.item.id===e.id&&(e.score=t.score,!0)})),e}));case"ACTIVATE_CHOICES":var a=n;return t.map((function(t){var e=t;return e.active=a.active,e}));case"CLEAR_CHOICES":return e.defaultState;default:return t}}},function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultState=!1,e.default=function(t,i){switch(void 0===t&&(t=e.defaultState),i.type){case"SET_IS_LOADING":return i.isLoading;default:return t}}},function(t,e,i){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var r=n(i(19));e.Dropdown=r.default;var s=n(i(20));e.Container=s.default;var o=n(i(21));e.Input=o.default;var a=n(i(22));e.List=a.default;var c=n(i(23));e.WrappedInput=c.default;var h=n(i(24));e.WrappedSelect=h.default},function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t){var e=t.type,i=t.classNames;this.element=t.element,this.classNames=i,this.type=e,this.isActive=!1,this.inline=!0}return Object.defineProperty(t.prototype,"distanceFromTopWindow",{get:function(){return this.element.getBoundingClientRect().bottom},enumerable:!0,configurable:!0}),t.prototype.getChild=function(t){return this.element.querySelector(t)},t.prototype.show=function(){return this.inline||(this.element.classList.add(this.classNames.activeState),this.element.setAttribute("aria-expanded","true"),this.isActive=!0),this},t.prototype.hide=function(){return this.inline||(this.element.classList.remove(this.classNames.activeState),this.element.setAttribute("aria-expanded","false"),this.isActive=!1),this},t}();e.default=i},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),r=i(0),s=function(){function t(t){var e=t.type,i=t.classNames,n=t.position;this.element=t.element,this.classNames=i,this.type=e,this.position=n,this.isOpen=this.inline,this.isFlipped=!1,this.isFocussed=!1,this.isDisabled=!1,this.isLoading=!1,this._onFocus=this._onFocus.bind(this),this._onBlur=this._onBlur.bind(this)}return t.prototype.addEventListeners=function(){this.element.addEventListener("focus",this._onFocus),this.element.addEventListener("blur",this._onBlur)},t.prototype.removeEventListeners=function(){this.element.removeEventListener("focus",this._onFocus),this.element.removeEventListener("blur",this._onBlur)},t.prototype.shouldFlip=function(t){if("number"!=typeof t)return!1;var e=!1;return"auto"===this.position?e=!window.matchMedia("(min-height: "+(t+1)+"px)").matches:"top"===this.position&&(e=!0),e},t.prototype.setActiveDescendant=function(t){this.element.setAttribute("aria-activedescendant",t)},t.prototype.removeActiveDescendant=function(){this.element.removeAttribute("aria-activedescendant")},t.prototype.open=function(t){this.element.classList.add(this.classNames.openState),this.element.setAttribute("aria-expanded","true"),this.isOpen=!0,this.shouldFlip(t)&&(this.element.classList.add(this.classNames.flippedState),this.isFlipped=!0)},t.prototype.close=function(){this.element.classList.remove(this.classNames.openState),this.element.setAttribute("aria-expanded","false"),this.removeActiveDescendant(),this.isOpen=!1,this.isFlipped&&(this.element.classList.remove(this.classNames.flippedState),this.isFlipped=!1)},t.prototype.focus=function(){this.isFocussed||this.element.focus()},t.prototype.addFocusState=function(){this.element.classList.add(this.classNames.focusState)},t.prototype.removeFocusState=function(){this.element.classList.remove(this.classNames.focusState)},t.prototype.enable=function(){this.element.classList.remove(this.classNames.disabledState),this.element.removeAttribute("aria-disabled"),this.type===r.SELECT_ONE_TYPE&&this.element.setAttribute("tabindex","0"),this.isDisabled=!1},t.prototype.disable=function(){this.element.classList.add(this.classNames.disabledState),this.element.setAttribute("aria-disabled","true"),this.type===r.SELECT_ONE_TYPE&&this.element.setAttribute("tabindex","-1"),this.isDisabled=!0},t.prototype.wrap=function(t){n.wrap(t,this.element)},t.prototype.unwrap=function(t){this.element.parentNode&&(this.element.parentNode.insertBefore(t,this.element),this.element.parentNode.removeChild(this.element))},t.prototype.addLoadingState=function(){this.element.classList.add(this.classNames.loadingState),this.element.setAttribute("aria-busy","true"),this.isLoading=!0},t.prototype.removeLoadingState=function(){this.element.classList.remove(this.classNames.loadingState),this.element.removeAttribute("aria-busy"),this.isLoading=!1},t.prototype._onFocus=function(){this.isFocussed=!0},t.prototype._onBlur=function(){this.isFocussed=!1},t}();e.default=s},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(1),r=i(0),s=function(){function t(t){var e=t.element,i=t.type,n=t.classNames,r=t.preventPaste;this.element=e,this.type=i,this.classNames=n,this.preventPaste=r,this.isFocussed=this.element.isEqualNode(document.activeElement),this.isDisabled=e.disabled,this._onPaste=this._onPaste.bind(this),this._onInput=this._onInput.bind(this),this._onFocus=this._onFocus.bind(this),this._onBlur=this._onBlur.bind(this)}return Object.defineProperty(t.prototype,"placeholder",{set:function(t){this.element.placeholder=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){return n.sanitise(this.element.value)},set:function(t){this.element.value=t},enumerable:!0,configurable:!0}),t.prototype.addEventListeners=function(){this.element.addEventListener("paste",this._onPaste),this.element.addEventListener("input",this._onInput,{passive:!0}),this.element.addEventListener("focus",this._onFocus,{passive:!0}),this.element.addEventListener("blur",this._onBlur,{passive:!0})},t.prototype.removeEventListeners=function(){this.element.removeEventListener("input",this._onInput),this.element.removeEventListener("paste",this._onPaste),this.element.removeEventListener("focus",this._onFocus),this.element.removeEventListener("blur",this._onBlur)},t.prototype.enable=function(){this.element.removeAttribute("disabled"),this.isDisabled=!1},t.prototype.disable=function(){this.element.setAttribute("disabled",""),this.isDisabled=!0},t.prototype.focus=function(){this.isFocussed||this.element.focus()},t.prototype.blur=function(){this.isFocussed&&this.element.blur()},t.prototype.clear=function(t){return void 0===t&&(t=this.type===r.TEXT_TYPE),this.element.value&&(this.element.value=""),t&&this.setWidth(),this},t.prototype.setWidth=function(){var t=this.element,e=t.style,i=t.value;e.minWidth=t.placeholder.length+1+"ch",e.width=i.length+1+"ch"},t.prototype.setActiveDescendant=function(t){this.element.setAttribute("aria-activedescendant",t)},t.prototype.removeActiveDescendant=function(){this.element.removeAttribute("aria-activedescendant")},t.prototype._onInput=function(){this.type===r.TEXT_TYPE&&this.setWidth()},t.prototype._onPaste=function(t){this.preventPaste&&t.preventDefault()},t.prototype._onFocus=function(){this.isFocussed=!0},t.prototype._onBlur=function(){this.isFocussed=!1},t}();e.default=s},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(0),r=function(){function t(t){this.element=t.element,this.scrollPos=this.element.scrollTop,this.height=this.element.offsetHeight}return t.prototype.clear=function(){this.element.innerHTML=""},t.prototype.append=function(t){this.element.appendChild(t)},t.prototype.getChild=function(t){return this.element.querySelector(t)},t.prototype.hasChildren=function(){return this.element.hasChildNodes()},t.prototype.scrollToTop=function(){this.element.scrollTop=0},t.prototype.scrollToChildElement=function(t,e){var i=this;if(t){var n=e>0?this.element.scrollTop+(t.offsetTop+t.offsetHeight)-(this.element.scrollTop+this.element.offsetHeight):t.offsetTop;requestAnimationFrame((function(){i._animateScroll(n,e)}))}},t.prototype._scrollDown=function(t,e,i){var n=(i-t)/e;this.element.scrollTop=t+(n>1?n:1)},t.prototype._scrollUp=function(t,e,i){var n=(t-i)/e;this.element.scrollTop=t-(n>1?n:1)},t.prototype._animateScroll=function(t,e){var i=this,r=n.SCROLLING_SPEED,s=this.element.scrollTop,o=!1;e>0?(this._scrollDown(s,r,t),s<t&&(o=!0)):(this._scrollUp(s,r,t),s>t&&(o=!0)),o&&requestAnimationFrame((function(){i._animateScroll(t,e)}))},t}();e.default=r},function(t,e,i){var n,r=this&&this.__extends||(n=function(t,e){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)},function(t,e){function i(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(i.prototype=e.prototype,new i)}),s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var o=function(t){function e(e){var i=e.delimiter,n=t.call(this,{element:e.element,classNames:e.classNames})||this;return n.delimiter=i,n}return r(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(t){this.element.setAttribute("value",t),this.element.value=t},enumerable:!0,configurable:!0}),e}(s(i(5)).default);e.default=o},function(t,e,i){var n,r=this&&this.__extends||(n=function(t,e){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)},function(t,e){function i(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(i.prototype=e.prototype,new i)}),s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});var o=function(t){function e(e){var i=e.template,n=t.call(this,{element:e.element,classNames:e.classNames})||this;return n.template=i,n}return r(e,t),Object.defineProperty(e.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"optionGroups",{get:function(){return Array.from(this.element.getElementsByTagName("OPTGROUP"))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return Array.from(this.element.options)},set:function(t){var e=this,i=document.createDocumentFragment();t.forEach((function(t){return n=e.template(t),void i.appendChild(n);var n})),this.appendDocFragment(i)},enumerable:!0,configurable:!0}),e.prototype.appendDocFragment=function(t){this.element.innerHTML="",this.element.appendChild(t)},e}(s(i(5)).default);e.default=o},function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.default={containerOuter:function(t,e,i,n,r,s){var o=t.containerOuter,a=Object.assign(document.createElement("div"),{className:o});return a.dataset.type=s,e&&(a.dir=e),n&&(a.tabIndex=0),i&&(a.setAttribute("role",r?"combobox":"listbox"),r&&a.setAttribute("aria-autocomplete","list")),a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false"),a},containerInner:function(t){var e=t.containerInner;return Object.assign(document.createElement("div"),{className:e})},itemList:function(t,e){var i=t.list,n=t.listSingle,r=t.listItems;return Object.assign(document.createElement("div"),{className:i+" "+(e?n:r)})},placeholder:function(t,e){var i=t.placeholder;return Object.assign(document.createElement("div"),{className:i,innerHTML:e})},item:function(t,e,i){var n=t.item,r=t.button,s=t.highlightedState,o=t.itemSelectable,a=t.placeholder,c=e.id,h=e.value,u=e.label,l=e.customProperties,f=e.active,d=e.disabled,v=e.highlighted,p=e.placeholder,b=Object.assign(document.createElement("div"),{className:n,innerHTML:u});if(Object.assign(b.dataset,{item:"",id:c,value:h,customProperties:l}),f&&b.setAttribute("aria-selected","true"),d&&b.setAttribute("aria-disabled","true"),p&&b.classList.add(a),b.classList.add(v?s:o),i){d&&b.classList.remove(o),b.dataset.deletable="";var m=Object.assign(document.createElement("button"),{type:"button",className:r,innerHTML:"Remove item"});m.setAttribute("aria-label","Remove item: '"+h+"'"),m.dataset.button="",b.appendChild(m)}return b},choiceList:function(t,e){var i=t.list,n=Object.assign(document.createElement("div"),{className:i});return e||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(t,e){var i=t.group,n=t.groupHeading,r=t.itemDisabled,s=e.id,o=e.value,a=e.disabled,c=Object.assign(document.createElement("div"),{className:i+" "+(a?r:"")});return c.setAttribute("role","group"),Object.assign(c.dataset,{group:"",id:s,value:o}),a&&c.setAttribute("aria-disabled","true"),c.appendChild(Object.assign(document.createElement("div"),{className:n,innerHTML:o})),c},choice:function(t,e,i){var n=t.item,r=t.itemChoice,s=t.itemSelectable,o=t.selectedState,a=t.itemDisabled,c=t.placeholder,h=e.id,u=e.value,l=e.label,f=e.groupId,d=e.elementId,v=e.disabled,p=e.selected,b=e.placeholder,m=Object.assign(document.createElement("div"),{id:d,innerHTML:l,className:n+" "+r});return p&&m.classList.add(o),b&&m.classList.add(c),m.setAttribute("role",f&&f>0?"treeitem":"option"),Object.assign(m.dataset,{choice:"",id:h,value:u,selectText:i}),v?(m.classList.add(a),m.dataset.choiceDisabled="",m.setAttribute("aria-disabled","true")):(m.classList.add(s),m.dataset.choiceSelectable=""),m},input:function(t,e){var i=t.input,n=t.inputCloned,r=Object.assign(document.createElement("input"),{type:"text",className:i+" "+n,autocomplete:"off",autocapitalize:"off",spellcheck:!1});return r.setAttribute("role","textbox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-label",e),r},dropdown:function(t){var e=t.list,i=t.listDropdown,n=document.createElement("div");return n.classList.add(e,i),n.setAttribute("aria-expanded","false"),n},notice:function(t,e,i){var n=t.noResults;void 0===i&&(i="");var r=[t.item,t.itemChoice];return"no-choices"===i?r.push(t.noChoices):"no-results"===i&&r.push(n),Object.assign(document.createElement("div"),{innerHTML:e,className:r.join(" ")})},option:function(t){var e=t.customProperties,i=t.disabled,n=new Option(t.label,t.value,!1,t.active);return e&&(n.dataset.customProperties=""+e),n.disabled=!!i,n}}},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(0);e.addChoice=function(t){return{type:n.ACTION_TYPES.ADD_CHOICE,value:t.value,label:t.label,id:t.id,groupId:t.groupId,disabled:t.disabled,elementId:t.elementId,customProperties:t.customProperties,placeholder:t.placeholder,keyCode:t.keyCode}},e.filterChoices=function(t){return{type:n.ACTION_TYPES.FILTER_CHOICES,results:t}},e.activateChoices=function(t){return void 0===t&&(t=!0),{type:n.ACTION_TYPES.ACTIVATE_CHOICES,active:t}},e.clearChoices=function(){return{type:n.ACTION_TYPES.CLEAR_CHOICES}}},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(0);e.addItem=function(t){return{type:n.ACTION_TYPES.ADD_ITEM,value:t.value,label:t.label,id:t.id,choiceId:t.choiceId,groupId:t.groupId,customProperties:t.customProperties,placeholder:t.placeholder,keyCode:t.keyCode}},e.removeItem=function(t,e){return{type:n.ACTION_TYPES.REMOVE_ITEM,id:t,choiceId:e}},e.highlightItem=function(t,e){return{type:n.ACTION_TYPES.HIGHLIGHT_ITEM,id:t,highlighted:e}}},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(0);e.addGroup=function(t){return{type:n.ACTION_TYPES.ADD_GROUP,value:t.value,id:t.id,active:t.active,disabled:t.disabled}}},function(t,e,i){Object.defineProperty(e,"__esModule",{value:!0});var n=i(0);e.clearAll=function(){return{type:n.ACTION_TYPES.CLEAR_ALL}},e.resetTo=function(t){return{type:n.ACTION_TYPES.RESET_TO,state:t}},e.setIsLoading=function(t){return{type:n.ACTION_TYPES.SET_IS_LOADING,isLoading:t}}}]).default},t.exports=e()}(o={path:undefined,exports:{},require:function(){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}()}}),o.exports)),c=class{constructor(i){t(this,i),this.bkkrSelectDidSearch=e(this,"bkkrSelectDidSearch",7),this.bkkrSelectDidReset=e(this,"bkkrSelectDidReset",7),this.bkkrSelectDidLoad=e(this,"bkkrSelectDidLoad",7),this.didInit=!1,this.choicesReady=!1,this.choicesId="bkkr-sel-"+h++,this.choices=new Promise((t=>{this.readyChoices=t})),this.multiple=!1,this.name=this.choicesId,this.search=!0,this.interfaceOptions={},this.options=[]}async interfaceOptionsChanged(){if(this.choicesReady){const t=await this.getChoices();Object.assign(t.config,this.interfaceOptions),await this.update()}}async optionsChanged(){this.choicesReady&&await this.setChoices(this.options,"value","label",!0)}async onSelect(){const[t]=await Promise.all([this.getChoices()]),e=t.getValue(!0);let i,n=Array.isArray(e)?e:[e],r=[];n.forEach((t=>{const e=this.options.find((e=>!isNaN(e.value)&&!isNaN(t)&&parseInt(e.value)===parseInt(t)||e.value===t));r.push(e.value),i=e.handler})),this.value=r,i?i(r):this.bkkrSelectDidReset.emit()}connectedCallback(){"undefined"!=typeof MutationObserver&&((this.mutationO=new MutationObserver((()=>{this.choicesReady&&this.update()}))).observe(this.el,{childList:!0,subtree:!0}),this.el.componentOnReady().then((()=>{this.didInit||(this.didInit=!0,this.initChoices())})))}disconnectedCallback(){this.mutationO&&(this.mutationO.disconnect(),this.mutationO=void 0);const t=this.syncChoices;void 0!==t&&(t.destroy(),this.choices=new Promise((t=>{this.readyChoices=t})),this.choicesReady=!1,this.syncChoices=void 0)}async highlightItem(t,e){const[i]=await Promise.all([this.getChoices()]);return i.highlightItem(t,e),this}async unhighlightItem(t){const[e]=await Promise.all([this.getChoices()]);return e.unhighlightItem(t),this}async highlightAll(){const[t]=await Promise.all([this.getChoices()]);return t.highlightAll(),this}async unhighlightAll(){const[t]=await Promise.all([this.getChoices()]);return t.unhighlightAll(),this}async removeActiveItemsByValue(t){const[e]=await Promise.all([this.getChoices()]);return e.removeActiveItemsByValue(t),this}async removeActiveItems(t){const[e]=await Promise.all([this.getChoices()]);return e.removeActiveItems(t),this}async removeHighlightedItems(t){const[e]=await Promise.all([this.getChoices()]);return e.removeHighlightedItems(t),this}async showDropdown(t){const[e]=await Promise.all([this.getChoices()]);return e.showDropdown(t),this}async hideDropdown(t){const[e]=await Promise.all([this.getChoices()]);return e.hideDropdown(t),this}async getValue(t){const[e]=await Promise.all([this.getChoices()]);return e.getValue(t)}async setValue(t){const[e]=await Promise.all([this.getChoices()]);return e.setValue(t),this}async setChoiceByValue(t){const[e]=await Promise.all([this.getChoices()]);return e.setChoiceByValue(t),this}async setChoices(t,e,i,n){const[r]=await Promise.all([this.getChoices()]);return r.setChoices(t,e,i,n),this}async clearChoices(){const[t]=await Promise.all([this.getChoices()]);return t.clearChoices(),this}async clearStore(){const[t]=await Promise.all([this.getChoices()]);return t.clearStore(),this}async clearInput(){const[t]=await Promise.all([this.getChoices()]);return t.clearInput(),this}async enable(){const[t]=await Promise.all([this.getChoices()]);return t.enable(),this}async disable(){const[t]=await Promise.all([this.getChoices()]);return t.disable(),this}async update(){const[t]=await Promise.all([this.getChoices()]);return t}async getChoices(){return this.choices}async initChoices(){const t=this,e=this.normalizeOptions(),i=new a(this.el.querySelector("select"),e);this.el.addEventListener("change",(async function(){const[e]=await Promise.all([t.getChoices()]),i=e.getValue(!0);let n,r=Array.isArray(i)?i:[i],s=[];r.forEach((e=>{const i=t.options.find((t=>!isNaN(t.value)&&!isNaN(e)&&parseInt(t.value)===parseInt(e)||t.value===e));s.push(i.value),n=i.handler})),t.value=s,n?n(s):t.bkkrSelectDidReset.emit()}),!1),this.el.addEventListener("search",(function(e){t.bkkrSelectDidSearch.emit(e)}),!1),this.choicesReady=!0,this.syncChoices=i,this.readyChoices(i),this.el.querySelector(".choices-list").addEventListener("scroll",(function(t){console.log("scroll"),t.preventDefault(),t.stopPropagation()}),!1)}normalizeOptions(){const t={callbackOnInit:()=>{setTimeout((()=>{this.bkkrSelectDidLoad.emit()}),20)}};return Object.assign(Object.assign(Object.assign(Object.assign({},{silent:!1,items:[],choices:this.options,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,duplicateItemsAllowed:!1,delimiter:",",paste:!1,searchEnabled:this.search,searchChoices:!0,searchFloor:0,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!1,shouldSort:!1,shouldSortItems:!1,sorter:function(t,e){return e.label.length-t.label.length},placeholder:!0,placeholderValue:null,searchPlaceholderValue:"Search",prependValue:null,appendValue:null,renderSelectedChoices:"always",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",addItemText:t=>`Press Enter to add <b>"${t}"</b>`,maxItemText:t=>`Only ${t} values can be added`,valueComparer:(t,e)=>t===e}),this.interfaceOptions),{classNames:{containerOuter:"choices",containerInner:"choices-inner",input:"choices-input",inputCloned:"choices-input-cloned",list:"choices-list",listItems:"choices-list-multiple",listSingle:"choices-list-single",listDropdown:"choices-list-dropdown",item:"choices-item",itemSelectable:"choices-item-selectable",itemDisabled:"choices-item-disabled",itemChoice:"choices-item-choice",placeholder:"choices-placeholder",group:"choices-group",groupHeading:"choices-heading",button:"choices-button",activeState:"state-active",focusState:"state-focus",openState:"state-open",disabledState:"state-disabled",highlightedState:"state-highlighted",selectedState:"state-selected",flippedState:"state-flipped",loadingState:"state-loading",noResults:"has-no-results",noChoices:"has-no-choices"}}),t)}render(){const{multiple:t,name:e,search:r}=this;return i(n,{class:{"choices-container":!0,"choices-search-enabled":r}},i("select",{part:"native",multiple:t,name:e,class:"native-select"}),r&&i("div",{class:"choices-searchbar-icons search-icon"},i("bkkr-icon",{name:"search"})))}get el(){return r(this)}static get watchers(){return{interfaceOptions:["interfaceOptionsChanged"],options:["optionsChanged"]}}};let h=0;c.style='.choices-container{--searchbar-height:36px;--searchbar-placeholder-color:var(--bkkr-color-step-600, #666666);--searchbar-placeholder-font-style:initial;--searchbar-placeholder-font-weight:initial;--searchbar-placeholder-opacity:.5;--searchbar-border-radius:0.75em;--searchbar-background:rgba(var(--bkkr-text-color-rgb, 0, 0, 0), 0.065);--searchbar-background-hover:rgba(var(--bkkr-text-color-rgb, 0, 0, 0), 0.095);--searchbar-background-focus:rgba(var(--bkkr-text-color-rgb, 0, 0, 0), 0.095);--searchbar-background-active:rgba(var(--bkkr-text-color-rgb, 0, 0, 0), 0.12);--searchbar-transition:all 0.2s ease;--searchbar-icon-color:var(--bkkr-color-step-600, #666666);--searchbar-icon-size:22px;--searchbar-box-shadow:none;--item-color:var(--color, var(--bkkr-text-color, #000));--item-color-active:var(--color);--item-color-focus:var(--color);--item-color-hover:var(--color);--item-color-selected:var(--color-base, var(--color-primary, #3880ff));--item-background:transparent;--item-background-active:#000;--item-background-focus:#000;--item-background-hover:currentColor;--item-background-selected:var(--color-base, var(--color-primary, #3880ff));--item-background-active-opacity:.12;--item-background-focus-opacity:.04;--item-background-hover-opacity:.04;--item-background-selected-opacity:.12;--item-padding-top:0;--item-padding-bottom:0;--item-padding-end:0;--item-padding-start:var(--bkkr-spacer, 16px);--item-min-height:44px;--item-transition:0.2s border cubic-bezier(0.32, 0.72, 0, 1), 0.2s background cubic-bezier(0.32, 0.72, 0, 1)}.choices,.choices-list-dropdown{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:-ms-flexbox;display:flex;position:relative;-ms-flex-direction:column;flex-direction:column;height:100%;outline:0;font-family:var(--default-font-sans-serif);font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.choices-inner{display:none}.choices-list:not(.choices-list-dropdown){height:100%;overflow-y:auto;padding-bottom:var(--safe-area-bottom);border-top:0.55px solid var(--bkkr-border, rgba(var(--bkkr-text-color-rgb, 0, 0, 0), 0.1))}.choices-input{border-radius:0.75em;padding-left:36px;padding-right:36px;padding-top:0;padding-bottom:0;margin-left:var(--bkkr-spacer);margin-right:var(--bkkr-spacer);margin-top:0;margin-bottom:5px;color:inherit;font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-align:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;white-space:inherit;display:block;max-width:100%;min-height:var(--searchbar-height);margin-bottom:5px;-webkit-transition:var(--searchbar-transition);transition:var(--searchbar-transition);border:0;outline:none;background:var(--searchbar-background);font-size:16px;font-weight:400;line-height:var(--searchbar-height);-webkit-box-shadow:var(--searchbar-box-shadow);box-shadow:var(--searchbar-box-shadow);contain:strict;z-index:10;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.choices-input{padding-left:unset;padding-right:unset;-webkit-padding-start:36px;padding-inline-start:36px;-webkit-padding-end:36px;padding-inline-end:36px}}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.choices-input{margin-left:unset;margin-right:unset;-webkit-margin-start:var(--bkkr-spacer);margin-inline-start:var(--bkkr-spacer);-webkit-margin-end:var(--bkkr-spacer);margin-inline-end:var(--bkkr-spacer)}}.choices-input::-moz-placeholder{color:var(--searchbar-placeholder-color);font-family:inherit;font-style:var(--searchbar-placeholder-font-style);font-weight:var(--searchbar-placeholder-font-weight);opacity:var(--searchbar-placeholder-opacity)}.choices-input::-ms-input-placeholder{color:var(--searchbar-placeholder-color);font-family:inherit;font-style:var(--searchbar-placeholder-font-style);font-weight:var(--searchbar-placeholder-font-weight);opacity:var(--searchbar-placeholder-opacity)}.choices-input::-webkit-input-placeholder{color:var(--searchbar-placeholder-color);font-family:inherit;font-style:var(--searchbar-placeholder-font-style);font-weight:var(--searchbar-placeholder-font-weight);opacity:var(--searchbar-placeholder-opacity)}.choices-input:-ms-input-placeholder{color:var(--searchbar-placeholder-color);font-family:inherit;font-style:var(--searchbar-placeholder-font-style);font-weight:var(--searchbar-placeholder-font-weight);opacity:var(--searchbar-placeholder-opacity)}.choices-input::placeholder{color:var(--searchbar-placeholder-color);font-family:inherit;font-style:var(--searchbar-placeholder-font-style);font-weight:var(--searchbar-placeholder-font-weight);opacity:var(--searchbar-placeholder-opacity)}.choices-input::-webkit-search-cancel-button,.choices-input::-ms-clear{display:none}.popover-viewport .choices-input{margin-top:var(--bkkr-spacer)}@media (any-hover: hover){.choices-input:hover{background:var(--searchbar-background-hover)}}.choices-input:focus{background:var(--searchbar-background-focus)}.choices-input:active{background:var(--searchbar-background-active)}.choices-searchbar-icons{display:-ms-flexbox;display:flex;position:absolute;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;min-width:36px;min-height:var(--searchbar-height);z-index:15}.choices-searchbar-icons bkkr-icon{--color:var(--searchbar-icon-color);height:var(--searchbar-icon-size)}.search-icon{top:32px;left:var(--bkkr-spacer);pointer-events:none}.choices-item{color:inherit;font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-align:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;white-space:inherit;padding-left:calc(var(--item-padding-start) + var(--safe-area-left, 0));padding-right:var(--item-padding-end);padding-top:var(--item-padding-top);padding-bottom:var(--item-padding-bottom);display:-ms-flexbox;display:flex;position:relative;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;width:100%;min-height:var(--item-min-height);outline:none;color:var(--item-color);cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;z-index:1;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-user-drag:none}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.choices-item{padding-left:unset;padding-right:unset;-webkit-padding-start:calc(var(--item-padding-start) + var(--safe-area-left, 0));padding-inline-start:calc(var(--item-padding-start) + var(--safe-area-left, 0));-webkit-padding-end:var(--item-padding-end);padding-inline-end:var(--item-padding-end)}}.choices-item::-moz-focus-inner{border:0}.choices-item::after{top:0;right:0;bottom:0;left:0;position:absolute;content:"";opacity:0;-webkit-transition:var(--item-transition);transition:var(--item-transition);pointer-events:none;z-index:-1}.choices-item.has-no-results{cursor:initial}@media (any-hover: hover){.choices-item:hover{color:var(--item-color-hover)}.choices-item:hover::after{background:var(--item-background-hover);opacity:var(--item-background-hover-opacity)}}.choices-item.state-focus{color:var(--item-color-focus)}.choices-item.state-focus::after{background:var(--item-background-focus);opacity:var(--item-background-focus-opacity)}.choices-item.state-active{color:var(--item-color-active)}.choices-item.state-active::after{background:var(--item-background-active);opacity:var(--item-background-active-opacity)}.choices-item.state-selected{color:var(--item-color-selected)}.choices-item.state-selected::after{background:var(--item-background-selected);opacity:var(--item-background-selected-opacity)}.choices-item.state-disabled{pointer-events:none;cursor:default;opacity:0.3}';export{c as bkkr_select_choices} |
import glob
import os
from astroquery.irsa import Irsa
import astropy.coordinates as crd
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import readsav
from astropy.io import fits
from exoctk.utils import get_env_variables
EXOCTK_DATA = os.environ.get('EXOCTK_DATA')
if not EXOCTK_DATA:
print('WARNING: The $EXOCTK_DATA environment variable is not set. Contamination overlap will not work. Please set the '
'value of this variable to point to the location of the exoctk_data '
'download folder. Users may retreive this folder by clicking the '
'"ExoCTK Data Download" button on the ExoCTK website, or by using '
'the exoctk.utils.download_exoctk_data() function.'
)
TRACES_PATH = None
else:
TRACES_PATH = os.path.join(EXOCTK_DATA, 'exoctk_contam', 'traces')
def sossFieldSim(ra, dec, binComp='', dimX=256):
""" Produce a SOSS field simulation for a target.
Parameters
----------
ra: float
The RA of the target.
dec: float
The Dec of the target.
binComp: sequence
The parameters of a binary companion.
dimX: int
The subarray size.
Returns
-------
simuCub : np.ndarray
The simulated data cube.
"""
# stars in large field around target
targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))
targetRA = targetcrd.ra.value
targetDEC = targetcrd.dec.value
info = Irsa.query_region(targetcrd, catalog='fp_psc', spatial='Cone',
radius=2.5*u.arcmin)
# coordinates of all stars in FOV, including target
allRA = info['ra'].data.data
allDEC = info['dec'].data.data
Jmag = info['j_m'].data.data
Hmag = info['h_m'].data.data
Kmag = info['k_m'].data.data
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# target coords
aa = ((targetRA-allRA)*np.cos(targetDEC))
distance = np.sqrt(aa**2 + (targetDEC-allDEC)**2)
targetIndex = np.argmin(distance) # the target
# add any missing companion
if binComp != '':
deg2rad = np.pi/180
bb = binComp[0]/3600/np.cos(allDEC[targetIndex]*deg2rad)
allRA = np.append(allRA, (allRA[targetIndex] + bb))
allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1]/3600))
Jmag = np.append(Jmag, binComp[2])
Hmag = np.append(Kmag, binComp[3])
Kmag = np.append(Kmag, binComp[4])
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# number of stars
nStars = allRA.size
# Restoring model parameters
modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),
verbose=False)
models = modelParam['models']
modelPadX = modelParam['modelpadx']
modelPadY = modelParam['modelpady']
dimXmod = modelParam['dimxmod']
dimYmod = modelParam['dimymod']
jhMod = modelParam['jhmod']
hkMod = modelParam['hkmod']
teffMod = modelParam['teffmod']
# find/assign Teff of each star
starsT = np.empty(nStars)
for j in range(nStars):
color_separation = (J_Hobs[j]-jhMod)**2+(H_Kobs[j]-hkMod)**2
min_separation_ind = np.argmin(color_separation)
starsT[j] = teffMod[min_separation_ind]
radeg = 180/np.pi
niriss_pixel_scale = 0.065 # arcsec
sweetSpot = dict(x=856, y=107, RA=allRA[targetIndex],
DEC=allDEC[targetIndex], jmag=Jmag[targetIndex])
# offset between all stars and target
dRA = (allRA - sweetSpot['RA'])*np.cos(sweetSpot['DEC']/radeg)*3600
dDEC = (allDEC - sweetSpot['DEC'])*3600
# Put field stars positions and magnitudes in structured array
_ = dict(RA=allRA, DEC=allDEC, dRA=dRA, dDEC=dDEC, jmag=Jmag, T=starsT,
x=np.empty(nStars), y=np.empty(nStars), dx=np.empty(nStars),
dy=np.empty(nStars))
stars = np.empty(nStars,
dtype=[(key, val.dtype) for key, val in _.items()])
for key, val in _.items():
stars[key] = val
# Initialize final fits cube that contains the modelled traces
# with contamination
PAmin = 0 # instrument PA, degrees
PAmax = 360
dPA = 1 # degrees
# Set of IPA values to cover
PAtab = np.arange(PAmin, PAmax, dPA) # degrees
nPA = len(PAtab)
# dimX=256 #2048 #########now as argument, with default to 256
dimY = 2048
# cube of trace simulation at every degree of field rotation,
# +target at O1 and O2
simuCube = np.zeros([nPA+2, dimY, dimX])
# saveFiles = glob.glob('idlSaveFiles/*.sav')[:-1]
saveFiles = glob.glob(os.path.join(TRACES_PATH, 'NIRISS', '*.sav'))[:-1]
# pdb.set_trace()
# Big loop to generate a simulation at each instrument PA
for kPA in range(PAtab.size):
APA = PAtab[kPA]
V3PA = APA+0.57 # from APT
sindx = np.sin(np.pi/2+APA/radeg)*stars['dDEC']
cosdx = np.cos(np.pi/2+APA/radeg)*stars['dDEC']
nps = niriss_pixel_scale
stars['dx'] = (np.cos(np.pi/2+APA/radeg)*stars['dRA']-sindx)/nps
stars['dy'] = (np.sin(np.pi/2+APA/radeg)*stars['dRA']+cosdx)/nps
stars['x'] = stars['dx']+sweetSpot['x']
stars['y'] = stars['dy']+sweetSpot['y']
# Display the star field (blue), target (red), subarray (green),
# full array (blue), and axes
if (kPA == 0 and nStars > 1) and False:
plt.plot([0, 2047, 2047, 0, 0], [0, 0, 2047, 2047, 0], 'b')
plt.plot([0, 255, 255, 0, 0], [0, 0, 2047, 2047, 0], 'g')
# the order 1 & 2 traces
path = '/Users/david/Documents/work/jwst/niriss/soss/data/'
t1 = np.loadtxt(path+'trace_order1.txt', unpack=True)
plt.plot(t1[0], t1[1], 'r')
t2 = np.loadtxt(path+'trace_order2.txt', unpack=True)
plt.plot(t2[0], t2[1], 'r')
plt.plot(stars['x'], stars['y'], 'b*')
plt.plot(sweetSpot['x'], sweetSpot['y'], 'r*')
plt.title("APA= {} (V3PA={})".format(APA, V3PA))
ax = plt.gca()
# add V2 & V3 axes
l, hw, hl = 250, 50, 50
adx, ady = -l*np.cos(-0.57 / radeg), -l*np.sin(-0.57 / radeg)
ax.arrow(2500, 1800, adx, ady, head_width=hw, head_length=hl,
length_includes_head=True, fc='k') # V3
plt.text(2500+1.4*adx, 1800+1.4*ady, "V3", va='center',
ha='center')
adx, ady = -l*np.cos((-0.57-90)/radeg), -l*np.sin((-0.57-90)/radeg)
ax.arrow(2500, 1800, adx, ady, head_width=hw, head_length=hl,
length_includes_head=True, fc='k') # V2
plt.text(2500+1.4*adx, 1800+1.4*ady, "V2", va='center',
ha='center')
# add North and East
adx, ady = -l*np.cos(APA/radeg), -l*np.sin(APA/radeg)
ax.arrow(2500, 1300, adx, ady, head_width=hw, head_length=hl,
length_includes_head=True, fc='k') # N
plt.text(2500+1.4*adx, 1300+1.4*ady, "N", va='center', ha='center')
adx, ady = -l*np.cos((APA-90)/radeg), -l*np.sin((APA-90)/radeg)
ax.arrow(2500, 1300, adx, ady, head_width=hw, head_length=hl,
length_includes_head=True, fc='k') # E
plt.text(2500+1.4*adx, 1300+1.4*ady, "E", va='center', ha='center')
ax.set_xlim(-400, 2047+800)
ax.set_ylim(-400, 2047+400)
ax.set_aspect('equal')
plt.show()
# Retain stars that are within the Direct Image NIRISS POM FOV
ind, = np.where((stars['x'] >= -162) & (stars['x'] <= 2047+185) &
(stars['y'] >= -154) & (stars['y'] <= 2047+174))
starsInFOV = stars[ind]
for i in range(len(ind)):
intx = round(starsInFOV['dx'][i])
inty = round(starsInFOV['dy'][i])
k = np.where(teffMod == starsInFOV['T'][i])[0][0]
fluxscale = 10.0**(-0.4*(starsInFOV['jmag'][i]-sweetSpot['jmag']))
# deal with subection sizes
mx0 = int(modelPadX-intx)
mx1 = int(modelPadX-intx+dimX)
my0 = int(modelPadY-inty)
my1 = int(modelPadY-inty+dimY)
if (mx0 > dimXmod) or (my0 > dimYmod):
continue
if (mx1 < 0) or (my1 < 0):
continue
x0 = (mx0 < 0)*(-mx0)
y0 = (my0 < 0)*(-my0)
mx0 *= (mx0 >= 0)
mx1 = dimXmod if mx1 > dimXmod else mx1
my0 *= (my0 >= 0)
my1 = dimYmod if my1 > dimYmod else my1
# if target and first kPA, add target traces of order 1 and 2
# in output cube
if (intx == 0) & (inty == 0) & (kPA == 0):
fNameModO12 = saveFiles[k]
modelO12 = readsav(fNameModO12, verbose=False)['modelo12']
ord1 = modelO12[0, my0:my1, mx0:mx1]*fluxscale
ord2 = modelO12[1, my0:my1, mx0:mx1]*fluxscale
simuCube[0, y0:y0+my1-my0, x0:x0+mx1-mx0] = ord1
simuCube[1, y0:y0+my1-my0, x0:x0+mx1-mx0] = ord2
if (intx != 0) or (inty != 0):
mod = models[k, my0:my1, mx0:mx1]
simuCube[kPA+2, y0:y0+my1-my0, x0:x0+mx1-mx0] += mod*fluxscale
#mod = models[k, 1500:1500+2048, 100:100+256]
#simuCube[kPA+2, 0:dimY, 0:dimX] += mod*fluxscale
return simuCube
def gtsFieldSim(ra, dec, filter, binComp=''):
""" Produce a Grism Time Series field simulation for a target.
Parameters
----------
ra : float
The RA of the target.
dec : float
The Dec of the target.
filter : str
The NIRCam filter being used. Can either be:
'F444W' or 'F322W2' (case-sensitive)
binComp : sequence
The parameters of a binary companion.
Returns
-------
simuCube : np.ndarray
The simulated data cube. Index 0 and 1 (axis=0) show the trace of
the target for orders 1 and 2 (respectively). Index 2-362 show the trace
of the target at every position angle (PA) of the instrument.
"""
# Calling the variables which depend on what NIRCam filter you use
if filter=='F444W':
dimX = 51
dimY = 1343
rad = 2.5
pixel_scale = 0.063 # arsec
xval, yval = 1096.9968649303112, 34.99693173255946 # got from PYSIAF
add_to_apa = 0.0265 # got from jwst_gtvt/find_tgt_info.py
elif filter=='F322W2':
dimX = 51
dimY = 1823
rad = 2.5
pixel_scale = 0.063 # arsec
xval, yval = 468.0140991987737, 35.007956285677665
add_to_apa = 0.0265 # got from jwst_gtvt/find_tgt_info.py
# stars in large field around target
targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))
targetRA = targetcrd.ra.value
targetDEC = targetcrd.dec.value
info = Irsa.query_region(targetcrd, catalog='fp_psc', spatial='Cone',
radius=rad*u.arcmin)
# Coordinates of all the stars in FOV, including target
allRA = info['ra'].data.data
allDEC = info['dec'].data.data
Jmag = info['j_m'].data.data
Hmag = info['h_m'].data.data
Kmag = info['k_m'].data.data
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# Coordiniates of target
aa = ((targetRA-allRA)*np.cos(targetDEC))
distance = np.sqrt(aa**2 + (targetDEC-allDEC)**2)
targetIndex = np.argmin(distance) # the target
# Add any missing companion
if binComp != '':
deg2rad = np.pi/180
bb = binComp[0]/3600/np.cos(allDEC[targetIndex]*deg2rad)
allRA = np.append(allRA, (allRA[targetIndex] + bb))
allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1]/3600))
Jmag = np.append(Jmag, binComp[2])
Hmag = np.append(Kmag, binComp[3])
Kmag = np.append(Kmag, binComp[4])
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# Number of stars
nStars = allRA.size
# Restoring model parameters
modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),
verbose=False)
models = modelParam['models']
modelPadX = modelParam['modelpadx']
modelPadY = modelParam['modelpady']
dimXmod = modelParam['dimxmod']
dimYmod = modelParam['dimymod']
jhMod = modelParam['jhmod']
hkMod = modelParam['hkmod']
#teffMod = modelParam['teffmod']
teffMod = np.linspace(2000, 6000, 41)
# Find/assign Teff of each star
starsT = np.empty(nStars)
for j in range(nStars):
color_separation = (J_Hobs[j]-jhMod)**2+(H_Kobs[j]-hkMod)**2
min_separation_ind = np.argmin(color_separation)
starsT[j] = teffMod[min_separation_ind]
radeg = 180/np.pi
sweetSpot = dict(x=xval, y=yval, RA=allRA[targetIndex],
DEC=allDEC[targetIndex], jmag=Jmag[targetIndex])
# Offset between all stars and target
dRA = (allRA - sweetSpot['RA'])*np.cos(sweetSpot['DEC']/radeg)*3600
dDEC = (allDEC - sweetSpot['DEC'])*3600
# Put field stars positions and magnitudes in structured array
_ = dict(RA=allRA, DEC=allDEC, dRA=dRA, dDEC=dDEC, jmag=Jmag, T=starsT,
x=np.empty(nStars), y=np.empty(nStars), dx=np.empty(nStars),
dy=np.empty(nStars))
stars = np.empty(nStars,
dtype=[(key, val.dtype) for key, val in _.items()])
for key, val in _.items():
stars[key] = val
# Initialize final fits cube that contains the modelled traces
# with contamination
PAmin = 0 # instrument PA, degrees
PAmax = 360
dPA = 1 # degrees
# Set of IPA values to cover
PAtab = np.arange(PAmin, PAmax, dPA) # degrees
nPA = len(PAtab)
# Cube of trace simulation at every degree of field rotation,
# +target at O1 and O2
simuCube = np.zeros([nPA+1, dimY+1, dimX+1])
fitsFiles = glob.glob(os.path.join(TRACES_PATH, 'NIRCam_{}'.format(filter), 'o1*.0.fits'))
fitsFiles = np.sort(fitsFiles)
# Big loop to generate a simulation at each instrument PA
for kPA in range(PAtab.size):
APA = PAtab[kPA] # Aperture Position Angle (PA of instrument)
V3PA = APA+add_to_apa # from APT
sindx = np.sin(np.pi/2+APA/radeg)*stars['dDEC']
cosdx = np.cos(np.pi/2+APA/radeg)*stars['dDEC']
ps = pixel_scale
stars['dx'] = (np.cos(np.pi/2+APA/radeg)*stars['dRA']-sindx)/ps
stars['dy'] = (np.sin(np.pi/2+APA/radeg)*stars['dRA']+cosdx)/ps
stars['x'] = stars['dx']+sweetSpot['x']
stars['y'] = stars['dy']+sweetSpot['y']
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~NOTE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Retain stars that are within the Direct Image NIRISS POM FOV
# This extends the subarray edges to the detector edges.
# It keeps the stars that fall out of the subarray but still
# fall into the detector.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ind, = np.where((stars['x'] >= -8000) & (stars['x'] <= dimY+8000) &
(stars['y'] >= -8000) & (stars['y'] <= dimY+8000))
starsInFOV = stars[ind]
for i in range(len(ind)):
intx = round(starsInFOV['dx'][i])
inty = round(starsInFOV['dy'][i])
# This indexing assumes that teffMod is
# sorted the same way fitsFiles was sorted
k = np.where(teffMod == starsInFOV['T'][i])[0][0]
fluxscale = 10.0**(-0.4*(starsInFOV['jmag'][i]-sweetSpot['jmag']))
# deal with subection sizes
modelPadX = 0
modelPadY = 0
mx0 = int(modelPadX-intx)
mx1 = int(modelPadX-intx+dimX)
my0 = int(modelPadY-inty)
my1 = int(modelPadY-inty+dimY)
if (mx0 > dimX) or (my0 > dimY):
continue
if (mx1 < 0) or (my1 < 0):
continue
x0 = (mx0 < 0)*(-mx0)
y0 = (my0 < 0)*(-my0)
mx0 *= (mx0 >= 0)
mx1 = dimX if mx1 > dimX else mx1
my0 *= (my0 >= 0)
my1 = dimY if my1 > dimY else my1
# Fleshing out index 0 of the simulation cube (trace of target)
if (intx == 0) & (inty == 0) & (kPA == 0):
fNameModO12 = fitsFiles[k]
modelO1 = fits.getdata(fNameModO12, 1)
ord1 = modelO1[0, my0:my1, mx0:mx1]*fluxscale
simuCube[0, y0:y0+my1-my0, x0:x0+mx1-mx0] = ord1
# Fleshing out indexes 1-361 of the simulation cube
# (trace of neighboring stars at every position angle)
if (intx != 0) or (inty != 0):
fNameModO12 = fitsFiles[k]
modelO12 = fits.getdata(fNameModO12)
simuCube[kPA+1, y0:y0+my1-my0, x0:x0+mx1-mx0] += modelO12[0, my0:my1, mx0:mx1]*fluxscale
return simuCube
def lrsFieldSim(ra, dec, binComp=''):
""" Produce a Grism Time Series field simulation for a target.
Parameters
----------
ra : float
The RA of the target.
dec : float
The Dec of the target.
binComp : sequence
The parameters of a binary companion.
Returns
-------
simuCube : np.ndarray
The simulated data cube. Index 0 and 1 (axis=0) show the trace of
the target for orders 1 and 2 (respectively). Index 2-362 show the trace
of the target at every position angle (PA) of the instrument.
"""
# Calling the variables
dimX = 55
dimY = 427
rad = 2.5
pixel_scale = 0.11 # arsec
xval, yval = 38.5, 829.0
add_to_apa = 4.83425324
# stars in large field around target
targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))
targetRA = targetcrd.ra.value
targetDEC = targetcrd.dec.value
info = Irsa.query_region(targetcrd, catalog='fp_psc', spatial='Cone',
radius=rad*u.arcmin)
# Coordinates of all the stars in FOV, including target
allRA = info['ra'].data.data
allDEC = info['dec'].data.data
Jmag = info['j_m'].data.data
Hmag = info['h_m'].data.data
Kmag = info['k_m'].data.data
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# Coordiniates of target
aa = ((targetRA-allRA)*np.cos(targetDEC))
distance = np.sqrt(aa**2 + (targetDEC-allDEC)**2)
targetIndex = np.argmin(distance) # the target
# Add any missing companion
if binComp != '':
deg2rad = np.pi/180
bb = binComp[0]/3600/np.cos(allDEC[targetIndex]*deg2rad)
allRA = np.append(allRA, (allRA[targetIndex] + bb))
allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1]/3600))
Jmag = np.append(Jmag, binComp[2])
Hmag = np.append(Kmag, binComp[3])
Kmag = np.append(Kmag, binComp[4])
J_Hobs = Jmag-Hmag
H_Kobs = Hmag-Kmag
# Number of stars
nStars = allRA.size
# Restoring model parameters
modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),
verbose=False)
models = modelParam['models']
modelPadX = modelParam['modelpadx']
modelPadY = modelParam['modelpady']
dimXmod = modelParam['dimxmod']
dimYmod = modelParam['dimymod']
jhMod = modelParam['jhmod']
hkMod = modelParam['hkmod']
#teffMod = modelParam['teffmod']
teffMod = np.linspace(2000, 6000, 41)
# Find/assign Teff of each star
starsT = np.empty(nStars)
for j in range(nStars):
color_separation = (J_Hobs[j]-jhMod)**2+(H_Kobs[j]-hkMod)**2
min_separation_ind = np.argmin(color_separation)
starsT[j] = teffMod[min_separation_ind]
radeg = 180/np.pi
sweetSpot = dict(x=xval, y=yval, RA=allRA[targetIndex],
DEC=allDEC[targetIndex], jmag=Jmag[targetIndex])
# Offset between all stars and target
dRA = (allRA - sweetSpot['RA'])*np.cos(sweetSpot['DEC']/radeg)*3600
dDEC = (allDEC - sweetSpot['DEC'])*3600
# Put field stars positions and magnitudes in structured array
_ = dict(RA=allRA, DEC=allDEC, dRA=dRA, dDEC=dDEC, jmag=Jmag, T=starsT,
x=np.empty(nStars), y=np.empty(nStars), dx=np.empty(nStars),
dy=np.empty(nStars))
stars = np.empty(nStars,
dtype=[(key, val.dtype) for key, val in _.items()])
for key, val in _.items():
stars[key] = val
# Initialize final fits cube that contains the modelled traces
# with contamination
PAmin = 0 # instrument PA, degrees
PAmax = 360
dPA = 1 # degrees
# Set of IPA values to cover
PAtab = np.arange(PAmin, PAmax, dPA) # degrees
nPA = len(PAtab)
# Cube of trace simulation at every degree of field rotation,
# +target at O1 and O2
simuCube = np.zeros([nPA+1, dimY+1, dimX+1])
fitsFiles = glob.glob(os.path.join(TRACES_PATH, 'MIRI', '_*.fits'))
fitsFiles = np.sort(fitsFiles)
# Big loop to generate a simulation at each instrument PA
for kPA in range(PAtab.size):
APA = PAtab[kPA] # Aperture Position Angle (PA of instrument)
V3PA = APA+add_to_apa # from APT
sindx = np.sin(np.pi/2+APA/radeg)*stars['dDEC']
cosdx = np.cos(np.pi/2+APA/radeg)*stars['dDEC']
ps = pixel_scale
stars['dx'] = (np.cos(np.pi/2+APA/radeg)*stars['dRA']-sindx)/ps
stars['dy'] = (np.sin(np.pi/2+APA/radeg)*stars['dRA']+cosdx)/ps
stars['x'] = stars['dx']+sweetSpot['x']
stars['y'] = stars['dy']+sweetSpot['y']
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~NOTE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Retain stars that are within the Direct Image NIRISS POM FOV
# This extends the subarray edges to the detector edges.
# It keeps the stars that fall out of the subarray but still
# fall into the detector.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ind, = np.where((stars['x'] >= -8000) & (stars['x'] <= dimY+8000) &
(stars['y'] >= -8000) & (stars['y'] <= dimY+8000))
starsInFOV = stars[ind]
for i in range(len(ind)):
intx = round(starsInFOV['dx'][i])
inty = round(starsInFOV['dy'][i])
# This indexing assumes that teffMod is
# sorted the same way fitsFiles was sorted
k = np.where(teffMod == starsInFOV['T'][i])[0][0]
fluxscale = 10.0**(-0.4*(starsInFOV['jmag'][i]-sweetSpot['jmag']))
# deal with subection sizes
modelPadX = 0
modelPadY = 0
mx0 = int(modelPadX-intx)
mx1 = int(modelPadX-intx+dimX)
my0 = int(modelPadY-inty)
my1 = int(modelPadY-inty+dimY)
if (mx0 > dimX) or (my0 > dimY):
continue
if (mx1 < 0) or (my1 < 0):
continue
x0 = (mx0 < 0)*(-mx0)
y0 = (my0 < 0)*(-my0)
mx0 *= (mx0 >= 0)
mx1 = dimX if mx1 > dimX else mx1
my0 *= (my0 >= 0)
my1 = dimY if my1 > dimY else my1
# Fleshing out index 0 of the simulation cube (trace of target)
if (intx == 0) & (inty == 0) & (kPA == 0):
fNameModO12 = fitsFiles[k]
modelO1 = fits.getdata(fNameModO12, 1)
ord1 = modelO1[0, my0:my1, mx0:mx1]*fluxscale
simuCube[0, y0:y0+my1-my0, x0:x0+mx1-mx0] = ord1
# Fleshing out indexes 1-361 of the simulation cube
# (trace of neighboring stars at every position angle)
if (intx != 0) or (inty != 0):
fNameModO12 = fitsFiles[k]
modelO12 = fits.getdata(fNameModO12)
simuCube[kPA+1, y0:y0+my1-my0, x0:x0+mx1-mx0] += modelO12[0, my0:my1, mx0:mx1]*fluxscale
return simuCube
def fieldSim(ra, dec, instrument, binComp=''):
""" Wraps ``sossFieldSim``, ``gtsFieldSim``, and ``lrsFieldSim`` together.
Produces a field simulation for a target using any instrument (NIRISS,
NIRCam, or MIRI).
Parameters
----------
ra : float
The RA of the target.
dec : float
The Dec of the target.
instrument : str
The instrument the contamination is being calculated for.
Can either be (case-sensitive):
'NIRISS', 'NIRCam F322W2', 'NIRCam F444W', 'MIRI'
binComp : sequence
The parameters of a binary companion.
Returns
-------
simuCube : np.ndarray
The simulated data cube. Index 0 and 1 (axis=0) show the trace of
the target for orders 1 and 2 (respectively). Index 2-362 show the trace
of the target at every position angle (PA) of the instrument.
"""
# Calling the variables which depend on what instrument you use
if instrument=='NIRISS':
simuCube = sossFieldSim(ra, dec, binComp)
elif instrument=='NIRCam F444W':
simuCube = gtsFieldSim(ra, dec, 'F444W', binComp)
elif instrument=='NIRCam F322W2':
simuCube = gtsFieldSim(ra, dec, 'F322W2', binComp)
elif instrument=='MIRI':
simuCube = lrsFieldSim(ra, dec, binComp)
return simuCube
if __name__ == '__main__':
ra, dec = "04 25 29.0162", "-30 36 01.603" # Wasp 79
#sossFieldSim(ra, dec)
if EXOCTK_DATA:
fieldSim(ra, dec, instrument='NIRISS')
|
#!/usr/bin/env python
# compare_4_dens.py v1.0 9-27-2012 Jeff Doak [email protected]
from chargedensity import *
import numpy as np
# The first file should have the density grid that will be used for the final
# density that is returned.
locname1 = str(sys.argv[1])
locname2 = str(sys.argv[2])
locname3 = str(sys.argv[3])
locname4 = str(sys.argv[4])
locfile1 = open(locname1,'r')
locfile2 = open(locname2,'r')
locfile3 = open(locname3,'r')
locfile4 = open(locname4,'r')
loc1 = ChargeDensity(locfile1,"chgcar")
loc2 = ChargeDensity(locfile2,"chgcar")
loc3 = ChargeDensity(locfile3,"chgcar")
loc4 = ChargeDensity(locfile4,"chgcar")
den_z1 = loc1.integrate_z_density()
den_z2 = loc2.integrate_z_density()
den_z3 = loc3.integrate_z_density()
den_z4 = loc4.integrate_z_density()
z_pos = np.linspace(0,loc1.unitcell.cell_vec[2,2],len(den_z1))
spline1 = loc1.spline_density_z(den_z1)
spline2 = loc2.spline_density_z(den_z2)
spline3 = loc2.spline_density_z(den_z3)
spline4 = loc2.spline_density_z(den_z4)
z_diff,diff1 = loc1.dens_diff_z(spline1,spline2)
z_diff2,diff2 = loc1.dens_diff_z(spline3,spline4)
for i in range(len(diff1)):
print z_diff[i],(diff1[i]-diff2[i])
|
#!/usr/bin/env python3.6
#Author: Vishwas K Singh
#email: [email protected]
#Program: Print out a date,given year, month and day as numbers
# Listing 2.1
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
# A list with one ending for each number from 1 to 31
endings = ['st','nd','rd'] + 17 * ['th'] \
+ ['st', 'nd','rd'] + 7 * ['th'] \
+ ['st']
year = input('Year: ')
month = input('Month (1-12): ')
day = input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
# Remember to subtract 1 from month to get a current index
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print(month_name + ' ' + ordinal + ', ' + year)
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VirtualNetworkTapsOperations:
"""VirtualNetworkTapsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2018_10_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _delete_initial(
self,
resource_group_name: str,
tap_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
tap_name: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes the specified virtual network tap.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param tap_name: The name of the virtual network tap.
:type tap_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
tap_name=tap_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def get(
self,
resource_group_name: str,
tap_name: str,
**kwargs: Any
) -> "_models.VirtualNetworkTap":
"""Gets information about the specified virtual network tap.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param tap_name: The name of virtual network tap.
:type tap_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VirtualNetworkTap, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTap
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTap"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
tap_name: str,
parameters: "_models.VirtualNetworkTap",
**kwargs: Any
) -> "_models.VirtualNetworkTap":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTap"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'VirtualNetworkTap')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
tap_name: str,
parameters: "_models.VirtualNetworkTap",
**kwargs: Any
) -> AsyncLROPoller["_models.VirtualNetworkTap"]:
"""Creates or updates a Virtual Network Tap.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param tap_name: The name of the virtual network tap.
:type tap_name: str
:param parameters: Parameters supplied to the create or update virtual network tap operation.
:type parameters: ~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTap
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VirtualNetworkTap or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTap]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTap"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
tap_name=tap_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def _update_tags_initial(
self,
resource_group_name: str,
tap_name: str,
tap_parameters: "_models.TagsObject",
**kwargs: Any
) -> "_models.VirtualNetworkTap":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTap"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._update_tags_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(tap_parameters, 'TagsObject')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
async def begin_update_tags(
self,
resource_group_name: str,
tap_name: str,
tap_parameters: "_models.TagsObject",
**kwargs: Any
) -> AsyncLROPoller["_models.VirtualNetworkTap"]:
"""Updates an VirtualNetworkTap tags.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param tap_name: The name of the tap.
:type tap_name: str
:param tap_parameters: Parameters supplied to update VirtualNetworkTap tags.
:type tap_parameters: ~azure.mgmt.network.v2018_10_01.models.TagsObject
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VirtualNetworkTap or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTap]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTap"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_tags_initial(
resource_group_name=resource_group_name,
tap_name=tap_name,
tap_parameters=tap_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualNetworkTap', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'tapName': self._serialize.url("tap_name", tap_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}'} # type: ignore
def list_all(
self,
**kwargs: Any
) -> AsyncIterable["_models.VirtualNetworkTapListResult"]:
"""Gets all the VirtualNetworkTaps in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualNetworkTapListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTapListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTapListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_all.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualNetworkTapListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworkTaps'} # type: ignore
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.VirtualNetworkTapListResult"]:
"""Gets all the VirtualNetworkTaps in a subscription.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualNetworkTapListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_10_01.models.VirtualNetworkTapListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkTapListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-10-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualNetworkTapListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps'} # type: ignore
|
#ifndef INCLUDE_COMPUTEGROUP2_HPP_
#define INCLUDE_COMPUTEGROUP2_HPP_
#include "DataHandler.h"
namespace lmfao
{
void computeGroup2();
}
#endif /* INCLUDE_COMPUTEGROUP2_HPP_*/
|
import logging
import time
from collections import defaultdict, OrderedDict
from collections.abc import Mapping
import weakref
import random
import warnings
from typing import Union, Optional, Callable, Iterable, Iterator, Any, Tuple
import torch
from ignite.engine.events import Events, State, CallableEventWithFilter, RemovableEventHandle, EventsList
from ignite.engine.utils import ReproducibleBatchSampler, _update_dataloader, _check_signature
from ignite._utils import _to_hours_mins_secs
__all__ = ["Engine"]
class Engine:
"""Runs a given `process_function` over each batch of a dataset, emitting events as it goes.
Args:
process_function (callable): A function receiving a handle to the engine and the current batch
in each iteration, and returns data to be stored in the engine's state.
Attributes:
state (State): object that is used to pass internal and user-defined state between event handlers.
It is created and reset on every :meth:`~ignite.engine.Engine.run`.
last_event_name (Events): last event name triggered by the engine.
Examples:
Create a basic trainer
.. code-block:: python
def update_model(engine, batch):
inputs, targets = batch
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
return loss.item()
trainer = Engine(update_model)
@trainer.on(Events.ITERATION_COMPLETED(every=100))
def log_training(engine):
batch_loss = engine.state.output
lr = optimizer.param_groups[0]['lr']
e = engine.state.epoch
n = engine.state.max_epochs
i = engine.state.iteration
print("Epoch {}/{} : {} - batch loss: {}, lr: {}".format(e, n, i, batch_loss, lr))
trainer.run(data_loader, max_epochs=5)
> Epoch 1/5 : 100 - batch loss: 0.10874069479016124, lr: 0.01
> ...
> Epoch 2/5 : 1700 - batch loss: 0.4217900575859437, lr: 0.01
Create a basic evaluator to compute metrics
.. code-block:: python
from ignite.metrics import Accuracy
def predict_on_batch(engine, batch)
model.eval()
with torch.no_grad():
x, y = prepare_batch(batch, device=device, non_blocking=non_blocking)
y_pred = model(x)
return y_pred, y
evaluator = Engine(predict_on_batch)
Accuracy().attach(evaluator, "val_acc")
evaluator.run(val_dataloader)
Compute image mean/std on training dataset
.. code-block:: python
from ignite.metrics import Average
def compute_mean_std(engine, batch):
b, c, *_ = batch['image'].shape
data = batch['image'].reshape(b, c, -1).to(dtype=torch.float64)
mean = torch.mean(data, dim=-1).sum(dim=0)
mean2 = torch.mean(data ** 2, dim=-1).sum(dim=0)
return {"mean": mean, "mean^2": mean2}
compute_engine = Engine(compute_mean_std)
img_mean = Average(output_transform=lambda output: output['mean'])
img_mean.attach(compute_engine, 'mean')
img_mean2 = Average(output_transform=lambda output: output['mean^2'])
img_mean2.attach(compute_engine, 'mean2')
state = compute_engine.run(train_loader)
state.metrics['std'] = torch.sqrt(state.metrics['mean2'] - state.metrics['mean'] ** 2)
mean = state.metrics['mean'].tolist()
std = state.metrics['std'].tolist()
Resume engine's run from a state. User can load a `state_dict` and run engine starting from loaded state :
.. code-block:: python
# Restore from an epoch
state_dict = {"seed": 0, "epoch": 3, "max_epochs": 100, "epoch_length": len(data_loader)}
# or an iteration
# state_dict = {"seed": 0, "iteration": 500, "max_epochs": 100, "epoch_length": len(data_loader)}
trainer = Engine(...)
trainer.load_state_dict(state_dict)
trainer.run(data)
"""
_state_dict_all_req_keys = ("seed", "epoch_length", "max_epochs")
_state_dict_one_of_opt_keys = ("iteration", "epoch")
def __init__(self, process_function: Callable):
self._event_handlers = defaultdict(list)
self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
self._process_function = process_function
self.last_event_name = None
self.should_terminate = False
self.should_terminate_single_epoch = False
self.state = None
self._allowed_events = []
self._dataloader_iter = None
self._init_iter = []
self.register_events(*Events)
if self._process_function is None:
raise ValueError("Engine must be given a processing function in order to run.")
_check_signature(self, process_function, "process_function", None)
def register_events(self, *event_names: Any, event_to_attr: Optional[dict] = None) -> None:
"""Add events that can be fired.
Registering an event will let the user fire these events at any point.
This opens the door to make the :meth:`~ignite.engine.Engine.run` loop even more
configurable.
By default, the events from :class:`~ignite.engine.Events` are registered.
Args:
*event_names: An object (ideally a string or int) to define the
name of the event being supported.
event_to_attr (dict, optional): A dictionary to map an event to a state attribute.
Example usage:
.. code-block:: python
from ignite.engine import Engine, EventEnum
class CustomEvents(EventEnum):
FOO_EVENT = "foo_event"
BAR_EVENT = "bar_event"
engine = Engine(process_function)
engine.register_events(*CustomEvents)
Example with State Attribute:
.. code-block:: python
from enum import Enum
from ignite.engine import Engine, EventEnum
class TBPTT_Events(EventEnum):
TIME_ITERATION_STARTED = "time_iteration_started"
TIME_ITERATION_COMPLETED = "time_iteration_completed"
TBPTT_event_to_attr = {
TBPTT_Events.TIME_ITERATION_STARTED: 'time_iteration',
TBPTT_Events.TIME_ITERATION_COMPLETED: 'time_iteration'
}
engine = Engine(process_function)
engine.register_events(*TBPTT_Events, event_to_attr=TBPTT_event_to_attr)
engine.run(data)
# engine.state contains an attribute time_iteration, which can be accessed using engine.state.time_iteration
"""
if not (event_to_attr is None or isinstance(event_to_attr, dict)):
raise ValueError("Expected event_to_attr to be dictionary. Got {}.".format(type(event_to_attr)))
for e in event_names:
self._allowed_events.append(e)
if event_to_attr and e in event_to_attr:
State.event_to_attr[e] = event_to_attr[e]
@staticmethod
def _handler_wrapper(handler: Callable, event_name: Any, event_filter: Callable) -> Callable:
def wrapper(engine: Engine, *args, **kwargs) -> Any:
event = engine.state.get_event_attrib_value(event_name)
if event_filter(engine, event):
return handler(engine, *args, **kwargs)
# setup input handler as parent to make has_event_handler work
wrapper._parent = weakref.ref(handler)
return wrapper
def add_event_handler(self, event_name: Any, handler: Callable, *args, **kwargs):
"""Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event or a list of events to attach the handler. Valid events are
from :class:`~ignite.engine.Events` or any `event_name` added by
:meth:`~ignite.engine.Engine.register_events`.
handler (callable): the callable event handler that should be invoked
*args: optional args to be passed to `handler`.
**kwargs: optional keyword args to be passed to `handler`.
Note:
The handler function's first argument will be `self`, the :class:`~ignite.engine.Engine` object it
was bound to.
Note that other arguments can be passed to the handler in addition to the `*args` and `**kwargs`
passed here, for example during :attr:`~ignite.engine.Events.EXCEPTION_RAISED`.
Returns:
:class:`~ignite.engine.RemovableEventHandle`, which can be used to remove the handler.
Example usage:
.. code-block:: python
engine = Engine(process_function)
def print_epoch(engine):
print("Epoch: {}".format(engine.state.epoch))
engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch)
events_list = Events.EPOCH_COMPLETED | Events.COMPLETED
def execute_validation(engine):
# do some validations
engine.add_event_handler(events_list, execute_validation)
Note:
Since v0.3.0, Events become more flexible and allow to pass an event filter to the Engine.
See :class:`~ignite.engine.Events` for more details.
"""
if isinstance(event_name, EventsList):
for e in event_name:
self.add_event_handler(e, handler, *args, **kwargs)
return RemovableEventHandle(event_name, handler, self)
if (
isinstance(event_name, CallableEventWithFilter)
and event_name.filter != CallableEventWithFilter.default_event_filter
):
event_filter = event_name.filter
handler = Engine._handler_wrapper(handler, event_name, event_filter)
if event_name not in self._allowed_events:
self.logger.error("attempt to add event handler to an invalid event %s.", event_name)
raise ValueError("Event {} is not a valid event for this Engine.".format(event_name))
event_args = (Exception(),) if event_name == Events.EXCEPTION_RAISED else ()
_check_signature(self, handler, "handler", *(event_args + args), **kwargs)
self._event_handlers[event_name].append((handler, args, kwargs))
self.logger.debug("added handler for event %s.", event_name)
return RemovableEventHandle(event_name, handler, self)
@staticmethod
def _assert_non_filtered_event(event_name: Any):
if (
isinstance(event_name, CallableEventWithFilter)
and event_name.filter != CallableEventWithFilter.default_event_filter
):
raise TypeError(
"Argument event_name should not be a filtered event, " "please use event without any event filtering"
)
def has_event_handler(self, handler: Callable, event_name: Optional[Any] = None):
"""Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events.
"""
if event_name is not None:
self._assert_non_filtered_event(event_name)
if event_name not in self._event_handlers:
return False
events = [event_name]
else:
events = self._event_handlers
for e in events:
for h, _, _ in self._event_handlers[e]:
if self._compare_handlers(handler, h):
return True
return False
@staticmethod
def _compare_handlers(user_handler: Callable, registered_handler: Callable) -> bool:
if hasattr(registered_handler, "_parent"):
registered_handler = registered_handler._parent()
return registered_handler == user_handler
def remove_event_handler(self, handler: Callable, event_name: Any):
"""Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to.
"""
self._assert_non_filtered_event(event_name)
if event_name not in self._event_handlers:
raise ValueError("Input event name '{}' does not exist".format(event_name))
new_event_handlers = [
(h, args, kwargs)
for h, args, kwargs in self._event_handlers[event_name]
if not self._compare_handlers(handler, h)
]
if len(new_event_handlers) == len(self._event_handlers[event_name]):
raise ValueError("Input handler '{}' is not found among registered event handlers".format(handler))
self._event_handlers[event_name] = new_event_handlers
def on(self, event_name, *args, **kwargs):
"""Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
*args: optional args to be passed to `handler`.
**kwargs: optional keyword args to be passed to `handler`.
"""
def decorator(f: Callable) -> Callable:
self.add_event_handler(event_name, f, *args, **kwargs)
return f
return decorator
def _fire_event(self, event_name: Any, *event_args, **event_kwargs) -> None:
"""Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers added with this event. These
arguments updates arguments passed using :meth:`~ignite.engine.Engine.add_event_handler`.
Args:
event_name: event for which the handlers should be executed. Valid
events are from :class:`~ignite.engine.Events` or any `event_name` added by
:meth:`~ignite.engine.Engine.register_events`.
*event_args: optional args to be passed to all handlers.
**event_kwargs: optional keyword args to be passed to all handlers.
"""
if event_name in self._allowed_events:
self.logger.debug("firing handlers for event %s ", event_name)
self.last_event_name = event_name
for func, args, kwargs in self._event_handlers[event_name]:
kwargs.update(event_kwargs)
func(self, *(event_args + args), **kwargs)
def fire_event(self, event_name: Any) -> None:
"""Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. This is the method used in :meth:`~ignite.engine.Engine.run` to call the
core events found in :class:`~ignite.engine.Events`.
Custom events can be fired if they have been registered before with
:meth:`~ignite.engine.Engine.register_events`. The engine `state` attribute should be used
to exchange "dynamic" data among `process_function` and handlers.
This method is called automatically for core events. If no custom
events are used in the engine, there is no need for the user to call
the method.
Args:
event_name: event for which the handlers should be executed. Valid
events are from :class:`~ignite.engine.Events` or any `event_name` added by
:meth:`~ignite.engine.Engine.register_events`.
"""
return self._fire_event(event_name)
def terminate(self) -> None:
"""Sends terminate signal to the engine, so that it terminates completely the run after the current iteration.
"""
self.logger.info("Terminate signaled. Engine will stop after current iteration is finished.")
self.should_terminate = True
def terminate_epoch(self) -> None:
"""Sends terminate signal to the engine, so that it terminates the current epoch after the current iteration.
"""
self.logger.info(
"Terminate current epoch is signaled. "
"Current epoch iteration will stop after current iteration is finished."
)
self.should_terminate_single_epoch = True
def _run_once_on_dataset(self) -> Tuple[int, int, int]:
start_time = time.time()
# We need to setup iter_counter > 0 if we resume from an iteration
iter_counter = self._init_iter.pop() if len(self._init_iter) > 0 else 0
should_exit = False
try:
while True:
try:
self._fire_event(Events.GET_BATCH_STARTED)
batch = next(self._dataloader_iter)
self._fire_event(Events.GET_BATCH_COMPLETED)
iter_counter += 1
should_exit = False
except StopIteration:
if self._dataloader_len is None:
if iter_counter > 0:
self._dataloader_len = iter_counter
else:
# this can happen when data is finite iterator and epoch_length is equal to its size
self._dataloader_len = self.state.iteration
# Should exit while loop if we can not iterate
if should_exit:
if not self._is_done(self.state):
warnings.warn(
"Data iterator can not provide data anymore but required total number of "
"iterations to run is not reached. "
"Current iteration: {} vs Total iterations to run : {}".format(
self.state.iteration, self.state.epoch_length * self.state.max_epochs
)
)
break
# set seed on restart of data iterator
self.setup_seed()
self._dataloader_iter = iter(self.state.dataloader)
should_exit = True
continue
self.state.batch = batch
self.state.iteration += 1
self._fire_event(Events.ITERATION_STARTED)
self.state.output = self._process_function(self, self.state.batch)
self._fire_event(Events.ITERATION_COMPLETED)
# TODO: remove refs on batch to avoid high mem consumption ? -> need verification
# self.state.batch = batch = None
if self.should_terminate or self.should_terminate_single_epoch:
self.should_terminate_single_epoch = False
self._manual_seed(self.state.seed, self.state.iteration // iter_counter)
self._dataloader_iter = iter(self.state.dataloader)
break
if iter_counter == self.state.epoch_length:
break
except BaseException as e:
self.logger.error("Current run is terminating due to exception: %s.", str(e))
self._handle_exception(e)
time_taken = time.time() - start_time
hours, mins, secs = _to_hours_mins_secs(time_taken)
return hours, mins, secs
def _handle_exception(self, e: Exception) -> None:
if Events.EXCEPTION_RAISED in self._event_handlers:
self._fire_event(Events.EXCEPTION_RAISED, e)
else:
raise e
def state_dict(self) -> OrderedDict:
"""Returns a dictionary containing engine's state: "seed", "epoch_length", "max_epochs" and "iteration"
Returns:
dict:
a dictionary containing engine's state
"""
if self.state is None:
return OrderedDict()
keys = self._state_dict_all_req_keys + (self._state_dict_one_of_opt_keys[0],)
return OrderedDict([(k, getattr(self.state, k)) for k in keys])
def load_state_dict(self, state_dict: Mapping) -> None:
"""Setups engine from `state_dict`.
State dictionary should contain keys: `iteration` or `epoch` and `max_epochs`, `epoch_length` and
`seed`. Iteration and epoch values are 0-based: the first iteration or epoch is zero.
Args:
state_dict (Mapping): a dict with parameters
.. code-block:: python
# Restore from an epoch
state_dict = {"seed": 0, "epoch": 3, "max_epochs": 100, "epoch_length": len(data_loader)}
# or an iteration
# state_dict = {"seed": 0, "iteration": 500, "max_epochs": 100, "epoch_length": len(data_loader)}
trainer = Engine(...)
trainer.load_state_dict(state_dict)
trainer.run(data)
"""
if not isinstance(state_dict, Mapping):
raise TypeError("Argument state_dict should be a dictionary, but given {}".format(type(state_dict)))
for k in self._state_dict_all_req_keys:
if k not in state_dict:
raise ValueError(
"Required state attribute '{}' is absent in provided state_dict '{}'".format(k, state_dict.keys())
)
opts = [k in state_dict for k in self._state_dict_one_of_opt_keys]
if (not any(opts)) or (all(opts)):
raise ValueError("state_dict should contain only one of '{}' keys".format(self._state_dict_one_of_opt_keys))
self.state = State(
seed=state_dict["seed"],
max_epochs=state_dict["max_epochs"],
epoch_length=state_dict["epoch_length"],
metrics={},
)
if "iteration" in state_dict:
self.state.iteration = state_dict["iteration"]
self.state.epoch = self.state.iteration // self.state.epoch_length
elif "epoch" in state_dict:
self.state.epoch = state_dict["epoch"]
self.state.iteration = self.state.epoch_length * self.state.epoch
@staticmethod
def _is_done(state: State) -> bool:
return state.iteration == state.epoch_length * state.max_epochs
def run(
self,
data: Iterable,
max_epochs: Optional[int] = None,
epoch_length: Optional[int] = None,
seed: Optional[int] = None,
) -> State:
"""Runs the `process_function` over the passed data.
Engine has a state and the following logic is applied in this function:
- At the first call, new state is defined by `max_epochs`, `epoch_length`, `seed` if provided.
- If state is already defined such that there are iterations to run until `max_epochs` and no input arguments
provided, state is kept and used in the function.
- If state is defined and engine is "done" (no iterations to run until `max_epochs`), a new state is defined.
- If state is defined, engine is NOT "done", then input arguments if provided override defined state.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): Max epochs to run for (default: None).
If a new state should be created (first run or run again from ended engine), it's default value is 1.
This argument should be `None` if run is resuming from a state.
epoch_length (int, optional): Number of iterations to count as one epoch. By default, it can be set as
`len(data)`. If `data` is an iterator and `epoch_length` is not set, an error is raised.
This argument should be `None` if run is resuming from a state.
seed (int, optional): Seed to use for dataflow consistency, by default it
will respect the global random state. This argument should be `None` if run is resuming from a state.
Returns:
State: output state.
Note:
User can dynamically preprocess input batch at :attr:`~ignite.engine.Events.ITERATION_STARTED` and store
output batch in `engine.state.batch`. Latter is passed as usually to `process_function` as argument:
.. code-block:: python
trainer = ...
@trainer.on(Events.ITERATION_STARTED)
def switch_batch(engine):
engine.state.batch = preprocess_batch(engine.state.batch)
Note:
In order to perform a reproducible run, if input `data` is `torch.utils.data.DataLoader`, its batch sampler
is replaced by a batch sampler (:class:`~ignite.engine.engine.ReproducibleBatchSampler`) such that random
sampling indices are reproducible by prefetching them before data iteration.
"""
if self.state is None or self._is_done(self.state):
# Create new state
if max_epochs is None:
max_epochs = 1
if seed is None:
seed = torch.randint(0, int(1e9), (1,)).item()
if epoch_length is None:
if hasattr(data, "__len__"):
epoch_length = len(data)
if epoch_length < 1:
raise ValueError("Input data has zero size. Please provide non-empty data")
else:
raise ValueError("Argument `epoch_length` should be defined if `data` is an iterator")
self.state = State(seed=seed, iteration=0, epoch=0, max_epochs=max_epochs, epoch_length=epoch_length)
self.logger.info("Engine run starting with max_epochs={}.".format(max_epochs))
else:
# Keep actual state and override it if input args provided
if max_epochs is not None:
self.state.max_epochs = max_epochs
if seed is not None:
self.state.seed = seed
if epoch_length is not None:
self.state.epoch_length = epoch_length
self.logger.info(
"Engine run resuming from iteration {}, epoch {} until {} epochs".format(
self.state.iteration, self.state.epoch, self.state.max_epochs
)
)
self.state.dataloader = data
return self._internal_run()
def _setup_engine(self) -> None:
try:
self._dataloader_len = len(self.state.dataloader) if hasattr(self.state.dataloader, "__len__") else None
except TypeError:
# _InfiniteConstantSampler can raise a TypeError on DataLoader length of a IterableDataset
self._dataloader_len = None
# setup seed here, as iter(data) can start prefetching
self.setup_seed()
# if input data is torch dataloader we replace batch sampler by a batch sampler
# such that its random sampling indices are reproducible by prefetching them before data iteration
if isinstance(self.state.dataloader, torch.utils.data.DataLoader):
_dataloader_kind = self.state.dataloader._dataset_kind
if _dataloader_kind == torch.utils.data.dataloader._DatasetKind.Map:
if (self._dataloader_len is not None) and hasattr(self.state.dataloader.sampler, "epoch"):
if self._dataloader_len != self.state.epoch_length:
warnings.warn(
"When defined engine's epoch length is different of input dataloader length, "
"distributed sampler indices can not be setup in a reproducible manner"
)
batch_sampler = self.state.dataloader.batch_sampler
if not isinstance(batch_sampler, ReproducibleBatchSampler):
self.state.dataloader = _update_dataloader(
self.state.dataloader, ReproducibleBatchSampler(batch_sampler)
)
iteration = self.state.iteration
self._dataloader_iter = self._from_iteration(self.state.dataloader, iteration)
# Below we define initial counter value for _run_once_on_dataset to measure a single epoch
if self.state.epoch_length is not None:
iteration %= self.state.epoch_length
self._init_iter.append(iteration)
@staticmethod
def _from_iteration(data: Union[Iterable, torch.utils.data.DataLoader], iteration: int) -> Iterator:
if isinstance(data, torch.utils.data.DataLoader):
try:
# following is unsafe for IterableDatasets
iteration %= len(data.batch_sampler)
if iteration > 0:
# batch sampler is ReproducibleBatchSampler
data.batch_sampler.start_iteration = iteration
except TypeError:
# Probably we can do nothing with DataLoader built upon IterableDatasets
pass
data_iter = iter(data)
else:
if hasattr(data, "__len__"):
iteration %= len(data)
data_iter = iter(data)
counter = 0
while counter < iteration:
try:
next(data_iter)
counter += 1
except StopIteration:
data_iter = iter(data)
return data_iter
@staticmethod
def _manual_seed(seed: int, epoch: int) -> None:
random.seed(seed + epoch)
torch.manual_seed(seed + epoch)
try:
import numpy as np
np.random.seed(seed + epoch)
except ImportError:
pass
def setup_seed(self) -> None:
# seed value should be related to input data iterator length -> iteration at data iterator restart
# - seed can not be epoch because during a single epoch we can have multiple `_dataloader_len`
# - seed can not be iteration because when resuming from iteration we need to set the seed from the start of the
# dataloader and then rewind to required iteration
le = self._dataloader_len if self._dataloader_len is not None else 1
self._manual_seed(self.state.seed, self.state.iteration // le)
def _internal_run(self) -> State:
self.should_terminate = self.should_terminate_single_epoch = False
try:
start_time = time.time()
self._fire_event(Events.STARTED)
while self.state.epoch < self.state.max_epochs and not self.should_terminate:
self.state.epoch += 1
self._fire_event(Events.EPOCH_STARTED)
if self._dataloader_iter is None:
self._setup_engine()
hours, mins, secs = self._run_once_on_dataset()
self.logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs)
if self.should_terminate:
break
self._fire_event(Events.EPOCH_COMPLETED)
self._fire_event(Events.COMPLETED)
time_taken = time.time() - start_time
hours, mins, secs = _to_hours_mins_secs(time_taken)
self.logger.info("Engine run complete. Time taken %02d:%02d:%02d" % (hours, mins, secs))
except BaseException as e:
self._dataloader_iter = self._dataloader_len = None
self.logger.error("Engine run is terminating due to exception: %s.", str(e))
self._handle_exception(e)
self._dataloader_iter = self._dataloader_len = None
return self.state
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2014-2017 XDN developers
// Copyright (c) 2016-2017 BXC developers
// Copyright (c) 2017 UltraNote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
namespace System {
class Dispatcher;
class Event {
public:
Event();
explicit Event(Dispatcher& dispatcher);
Event(const Event&) = delete;
Event(Event&& other);
~Event();
Event& operator=(const Event&) = delete;
Event& operator=(Event&& other);
bool get() const;
void clear();
void set();
void wait();
private:
Dispatcher* dispatcher;
bool state;
void* first;
void* last;
};
}
|
module.exports = {
clearMocks: true,
moduleFileExtensions: ["js", "ts"],
testEnvironment: "node",
testMatch: ["**/*.test.ts"],
testRunner: "jest-circus/runner",
transform: {
"^.+\\.ts$": "ts-jest",
},
verbose: true,
};
|
import $ from 'jquery';
import select2 from 'select2';
select2($); //Hook up select2 to jQuery
// window.jQuery = $;
// select2(jQuery);
// import 'select2/dist/js/i18n/it.js';
export const select2_defaults = {
theme : 'bootstrap4',
width : '100%',
language : {
errorLoading: function () {
return 'I risultati non possono essere caricati.';
},
inputTooLong: function (e) {
var n = e.input.length - e.maximum,
t = 'Devi rimuovere almeno ' + n + ' caratter';
return t += 1 !== n ? 'i' : 'e';
},
inputTooShort: function (e) {
return 'Inserisci ' + (e.minimum - e.input.length) + ' o più caratteri';
},
loadingMore: function () {
return 'Sto caricando i risultati...';
},
maximumSelected: function (e) {
var n = 'Puoi selezionare solo ' + e.maximum + ' element';
return 1 !== e.maximum ? n += 'i' : n += 'o', n;
},
noResults: function () {
return 'Nessun risultato per la ricerca inserita';
},
searching: function () {
return 'Sto cercando...';
},
removeAllItems: function () {
return 'Rimuovi tutto';
}
},
debug: false,
multiple: false,
minimumInputLength : 3,
placeholder : 'Clic per selezionare',
allowClear : true, // mostra il pulsante di deselezione
//closeOnSelect : false, // Force the dropdown to remain open after selection
selectOnClose: true,
ajax: {
dataType : 'json',
delay : 400,
data: function (/* params */) {
return {};
},
// url: function (params) {
// return '/autocomplete/xxxx/' + params.term;
// },
cache: true,
// You can use the ajax.processResults option to transform the data
// returned by your API into the format expected by Select2:
processResults: function (data) {
return { results: data };
}
},
escapeMarkup: markup => markup,
templateResult: function(data) { // lista risultati
if (data.text) {
return 'Sto cercando...'; // return data.text
} else {
// data.text = data.nome + data.cognome;
return data.text;
}
},
templateSelection: data => data.text // text option preregistrati
};
export function set_select2(field, options = {}, default_opts = select2_defaults) {
/*
funzione per inizializzare select2 su un campo
può essere utilizzata anche come callback per un macro di aggiunta record
field => elemento DOM (non jquery) su cui attuvare select2
options:
{
// url dell'autocomplete (senza slash finale), a cui sarà aggiunto /{term}
// obbligatorio
autocomplete_url: '',
// formattazione lista risultati
templateResult: function(data) {
if (data.text) {
return 'Sto cercando xxxx ...'; // return data.text
} else {
data.text = data.nome + data.cognome;
return data.text;
}
}
}
*/
let select2_options = Object.assign({}, default_opts);
select2_options.ajax.url = function (params) {
return options.autocomplete_url + '/' + params.term;
};
if(options.templateResult) {
select2_options.templateResult = options.templateResult;
}
if(options.templateSelection) {
select2_options.templateSelection = options.templateSelection;
}
$(field).select2(select2_options);
}
|
services.factory('vendorMarkers', ['$http', 'SERVER',
function($http, SERVER){
var markers = [];
return {
getMarkers: function() {
return $http.get(SERVER.url + '/').then(function(response){
markers = response;
return markers;
});
},
getMarker: function(id) {
}
}
}]) |
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
$run();
}
} )(); |
""" NonLocal Scopes
Inner Functions
We can define functions from inside another function:
"""
def outer_func():
# some code
# this is an example of a nested function
def inner_func():
# some code
inner_func()
outer_func()
"""[summary]
"""
Both functions have access to the global and built-in scopes as well as thier respective local scopes
|
/*
* BSD 3-Clause License
*
* Copyright (c) 2019, NTT Ltd.
* 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 the copyright holder 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 HOLDER 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.
*/
const chai = require("chai");
const chaiSubset = require('chai-subset');
const readLastLines = require('read-last-lines');
const moment = require('moment');
const fs = require('fs');
chai.use(chaiSubset);
const expect = chai.expect;
const volume = "volumetests/";
const asyncTimeout = 20000;
global.EXTERNAL_VERSION_FOR_TEST = "0.0.1";
global.EXTERNAL_CONFIG_FILE = volume + "config.test.yml";
// Prepare test environment
if (!fs.existsSync(volume)) {
fs.mkdirSync(volume);
}
fs.copyFileSync("tests/config.test.yml", volume + "config.test.yml");
fs.copyFileSync("tests/prefixes.test.yml", volume + "prefixes.test.yml");
describe("Core functions", function() {
describe("Configuration loader", function () {
const worker = require("../index");
const config = worker.config;
it("config structure", function () {
expect(config).to.have
.keys([
"environment",
"connectors",
"monitors",
"reports",
"notificationIntervalSeconds",
"alertOnlyOnce",
"monitoredPrefixesFiles",
"logging",
"checkForUpdatesAtBoot",
"processMonitors",
"pidFile",
"multiProcess",
"maxMessagesPerSecond",
"fadeOffSeconds",
"checkFadeOffGroupsSeconds",
"volume",
"persistStatus",
"rpki"
]);
expect(config.connectors[0]).to.have
.property('class')
});
it("volume setting", function () {
expect(config.volume).to.equals(volume);
});
it("check for updates setting", function () {
expect(config.checkForUpdatesAtBoot).to.equals(true);
});
it("loading connectors", function () {
expect(config.connectors[0]).to
.containSubset({
"params": { "testType": "withdrawal" },
"name": "tes"
});
expect(config.connectors[0]).to.have
.property('class')
});
it("loading monitors", function () {
expect(config.monitors.length).to.equal(8);
expect(config.monitors[0]).to
.containSubset({
"channel": "hijack",
"name": "basic-hijack-detection",
"params": {
"thresholdMinPeers": 0
}
});
expect(config.monitors[1]).to
.containSubset({
"channel": "newprefix",
"name": "prefix-detection",
"params": {
"thresholdMinPeers": 0
}
});
expect(config.monitors[2]).to
.containSubset({
"channel": "visibility",
"name": "withdrawal-detection",
"params": {
"thresholdMinPeers": 4
}
});
expect(config.monitors[3]).to
.containSubset({
"channel": "path",
"name": "path-matching",
"params": {
"thresholdMinPeers": 0
}
});
expect(config.monitors[4]).to
.containSubset({
"channel": "misconfiguration",
"name": "asn-monitor",
"params": {
"thresholdMinPeers": 2
}
});
expect(config.monitors[5]).to
.containSubset({
"channel": "rpki",
"name": "rpki-monitor",
"params": {
"thresholdMinPeers": 1,
"checkUncovered": true
}
});
expect(config.monitors[6]).to
.containSubset({
"channel": "rpki",
"name": "rpki-monitor"
});
expect(config.monitors[config.monitors.length - 1]).to
.containSubset({
"channel": "software-update",
"name": "software-update",
"params": undefined
});
expect(config.monitors[0]).to.have
.property('class')
});
it("loading reports", function () {
expect(config.reports[0]).to
.containSubset({
"channels": [
"hijack",
"newprefix",
"visibility"
],
"params": {}
});
expect(config.reports[0]).to.have
.property('class')
});
it("rpki config", function () {
expect(config.rpki).to
.containSubset({
"vrpProvider": "ntt",
"preCacheROAs": true,
"refreshVrpListMinutes": 15,
"markDataAsStaleAfterMinutes": 120
});
});
});
describe("Software updates check", function () {
it("new version detected", function (done) {
const worker = require("../index");
const pubSub = worker.pubSub;
pubSub.subscribe("software-update", function (message, type) {
expect(type).to.equal("software-update");
done();
});
}).timeout(asyncTimeout);
});
describe("Input loader", function () {
const worker = require("../index");
const input = worker.input;
it("loading prefixes", function () {
expect(input.prefixes.length).to.equal(15);
expect(JSON.parse(JSON.stringify(input))).to
.containSubset({
"prefixes": [
{
"asn": [1234],
"description": "rpki valid not monitored AS",
"ignoreMorespecifics": false,
"prefix": "193.0.0.0/21",
"group": "default",
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [15562],
"description": "description 1",
"ignoreMorespecifics": false,
"prefix": "165.254.225.0/24",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [15562],
"description": "description 2",
"ignoreMorespecifics": false,
"prefix": "165.254.255.0/24",
"group": "groupName",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [15562],
"description": "description 3",
"ignoreMorespecifics": true,
"prefix": "192.147.168.0/24",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [204092, 45],
"description": "alarig fix test",
"ignoreMorespecifics": false,
"prefix": "2a00:5884::/32",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [208585],
"description": "alarig fix test 2",
"ignoreMorespecifics": false,
"prefix": "2a0e:f40::/29",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [1234],
"description": "ignore sub test",
"ignoreMorespecifics": true,
"prefix": "2a0e:f40::/30",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [1234],
"description": "ignore flag test",
"ignoreMorespecifics": true,
"prefix": "2a0e:240::/32",
"group": "default",
"ignore": true,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [1234],
"description": "include exclude test",
"ignoreMorespecifics": false,
"prefix": "175.254.205.0/24",
"group": "default",
"ignore": false,
"excludeMonitors" : ["basic-hijack-detection", "withdrawal-detection"],
"includeMonitors": []
},
{
"asn": [1234],
"description": "include exclude test",
"ignoreMorespecifics": false,
"prefix": "170.254.205.0/24",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": ["prefix-detection"]
},
{
"asn": [15562],
"description": "test fade off",
"ignoreMorespecifics": false,
"prefix": "165.24.225.0/24",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
},
{
"asn": [65000],
"description": "exact matching test",
"ignoreMorespecifics": true,
"prefix": "2001:db8:123::/48",
"group": "default",
"ignore": false,
"excludeMonitors" : [],
"includeMonitors": []
}
]
});
expect(input.asns.map(i => i.asn.getValue())).to.eql([ 2914, 3333, 13335, 65000 ]);
});
});
describe("Logging", function () {
const worker = require("../index");
const config = worker.config;
const logger = worker.logger;
it("errors logging on the right file", function (done) {
const message = "Test message";
logger
.log({
level: "error",
message: message
});
const file = volume + config.logging.directory + "/error-" + moment().format('YYYY-MM-DD') + ".log";
readLastLines
.read(file, 1)
.then((line) => {
const lineMessage = line.split(" ").slice(2, 4).join(" ").trim();
expect(lineMessage).to
.equal(message);
done();
});
});
it("reports logging on the right file", function (done) {
const message = "Test message";
logger
.log({
level: "verbose",
message: message
});
const file = volume + config.logging.directory + "/reports-" + moment().format('YYYY-MM-DD') + ".log";
readLastLines
.read(file, 1)
.then((line) => {
const lineMessage = line.split(" ").slice(2, 5).join(" ").trim();
expect(lineMessage).to.equal(message);
done();
});
});
it("write pid file", function (done) {
const file = config.pidFile;
expect("bgpalerter.pid").to.equal(file);
if (file) {
readLastLines
.read(file, 1)
.then((line) => {
expect(parseInt(line)).to.equal(process.pid);
done();
});
}
});
});
}); |
/*
** ###################################################################
** Processors: MK60DN512ZVLL10
** MK60DX256ZVLL10
** MK60DN256ZVLL10
** MK60DN512ZVLQ10
** MK60DN256ZVLQ10
** MK60DX256ZVLQ10
** MK60DN512ZVMC10
** MK60DN256ZVMC10
** MK60DX256ZVMC10
** MK60DN512ZVMD10
** MK60DX256ZVMD10
** MK60DN256ZVMD10
**
** Compilers: ARM Compiler
** Freescale C/C++ for Embedded ARM
** GNU C Compiler
** IAR ANSI C/C++ Compiler for ARM
**
** Reference manual: K60P144M100SF2RM, Rev. 5, 8 May 2011
** Version: rev. 1.2, 2011-09-08
**
** Abstract:
** Provides a system configuration function and a global variable that
** contains the system frequency. It configures the device and initializes
** the oscillator (PLL) that is part of the microcontroller device.
**
** Copyright: 2011 Freescale Semiconductor, Inc. All Rights Reserved.
**
** http: www.freescale.com
** mail: [email protected]
**
** Revisions:
** - rev. 1.0 (2011-06-10)
** Initial version.
** Changes with respect to the previous MK60NxxxMD100 header file:
** RTC - CCR register removed. Replaced by IER register.
** CRC - added CTRLHU register for 8-bit access to the CTRL register.
** FB - bit FB_CSCR_EXALE renamed to FB_CSCR_EXTS.
** SIM - bit group FSIZE in SIM_FCFG1 split into groups PFSIZE and NVMSIZE.
** I2S - bit SSIEN in I2S_CR register renamed to I2SEN.
** SDHC - bit VOLTSEL in SDHC_VENDOR register removed.
** - rev. 1.1 (2011-06-29)
** Order of declarations changed.
** - rev. 1.2 (2011-09-08)
** Cortex_Core_Configuration extended with additional parameters.
** Gap between end of interrupt vector table and flash configuration field filled by default ISR.
**
** ###################################################################
*/
/**
* @file MK60DZ10
* @version 1.2
* @date 2011-09-08
* @brief Device specific configuration file for MK60DZ10 (header file)
*
* Provides a system configuration function and a global variable that contains
* the system frequency. It configures the device and initializes the oscillator
* (PLL) that is part of the microcontroller device.
*/
#ifndef SYSTEM_MK60DZ10_H_
#define SYSTEM_MK60DZ10_H_ /**< Symbol preventing repeated inclusion */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/**
* @brief System clock frequency (core clock)
*
* The system clock frequency supplied to the SysTick timer and the processor
* core clock. This variable can be used by the user application to setup the
* SysTick timer or configure other parameters. It may also be used by debugger to
* query the frequency of the debug timer or configure the trace clock speed
* SystemCoreClock is initialized with a correct predefined value.
*/
extern uint32_t SystemCoreClock;
/**
* @brief Setup the microcontroller system.
*
* Typically this function configures the oscillator (PLL) that is part of the
* microcontroller device. For systems with variable clock speed it also updates
* the variable SystemCoreClock. SystemInit is called from startup_device file.
*/
void SystemInit (void);
/**
* @brief Updates the SystemCoreClock variable.
*
* It must be called whenever the core clock is changed during program
* execution. SystemCoreClockUpdate() evaluates the clock register settings and calculates
* the current core clock.
*/
void SystemCoreClockUpdate (void);
#ifdef __cplusplus
}
#endif
#endif /* #if !defined(SYSTEM_MK60DZ10_H_) */
|
#
# PySNMP MIB module HH3C-MPLS-LSR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-MPLS-LSR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:28:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint")
hh3cMpls, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cMpls")
AddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers")
InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")
InetAddressIPv6, InetAddressIPv4, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressIPv6", "InetAddressIPv4", "InetAddressType")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
Gauge32, NotificationType, Bits, MibIdentifier, Counter32, ModuleIdentity, Unsigned32, TimeTicks, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, IpAddress, ObjectIdentity, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "NotificationType", "Bits", "MibIdentifier", "Counter32", "ModuleIdentity", "Unsigned32", "TimeTicks", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "IpAddress", "ObjectIdentity", "iso")
RowPointer, TimeStamp, TruthValue, StorageType, TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowPointer", "TimeStamp", "TruthValue", "StorageType", "TextualConvention", "RowStatus", "DisplayString")
hh3cMplsLsr = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1))
hh3cMplsLsr.setRevisions(('2000-07-12 12:00', '2000-07-07 12:00', '2000-04-26 12:00', '2000-04-21 12:00', '2000-03-06 12:00', '2000-02-16 12:00', '1999-06-16 12:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hh3cMplsLsr.setRevisionsDescriptions(('Seventh draft version. Fix minor compilation errors.', 'Sixth draft version. Made minor typographical corrections noted from WG mailing list during second working group last call.', 'Fifth draft version. Made minor typographical corrections noted from WG mailing list.', 'Fourth draft version. Made corrections from WG Last Call comments.', 'Third draft version.', 'Second draft version.', 'Initial draft version.',))
if mibBuilder.loadTexts: hh3cMplsLsr.setLastUpdated('200007121200Z')
if mibBuilder.loadTexts: hh3cMplsLsr.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts: hh3cMplsLsr.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts: hh3cMplsLsr.setDescription('This MIB contains managed object definitions for the Multiprotocol Label Switching (MPLS) Router as defined in: Rosen, E., Viswanathan, A., and R. Callon, Multiprotocol Label Switching Architecture, Internet Draft <draft-ietf-mpls-arch-06.txt>, August 1999.')
class Hh3cMplsLSPID(TextualConvention, OctetString):
description = 'An identifier that is assigned to each LSP and is used to uniquely identify it. This is assigned at the head end of the LSP and can be used by all LSRs to identify this LSP. This value is piggybacked by the signaling protocol when this LSP is signaled within the network. This identifier can then be used at each LSR to identify which labels are being swapped to other labels for this LSP. For IPv4 addresses this results in a 6-octet long cookie.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 31)
class Hh3cMplsLabel(TextualConvention, Unsigned32):
reference = '1. MPLS Label Stack Encoding, Rosen et al, draft- ietf-mpls-label-encaps-07.txt, March 2000. 2. Use of Label Switching on Frame Relay Networks, Conta et al, draft-ietf-mpls-fr-03.txt, Nov. 1998. 3. MPLS using LDP and ATM VC switching, Davie et al, draft-ietf-mpls-atm-02.txt, April 1999.'
description = 'This value represents an MPLS label. Note that the contents of a label field are interpreted in an interface-type specific fashion. For example, the 20-bit wide label carried in the MPLS shim header is contained in bits 0-19 and bits 20-31 must be zero. The frame relay label can be either 10 or 23 bits wide depending on the size of the DLCI field and bits 10-31, or 23-31 must be zero, respectively. For an ATM interface, bits 0-15 must be interpreted as the VCI, bits 16-23 as the VPI and bits 24-31 must be zero. Note that the permissible label values are also a function of the interface type. For example, the value 3 has special semantics in the control plane for an MPLS shim header label and is not a valid label value in the data path.'
status = 'current'
subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 4294967295)
class Hh3cMplsBitRate(TextualConvention, Integer32):
description = "An estimate of bandwidth in units of 1,000 bits per second. If this object reports a value of 'n' then the rate of the object is somewhere in the range of 'n-500' to 'n+499'. For objects which do not vary in bitrate, or for those where no accurate estimation can be made, this object should contain the nominal bitrate."
status = 'current'
displayHint = 'd'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 2147483647)
class Hh3cMplsBurstSize(TextualConvention, Integer32):
description = 'The number of octets of MPLS data that the stream may send back-to-back without concern for policing.'
status = 'current'
displayHint = 'd'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 2147483647)
class Hh3cMplsObjectOwner(TextualConvention, Integer32):
description = 'The entity which owns the object in question.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))
namedValues = NamedValues(("other", 1), ("snmp", 2), ("ldp", 3), ("rsvp", 4), ("crldp", 5), ("policyAgent", 6), ("unknown", 7))
hh3cmplsLsrObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1))
hh3cmplsLsrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 2))
hh3cmplsLsrNotifyPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 2, 0))
hh3cmplsLsrConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3))
hh3cmplsInterfaceConfTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1), )
if mibBuilder.loadTexts: hh3cmplsInterfaceConfTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceConfTable.setDescription('This table specifies per-interface MPLS capability and associated information.')
hh3cmplsInterfaceConfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceConfIndex"))
if mibBuilder.loadTexts: hh3cmplsInterfaceConfEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceConfEntry.setDescription('An entry in this table is created by an LSR for every interface capable of supporting MPLS. The entry with index 0 represents the per-platform label space and contains parameters that apply to all interfaces that participate in the per-platform label space. Other entries defined in this table represent additional MPLS interfaces that may participate in either the per-platform or per- interface label spaces, or both. Additional information about label space participation of an interface is provided in the description clause of hh3cmplsInterfaceLabelParticipationType.')
hh3cmplsInterfaceConfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 1), InterfaceIndexOrZero())
if mibBuilder.loadTexts: hh3cmplsInterfaceConfIndex.setReference('RFC 2233 - The Interfaces Group MIB using SMIv2, McCloghrie, K., and F. Kastenholtz, Nov. 1997')
if mibBuilder.loadTexts: hh3cmplsInterfaceConfIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceConfIndex.setDescription('This is a unique index for an entry in the hh3cmplsInterfaceConfTable. A non-zero index for an entry indicates the ifIndex for the corresponding interface entry in of the MPLS-layer in the ifTable. Note that the per-platform label space may apply to several interfaces, and therefore the configuration of the per-platform label space interface parameters will apply to all of the interfaces that are participating in the per-platform label space.')
hh3cmplsInterfaceLabelMinIn = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 2), Hh3cMplsLabel()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMinIn.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMinIn.setDescription('This is the minimum value of an MPLS label that this LSR is willing to receive on this interface.')
hh3cmplsInterfaceLabelMaxIn = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 3), Hh3cMplsLabel()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMaxIn.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMaxIn.setDescription('This is the maximum value of an MPLS label that this LSR is willing to receive on this interface.')
hh3cmplsInterfaceLabelMinOut = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 4), Hh3cMplsLabel()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMinOut.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMinOut.setDescription('This is the minimum value of an MPLS label that this LSR is willing to send on this interface.')
hh3cmplsInterfaceLabelMaxOut = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 5), Hh3cMplsLabel()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMaxOut.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelMaxOut.setDescription('This is the maximum value of an MPLS label that this LSR is willing to send on this interface.')
hh3cmplsInterfaceTotalBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 6), Hh3cMplsBitRate()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceTotalBandwidth.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceTotalBandwidth.setDescription('This value indicates the total amount of usable bandwidth on this interface and is specified in kilobits per second (Kbps). This variable is not applicable when applied to the interface with index 0.')
hh3cmplsInterfaceAvailableBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 7), Hh3cMplsBitRate()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceAvailableBandwidth.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceAvailableBandwidth.setDescription('This value indicates the total amount of available bandwidth available on this interface and is specified in kilobits per second (Kbps). This value is calculated as the difference between the amount of bandwidth currently in use and that specified in hh3cmplsInterfaceTotalBandwidth. This variable is not applicable when applied to the interface with index 0.')
hh3cmplsInterfaceLabelParticipationType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 8), Bits().clone(namedValues=NamedValues(("perPlatform", 0), ("perInterface", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelParticipationType.setReference('Multiprotocol Label Switching, Rosen et al, draft-ietf-mpls- arch-06.txt, August 1999.')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelParticipationType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceLabelParticipationType.setDescription('Either the perPlatform(0) or perInterface(1) bit MUST be set. If the value of the hh3cmplsInterfaceConfIndex for this entry is zero, then only the perPlatform(0) bit MUST be set and the perInterface(1) bit is meaningless. If the perInterface(1) bit is set then the value of hh3cmplsInterfaceLabelMinIn, hh3cmplsInterfaceLabelMaxIn, hh3cmplsInterfaceLabelMinOut, and hh3cmplsInterfaceLabelMaxOut for this entry reflect the label ranges for this interface. If only the perPlatform(0) bit is set, then the value of hh3cmplsInterfaceLabelMinIn, hh3cmplsInterfaceLabelMaxIn, hh3cmplsInterfaceLabelMinOut, and hh3cmplsInterfaceLabelMaxOut for this entry must be identical to the instance of these objects with index 0.')
hh3cmplsInterfaceConfStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 1, 1, 9), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInterfaceConfStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceConfStorageType.setDescription('The storage type for this entry.')
hh3cmplsInterfacePerfTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2), )
if mibBuilder.loadTexts: hh3cmplsInterfacePerfTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfacePerfTable.setDescription('This table provides MPLS performance information on a per-interface basis.')
hh3cmplsInterfacePerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2, 1), )
hh3cmplsInterfaceConfEntry.registerAugmentions(("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfacePerfEntry"))
hh3cmplsInterfacePerfEntry.setIndexNames(*hh3cmplsInterfaceConfEntry.getIndexNames())
if mibBuilder.loadTexts: hh3cmplsInterfacePerfEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfacePerfEntry.setDescription('An entry in this table is created by the LSR for every interface capable of supporting MPLS. Its is an extension to the hh3cmplsInterfaceConfEntry table.')
hh3cmplsInterfaceInLabelsUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceInLabelsUsed.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceInLabelsUsed.setDescription('This object counts the number of labels that are in use at this point in time on this interface in the incoming direction. If the interface participates in the per-platform label space only, then this instance of this object MUST be identical with the instance with index 0. If the interface participates in the per-interface label space, then this this instance of this object MUST represent the number of of per-interface labels that are in use at this point in time on this interface.')
hh3cmplsInterfaceFailedLabelLookup = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceFailedLabelLookup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceFailedLabelLookup.setDescription('This object counts the number of labeled packets that have been received on this interface and were discarded because there was no matching cross-connect entry. This object MUST count on a per-interface basis regardless of which label space the interface participates in.')
hh3cmplsInterfaceOutLabelsUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceOutLabelsUsed.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceOutLabelsUsed.setDescription('This object counts the number of top-most labels in the outgoing label stacks that are in use at this point in time on this interface. This object MUST count on a per-interface basis regardless of which label space the interface participates in.')
hh3cmplsInterfaceOutFragments = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInterfaceOutFragments.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceOutFragments.setDescription('This object counts the number of outgoing MPLS packets that required fragmentation before transmission on this interface. This object transmission on this interface. This object MUST count on a per-interface basis regardless of which label space the interface participates in.')
hh3cmplsInSegmentTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3), )
if mibBuilder.loadTexts: hh3cmplsInSegmentTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentTable.setDescription('This table contains a collection of incoming segments to an LSR.')
hh3cmplsInSegmentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentIfIndex"), (0, "HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentLabel"))
if mibBuilder.loadTexts: hh3cmplsInSegmentEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentEntry.setDescription('An entry in this table represents one incoming segment. An entry can be created by a network administrator or an SNMP agent, or an MPLS signaling protocol. The creator of the entry is denoted by hh3cmplsInSegmentOwner. An entry in this table is indexed by the ifIndex of the incoming interface and the (top) label.')
hh3cmplsInSegmentIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 1), InterfaceIndexOrZero()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cmplsInSegmentIfIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentIfIndex.setDescription('This is a unique index for an entry in the hh3cmplsInSegmentTable. This value represents the interface index for the incoming MPLS interface. A value of zero represents an incoming label from the per-platform label space. In this case, the hh3cmplsInSegmentLabel is interpreted to be an MPLS-type label.')
hh3cmplsInSegmentLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 2), Hh3cMplsLabel()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cmplsInSegmentLabel.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentLabel.setDescription('The incoming label for this segment.')
hh3cmplsInSegmentNPop = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentNPop.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentNPop.setDescription('The number of labels to pop from the incoming packet. Normally only the top label is popped from the packet and used for all switching decisions for that packet. Note that technologies which do not support label popping should set this value to its default value of 1.')
hh3cmplsInSegmentAddrFamily = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 4), AddressFamilyNumbers().clone('other')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentAddrFamily.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentAddrFamily.setDescription('The IANA address family [IANAFamily] of the incoming packet. A value of other(0) indicates that the family type is either unknown or undefined.')
hh3cmplsInSegmentXCIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentXCIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentXCIndex.setDescription('Index into hh3cmplsXCTable which identifies which cross- connect entry this segment is part of. A value of zero indicates that this entry is not referred to by any cross-connect entry. When a cross-connect entry is created which this in-segment is a part of, this object is automatically updated to reflect the value of hh3cmplsXCIndex of that cross-connect entry.')
hh3cmplsInSegmentOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 6), Hh3cMplsObjectOwner().clone('unknown')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentOwner.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentOwner.setDescription('Denotes the entity that created and is responsible for managing this segment.')
hh3cmplsInSegmentTrafficParamPtr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 7), RowPointer()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentTrafficParamPtr.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentTrafficParamPtr.setDescription('This variable represents a pointer to the traffic parameter specification for this in-segment. This value may point at an entry in the hh3cmplsTrafficParamTable to indicate which hh3cmplsTrafficParamEntry is to be assigned to this segment. This value may optionally point at an externally defined traffic parameter specification table. A value of zero-dot-zero indicates best-effort treatment. By having the same value of this object, two or more segments can indicate resource sharing.')
hh3cmplsInSegmentRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentRowStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentRowStatus.setDescription('This variable is used to create, modify, and/or delete a row in this table.')
hh3cmplsInSegmentStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 3, 1, 9), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsInSegmentStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentStorageType.setDescription('This variable indicates the storage type for this object.')
hh3cmplsInSegmentPerfTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4), )
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfTable.setDescription('This table contains statistical information for incoming MPLS segments to an LSR.')
hh3cmplsInSegmentPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1), )
hh3cmplsInSegmentEntry.registerAugmentions(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentPerfEntry"))
hh3cmplsInSegmentPerfEntry.setIndexNames(*hh3cmplsInSegmentEntry.getIndexNames())
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfEntry.setDescription('An entry in this table contains statistical information about one incoming segment which was configured in the hh3cmplsInSegmentTable. The counters in this entry should behave in a manner similar to that of the interface.')
hh3cmplsInSegmentOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentOctets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentOctets.setDescription('This value represents the total number of octets received by this segment.')
hh3cmplsInSegmentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentPackets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentPackets.setDescription('Total number of packets received by this segment.')
hh3cmplsInSegmentErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentErrors.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentErrors.setDescription('The number of errored packets received on this segment.')
hh3cmplsInSegmentDiscards = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentDiscards.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentDiscards.setDescription('The number of labeled packets received on this in- segment, which were chosen to be discarded even though no errors had been detected to prevent their being transmitted. One possible reason for discarding such a labeled packet could be to free up buffer space.')
hh3cmplsInSegmentHCOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentHCOctets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentHCOctets.setDescription('The total number of octets received. This is the 64 bit version of hh3cmplsInSegmentOctets.')
hh3cmplsInSegmentPerfDiscontinuityTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 4, 1, 6), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfDiscontinuityTime.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentPerfDiscontinuityTime.setDescription("The value of sysUpTime on the most recent occasion at which any one or more of this segment's Counter32 or Counter64 suffered a discontinuity. If no such discontinuities have occurred since the last re- initialization of the local management subsystem, then this object contains a zero value.")
hh3cmplsOutSegmentIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentIndexNext.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentIndexNext.setDescription('This object contains the next appropriate value to be used for hh3cmplsOutSegmentIndex when creating entries in the hh3cmplsOutSegmentTable. If the number of unassigned entries is exhausted, this object will take on the value of 0. To obtain the hh3cmplsOutSegmentIndex value for a new entry, the manager must first issue a management protocol retrieval operation to obtain the current value of this object. The agent should modify the value to reflect the next unassigned index after each retrieval operation. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse.')
hh3cmplsOutSegmentTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6), )
if mibBuilder.loadTexts: hh3cmplsOutSegmentTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentTable.setDescription('This table contains a representation of the outgoing segments from an LSR.')
hh3cmplsOutSegmentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIndex"))
if mibBuilder.loadTexts: hh3cmplsOutSegmentEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentEntry.setDescription('An entry in this table represents one outgoing segment. An entry can be created by a network administrator or an SNMP agent, or an MPLS signaling protocol. The object hh3cmplsOutSegmentOwner indicates the creator of this entry.')
hh3cmplsOutSegmentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cmplsOutSegmentIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentIndex.setDescription('This value contains a unique index for this row. While a value of 0 is not valid as an index for this row it can be supplied as a valid value to index hh3cmplsXCTable to access entries for which no out- segment has been configured.')
hh3cmplsOutSegmentIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 2), InterfaceIndex()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentIfIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentIfIndex.setDescription('This value contains the interface index of the outgoing interface.')
hh3cmplsOutSegmentPushTopLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 3), TruthValue()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentPushTopLabel.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentPushTopLabel.setDescription("This value indicates whether or not a top label should be pushed onto the outgoing packet's label stack. The value of this variable must be set to true if the outgoing interface does not support pop- and-go (for example an ATM interface) or if it is a tunnel origination. Note that it is considered an error in the case that hh3cmplsOutSegmentPushTopLabel is set to false, but the cross-connect entry which refers to this out-segment has a non-zero hh3cmplsLabelStackIndex. The LSR MUST ensure that this situation does not happen ")
hh3cmplsOutSegmentTopLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 4), Hh3cMplsLabel()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentTopLabel.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentTopLabel.setDescription("If hh3cmplsOutSegmentPushTopLabel is true then this represents the label that should be pushed onto the top of the outgoing packet's label stack.")
hh3cmplsOutSegmentNextHopIpAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 5), InetAddressType().clone('unknown')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpAddrType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpAddrType.setDescription('Indicates whether the next hop address is IPv4 or IPv6. Note that a value of unknown (0) is valid only when the outgoing interface is of type point-to- point.')
hh3cmplsOutSegmentNextHopIpv4Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 6), InetAddressIPv4()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpv4Addr.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpv4Addr.setDescription('IPv4 Address of the next hop. Its value is significant only when hh3cmplsOutSegmentNextHopIpAddrType is ipV4 (1), otherwise it should return a value of 0.')
hh3cmplsOutSegmentNextHopIpv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 7), InetAddressIPv6()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpv6Addr.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentNextHopIpv6Addr.setDescription('IPv6 address of the next hop. Its value is significant only when hh3cmplsOutSegmentNextHopIpAddrType is ipV6 (2), otherwise it should return a value of 0.')
hh3cmplsOutSegmentXCIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentXCIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentXCIndex.setDescription('Index into hh3cmplsXCTable which identifies which cross- connect entry this segment is part of. A value of zero indicates that this entry is not referred to by any cross-connect entry. When a cross-connect entry is created which this out-segment is a part of, this object is automatically updated to reflect the value of hh3cmplsXCIndex of that cross-connect entry.')
hh3cmplsOutSegmentOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 9), Hh3cMplsObjectOwner().clone('unknown')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentOwner.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentOwner.setDescription('Denotes the entity which created and is responsible for managing this segment.')
hh3cmplsOutSegmentTrafficParamPtr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 10), RowPointer()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentTrafficParamPtr.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentTrafficParamPtr.setDescription('This variable represents a pointer to the traffic parameter specification for this out-segment. This value may point at an entry in the hh3cmplsTrafficParamTable to indicate which hh3cmplsTrafficParamEntry is to be assigned to this segment. This value may optionally point at an externally defined traffic parameter specification table. A value of zero-dot-zero indicates best- effort treatment. By having the same value of this object, two or more segments can indicate resource sharing.')
hh3cmplsOutSegmentRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 11), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentRowStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentRowStatus.setDescription('For creating, modifying, and deleting this row.')
hh3cmplsOutSegmentStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 6, 1, 12), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsOutSegmentStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentStorageType.setDescription('This variable indicates the storage type for this object.')
hh3cmplsOutSegmentPerfTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7), )
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfTable.setDescription('This table contains statistical information about outgoing segments from an LSR. The counters in this entry should behave in a manner similar to that of the interface.')
hh3cmplsOutSegmentPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1), )
hh3cmplsOutSegmentEntry.registerAugmentions(("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentPerfEntry"))
hh3cmplsOutSegmentPerfEntry.setIndexNames(*hh3cmplsOutSegmentEntry.getIndexNames())
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfEntry.setDescription('An entry in this table contains statistical information about one outgoing segment configured in hh3cmplsOutSegmentTable.')
hh3cmplsOutSegmentOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentOctets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentOctets.setDescription('This value contains the total number of octets sent on this segment.')
hh3cmplsOutSegmentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentPackets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentPackets.setDescription('This value contains the total number of packets sent on this segment.')
hh3cmplsOutSegmentErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentErrors.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentErrors.setDescription('Number of packets that could not be sent due to errors on this segment.')
hh3cmplsOutSegmentDiscards = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentDiscards.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentDiscards.setDescription('The number of labeled packets received on this out- segment, which were chosen to be discarded even though no errors had been detected to prevent their being transmitted. One possible reason for discarding such a labeled packet could be to free up buffer space.')
hh3cmplsOutSegmentHCOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentHCOctets.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentHCOctets.setDescription('Total number of octets sent. This is the 64 bit version of hh3cmplsOutSegmentOctets.')
hh3cmplsOutSegmentPerfDiscontinuityTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 7, 1, 6), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfDiscontinuityTime.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentPerfDiscontinuityTime.setDescription("The value of sysUpTime on the most recent occasion at which any one or more of this segment's Counter32 or Counter64 suffered a discontinuity. If no such discontinuities have occurred since the last re- initialization of the local management subsystem, then this object contains a zero value.")
hh3cmplsXCIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsXCIndexNext.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCIndexNext.setDescription('This object contains an appropriate value to be used for hh3cmplsXCIndex when creating entries in the hh3cmplsXCTable. The value 0 indicates that no unassigned entries are available. To obtain the value of hh3cmplsXCIndex for a new entry in the hh3cmplsXCTable, the manager issues a management protocol retrieval operation to obtain the current value of hh3cmplsXCIndex. After each retrieval operation, the agent should modify the value to reflect the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse.')
hh3cmplsXCTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9), )
if mibBuilder.loadTexts: hh3cmplsXCTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCTable.setDescription('This table specifies information for switching between LSP segments. It supports point-to-point, point-to-multipoint and multipoint-to-point connections. hh3cmplsLabelStackTable specifies the label stack information for a cross-connect LSR and is referred to from hh3cmplsXCTable.')
hh3cmplsXCEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsXCIndex"), (0, "HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentIfIndex"), (0, "HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentLabel"), (0, "HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIndex"))
if mibBuilder.loadTexts: hh3cmplsXCEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCEntry.setDescription('A row in this table represents one cross-connect entry. The following objects index it: - cross-connect index hh3cmplsXCIndex that uniquely identifies a group of cross-connect entries - interface index of the in-segment, hh3cmplsInSegmentIfIndex - incoming label(s), hh3cmplsInSegmentLabel - out-segment index, hh3cmplsOutSegmentIndex Originating LSPs: These are represented by using the special combination of values hh3cmplsInSegmentIfIndex=0 and hh3cmplsInSegmentLabel=0 as indexes. In this case the hh3cmplsOutSegmentIndex MUST be non-zero. Terminating LSPs: These are represented by using the special value hh3cmplsOutSegmentIndex=0 as index. Special labels: Entries indexed by reserved MPLS label values 0 through 15 imply terminating LSPs and MUST have hh3cmplsOutSegmentIfIndex = 0. Note that situations where LSPs are terminated with incoming label equal to 0, should have hh3cmplsInSegmentIfIndex = 0 as well, but can be distinguished from originating LSPs because the hh3cmplsOutSegmentIfIndex = 0. The hh3cmplsOutSegmentIfIndex MUST only be set to 0 in cases of terminating LSPs. An entry can be created by a network administrator or by an SNMP agent as instructed by an MPLS signaling protocol.')
hh3cmplsXCIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cmplsXCIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCIndex.setDescription('Primary index for the conceptual row identifying a group of cross-connect segments.')
hh3cmplsXCLspId = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 2), Hh3cMplsLSPID()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCLspId.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCLspId.setDescription('This value identifies the label switched path that this cross-connect entry belongs to.')
hh3cmplsXCLabelStackIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCLabelStackIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCLabelStackIndex.setDescription('Primary index into hh3cmplsLabelStackTable identifying a stack of labels to be pushed beneath the top label. Note that the top label identified by the out- segment ensures that all the components of a multipoint-to-point connection have the same outgoing label. A value of 0 indicates that no labels are to be stacked beneath the top label.')
hh3cmplsXCIsPersistent = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 4), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCIsPersistent.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCIsPersistent.setDescription('Denotes whether or not this cross-connect entry and associated in- and out-segments should be restored automatically after failures. This value MUST be set to false in cases where this cross-connect entry was created by a signaling protocol.')
hh3cmplsXCOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 5), Hh3cMplsObjectOwner()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCOwner.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCOwner.setDescription('Denotes the entity that created and is responsible for managing this cross-connect.')
hh3cmplsXCRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCRowStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCRowStatus.setDescription('For creating, modifying, and deleting this row.')
hh3cmplsXCStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 7), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCStorageType.setDescription('Defines the storage type for this object.')
hh3cmplsXCAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsXCAdminStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCAdminStatus.setDescription('The desired operational status of this segment.')
hh3cmplsXCOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 9, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3), ("unknown", 4), ("dormant", 5), ("notPresent", 6), ("lowerLayerDown", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsXCOperStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCOperStatus.setDescription('The actual operational status of this cross- connect.')
hh3cmplsMaxLabelStackDepth = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsMaxLabelStackDepth.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsMaxLabelStackDepth.setDescription('The maximum stack depth supported by this LSR.')
hh3cmplsLabelStackIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsLabelStackIndexNext.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackIndexNext.setDescription('This object contains an appropriate value to be used for hh3cmplsLabelStackIndex when creating entries in the hh3cmplsLabelStackTable. The value 0 indicates that no unassigned entries are available. To obtain an hh3cmplsLabelStackIndex value for a new entry, the manager issues a management protocol retrieval operation to obtain the current value of this object. After each retrieval operation, the agent should modify the value to reflect the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse.')
hh3cmplsLabelStackTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12), )
if mibBuilder.loadTexts: hh3cmplsLabelStackTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackTable.setDescription('This table specifies the label stack to be pushed onto a packet, beneath the top label. Entries into this table are referred to from hh3cmplsXCTable.')
hh3cmplsLabelStackEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackIndex"), (0, "HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackLabelIndex"))
if mibBuilder.loadTexts: hh3cmplsLabelStackEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackEntry.setDescription('An entry in this table represents one label which is to be pushed onto an outgoing packet, beneath the top label. An entry can be created by a network administrator or by an SNMP agent as instructed by an MPLS signaling protocol.')
hh3cmplsLabelStackIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: hh3cmplsLabelStackIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackIndex.setDescription('Primary index for this row identifying a stack of labels to be pushed on an outgoing packet, beneath the top label.')
hh3cmplsLabelStackLabelIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: hh3cmplsLabelStackLabelIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackLabelIndex.setDescription('Secondary index for this row identifying one label of the stack. Note that an entry with a smaller hh3cmplsLabelStackLabelIndex would refer to a label higher up the label stack and would be popped at a downstream LSR before a label represented by a higher hh3cmplsLabelStackLabelIndex at a downstream LSR.')
hh3cmplsLabelStackLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1, 3), Hh3cMplsLabel()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsLabelStackLabel.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackLabel.setDescription('The label to pushed.')
hh3cmplsLabelStackRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsLabelStackRowStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackRowStatus.setDescription('For creating, modifying, and deleting this row.')
hh3cmplsLabelStackStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 12, 1, 5), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsLabelStackStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackStorageType.setDescription('Defines the storage type for this object.')
hh3cmplsTrafficParamIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cmplsTrafficParamIndexNext.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamIndexNext.setDescription('This object contains an appropriate value which will be used for hh3cmplsTrafficParamIndex when creating entries in the hh3cmplsTrafficParamTable. The value 0 indicates that no unassigned entries are available. To obtain the hh3cmplsTrafficParamIndex value for a new entry, the manager issues a management protocol retrieval operation to obtain the current value of this object. After each retrieval operation, the agent should modify the value to reflect the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse.')
hh3cmplsTrafficParamTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14), )
if mibBuilder.loadTexts: hh3cmplsTrafficParamTable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamTable.setDescription('This table specifies the Traffic Parameter objects for in and out-segments.')
hh3cmplsTrafficParamEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1), ).setIndexNames((0, "HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamIndex"))
if mibBuilder.loadTexts: hh3cmplsTrafficParamEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamEntry.setDescription('An entry in this table represents the TrafficParam objects for one or more in or out segments. A single entry can be pointed to by multiple segments indicating resource sharing.')
hh3cmplsTrafficParamIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: hh3cmplsTrafficParamIndex.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamIndex.setDescription('Uniquely identifies this row of the table. Note that zero represents an invalid index.')
hh3cmplsTrafficParamMaxRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 2), Hh3cMplsBitRate()).setUnits('kilobits per second').setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsTrafficParamMaxRate.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamMaxRate.setDescription('Maximum rate in kilobits/second.')
hh3cmplsTrafficParamMeanRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 3), Hh3cMplsBitRate()).setUnits('kilobits per second').setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsTrafficParamMeanRate.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamMeanRate.setDescription('Mean rate in kilobits/second.')
hh3cmplsTrafficParamMaxBurstSize = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 4), Hh3cMplsBurstSize()).setUnits('bytes').setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsTrafficParamMaxBurstSize.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamMaxBurstSize.setDescription('Maximum burst size in bytes.')
hh3cmplsTrafficParamRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsTrafficParamRowStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamRowStatus.setDescription('For creating, modifying, and deleting this row.')
hh3cmplsTrafficParamStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 14, 1, 6), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cmplsTrafficParamStorageType.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamStorageType.setDescription('The storage type for this object.')
hh3cmplsXCTrapEnable = MibScalar((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 1, 15), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hh3cmplsXCTrapEnable.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCTrapEnable.setDescription('If this object is true, then it enables the generation of hh3cmplsXCUp and hh3cmplsXCDown traps, otherwise these traps are not emitted.')
hh3cmplsXCUp = NotificationType((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 2, 0, 1)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentIfIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentLabel"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCAdminStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCOperStatus"))
if mibBuilder.loadTexts: hh3cmplsXCUp.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCUp.setDescription('This notification is generated when a hh3cmplsXCOperStatus object for one of the configured cross-connect entries is about to leave the down state and transition into some other state (but not into the notPresent state). This other state is indicated by the included value of hh3cmplsXCOperStatus.')
hh3cmplsXCDown = NotificationType((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 2, 0, 2)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentIfIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentLabel"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCAdminStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCOperStatus"))
if mibBuilder.loadTexts: hh3cmplsXCDown.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCDown.setDescription('This notification is generated when a hh3cmplsXCOperStatus object for one of the configured cross-connect entries is about to enter the down state from some other state (but not from the notPresent state). This other state is indicated by the included value of hh3cmplsXCOperStatus.')
hh3cmplsLsrGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1))
hh3cmplsLsrCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 2))
hh3cmplsLsrModuleCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 2, 1)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsPerfGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsSegmentDiscontinuityGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsHCInSegmentPerfGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsHCOutSegmentPerfGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIsPersistentGroup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIsNotPersistentGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsLsrModuleCompliance = hh3cmplsLsrModuleCompliance.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLsrModuleCompliance.setDescription('Compliance statement for agents that support the MPLS LSR MIB.')
hh3cmplsInterfaceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 1)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceLabelMinIn"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceLabelMaxIn"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceLabelMinOut"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceLabelMaxOut"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceTotalBandwidth"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceAvailableBandwidth"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceLabelParticipationType"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceConfStorageType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsInterfaceGroup = hh3cmplsInterfaceGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInterfaceGroup.setDescription('Collection of objects needed for MPLS interface configuration and performance information.')
hh3cmplsInSegmentGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 2)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentNPop"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentAddrFamily"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentXCIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentOctets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentDiscards"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentOwner"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentRowStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentStorageType"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentTrafficParamPtr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsInSegmentGroup = hh3cmplsInSegmentGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsInSegmentGroup.setDescription('Collection of objects needed to implement an in- segment.')
hh3cmplsOutSegmentGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 3)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIndexNext"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentIfIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentPushTopLabel"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentTopLabel"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentNextHopIpAddrType"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentNextHopIpv4Addr"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentNextHopIpv6Addr"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentXCIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentOwner"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentOctets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentDiscards"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentErrors"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentRowStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentStorageType"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentTrafficParamPtr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsOutSegmentGroup = hh3cmplsOutSegmentGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsOutSegmentGroup.setDescription('Collection of objects needed to implement an out- segment.')
hh3cmplsXCGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 4)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIndexNext"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCLabelStackIndex"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCOwner"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCAdminStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCOperStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCRowStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCTrapEnable"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCStorageType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsXCGroup = hh3cmplsXCGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCGroup.setDescription('Collection of objects needed to implement a cross-connect entry.')
hh3cmplsXCOptionalGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 5)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCLspId"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsXCOptionalGroup = hh3cmplsXCOptionalGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCOptionalGroup.setDescription('Collection of optional objects for implementing a cross-connect entry.')
hh3cmplsPerfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 6)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentOctets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentPackets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentErrors"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentDiscards"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentOctets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentPackets"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentDiscards"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceInLabelsUsed"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceFailedLabelLookup"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceOutFragments"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsInterfaceOutLabelsUsed"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsPerfGroup = hh3cmplsPerfGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsPerfGroup.setDescription('Collection of objects providing performance information about an LSR.')
hh3cmplsHCInSegmentPerfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 7)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentHCOctets"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsHCInSegmentPerfGroup = hh3cmplsHCInSegmentPerfGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsHCInSegmentPerfGroup.setDescription('Object(s) providing performance information specific to out-segments for which the object hh3cmplsInterfaceInOctets wraps around too quickly.')
hh3cmplsHCOutSegmentPerfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 8)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentHCOctets"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsHCOutSegmentPerfGroup = hh3cmplsHCOutSegmentPerfGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsHCOutSegmentPerfGroup.setDescription('Object(s) providing performance information specific to out-segments for which the object hh3cmplsInterfaceOutOctets wraps around too quickly.')
hh3cmplsTrafficParamGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 9)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamIndexNext"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamMaxRate"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamMeanRate"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamMaxBurstSize"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamRowStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsTrafficParamStorageType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsTrafficParamGroup = hh3cmplsTrafficParamGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsTrafficParamGroup.setDescription('Object(s) required for supporting QoS resource reservation.')
hh3cmplsXCIsPersistentGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 10)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIsPersistent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsXCIsPersistentGroup = hh3cmplsXCIsPersistentGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCIsPersistentGroup.setDescription('Objects needed to support persistent cross- connects.')
hh3cmplsXCIsNotPersistentGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 11)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCIsPersistent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsXCIsNotPersistentGroup = hh3cmplsXCIsNotPersistentGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsXCIsNotPersistentGroup.setDescription('Objects needed to support non-persistent cross- connects.')
hh3cmplsLabelStackGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 12)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackLabel"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackRowStatus"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackStorageType"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsMaxLabelStackDepth"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsLabelStackIndexNext"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsLabelStackGroup = hh3cmplsLabelStackGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLabelStackGroup.setDescription('Objects needed to support label stacking.')
hh3cmplsSegmentDiscontinuityGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 13)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsInSegmentPerfDiscontinuityTime"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsOutSegmentPerfDiscontinuityTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsSegmentDiscontinuityGroup = hh3cmplsSegmentDiscontinuityGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsSegmentDiscontinuityGroup.setDescription(' A collection of objects providing information specific to segment discontinuities..')
hh3cmplsLsrNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 25506, 8, 12, 1, 3, 1, 14)).setObjects(("HH3C-MPLS-LSR-MIB", "hh3cmplsXCUp"), ("HH3C-MPLS-LSR-MIB", "hh3cmplsXCDown"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cmplsLsrNotificationGroup = hh3cmplsLsrNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: hh3cmplsLsrNotificationGroup.setDescription('Set of notifications implemented in this module. None is mandatory.')
mibBuilder.exportSymbols("HH3C-MPLS-LSR-MIB", hh3cmplsOutSegmentNextHopIpv6Addr=hh3cmplsOutSegmentNextHopIpv6Addr, hh3cmplsOutSegmentTrafficParamPtr=hh3cmplsOutSegmentTrafficParamPtr, hh3cmplsTrafficParamIndexNext=hh3cmplsTrafficParamIndexNext, hh3cmplsInterfaceLabelMaxIn=hh3cmplsInterfaceLabelMaxIn, hh3cmplsTrafficParamMeanRate=hh3cmplsTrafficParamMeanRate, Hh3cMplsLSPID=Hh3cMplsLSPID, hh3cmplsInterfaceConfStorageType=hh3cmplsInterfaceConfStorageType, hh3cmplsInSegmentOwner=hh3cmplsInSegmentOwner, hh3cmplsOutSegmentIndex=hh3cmplsOutSegmentIndex, hh3cmplsOutSegmentRowStatus=hh3cmplsOutSegmentRowStatus, Hh3cMplsObjectOwner=Hh3cMplsObjectOwner, hh3cmplsInterfaceTotalBandwidth=hh3cmplsInterfaceTotalBandwidth, hh3cmplsLabelStackTable=hh3cmplsLabelStackTable, hh3cMplsLsr=hh3cMplsLsr, hh3cmplsXCOptionalGroup=hh3cmplsXCOptionalGroup, hh3cmplsInSegmentGroup=hh3cmplsInSegmentGroup, hh3cmplsOutSegmentNextHopIpv4Addr=hh3cmplsOutSegmentNextHopIpv4Addr, hh3cmplsLsrNotifyPrefix=hh3cmplsLsrNotifyPrefix, hh3cmplsInSegmentPerfDiscontinuityTime=hh3cmplsInSegmentPerfDiscontinuityTime, Hh3cMplsBitRate=Hh3cMplsBitRate, hh3cmplsInSegmentRowStatus=hh3cmplsInSegmentRowStatus, hh3cmplsTrafficParamIndex=hh3cmplsTrafficParamIndex, hh3cmplsInSegmentErrors=hh3cmplsInSegmentErrors, hh3cmplsInterfaceGroup=hh3cmplsInterfaceGroup, hh3cmplsLabelStackStorageType=hh3cmplsLabelStackStorageType, hh3cmplsInterfacePerfTable=hh3cmplsInterfacePerfTable, hh3cmplsTrafficParamGroup=hh3cmplsTrafficParamGroup, hh3cmplsXCIsPersistentGroup=hh3cmplsXCIsPersistentGroup, hh3cmplsTrafficParamEntry=hh3cmplsTrafficParamEntry, hh3cmplsInSegmentNPop=hh3cmplsInSegmentNPop, hh3cmplsXCDown=hh3cmplsXCDown, hh3cmplsInSegmentAddrFamily=hh3cmplsInSegmentAddrFamily, hh3cmplsOutSegmentPerfTable=hh3cmplsOutSegmentPerfTable, hh3cmplsXCUp=hh3cmplsXCUp, PYSNMP_MODULE_ID=hh3cMplsLsr, hh3cmplsInSegmentTable=hh3cmplsInSegmentTable, hh3cmplsInterfaceConfTable=hh3cmplsInterfaceConfTable, hh3cmplsInSegmentPackets=hh3cmplsInSegmentPackets, hh3cmplsLsrModuleCompliance=hh3cmplsLsrModuleCompliance, hh3cmplsLsrNotificationGroup=hh3cmplsLsrNotificationGroup, hh3cmplsInSegmentPerfTable=hh3cmplsInSegmentPerfTable, hh3cmplsOutSegmentTopLabel=hh3cmplsOutSegmentTopLabel, hh3cmplsXCTable=hh3cmplsXCTable, hh3cmplsOutSegmentIfIndex=hh3cmplsOutSegmentIfIndex, hh3cmplsTrafficParamStorageType=hh3cmplsTrafficParamStorageType, hh3cmplsTrafficParamMaxRate=hh3cmplsTrafficParamMaxRate, hh3cmplsInSegmentXCIndex=hh3cmplsInSegmentXCIndex, hh3cmplsLabelStackIndex=hh3cmplsLabelStackIndex, Hh3cMplsBurstSize=Hh3cMplsBurstSize, hh3cmplsOutSegmentPerfDiscontinuityTime=hh3cmplsOutSegmentPerfDiscontinuityTime, hh3cmplsXCLspId=hh3cmplsXCLspId, hh3cmplsHCInSegmentPerfGroup=hh3cmplsHCInSegmentPerfGroup, hh3cmplsInSegmentHCOctets=hh3cmplsInSegmentHCOctets, hh3cmplsInSegmentEntry=hh3cmplsInSegmentEntry, hh3cmplsLsrObjects=hh3cmplsLsrObjects, hh3cmplsOutSegmentPerfEntry=hh3cmplsOutSegmentPerfEntry, hh3cmplsXCEntry=hh3cmplsXCEntry, hh3cmplsInterfaceLabelMaxOut=hh3cmplsInterfaceLabelMaxOut, hh3cmplsXCIndexNext=hh3cmplsXCIndexNext, hh3cmplsLsrGroups=hh3cmplsLsrGroups, hh3cmplsInSegmentLabel=hh3cmplsInSegmentLabel, hh3cmplsXCStorageType=hh3cmplsXCStorageType, hh3cmplsInterfaceLabelParticipationType=hh3cmplsInterfaceLabelParticipationType, hh3cmplsInterfaceLabelMinOut=hh3cmplsInterfaceLabelMinOut, hh3cmplsOutSegmentHCOctets=hh3cmplsOutSegmentHCOctets, hh3cmplsXCIndex=hh3cmplsXCIndex, hh3cmplsOutSegmentIndexNext=hh3cmplsOutSegmentIndexNext, hh3cmplsOutSegmentNextHopIpAddrType=hh3cmplsOutSegmentNextHopIpAddrType, hh3cmplsLabelStackLabel=hh3cmplsLabelStackLabel, hh3cmplsTrafficParamTable=hh3cmplsTrafficParamTable, hh3cmplsLabelStackIndexNext=hh3cmplsLabelStackIndexNext, hh3cmplsInterfaceOutLabelsUsed=hh3cmplsInterfaceOutLabelsUsed, hh3cmplsXCIsPersistent=hh3cmplsXCIsPersistent, hh3cmplsOutSegmentXCIndex=hh3cmplsOutSegmentXCIndex, hh3cmplsInterfaceOutFragments=hh3cmplsInterfaceOutFragments, hh3cmplsInterfaceFailedLabelLookup=hh3cmplsInterfaceFailedLabelLookup, hh3cmplsLabelStackLabelIndex=hh3cmplsLabelStackLabelIndex, hh3cmplsInSegmentTrafficParamPtr=hh3cmplsInSegmentTrafficParamPtr, hh3cmplsTrafficParamMaxBurstSize=hh3cmplsTrafficParamMaxBurstSize, hh3cmplsLsrConformance=hh3cmplsLsrConformance, hh3cmplsXCOperStatus=hh3cmplsXCOperStatus, hh3cmplsLsrCompliances=hh3cmplsLsrCompliances, hh3cmplsOutSegmentOwner=hh3cmplsOutSegmentOwner, hh3cmplsOutSegmentTable=hh3cmplsOutSegmentTable, hh3cmplsHCOutSegmentPerfGroup=hh3cmplsHCOutSegmentPerfGroup, Hh3cMplsLabel=Hh3cMplsLabel, hh3cmplsOutSegmentOctets=hh3cmplsOutSegmentOctets, hh3cmplsOutSegmentStorageType=hh3cmplsOutSegmentStorageType, hh3cmplsTrafficParamRowStatus=hh3cmplsTrafficParamRowStatus, hh3cmplsOutSegmentGroup=hh3cmplsOutSegmentGroup, hh3cmplsLsrNotifications=hh3cmplsLsrNotifications, hh3cmplsPerfGroup=hh3cmplsPerfGroup, hh3cmplsOutSegmentEntry=hh3cmplsOutSegmentEntry, hh3cmplsXCAdminStatus=hh3cmplsXCAdminStatus, hh3cmplsInSegmentStorageType=hh3cmplsInSegmentStorageType, hh3cmplsXCTrapEnable=hh3cmplsXCTrapEnable, hh3cmplsMaxLabelStackDepth=hh3cmplsMaxLabelStackDepth, hh3cmplsInSegmentOctets=hh3cmplsInSegmentOctets, hh3cmplsInSegmentDiscards=hh3cmplsInSegmentDiscards, hh3cmplsXCGroup=hh3cmplsXCGroup, hh3cmplsInterfaceConfIndex=hh3cmplsInterfaceConfIndex, hh3cmplsInterfaceConfEntry=hh3cmplsInterfaceConfEntry, hh3cmplsInterfacePerfEntry=hh3cmplsInterfacePerfEntry, hh3cmplsOutSegmentPackets=hh3cmplsOutSegmentPackets, hh3cmplsXCLabelStackIndex=hh3cmplsXCLabelStackIndex, hh3cmplsSegmentDiscontinuityGroup=hh3cmplsSegmentDiscontinuityGroup, hh3cmplsOutSegmentDiscards=hh3cmplsOutSegmentDiscards, hh3cmplsXCIsNotPersistentGroup=hh3cmplsXCIsNotPersistentGroup, hh3cmplsXCRowStatus=hh3cmplsXCRowStatus, hh3cmplsOutSegmentErrors=hh3cmplsOutSegmentErrors, hh3cmplsInSegmentIfIndex=hh3cmplsInSegmentIfIndex, hh3cmplsOutSegmentPushTopLabel=hh3cmplsOutSegmentPushTopLabel, hh3cmplsInterfaceAvailableBandwidth=hh3cmplsInterfaceAvailableBandwidth, hh3cmplsInSegmentPerfEntry=hh3cmplsInSegmentPerfEntry, hh3cmplsLabelStackRowStatus=hh3cmplsLabelStackRowStatus, hh3cmplsXCOwner=hh3cmplsXCOwner, hh3cmplsInterfaceLabelMinIn=hh3cmplsInterfaceLabelMinIn, hh3cmplsLabelStackEntry=hh3cmplsLabelStackEntry, hh3cmplsLabelStackGroup=hh3cmplsLabelStackGroup, hh3cmplsInterfaceInLabelsUsed=hh3cmplsInterfaceInLabelsUsed)
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _path = _interopRequireDefault(__webpack_require__(2));
var _url = _interopRequireDefault(__webpack_require__(3));
var _electron = __webpack_require__(4);
var _env = _interopRequireDefault(__webpack_require__(5));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// This is main process of Electron, started as first thing when your
// app starts. It runs through entire life of your application.
// It doesn't have any windows which you can see on screen, but we can open
// window from here.
// Special module holding environment variables which you declared
// in config/env_xxx.json file.
// Save userData in separate folders for each environment.
// Thanks to this you can use production and development versions of the app
// on same machine like those are two separate apps.
if (_env.default.name !== "production") {
const userDataPath = _electron.app.getPath("userData");
_electron.app.setPath("userData", `${userDataPath} (${_env.default.name})`);
}
_electron.app.on("ready", () => {
const mainWindow = new _electron.BrowserWindow({
width: 800,
height: 600
});
mainWindow.loadURL(_url.default.format({
pathname: _path.default.join(__dirname, "app.html"),
protocol: "file:",
slashes: true
}));
if (_env.default.name === "development") {
mainWindow.openDevTools();
}
});
_electron.app.on("window-all-closed", () => {
_electron.app.quit();
});
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("url");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("electron");
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = {"name":"development","description":"Add here any environment specific stuff you like."}
/***/ })
/******/ ]);
//# sourceMappingURL=background.js.map |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.