text
stringlengths 3
1.05M
|
|---|
import dataclasses
from typing import TYPE_CHECKING
import pytest
from app import crud
if TYPE_CHECKING:
from app.models.user import User
from fastapi.testclient import TestClient
from ..conftest import TestDatabase
from app.api.deps import get_db
from app.main import app
from .utils import BearerAuth, login_user
@pytest.fixture(scope="package", autouse=True)
def db(package_db: "TestDatabase"):
"""Gets the database session
:param package_db: clean database session class
:return: Database session
"""
app.dependency_overrides[get_db] = package_db
return package_db.get_db()
@pytest.fixture(scope="package", autouse=True)
def super_auth(db, client: "TestClient") -> BearerAuth:
"""Login a superuser and return a request BearerAuth to be used in tests.
:param db: Database connection
:param client: Test Client
:return: Requests Bearer Auth class
"""
login_data = login_user(client, "superuser@email.com", "superuserpassword")
bearer_auth = BearerAuth(login_data.access_token)
return bearer_auth
@pytest.fixture(scope="package", autouse=True)
def active_auth(db, client: "TestClient") -> BearerAuth:
"""Login an active test user and return a request BearerAuth to be used in tests.
:param db: Database connection
:param client: Test Client
:return: Requests Bearer Auth class
"""
login_data = login_user(client, "active_user@email.com", "activeuserpassword")
bearer_auth = BearerAuth(login_data.access_token)
return bearer_auth
@pytest.fixture(scope="package", autouse=True)
def invalid_auth() -> BearerAuth:
return BearerAuth("totally-made-up-and-invalid")
@dataclasses.dataclass()
class UserTokens:
superuser: BearerAuth
active_user: BearerAuth
inactive_user: BearerAuth
@pytest.fixture(scope="package", autouse=True)
def tokens(super_auth, active_auth, invalid_auth) -> UserTokens:
return UserTokens(
superuser=super_auth, active_user=active_auth, inactive_user=invalid_auth
)
@pytest.fixture()
def superuser(db) -> "User":
"""Gets the sample super user
:param db: Database connection
:return: Super User model
"""
return _get_user(db, "superuser@email.com")
@pytest.fixture()
def active_user(db) -> "User":
"""Gets the sample active user.
:param db: Database connection
:return: Active user model
"""
return _get_user(db, "active_user@email.com")
@pytest.fixture()
def inactive_user(db) -> "User":
"""Gets the sample active user.
:param db: Database connection
:return: Active user model
"""
return _get_user(db, "inactive_user@email.com")
def _get_user(db, email):
user = crud.user.get_by_email(db, email=email)
assert user
return user
|
var searchData=
[
['handstart',['handStart',['../class_mouse.html#a91adaf5402708bc55a9aa0989c1dc8ce',1,'Mouse']]],
['heading',['heading',['../class_mouse.html#a4163df77f3c8e2399abeb1f424da7d6d',1,'Mouse']]],
['hour',['hour',['../struct___t_i_m_e.html#a7f52e31c2ee006f9dc13fed0b2baecd3',1,'_TIME']]]
];
|
/*++
Copyright (c) 2016 Microsoft Corporation
Module Name:
solver2tactic.h
Abstract:
Convert solver to a tactic.
Author:
Nikolaj Bjorner (nbjorner) 2016-10-17
Notes:
--*/
#ifndef SOLVER2TACTIC_H_
#define SOLVER2TACTIC_H_
#include "tactic.h"
#include "filter_model_converter.h"
class solver;
tactic * mk_solver2tactic(solver* s);
void extract_clauses_and_dependencies(goal_ref const& g, expr_ref_vector& clauses, ptr_vector<expr>& assumptions, obj_map<expr, expr*>& bool2dep, ref<filter_model_converter>& fmc);
#endif
|
import csv
from scripts.base import QcatApiMixin
class QcatDataCsv(QcatApiMixin):
"""
Store QCAT API data as CSV.
"""
def check_local_questionnaires(self, local_questionnaires):
if local_questionnaires:
# Sanity check
self._check_attribute_length(local_questionnaires[0])
def read_data(self) -> list:
"""Read a local CSV file"""
rows = []
output_file = self.get_output_file_path()
try:
with open(output_file, newline='',encoding='utf-8') as csv_file:
reader = csv.DictReader(csv_file, **self._get_csv_options())
for row in reader:
rows.append(row)
self.log(
'Found existing attribute file "{output_file}" with {len_rows}'
' entries.'.format(
output_file=output_file, len_rows=len(rows)))
except FileNotFoundError:
self.log('No existing attribute file found.')
return rows
def write_data(self, data: list) -> None:
"""Write a local CSV file"""
try:
fieldnames = data[0].keys()
except IndexError:
fieldnames = []
output_file = self.get_output_file_path()
with open(output_file, 'w', newline='',encoding='utf-8') as csv_file:
writer = csv.DictWriter(
csv_file, fieldnames=fieldnames, **self._get_csv_options())
writer.writeheader()
for row in data:
writer.writerow(row)
print('Output file "{output_file}" written.'.format(
output_file=output_file))
@staticmethod
def _get_csv_options() -> dict:
"""Options for CSV writing and reading"""
return {'delimiter': ';', 'quoting': csv.QUOTE_NONNUMERIC}
def _check_attribute_length(self, local_questionnaire: dict):
"""
Small sanity check: If number of attributes in local file does not match
those in configuration, return.
"""
if len(self._get_basic_attributes({})) + \
len(self.config.qcat_attributes) != \
len(local_questionnaire):
qcat_attributes_length = len(self._get_basic_attributes({})) + \
len(self.config.qcat_attributes)
self.error(
'Number of attributes ({len_local_questionnaires}) in the local'
' file "{output_file_path}" does not match number of '
'qcat_attributes ({qcat_attributes_length}) set in the '
'configuration file. Please adjust configuration or delete '
'previous output file.'.format(
len_local_questionnaires=len(local_questionnaire),
output_file_path=self.get_output_file_path(),
qcat_attributes_length=qcat_attributes_length
))
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.10.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1CustomResourceDefinitionCondition(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'last_transition_time': 'datetime',
'message': 'str',
'reason': 'str',
'status': 'str',
'type': 'str'
}
attribute_map = {
'last_transition_time': 'lastTransitionTime',
'message': 'message',
'reason': 'reason',
'status': 'status',
'type': 'type'
}
def __init__(self, last_transition_time=None, message=None, reason=None, status=None, type=None):
"""
V1beta1CustomResourceDefinitionCondition - a model defined in Swagger
"""
self._last_transition_time = None
self._message = None
self._reason = None
self._status = None
self._type = None
self.discriminator = None
if last_transition_time is not None:
self.last_transition_time = last_transition_time
if message is not None:
self.message = message
if reason is not None:
self.reason = reason
self.status = status
self.type = type
@property
def last_transition_time(self):
"""
Gets the last_transition_time of this V1beta1CustomResourceDefinitionCondition.
Last time the condition transitioned from one status to another.
:return: The last_transition_time of this V1beta1CustomResourceDefinitionCondition.
:rtype: datetime
"""
return self._last_transition_time
@last_transition_time.setter
def last_transition_time(self, last_transition_time):
"""
Sets the last_transition_time of this V1beta1CustomResourceDefinitionCondition.
Last time the condition transitioned from one status to another.
:param last_transition_time: The last_transition_time of this V1beta1CustomResourceDefinitionCondition.
:type: datetime
"""
self._last_transition_time = last_transition_time
@property
def message(self):
"""
Gets the message of this V1beta1CustomResourceDefinitionCondition.
Human-readable message indicating details about last transition.
:return: The message of this V1beta1CustomResourceDefinitionCondition.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""
Sets the message of this V1beta1CustomResourceDefinitionCondition.
Human-readable message indicating details about last transition.
:param message: The message of this V1beta1CustomResourceDefinitionCondition.
:type: str
"""
self._message = message
@property
def reason(self):
"""
Gets the reason of this V1beta1CustomResourceDefinitionCondition.
Unique, one-word, CamelCase reason for the condition's last transition.
:return: The reason of this V1beta1CustomResourceDefinitionCondition.
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""
Sets the reason of this V1beta1CustomResourceDefinitionCondition.
Unique, one-word, CamelCase reason for the condition's last transition.
:param reason: The reason of this V1beta1CustomResourceDefinitionCondition.
:type: str
"""
self._reason = reason
@property
def status(self):
"""
Gets the status of this V1beta1CustomResourceDefinitionCondition.
Status is the status of the condition. Can be True, False, Unknown.
:return: The status of this V1beta1CustomResourceDefinitionCondition.
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""
Sets the status of this V1beta1CustomResourceDefinitionCondition.
Status is the status of the condition. Can be True, False, Unknown.
:param status: The status of this V1beta1CustomResourceDefinitionCondition.
:type: str
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`")
self._status = status
@property
def type(self):
"""
Gets the type of this V1beta1CustomResourceDefinitionCondition.
Type is the type of the condition.
:return: The type of this V1beta1CustomResourceDefinitionCondition.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""
Sets the type of this V1beta1CustomResourceDefinitionCondition.
Type is the type of the condition.
:param type: The type of this V1beta1CustomResourceDefinitionCondition.
:type: str
"""
if type is None:
raise ValueError("Invalid value for `type`, must not be `None`")
self._type = type
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1beta1CustomResourceDefinitionCondition):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
import React from "react";
const CreateMeetup = () => {
return (
<div>
<p>This is the CreateMeetup Page</p>
</div>
)
}
export default CreateMeetup;
|
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from socialregistration.clients.oauth import OAuth, OAuthError
from socialregistration.settings import SESSION_KEY
import urlparse
import json
class Twitter(OAuth):
api_key = getattr(settings, 'TWITTER_CONSUMER_KEY', '')
secret_key = getattr(settings, 'TWITTER_CONSUMER_SECRET_KEY', '')
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
auth_url = 'https://api.twitter.com/oauth/authenticate'
info_url = 'https://api.twitter.com/1/account/verify_credentials.json'
def get_callback_url(self, **kwargs):
if self.is_https():
return urlparse.urljoin(
'https://%s' % Site.objects.get_current().domain,
reverse('socialregistration:twitter:callback'))
return urlparse.urljoin(
'http://%s' % Site.objects.get_current().domain,
reverse('socialregistration:twitter:callback'))
def get_user_info(self):
dct = self._access_token_dict or {}
try:
dct.update(json.loads(self.request(self.info_url)))
except OAuthError:
pass
return dct
@staticmethod
def get_session_key():
return '%stwitter' % SESSION_KEY
|
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
from pathlib import Path
import pytest
from playwright.async_api import Browser, Page
@pytest.mark.only_browser("chromium")
async def test_should_output_a_trace(
browser: Browser, page: Page, server, tmpdir: Path
):
output_file = tmpdir / "trace.json"
await browser.start_tracing(page=page, screenshots=True, path=output_file)
await page.goto(server.PREFIX + "/grid.html")
await browser.stop_tracing()
assert os.path.getsize(output_file) > 0
@pytest.mark.only_browser("chromium")
async def test_should_create_directories_as_needed(
browser: Browser, page: Page, server, tmpdir
):
output_file = tmpdir / "these" / "are" / "directories" / "trace.json"
await browser.start_tracing(page=page, screenshots=True, path=output_file)
await page.goto(server.PREFIX + "/grid.html")
await browser.stop_tracing()
assert os.path.getsize(output_file) > 0
@pytest.mark.only_browser("chromium")
async def test_should_run_with_custom_categories_if_provided(
browser: Browser, page: Page, tmpdir: Path
):
output_file = tmpdir / "trace.json"
await browser.start_tracing(
page=page,
screenshots=True,
path=output_file,
categories=["disabled-by-default-v8.cpu_profiler.hires"],
)
await browser.stop_tracing()
with open(output_file, mode="r") as of:
trace_json = json.load(of)
assert (
"disabled-by-default-v8.cpu_profiler.hires"
in trace_json["metadata"]["trace-config"]
)
@pytest.mark.only_browser("chromium")
async def test_should_throw_if_tracing_on_two_pages(
browser: Browser, page: Page, tmpdir: Path
):
output_file_1 = tmpdir / "trace1.json"
await browser.start_tracing(page=page, screenshots=True, path=output_file_1)
output_file_2 = tmpdir / "trace2.json"
with pytest.raises(Exception):
await browser.start_tracing(page=page, screenshots=True, path=output_file_2)
await browser.stop_tracing()
@pytest.mark.only_browser("chromium")
async def test_should_return_a_buffer(
browser: Browser, page: Page, server, tmpdir: Path
):
output_file = tmpdir / "trace.json"
await browser.start_tracing(page=page, path=output_file, screenshots=True)
await page.goto(server.PREFIX + "/grid.html")
value = await browser.stop_tracing()
with open(output_file, mode="r") as trace_file:
assert trace_file.read() == value.decode()
@pytest.mark.only_browser("chromium")
async def test_should_work_without_options(browser: Browser, page: Page, server):
await browser.start_tracing()
await page.goto(server.PREFIX + "/grid.html")
trace = await browser.stop_tracing()
assert trace
@pytest.mark.only_browser("chromium")
async def test_should_support_a_buffer_without_a_path(
browser: Browser, page: Page, server
):
await browser.start_tracing(page=page, screenshots=True)
await page.goto(server.PREFIX + "/grid.html")
trace = await browser.stop_tracing()
assert "screenshot" in trace.decode()
|
from django.contrib import admin
from Floo.models import *
admin.site.site_header = "Floo Administration"
# Register your models here.
admin.site.register(User)
admin.site.register(Meeting)
admin.site.register(Team)
admin.site.register(Topic)
|
class Block {
constructor(x, z, parent) {
this.pos = { x: x, z: z };
//console.log(this.pos)
this.dimensions = { x: 10, y: 10, x: 10 };
var i = x;
var j = z;
this.h = Math.round(
simplex.noise2D(i / 20, j / 20) * 1 +
simplex.noise2D(i / 350, j / 350) * 2 +
simplex.noise2D(i / 550, j / 550) * 5 +
simplex.noise2D(i / 800, j / 800) * 10 +
simplex.noise2D(i / 2000, j / 2000) * 100 +
simplex.noise2D(i / 10000, j / 10000) * 500
);
this.shown = true;
this.current = false;
this.geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
});
this.mesh = new THREE.Mesh(this.geometry, this.material);
scene.add(this.mesh);
this.mesh.position.set(this.pos.x, this.h, this.pos.z);
this.parent = parent;
this.mesh.name = parseInt(this.pos.x.toString() + this.pos.z.toString + this.h.toString())
}
update() {
if (
Math.round(camera.position.x) === this.pos.x &&
Math.round(camera.position.z) === this.pos.z
) {
this.current = true;
camera.position.setY(this.h + 2);
world.currPlayerChunk = {
x: this.parent.position.x,
z: this.parent.position.z,
};
//console.log(this.pos)
} else {
this.current = false;
}
}
refresh() {
var i = this.pos.x;
var j = this.pos.z;
this.h = Math.round(
simplex.noise2D(i / 20, j / 20) * 1 +
simplex.noise2D(i / 350, j / 350) * 2 +
simplex.noise2D(i / 550, j / 550) * 5 +
simplex.noise2D(i / 800, j / 800) * 10 +
simplex.noise2D(i / 2000, j / 2000) * 100 +
simplex.noise2D(i / 10000, j / 10000) * 500
);
this.shown = true;
this.current = false;
this.mesh.position.set(this.pos.x, this.h, this.pos.z);
}
dispose() {
remove(this.mesh.name)
}
}
|
/*
Copyright (c) 1999 - 2010, Vodafone Group Services 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 Vodafone Group Services Ltd 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.
*/
#ifndef LOCKEDVARIABLE_H
#define LOCKEDVARIABLE_H
#include "ISABThread.h"
template < typename T >
class LockedVariable {
public:
explicit LockedVariable( const T& value ):
m_var( value ) {
}
void set( const T& newValue ) {
ISABSync sync( m_mutex );
m_var = newValue;
}
const T operator *() {
ISABSync sync( m_mutex );
// create copy and return
return m_var;
}
private:
T m_var;
ISABMutex m_mutex;
};
#endif // LOCKEDVARIABLE_H
|
function toggleDivWithclass(e,t){if($(window).width()<768){$("#"+e).slideToggle("slow",function(){});var n=$("#"+t);n&&n.find("i").toggleClass("rotateBack rotate")}}function activateDate(){"date"!=$('[type="date"]').prop("type")&&$('[type="date"]').datepicker()}function toggleDivWithFilter(e,t){$(window).width()<992&&$("#"+e).slideToggle("none",function(){});var n=$("#"+t);n&&n.toggleClass("clickedFilt")}function showImage(e,t){$("#mainImage").attr("src",br+e),$("#mainImage").fadeOut(),$("#mainImage").fadeIn(),$("#voucherType").val(t)}function showImageVoucherMultiple(){$("#multiplePhoto").show(),$("#onePhoto").hide(),$("#vauchTemp").val(0)}function showImageVoucherSingle(e,t){$("#multiplePhoto").hide(),$("#onePhoto").show(),$("#onePhotoSwitch").attr("src",br+e),$("#voucherType").val(t),$("#vauchTemp").val(t)}function changeDetectorInput(){var e=new Date,t=e.getDate(),n=e.getMonth()+1,i=e.getFullYear();t<10&&(t="0"+t),n<10&&(n="0"+n),e=i+"-"+n+"-"+t;var r=document.getElementById("minDateChange");r&&r.setAttribute("min",e),$("#minDateChange").on("change",function(){var e=this.value;$("#vouchDate").text(e)}),$(document).on("keyup","#otherValue",function(){var e=this.value;$("input[type=radio][name=optionsRadios]:checked");"other"==vaucherCustom&&$("#vouchPrice").text("CHF "+e)}),$(document).on("change","input[type=radio][name=optionsRadios]",function(){vaucherCustom=this.value;var e=parseInt($(this).attr("data-update-h"))-1;if($("input[type=radio][name=optionsRadios]").each(function(t){var n=t+1;t==e?$("#optionsRadios"+n).attr("checked","checked"):$("#optionsRadios"+n).removeAttr("checked")}),"other"==this.value){var t=$("#otherValue").val();$("#vouchPrice").text("CHF "+t)}else $("#vouchPrice").text("CHF "+this.value)}),$(document).on("keyup","#exampleTextarea",function(){var e=$("#exampleTextarea").val().replace(/\n/g,"<br />");$("#voucherDescArea").html(e)}),$(document).on("keyup","#offerVaucherTextarea",function(e){var t=$("#offerVaucherTextarea").val().replace(/\n/g,"<br />");e.currentTarget.innerHTML=$("#offerVaucherTextarea").val(),$("#voucherDescArea").html("<p>"+t+"<p>")}),$(document).on("keyup","#vouchName",function(){var e=this.value;$("#vouchNameTag").html(e)});var a=$("#offerVaucherTextarea");if(a.length>0){var o=a.val();""!=o&&$("#voucherDescArea").html("<p>"+o+"<p>")}var s=$("#vouchName");if(s.length>0){var o=s.val();""!=o&&$("#vouchNameTag").text(o)}var l=$("#exampleTextarea");if(l.length>0){var o=l.val();""!=o&&$("#voucherDescArea").text(o)}}function validateCap(){if(grecaptcha){return""!=grecaptcha.getResponse()||($(".g-recaptcha").children().first().attr("style","width: 304px; height: 78px;border:1px solid red;"),setTimeout(function(){$(".g-recaptcha").children().first().attr("style","width: 304px;")},1e3),!1)}}function validateVoucherOffer(e,t,n,i){var r={},a={};if(1==e){if(1==t)r={selectedPricesInp:"required"},a={selectedPricesInp:{required:"Bitte um Ihre Angaben: Ihre Reservationen."}};else if(2==t){parseInt(creditCardR);if(1==creditCardR){validator&&validator.resetForm(),r={user_name:{required:!0,normalizer:function(e){return $.trim(e)}},user_surname:{required:!0,normalizer:function(e){return $.trim(e)}},user_address:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalCode:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalPlace:{required:!0,normalizer:function(e){return $.trim(e)}},user_country:{required:!0,normalizer:function(e){return $.trim(e)}},user_telephone:{required:!0,normalizer:function(e){return $.trim(e)}},user_email:{required:!0,normalizer:function(e){return $.trim(e)}},user_payment:"required",user_shipping:"required",termsCheck:"required"};var o=$("#reservationgarantee_check");a={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_payment:{required:"Bitte um Ihre Angaben: Zahlungsart"},user_shipping:{required:"Bitte um Ihre Angaben: Versand"},termsCheck:{required:"Bitte AGB‘s akzeptieren"}},o.attr("val")}else r={user_name:"required",user_surname:"required",user_address:"required",user_postalCode:"required",user_postalPlace:"required",user_country:"required",user_telephone:"required",user_email:"required",user_payment:"required",user_shipping:"required",termsCheck:"required"},a={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_payment:{required:"Bitte um Ihre Angaben: Zahlungsart"},user_shipping:{required:"Bitte um Ihre Angaben: Versand"},termsCheck:{required:"Bitte AGB‘s akzeptieren"}}}if($(n).validate({errorClass:"bad-message",rules:r,messages:a,submitHandler:function(e){if(1==t){$(".bookingSteps").removeClass("stepShowBooking"),$(".stepsIndic").removeClass("step1"),$("#step3I").addClass("step1");selectPrices($("input[name=_token]").val()),$("#bookingStep3").addClass("stepShowBooking");var n=window.location.href,r=n.replace(br+"/reservation",""),a=r.replace("step=2","step=3");window.history.pushState(null,null,a)}else 2==t&&submitBooking(i);return!1},highlight:function(e,t){$(e).removeClass(t)}}),1==t||2==t){if(2==t){var o=$("#reservationgarantee_check");"1"!=o.attr("val")?($("#reservationgarantee_cardno").length>0&&($("body #reservationgarantee_cardno").rules("add",{required:!0,messages:{required:"Bitte um Ihre Angaben: Kreditkartennummer"}}),$(n).validate().element("#reservationgarantee_cardno")),$("#reservationgarantee_cardno").length>0&&($("body #reservationgarantee_name").rules("add",{required:!0,messages:{required:"Name und Vorname des Karteninhabers"}}),$(n).validate().element("#reservationgarantee_name"))):($("#reservationgarantee_cardno").length>0&&($("#reservationgarantee_cardno").rules("remove"),$(n).validate().element("#reservationgarantee_cardno")),$("#reservationgarantee_name").length>0&&($("#reservationgarantee_name").rules("remove"),$(n).validate().element("#reservationgarantee_name")))}$(n).submit()}}else if(2==e)1==t?(r={vouchName:{required:!0,normalizer:function(e){return $.trim(e)}},vouchText:{required:!0,normalizer:function(e){return $.trim(e)}},vouchDate:"required"},a={vouchName:{required:"Bitte um Ihre Angaben: Ausgestellt auf"},vouchText:{required:"Bitte um Ihre Angaben: Text auf Gutschein"},vouchDate:{required:"Bitte um Ihre Angaben: Date auf Gutschein"}}):2==t?(r={user_name:{required:!0,normalizer:function(e){return $.trim(e)}},user_surname:{required:!0,normalizer:function(e){return $.trim(e)}},user_address:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalCode:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalPlace:{required:!0,normalizer:function(e){return $.trim(e)}},user_country:{required:!0,normalizer:function(e){return $.trim(e)}},user_telephone:{required:!0,normalizer:function(e){return $.trim(e)}},user_email:{required:!0,normalizer:function(e){return $.trim(e)}},user_payment:"required",user_shipping:"required",termsCheck:"required"},a={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_payment:{required:"Bitte um Ihre Angaben: Zahlungsart"},user_shipping:{required:"Bitte um Ihre Angaben: Versand"},termsCheck:{required:"Bitte AGB‘s akzeptieren"}}):3==t&&(r={user_name:{required:!0,normalizer:function(e){return $.trim(e)}},user_surname:{required:!0,normalizer:function(e){return $.trim(e)}},user_address:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalCode:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalPlace:{required:!0,normalizer:function(e){return $.trim(e)}},user_country:{required:!0,normalizer:function(e){return $.trim(e)}},user_telephone:{required:!0,normalizer:function(e){return $.trim(e)}},user_email:{required:!0,normalizer:function(e){return $.trim(e)}},user_payment:"required",user_shipping:"required",termsCheck:"required"},a={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_payment:{required:"Bitte um Ihre Angaben: Zahlungsart"},user_shipping:{required:"Bitte um Ihre Angaben: Versand"},termsCheck:{required:"Bitte AGB‘s akzeptieren"}}),$(n).validate({errorClass:"bad-message",rules:r,messages:a,submitHandler:function(e){if(1==t){$("#exampleTextarea").html($("#exampleTextarea").val());var n=$("#mainVaucherFormS1").html(),r=$("#voucherMainTableTop").html(),a=$("#vaucherLastStepTop").html(),o={step:2,imgForm:n,st2Price:r,st3Price:a};console.log("pData",o),submitVaucherStFirst(o)}else if(2==t){var n=$("#mainVauchContact").html();$(".voucherSteps").removeClass("stepShowVoucher"),$("#voucherStep3").addClass("stepShowVoucher");var s=window.location.href,l=s.replace(br+"/geschenkgutschein",""),u="";u=-1!==l.indexOf("step=2")?l.replace("step=2","step=3"):-1!==l.indexOf("step=3")?l:l+"?step=3",window.history.pushState(null,null,u),i.step=2,i.imgForm=n;var r=$("#voucherStep3Confirm").html();i.vaucherConfirmTable=r,submitVaucherStSecond(i)}else if(3==t){var n=$("#mainVauchContact").html();i.step=2,i.imgForm=n;var r=$("#voucherStep3Confirm").html();i.vaucherConfirmTable=r,submitVaucherStSecondPay(i)}return!1},highlight:function(e,t){$(e).removeClass(t)}});else if(3==e&&(1==t?(r={vouchName:{required:!0,normalizer:function(e){return $.trim(e)}},selectedPricesInp:"required",vouchText:{required:!0,normalizer:function(e){return $.trim(e)}},vouchDate:"required"},a={vouchName:{required:"Bitte um Ihre Angaben: Ausgestellt auf"},vouchText:{required:"Bitte um Ihre Angaben: Text auf Gutschein"},vouchDate:{required:"Bitte um Ihre Angaben: Date auf Gutschein"},selectedPricesInp:{required:"Bitte um Ihre Angaben: Ihre Reservationen."}}):2!=t&&3!=t||(r={user_name:{required:!0,normalizer:function(e){return $.trim(e)}},user_surname:{required:!0,normalizer:function(e){return $.trim(e)}},user_address:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalCode:{required:!0,normalizer:function(e){return $.trim(e)}},user_postalPlace:{required:!0,normalizer:function(e){return $.trim(e)}},user_country:{required:!0,normalizer:function(e){return $.trim(e)}},user_telephone:{required:!0,normalizer:function(e){return $.trim(e)}},user_email:{required:!0,normalizer:function(e){return $.trim(e)}},user_payment:"required",user_shipping:"required",termsCheck:"required"},a={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_payment:{required:"Bitte um Ihre Angaben: Zahlungsart"},user_shipping:{required:"Bitte um Ihre Angaben: Versand"},termsCheck:{required:"Bitte AGB‘s akzeptieren"}}),$(n).validate({errorClass:"bad-message",rules:r,messages:a,submitHandler:function(e){if(1==t){var n=$("input[name=_token]").val();console.log("window.location.pathname",window.location.pathname);var r=window.location.pathname,a=r.split("/"),o=a.length-1,s=a[o];s?console.log("window.location.pathname interestingPart",s):(console.log("parts",a),s=a[o-1],console.log("window.location.pathname interestingPart else ",s)),selectPricesOfferVaucher(n,s)}else if(2==t){var l=$("#offerVaucherContact").html(),u=$("#vaucherConfirmationInfo").html(),c={step:3,imgForm:l,saveConfOffVau:u};submitOfferVaucherTable(c);var d=window.location.href,h=d.substr(d.indexOf("?")+1);d==window.location.href&&(h="");var f="";f=-1!==h.indexOf("step=2")?h.replace("step=2","step=3"):-1!==h.indexOf("step=3")?h:h+"?step=3",window.history.pushState(null,null,f)}else if(3==t){var l=$("#offerVaucherContact").html(),u=$("#vaucherConfirmationInfo").html(),c={step:3,imgForm:l,saveConfOffVau:u};i.step=3,i.imgForm=l,i.saveConfOffVau=u,submitOfferVaucherTablePay(i)}return!1},highlight:function(e,t){$(e).removeClass(t)}}),2==t)){var o=$("#reservationgarantee_check");"1"!=o.attr("val")?($("#reservationgarantee_cardno").length>0&&($("body #reservationgarantee_cardno").rules("add",{required:!0,messages:{required:"Bitte um Ihre Angaben: Kreditkartennummer"}}),$(n).validate().element("#reservationgarantee_cardno")),$("#reservationgarantee_cardno").length>0&&($("body #reservationgarantee_name").rules("add",{required:!0,messages:{required:"Name und Vorname des Karteninhabers"}}),$(n).validate().element("#reservationgarantee_name"))):($("#reservationgarantee_cardno").length>0&&($("#reservationgarantee_cardno").rules("remove"),$(n).validate().element("#reservationgarantee_cardno")),$("#reservationgarantee_name").length>0&&($("#reservationgarantee_name").rules("remove"),$(n).validate().element("#reservationgarantee_name")))}}function submitGroupOffer(e){$.ajax({method:"POST",url:br+"submitGroupApplication",data:e}).done(function(e){$("#groupOfferFirstStep").hide(),$("#groupOfferSecondStep").show()})}function submitVaucherStFirst(e){var t=$('meta[name="csrf-token"]').attr("content");t||(t=$("input[name=_token]").val()),console.log("crfasdasdas",t),console.log("submitData",e),$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":t},url:br+"submitVaucherStepFirst/",data:e}).done(function(e){"true"==e.trim()?($(".loadingStepStyle").removeClass("forcedFlexNone"),navigateMaster("mainVaucherReservation?navigate=1&step=2",{manualPushState:"geschenkgutschein?step=1"}),$(".voucherSteps").removeClass("stepShowVoucher"),$("#voucherStep2").addClass("stepShowVoucher")):console.log("message falseee")})}function submitVaucherStSecond(e){$(".loadingStepStyle").addClass("forcedFlexNone");var t=$('meta[name="csrf-token"]').attr("content");t||(t=$("input[name=_token]").val()),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":t},url:br+"submitVaucherStepSecond",data:e}).done(function(e){$(".loadingStepStyle").removeClass("forcedFlexNone"),console.log(e)})}function submitVaucherStSecondPay(e){$(".loadingStepStyle").addClass("forcedFlexNone");var t=$('meta[name="csrf-token"]').attr("content");t||(t=$("input[name=_token]").val()),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":t},url:br+"submitVaucherStepSecondTest",data:e}).done(function(e){$(".loadingStepStyle").removeClass("forcedFlexNone"),$("#voucherStep5").html(e),$("#creditSub").trigger("click")})}function submitVaucherStThird(e){$(".loadingStepStyle").addClass("forcedFlexNone");var t=$('meta[name="csrf-token"]').attr("content");t||(t=$("input[name=_token]").val()),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":t},url:br+"submitVaucherStepThird",data:e}).done(function(e){$(".loadingStepStyle").removeClass("forcedFlexNone"),console.log(e)})}function submitOfferVaucherTable(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attr("content")},url:br+"submitOfferVaucherTable",data:e}).done(function(e){$(".bookingSteps").removeClass("stepShowBooking"),$(".bookingSteps").removeClass("stepShowBookingSpecial"),$("#bookingVouchers3").addClass("stepShowBooking"),$(".loadingStepStyle").removeClass("forcedFlexNone"),console.log(e)})}function submitOfferVaucherTablePay(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",headers:{"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attr("content")},url:br+"submitOfferVaucherTablePay",data:e}).done(function(e){$("#bookingVouchers5").html(e),$("#creditSub").trigger("click"),$(".loadingStepStyle").removeClass("forcedFlexNone"),console.log(e)})}function submitContact(e){$.ajax({method:"POST",url:br+"submitContact",data:e}).done(function(e){$("#contactTitleHolder").hide(),$("#contactFormHolder").hide(),$("#contactItemsHolder").hide(),$("#contactSendConfirmation").show()})}function submitVoucher(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",url:br+"submitVaucher",data:e}).done(function(e){$(".loadingStepStyle").removeClass("forcedFlexNone"),$(".voucherSteps").removeClass("stepShowVoucher"),$("#voucherStep4").addClass("stepShowVoucher")})}function submitBooking(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",url:br+"submitBooking",data:e}).done(function(e){$(".loadingStepStyle").addClass("forcedFlexNone"),console.log(e);var t=window.location.href,n=t.replace(br+"/reservation",""),i=n.replace("step=3","step=4");window.history.pushState(null,null,i),$(".bookingSteps").removeClass("stepShowBooking"),$("#bookingStep4").addClass("stepShowBooking")})}function submitOfferBooking(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$.ajax({method:"POST",url:br+"submitOfferVaucher",data:e}).done(function(e){$(".loadingStepStyle").addClass("forcedFlexNone"),$(".bookingSteps").removeClass("stepShowBookingSpecial"),$(".bookingSteps").removeClass("stepShowBooking"),$("#bookingVouchers4").addClass("stepShowBooking")})}function navigateMaster(e,t){var n=e,i="";i=t.urlCorrect?br+n:br+n+"?navigate=1",t&&t.gtype&&(i=br+n+"/"+t.gtype+"?navigate=1"),t.manualPushState&&(console.log("manualPushState","/"+t.manualPushState),window.history.pushState(null,null,br+t.manualPushState)),i=i.replace(/\/?$/,"/");var r=$("html, body").scrollTop();scrollHistory.push(r),$.ajax({url:i,type:"GET",headers:{allowNavigate:1},context:document.body,success:function(e,t,n){"https://www.meinweekend.ch/kontakt"!=i&&"https://www.meinweekend.ch/kontakt/"!=i||$.getScript("https://www.google.com/recaptcha/api.js",function(e,t,n){})},error:function(e,t){}}).done(function(e,n,r){if(!t.backPressed){var a=i.replace("?navigate=1&","?"),o=a.replace("?navigate=1","");o.indexOf("?")<0&&(o="https://www.meinweekend.ch//"==o||"https://www.meinweekend.ch/"==o||"https://www.meinweekend.ch"==o?o.replace(/^\/|\/$/g,""):o.replace(/^\/|\/$/g,"/")),window.history.pushState(null,null,o)}if(e.title_tag){var s=$("#titleTag");s.length>0&&s.text(e.title_tag)}else{var s=$("#titleTag");s.length>0&&s.text("Wellness Romantik Weekend Tagesausflüge Gruppenausflüge - Erlebnis Schweiz zum Buchen oder als Geschenkgutschein")}if(e.view?$("#pageDynamic").html(e.view):location.reload(),e.metaView){$("head meta").remove(),$("head title").remove();$('head link[rel="canonical"]').length>0&&$("head link[rel='canonical']").remove(),$("head").prepend(e.metaView)}$(this).addClass("done");if(-1!==i.indexOf("categoryType/weekend")?($(".wrapEr").removeClass("active"),$("#allWeekend .wrapEr").addClass("active")):-1!==i.indexOf("categoryType/Tagesausflug")?($(".wrapEr").removeClass("active"),$("#allTagesausflug .wrapEr").addClass("active")):-1!==i.indexOf("categoryType/Gruppenausflüge")&&($(".wrapEr").removeClass("active"),$("#allGruppenausfluge .wrapEr").addClass("active")),i.indexOf("geschenkgutschein"),t.scrollBack)if(t.scrollBack){var l=scrollHistory.length-2;scrollHistory[l]&&0!=scrollHistory[l]&&$("#pageDynamic").ready(function(){$("html, body").scrollTop(scrollHistory[l])}),scrollHistory.splice(l,2)}else $("html, body").scrollTop(0);else $("html, body").scrollTop(0);$("#slider1_container").length>0&&setTimeout(function(){ScaleSlider()},500),gtag("config","UA-8788907-1",{page_path:location.pathname})}).fail(function(e,t,n){})}function searchFilter(){var e="",t="",n="",i="",r="";"alle"!=offerRegion&&(t="/region/"+offerRegion),"alle"!=offerType&&(n="/"+offerType),"alle"!=offerDuration&&(i="/fuer/"+offerDuration),"alle"!=keyw&&(r="/geschenkideen/"+keyw);var a=n+t+i+r,o=a.replace(/^\/|\/$/g,"");e=o.replace("//","/"),$.ajax({url:br+e+"?navigate=1",type:"GET",headers:{allowNavigate:1},context:document.body}).done(function(t){if(window.history.pushState(null,null,br+e+"/"),t.view&&$("#pageDynamic").html(t.view),t.metaView){$("head meta").remove(),$("head title").remove();$('head link[rel="canonical"]').length>0&&$("head link[rel='canonical']").remove(),$("head").prepend(t.metaView)}$(this).addClass("done")})}function scrollToVoucher(){$("html, body").scrollTop(700)}function ScaleSlider(){var e=$("#slider1_container").parent().width();e?jssor1_slider.$ScaleWidth(e):window.setTimeout(ScaleSlider,30)}function activateSlider(){var e={$FillMode:2,$AutoPlay:1,$Loop:1,$SlideshowOptions:{$Class:$JssorSlideshowRunner$,$Transitions:[""]},$ThumbnailNavigatorOptions:{$Class:$JssorThumbnailNavigator$,$ChanceToShow:2,$ArrowKeyNavigation:1,$ArrowNavigatorOptions:{$Class:$JssorArrowNavigator$,$ChanceToShow:2,$Steps:1}}};jssor1_slider=new $JssorSlider$("slider1_container",e),ScaleSlider(),$(window).bind("load",ScaleSlider),$(window).bind("resize",ScaleSlider),$(window).bind("orientationchange",ScaleSlider)}function br2nl(e){return preg_replace("/<brs?/?>/ius","\n",str_replace("\n","",str_replace("\r","",htmlspecialchars_decode(e))))}function formatDate(e){return e.getDate()+"."+(e.getMonth()+1)+"."+e.getFullYear()}function formatBookingDate(e){var t=["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"];return["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"][e.getDay()]+", "+e.getDate()+". "+t[e.getMonth()]+" "+e.getFullYear()}function formatVaucherDate(e){return e.getDate()+"."+("0"+(e.getMonth()+1)).slice(-2)+"."+e.getFullYear()}function formatEnableDate(e){return("0"+(e.getDate()+1)).slice(-2)+"/"+("0"+(e.getMonth()+1)).slice(-2)+"/"+e.getFullYear()}function formatEnableDate2(e){var t=("0"+e.getDate()).slice(-2);return("0"+(e.getMonth()+1)).slice(-2)+"/"+t+"/"+e.getFullYear()}function disableDays(e){var t=formatDate(e),n=!1;$.inArray(t.toString(),enableDays);if(disDays.length>0)for(var i=0;i<disDays.length;i++)return-1==$.inArray(t,disDays)||(!0,!1);if(enableDays.length>0)for(var i=0;i<enableDays.length;i++){$.inArray(t.toString(),enableDays);if(-1!=$.inArray(t,enableDays)){n=!0;formatEnableDate(e);return!0}return!1}if(!0!==n){if(!(e>stTime&&e<endTime))return!1;calendarValid}}function activateDateCalendar(){console.log("activateDae"),stTime=new Date(1e3*$("#stTime")[0].value),endTime=new Date(1e3*$("#endTime")[0].value),stFromDate=new Date(1e3*$("#defDate")[0].value);var e=parseInt($("#calendarValid")[0].value),t=e;$("#datetimepicker12").datepicker("destroy");var n=new Date,i=n.getDate(),r=n.getMonth()+1,a=n.getFullYear();if(i<10&&(i="0"+i),r<10&&(r="0"+r),(n=r+"/"+i+"/"+a)==formatEnableDate2(stFromDate)){var o=new Date(1e3*$("#defDate")[0].value);o.setDate(o.getDate()+1),stFromDate=o}if(0==t){var s=$("#openedDates")[0].value.replace(/ /g,""),l=s.replace(/(?:\r\n|\r|\n)/g,""),u=JSON.parse(l);enableDays=u;var c;if(u[0]){var d=u[0].split("."),h=d[1]+"/"+d[0]+"/"+d[2];c=new Date(h)}c||(c=new Date),$("#datetimepicker12").datepicker({startDate:stFromDate,inline:!0,sideBySide:!0,format:"DD/MM/YYYY",language:"de",allowInputToggle:!0,beforeShowDay:disableDays}).on("changeDate",function(e){var t=formatBookingDate(e.date),n=formatDate(e.date),i=$("#userDatePickShow"),r=$("#userDatePickShow1"),a=$("#userDatePickShow2");i&&i.html(t),r&&r.html(t),a&&a.html(t),bookingDate=n;var o={selDate:n},s=$.param(o);navigateMasterData("reservation/"+activeOffer,{manualPushState:"reservation/"+activeOffer,type:"GET",data:{step:2,pushD:s}})})}else{var f=$("#closedDates")[0].value.replace(/ /g,""),p=f.replace(/(?:\r\n|\r|\n)/g,""),m=JSON.parse(p),g=$("#availableDays")[0].value.replace(/ /g,""),v=g.replace(/(?:\r\n|\r|\n)/g,"");disDays=[],enableDays=[],disDays=m;var y;y=disDays.length>0?{inline:!0,startDate:stFromDate,endDate:endTime,sideBySide:!0,defaultDate:stFromDate,allowInputToggle:!0,daysOfWeekDisabled:v,format:"DD/MM/YYYY",language:"de",beforeShowDay:disableDays}:{inline:!0,startDate:stFromDate,endDate:endTime,sideBySide:!0,defaultDate:stFromDate,allowInputToggle:!0,daysOfWeekDisabled:v,format:"DD/MM/YYYY",language:"de"},$("#datetimepicker12").datepicker(y).on("changeDate",function(e){var t=formatBookingDate(e.date),n=formatDate(e.date),i=$("#userDatePickShow"),r=$("#userDatePickShow1"),a=$("#userDatePickShow2");i&&i.html(t),r&&r.html(t),a&&a.html(t),bookingDate=n;var o={selDate:n},s=$.param(o);navigateMasterData("reservation/"+activeOffer,{manualPushState:"reservation/"+activeOffer,type:"GET",data:{step:2,pushD:s}})}),$("#datepicker").datepicker("setStartDate",stFromDate)}}function navigateMasterData(e,t){var n=br+e+"?navigate=1";t&&t.gtype&&(n=br+e+"/"+t.gtype+"?navigate=1");var i=$.param(t.data);t.manualPushState&&window.history.pushState(null,null,br+t.manualPushState+"?"+i),$.ajax({url:n,type:t.type,context:document.body,headers:{"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attr("content"),allowNavigate:1},data:t.data}).done(function(e,t,i){i.getAllResponseHeaders();if(e.excUrl){var r=e.excUrl.replace(br,"");r.replace("?navigate=1","")}e.view&&$("#pageDynamic").html(e.view),e.metaView&&($("head meta").remove(),$("head title").remove(),$("head").prepend(e.metaView)),$(this).addClass("done");-1!==n.indexOf("categoryType/weekend")?($(".wrapEr").removeClass("active"),$("#allWeekend .wrapEr").addClass("active")):-1!==n.indexOf("categoryType/Tagesausflug")?($(".wrapEr").removeClass("active"),$("#allTagesausflug .wrapEr").addClass("active")):-1!==n.indexOf("categoryType/Gruppenausflüge")&&($(".wrapEr").removeClass("active"),$("#allGruppenausfluge .wrapEr").addClass("active")),n.indexOf("geschenkgutschein")})}function setOffer(e){totalBookingPrice=0,lastTotalBookingPrice=0,pricesSelected=[],aditionalSelected=[],activeOffer=e}function selectPrice(e,t,n){var i=Number($("#s_curr").val()),r=Number($("#s_exch").val()),a=e.target;if(0!=a.value){var o={priceId:t,priceValue:a.value,totalPrice:n},s="#price_"+t;$(s+" option").filter(function(e){e==a.value?$(s+" option[value="+a.value+"]").attr("selected","selected"):$(s+" option[value="+e+"]").removeAttr("selected")}),pricesSelected.length>0?(pricesSelected.forEach(function(e,t){e.priceId==o.priceId&&pricesSelected.splice(t,1)}),pricesSelected.push(o)):pricesSelected.push(o);var l=0;pricesSelected.forEach(function(e,t){l+=Number(e.totalPrice)*Number(e.priceValue)}),addUpBill(aditionalSelected,pricesSelected,i,r)}else{var u="#price_"+t;$(u+" option").filter(function(e){e==a.value?$(u+" option[value="+a.value+"]").attr("selected","selected"):$(u+" option[value="+e+"]").removeAttr("selected")});var c={priceId:t,priceValue:a.value,totalPrice:n};pricesSelected.forEach(function(e,t){e.priceId==c.priceId&&pricesSelected.splice(t,1)}),addUpBill(aditionalSelected,pricesSelected,i,r)}}function selectAditional(e,t,n){var i=Number($("#s_curr").val()),r=Number($("#s_exch").val()),a=e.target,o={additionalId:t,additionalValue:a.value,totalAdditional:n},s="#price_"+t;$(s+" option").filter(function(e){e==a.value?$(s+" option[value="+a.value+"]").attr("selected","selected"):$(s+" option[value="+e+"]").removeAttr("selected")}),aditionalSelected.length>0?(aditionalSelected.forEach(function(e,t){e.additionalId==o.additionalId&&aditionalSelected.splice(t,1)}),aditionalSelected.push(o)):aditionalSelected.push(o);var l=0;aditionalSelected.forEach(function(e,t){l+=Number(e.totalAdditional)*Number(e.additionalValue)}),addUpBill(aditionalSelected,pricesSelected,i,r)}function addUpBill(e,t,n,i){var r=0;if(e.length>0&&e.forEach(function(e,t){r+=Number(e.totalAdditional)*Number(e.additionalValue)}),t.length>0&&t.forEach(function(e,t){r+=Number(e.totalPrice)*Number(e.priceValue)}),0==n){$("#bookingTotal").text(r);var a=roundUp(r/i,0);$("#shiftBookingTotal").text(a)}else{$("#bookingTotal").text(r);var o=roundUp(r*i,0);$("#shiftBookingTotal").text(o)}0==e.length&&0==t.length?$("#selectedPricesInp").val(""):$("#selectedPricesInp").val("1")}function startGroupReservation(e){navigateMaster("gruppenanfrage/"+activeOffer+"/"+e.target.value,{})}function roundUp(e,t){return t=Math.pow(10,t),Math.ceil(e*t)/t}function configurePrices(e){}function selectPrices(e){$(".loadingStepStyle").addClass("forcedFlexNone");var t=$("#bookingTable").html(),n={_token:e,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,firstTable:t},i=$("#vaucherOfferT1");i.length>0&&(n.offerVaucherTable=i.html()),$.ajax({method:"POST",url:br+"selectedPrices",data:n,headers:{"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attr("content")}}).done(function(e){$(".loadingStepStyle").removeClass("forcedFlexNone"),e?(e.table?($("#selectedPricesTable").html(e.table),$("#lastStepPrices").html(e.table)):($("#selectedPricesTable").html(""),$("#lastStepPrices").html("")),e.isAdditionalNight?$("#additionalNight").html(e.isAdditionalNight):$("#additionalNight").html("")):($("#selectedPricesTable").html(""),$("#lastStepPrices").html(""),$("#additionalNight").html(""))})}function selectPricesOfferVaucher(e,t){$(".loadingStepStyle").addClass("forcedFlexNone");var n=$("#bookingTable").html(),i={_token:e,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,firstTable:n},r=$("#vaucherOfferT1");r.length>0&&(i.offerVaucherTable=r.html()),$.ajax({method:"POST",url:br+"selectedPrices",data:i}).done(function(e){console.log("submit"),$(".loadingStepStyle").removeClass("forcedFlexNone"),e?(navigateMaster("offerVaucherReservation/"+t+"?navigate=1&step=2",{manualPushState:"angebote/geschenkgutschein-geschenkidee/ideen/"+t+"?step=1"}),e.table?($("#selectedPricesTable").html(e.table),$("#lastStepPrices").html(e.table)):($("#selectedPricesTable").html(""),$("#lastStepPrices").html("")),e.isAdditionalNight?$("#additionalNight").html(e.isAdditionalNight):$("#additionalNight").html("")):($("#selectedPricesTable").html(""),$("#lastStepPrices").html(""),$("#additionalNight").html(""))})}function getPrices(e){$.ajax({method:"GET",url:br+"pricesForDate/"+e+"/"+activeOffer}).done(function(e){$("#bookingTable").html(e)})}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};!function(e,t){"object"==("undefined"==typeof module?"undefined":_typeof(module))&&"object"==_typeof(module.exports)?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=!!e&&"length"in e&&e.length,n=fe.type(e);return"function"!==n&&!fe.isWindow(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}function i(e,t,n){if(fe.isFunction(t))return fe.grep(e,function(e,i){return!!t.call(e,i,e)!==n});if(t.nodeType)return fe.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(Se.test(t))return fe.filter(t,e,n);t=fe.filter(t,e)}return fe.grep(e,function(e){return fe.inArray(e,t)>-1!==n})}function r(e,t){do{e=e[t]}while(e&&1!==e.nodeType);return e}function a(e){var t={}
;return fe.each(e.match(xe)||[],function(e,n){t[n]=!0}),t}function o(){ie.addEventListener?(ie.removeEventListener("DOMContentLoaded",s),e.removeEventListener("load",s)):(ie.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(ie.addEventListener||"load"===e.event.type||"complete"===ie.readyState)&&(o(),fe.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var i="data-"+t.replace(Me,"-$1").toLowerCase();if("string"==typeof(n=e.getAttribute(i))){try{n="true"===n||"false"!==n&&("null"===n?null:+n+""===n?+n:Ne.test(n)?fe.parseJSON(n):n)}catch(e){}fe.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!fe.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,i){if(Oe(e)){var r,a,o=fe.expando,s=e.nodeType,l=s?fe.cache:e,u=s?e[o]:e[o]&&o;if(u&&l[u]&&(i||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[o]=ne.pop()||fe.guid++:o),l[u]||(l[u]=s?{}:{toJSON:fe.noop}),("object"==(void 0===t?"undefined":_typeof(t))||"function"==typeof t)&&(i?l[u]=fe.extend(l[u],t):l[u].data=fe.extend(l[u].data,t)),a=l[u],i||(a.data||(a.data={}),a=a.data),void 0!==n&&(a[fe.camelCase(t)]=n),"string"==typeof t?null==(r=a[t])&&(r=a[fe.camelCase(t)]):r=a,r}}function d(e,t,n){if(Oe(e)){var i,r,a=e.nodeType,o=a?fe.cache:e,s=a?e[fe.expando]:fe.expando;if(o[s]){if(t&&(i=n?o[s]:o[s].data)){fe.isArray(t)?t=t.concat(fe.map(t,fe.camelCase)):t in i?t=[t]:(t=fe.camelCase(t),t=t in i?[t]:t.split(" ")),r=t.length;for(;r--;)delete i[t[r]];if(n?!u(i):!fe.isEmptyObject(i))return}(n||(delete o[s].data,u(o[s])))&&(a?fe.cleanData([e],!0):de.deleteExpando||o!=o.window?delete o[s]:o[s]=void 0)}}}function h(e,t,n,i){var r,a=1,o=20,s=i?function(){return i.cur()}:function(){return fe.css(e,t,"")},l=s(),u=n&&n[3]||(fe.cssNumber[t]?"":"px"),c=(fe.cssNumber[t]||"px"!==u&&+l)&&Re.exec(fe.css(e,t));if(c&&c[3]!==u){u=u||c[3],n=n||[],c=+l||1;do{a=a||".5",c/=a,fe.style(e,t,c+u)}while(a!==(a=s()/l)&&1!==a&&--o)}return n&&(c=+c||+l||0,r=n[1]?c+(n[1]+1)*n[2]:+n[2],i&&(i.unit=u,i.start=c,i.end=r)),r}function f(e){var t=je.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function p(e,t){var n,i,r=0,a=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):void 0;if(!a)for(a=[],n=e.childNodes||e;null!=(i=n[r]);r++)!t||fe.nodeName(i,t)?a.push(i):fe.merge(a,p(i,t));return void 0===t||t&&fe.nodeName(e,t)?fe.merge([e],a):a}function m(e,t){for(var n,i=0;null!=(n=e[i]);i++)fe._data(n,"globalEval",!t||fe._data(t[i],"globalEval"))}function g(e){Fe.test(e.type)&&(e.defaultChecked=e.checked)}function v(e,t,n,i,r){for(var a,o,s,l,u,c,d,h=e.length,v=f(t),y=[],_=0;h>_;_++)if((o=e[_])||0===o)if("object"===fe.type(o))fe.merge(y,o.nodeType?[o]:o);else if(We.test(o)){for(l=l||v.appendChild(t.createElement("div")),u=(Ye.exec(o)||["",""])[1].toLowerCase(),d=Be[u]||Be._default,l.innerHTML=d[1]+fe.htmlPrefilter(o)+d[2],a=d[0];a--;)l=l.lastChild;if(!de.leadingWhitespace&&qe.test(o)&&y.push(t.createTextNode(qe.exec(o)[0])),!de.tbody)for(o="table"!==u||Ue.test(o)?"<table>"!==d[1]||Ue.test(o)?0:l:l.firstChild,a=o&&o.childNodes.length;a--;)fe.nodeName(c=o.childNodes[a],"tbody")&&!c.childNodes.length&&o.removeChild(c);for(fe.merge(y,l.childNodes),l.textContent="";l.firstChild;)l.removeChild(l.firstChild);l=v.lastChild}else y.push(t.createTextNode(o));for(l&&v.removeChild(l),de.appendChecked||fe.grep(p(y,"input"),g),_=0;o=y[_++];)if(i&&fe.inArray(o,i)>-1)r&&r.push(o);else if(s=fe.contains(o.ownerDocument,o),l=p(v.appendChild(o),"script"),s&&m(l),n)for(a=0;o=l[a++];)Ve.test(o.type||"")&&n.push(o);return l=null,v}function y(){return!0}function _(){return!1}function b(){try{return ie.activeElement}catch(e){}}function $(e,t,n,i,r,a){var o,s;if("object"==(void 0===t?"undefined":_typeof(t))){"string"!=typeof n&&(i=i||n,n=void 0);for(s in t)$(e,s,n,i,t[s],a);return e}if(null==i&&null==r?(r=n,i=n=void 0):null==r&&("string"==typeof n?(r=i,i=void 0):(r=i,i=n,n=void 0)),!1===r)r=_;else if(!r)return e;return 1===a&&(o=r,r=function(e){return fe().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=fe.guid++)),e.each(function(){fe.event.add(this,t,r,i,n)})}function w(e,t){return fe.nodeName(e,"table")&&fe.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function S(e){return e.type=(null!==fe.find.attr(e,"type"))+"/"+e.type,e}function T(e){var t=it.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function C(e,t){if(1===t.nodeType&&fe.hasData(e)){var n,i,r,a=fe._data(e),o=fe._data(t,a),s=a.events;if(s){delete o.handle,o.events={};for(n in s)for(i=0,r=s[n].length;r>i;i++)fe.event.add(t,n,s[n][i])}o.data&&(o.data=fe.extend({},o.data))}}function D(e,t){var n,i,r;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!de.noCloneEvent&&t[fe.expando]){r=fe._data(t);for(i in r.events)fe.removeEvent(t,i,r.handle);t.removeAttribute(fe.expando)}"script"===n&&t.text!==e.text?(S(t).text=e.text,T(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),de.html5Clone&&e.innerHTML&&!fe.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Fe.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function k(e,t,n,i){t=ae.apply([],t);var r,a,o,s,l,u,c=0,d=e.length,h=d-1,f=t[0],m=fe.isFunction(f);if(m||d>1&&"string"==typeof f&&!de.checkClone&&nt.test(f))return e.each(function(r){var a=e.eq(r);m&&(t[0]=f.call(this,r,a.html())),k(a,t,n,i)});if(d&&(u=v(t,e[0].ownerDocument,!1,e,i),r=u.firstChild,1===u.childNodes.length&&(u=r),r||i)){for(s=fe.map(p(u,"script"),S),o=s.length;d>c;c++)a=u,c!==h&&(a=fe.clone(a,!0,!0),o&&fe.merge(s,p(a,"script"))),n.call(e[c],a,c);if(o)for(l=s[s.length-1].ownerDocument,fe.map(s,T),c=0;o>c;c++)a=s[c],Ve.test(a.type||"")&&!fe._data(a,"globalEval")&&fe.contains(l,a)&&(a.src?fe._evalUrl&&fe._evalUrl(a.src):fe.globalEval((a.text||a.textContent||a.innerHTML||"").replace(rt,"")));u=r=null}return e}function x(e,t,n){for(var i,r=t?fe.filter(t,e):e,a=0;null!=(i=r[a]);a++)n||1!==i.nodeType||fe.cleanData(p(i)),i.parentNode&&(n&&fe.contains(i.ownerDocument,i)&&m(p(i,"script")),i.parentNode.removeChild(i));return e}function E(e,t){var n=fe(t.createElement(e)).appendTo(t.body),i=fe.css(n[0],"display");return n.detach(),i}function A(e){var t=ie,n=lt[e];return n||(n=E(e,t),"none"!==n&&n||(st=(st||fe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(st[0].contentWindow||st[0].contentDocument).document,t.write(),t.close(),n=E(e,t),st.detach()),lt[e]=n),n}function O(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function N(e){if(e in St)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=wt.length;n--;)if((e=wt[n]+t)in St)return e}function M(e,t){for(var n,i,r,a=[],o=0,s=e.length;s>o;o++)i=e[o],i.style&&(a[o]=fe._data(i,"olddisplay"),n=i.style.display,t?(a[o]||"none"!==n||(i.style.display=""),""===i.style.display&&Le(i)&&(a[o]=fe._data(i,"olddisplay",A(i.nodeName)))):(r=Le(i),(n&&"none"!==n||!r)&&fe._data(i,"olddisplay",r?n:fe.css(i,"display"))));for(o=0;s>o;o++)i=e[o],i.style&&(t&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=t?a[o]||"":"none"));return e}function I(e,t,n){var i=_t.exec(t);return i?Math.max(0,i[1]-(n||0))+(i[2]||"px"):t}function R(e,t,n,i,r){for(var a=n===(i?"border":"content")?4:"width"===t?1:0,o=0;4>a;a+=2)"margin"===n&&(o+=fe.css(e,n+Pe[a],!0,r)),i?("content"===n&&(o-=fe.css(e,"padding"+Pe[a],!0,r)),"margin"!==n&&(o-=fe.css(e,"border"+Pe[a]+"Width",!0,r))):(o+=fe.css(e,"padding"+Pe[a],!0,r),"padding"!==n&&(o+=fe.css(e,"border"+Pe[a]+"Width",!0,r)));return o}function P(t,n,i){var r=!0,a="width"===n?t.offsetWidth:t.offsetHeight,o=ft(t),s=de.boxSizing&&"border-box"===fe.css(t,"boxSizing",!1,o);if(ie.msFullscreenElement&&e.top!==e&&t.getClientRects().length&&(a=Math.round(100*t.getBoundingClientRect()[n])),0>=a||null==a){if(a=pt(t,n,o),(0>a||null==a)&&(a=t.style[n]),ct.test(a))return a;r=s&&(de.boxSizingReliable()||a===t.style[n]),a=parseFloat(a)||0}return a+R(t,n,i||(s?"border":"content"),r,o)+"px"}function L(e,t,n,i,r){return new L.prototype.init(e,t,n,i,r)}function H(){return e.setTimeout(function(){Tt=void 0}),Tt=fe.now()}function F(e,t){var n,i={height:e},r=0;for(t=t?1:0;4>r;r+=2-t)n=Pe[r],i["margin"+n]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function Y(e,t,n){for(var i,r=(j.tweeners[t]||[]).concat(j.tweeners["*"]),a=0,o=r.length;o>a;a++)if(i=r[a].call(n,t,e))return i}function V(e,t,n){var i,r,a,o,s,l,u,c=this,d={},h=e.style,f=e.nodeType&&Le(e),p=fe._data(e,"fxshow");n.queue||(s=fe._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,c.always(function(){c.always(function(){s.unqueued--,fe.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],u=fe.css(e,"display"),"inline"===("none"===u?fe._data(e,"olddisplay")||A(e.nodeName):u)&&"none"===fe.css(e,"float")&&(de.inlineBlockNeedsLayout&&"inline"!==A(e.nodeName)?h.zoom=1:h.display="inline-block")),n.overflow&&(h.overflow="hidden",de.shrinkWrapBlocks()||c.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(i in t)if(r=t[i],Dt.exec(r)){if(delete t[i],a=a||"toggle"===r,r===(f?"hide":"show")){if("show"!==r||!p||void 0===p[i])continue;f=!0}d[i]=p&&p[i]||fe.style(e,i)}else u=void 0;if(fe.isEmptyObject(d))"inline"===("none"===u?A(e.nodeName):u)&&(h.display=u);else{p?"hidden"in p&&(f=p.hidden):p=fe._data(e,"fxshow",{}),a&&(p.hidden=!f),f?fe(e).show():c.done(function(){fe(e).hide()}),c.done(function(){var t;fe._removeData(e,"fxshow");for(t in d)fe.style(e,t,d[t])});for(i in d)o=Y(f?p[i]:0,i,c),i in p||(p[i]=o.start,f&&(o.end=o.start,o.start="width"===i||"height"===i?1:0))}}function q(e,t){var n,i,r,a,o;for(n in e)if(i=fe.camelCase(n),r=t[i],a=e[n],fe.isArray(a)&&(r=a[1],a=e[n]=a[0]),n!==i&&(e[i]=a,delete e[n]),(o=fe.cssHooks[i])&&"expand"in o){a=o.expand(a),delete e[i];for(n in a)n in e||(e[n]=a[n],t[n]=r)}else t[i]=r}function j(e,t,n){var i,r,a=0,o=j.prefilters.length,s=fe.Deferred().always(function(){delete l.elem}),l=function(){if(r)return!1;for(var t=Tt||H(),n=Math.max(0,u.startTime+u.duration-t),i=n/u.duration||0,a=1-i,o=0,l=u.tweens.length;l>o;o++)u.tweens[o].run(a);return s.notifyWith(e,[u,a,n]),1>a&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:fe.extend({},t),opts:fe.extend(!0,{specialEasing:{},easing:fe.easing._default},n),originalProperties:t,originalOptions:n,startTime:Tt||H(),duration:n.duration,tweens:[],createTween:function(t,n){var i=fe.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(i),i},stop:function(t){var n=0,i=t?u.tweens.length:0;if(r)return this;for(r=!0;i>n;n++)u.tweens[n].run(1);return t?(s.notifyWith(e,[u,1,0]),s.resolveWith(e,[u,t])):s.rejectWith(e,[u,t]),this}}),c=u.props;for(q(c,u.opts.specialEasing);o>a;a++)if(i=j.prefilters[a].call(u,e,c,u.opts))return fe.isFunction(i.stop)&&(fe._queueHooks(u.elem,u.opts.queue).stop=fe.proxy(i.stop,i)),i;return fe.map(c,Y,u),fe.isFunction(u.opts.start)&&u.opts.start.call(e,u),fe.fx.timer(fe.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function B(e){return fe.attr(e,"class")||""}function W(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var i,r=0,a=t.toLowerCase().match(xe)||[];if(fe.isFunction(n))for(;i=a[r++];)"+"===i.charAt(0)?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(n)):(e[i]=e[i]||[]).push(n)}}function U(e,t,n,i){function r(s){var l;return a[s]=!0,fe.each(e[s]||[],function(e,s){var u=s(t,n,i);return"string"!=typeof u||o||a[u]?o?!(l=u):void 0:(t.dataTypes.unshift(u),r(u),!1)}),l}var a={},o=e===Zt;return r(t.dataTypes[0])||!a["*"]&&r("*")}function z(e,t){var n,i,r=fe.ajaxSettings.flatOptions||{};for(i in t)void 0!==t[i]&&((r[i]?e:n||(n={}))[i]=t[i]);return n&&fe.extend(!0,e,n),e}function G(e,t,n){for(var i,r,a,o,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(o in s)if(s[o]&&s[o].test(r)){l.unshift(o);break}if(l[0]in n)a=l[0];else{for(o in n){if(!l[0]||e.converters[o+" "+l[0]]){a=o;break}i||(i=o)}a=a||i}return a?(a!==l[0]&&l.unshift(a),n[a]):void 0}function X(e,t,n,i){var r,a,o,s,l,u={},c=e.dataTypes.slice();if(c[1])for(o in e.converters)u[o.toLowerCase()]=e.converters[o];for(a=c.shift();a;)if(e.responseFields[a]&&(n[e.responseFields[a]]=t),!l&&i&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=a,a=c.shift())if("*"===a)a=l;else if("*"!==l&&l!==a){if(!(o=u[l+" "+a]||u["* "+a]))for(r in u)if(s=r.split(" "),s[1]===a&&(o=u[l+" "+s[0]]||u["* "+s[0]])){!0===o?o=u[r]:!0!==u[r]&&(a=s[0],c.unshift(s[1]));break}if(!0!==o)if(o&&e.throws)t=o(t);else try{t=o(t)}catch(e){return{state:"parsererror",error:o?e:"No conversion from "+l+" to "+a}}}return{state:"success",data:t}}function Z(e){return e.style&&e.style.display||fe.css(e,"display")}function K(e){for(;e&&1===e.nodeType;){if("none"===Z(e)||"hidden"===e.type)return!0;e=e.parentNode}return!1}function Q(e,t,n,i){var r;if(fe.isArray(t))fe.each(t,function(t,r){n||tn.test(e)?i(e,r):Q(e+"["+("object"==(void 0===r?"undefined":_typeof(r))&&null!=r?t:"")+"]",r,n,i)});else if(n||"object"!==fe.type(t))i(e,t);else for(r in t)Q(e+"["+r+"]",t[r],n,i)}function J(){try{return new e.XMLHttpRequest}catch(e){}}function ee(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function te(e){return fe.isWindow(e)?e:9===e.nodeType&&(e.defaultView||e.parentWindow)}var ne=[],ie=e.document,re=ne.slice,ae=ne.concat,oe=ne.push,se=ne.indexOf,le={},ue=le.toString,ce=le.hasOwnProperty,de={},he="1.12.1",fe=function e(t,n){return new e.fn.init(t,n)},pe=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,me=/^-ms-/,ge=/-([\da-z])/gi,ve=function(e,t){return t.toUpperCase()};fe.fn=fe.prototype={jquery:he,constructor:fe,selector:"",length:0,toArray:function(){return re.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:re.call(this)},pushStack:function(e){var t=fe.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e){return fe.each(this,e)},map:function(e){return this.pushStack(fe.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(re.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:oe,sort:ne.sort,splice:ne.splice},fe.extend=fe.fn.extend=function(){var e,t,n,i,r,a,o=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof o&&(u=o,o=arguments[s]||{},s++),"object"==(void 0===o?"undefined":_typeof(o))||fe.isFunction(o)||(o={}),s===l&&(o=this,s--);l>s;s++)if(null!=(r=arguments[s]))for(i in r)e=o[i],n=r[i],o!==n&&(u&&n&&(fe.isPlainObject(n)||(t=fe.isArray(n)))?(t?(t=!1,a=e&&fe.isArray(e)?e:[]):a=e&&fe.isPlainObject(e)?e:{},o[i]=fe.extend(u,a,n)):void 0!==n&&(o[i]=n));return o},fe.extend({expando:"jQuery"+(he+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===fe.type(e)},isArray:Array.isArray||function(e){return"array"===fe.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){var t=e&&e.toString();return!fe.isArray(e)&&t-parseFloat(t)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==fe.type(e)||e.nodeType||fe.isWindow(e))return!1;try{if(e.constructor&&!ce.call(e,"constructor")&&!ce.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(e){return!1}if(!de.ownFirst)for(t in e)return ce.call(e,t);for(t in e);return void 0===t||ce.call(e,t)},type:function(e){return null==e?e+"":"object"==(void 0===e?"undefined":_typeof(e))||"function"==typeof e?le[ue.call(e)]||"object":void 0===e?"undefined":_typeof(e)},globalEval:function(t){t&&fe.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(me,"ms-").replace(ge,ve)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t){var i,r=0;if(n(e))for(i=e.length;i>r&&!1!==t.call(e[r],r,e[r]);r++);else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(pe,"")},makeArray:function(e,t){var i=t||[];return null!=e&&(n(Object(e))?fe.merge(i,"string"==typeof e?[e]:e):oe.call(i,e)),i},inArray:function(e,t,n){var i;if(t){if(se)return se.call(t,e,n);for(i=t.length,n=n?0>n?Math.max(0,i+n):n:0;i>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,i=0,r=e.length;n>i;)e[r++]=t[i++];if(n!==n)for(;void 0!==t[i];)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){for(var i=[],r=0,a=e.length,o=!n;a>r;r++)!t(e[r],r)!==o&&i.push(e[r]);return i},map:function(e,t,i){var r,a,o=0,s=[];if(n(e))for(r=e.length;r>o;o++)null!=(a=t(e[o],o,i))&&s.push(a);else for(o in e)null!=(a=t(e[o],o,i))&&s.push(a);return ae.apply([],s)},guid:1,proxy:function(e,t){var n,i,r;return"string"==typeof t&&(r=e[t],t=e,e=r),fe.isFunction(e)?(n=re.call(arguments,2),i=function(){return e.apply(t||this,n.concat(re.call(arguments)))},i.guid=e.guid=e.guid||fe.guid++,i):void 0},now:function(){return+new Date},support:de}),"function"==typeof Symbol&&(fe.fn[Symbol.iterator]=ne[Symbol.iterator]),fe.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){le["[object "+t+"]"]=t.toLowerCase()});var ye=function(e){function t(e,t,n,i){var r,a,o,s,u,d,h,f,p=t&&t.ownerDocument,m=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==m&&9!==m&&11!==m)return n;if(!i&&((t?t.ownerDocument||t:H)!==A&&E(t),t=t||A,N)){if(11!==m&&(d=me.exec(e)))if(r=d[1]){if(9===m){if(!(o=t.getElementById(r)))return n;if(o.id===r)return n.push(o),n}else if(p&&(o=p.getElementById(r))&&P(t,o)&&o.id===r)return n.push(o),n}else{if(d[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((r=d[3])&&_.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(r)),n}if(_.qsa&&!j[e+" "]&&(!M||!M.test(e))){if(1!==m)p=t,f=e;else if("object"!==t.nodeName.toLowerCase()){for((s=t.getAttribute("id"))?s=s.replace(ve,"\\$&"):t.setAttribute("id",s=L),h=S(e),a=h.length,u=ce.test(s)?"#"+s:"[id='"+s+"']";a--;)h[a]=u+" "+c(h[a]);f=h.join(","),p=ge.test(e)&&l(t.parentNode)||t}if(f)try{return Z.apply(n,p.querySelectorAll(f)),n}catch(e){}finally{s===L&&t.removeAttribute("id")}}}return C(e.replace(ae,"$1"),t,n,i)}function n(){function e(n,i){return t.push(n+" ")>b.cacheLength&&delete e[t.shift()],e[n+" "]=i}var t=[];return e}function i(e){return e[L]=!0,e}function r(e){var t=A.createElement("div");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function a(e,t){for(var n=e.split("|"),i=n.length;i--;)b.attrHandle[n[i]]=t}function o(e,t){var n=t&&e,i=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||W)-(~e.sourceIndex||W);if(i)return i;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return i(function(t){return t=+t,i(function(n,i){for(var r,a=e([],n.length,t),o=a.length;o--;)n[r=a[o]]&&(n[r]=!(i[r]=n[r]))})})}function l(e){return e&&void 0!==e.getElementsByTagName&&e}function u(){}function c(e){for(var t=0,n=e.length,i="";n>t;t++)i+=e[t].value;return i}function d(e,t,n){var i=t.dir,r=n&&"parentNode"===i,a=Y++;return t.first?function(t,n,a){for(;t=t[i];)if(1===t.nodeType||r)return e(t,n,a)}:function(t,n,o){var s,l,u,c=[F,a];if(o){for(;t=t[i];)if((1===t.nodeType||r)&&e(t,n,o))return!0}else for(;t=t[i];)if(1===t.nodeType||r){if(u=t[L]||(t[L]={}),l=u[t.uniqueID]||(u[t.uniqueID]={}),(s=l[i])&&s[0]===F&&s[1]===a)return c[2]=s[2];if(l[i]=c,c[2]=e(t,n,o))return!0}}}function h(e){return e.length>1?function(t,n,i){for(var r=e.length;r--;)if(!e[r](t,n,i))return!1;return!0}:e[0]}function f(e,n,i){for(var r=0,a=n.length;a>r;r++)t(e,n[r],i);return i}function p(e,t,n,i,r){for(var a,o=[],s=0,l=e.length,u=null!=t;l>s;s++)(a=e[s])&&(!n||n(a,i,r))&&(o.push(a),u&&t.push(s));return o}function m(e,t,n,r,a,o){return r&&!r[L]&&(r=m(r)),a&&!a[L]&&(a=m(a,o)),i(function(i,o,s,l){var u,c,d,h=[],m=[],g=o.length,v=i||f(t||"*",s.nodeType?[s]:s,[]),y=!e||!i&&t?v:p(v,h,e,s,l),_=n?a||(i?e:g||r)?[]:o:y;if(n&&n(y,_,s,l),r)for(u=p(_,m),r(u,[],s,l),c=u.length;c--;)(d=u[c])&&(_[m[c]]=!(y[m[c]]=d));if(i){if(a||e){if(a){for(u=[],c=_.length;c--;)(d=_[c])&&u.push(y[c]=d);a(null,_=[],u,l)}for(c=_.length;c--;)(d=_[c])&&(u=a?Q(i,d):h[c])>-1&&(i[u]=!(o[u]=d))}}else _=p(_===o?_.splice(g,_.length):_),a?a(null,o,_,l):Z.apply(o,_)})}function g(e){for(var t,n,i,r=e.length,a=b.relative[e[0].type],o=a||b.relative[" "],s=a?1:0,l=d(function(e){return e===t},o,!0),u=d(function(e){return Q(t,e)>-1},o,!0),f=[function(e,n,i){var r=!a&&(i||n!==D)||((t=n).nodeType?l(e,n,i):u(e,n,i));return t=null,r}];r>s;s++)if(n=b.relative[e[s].type])f=[d(h(f),n)];else{if(n=b.filter[e[s].type].apply(null,e[s].matches),n[L]){for(i=++s;r>i&&!b.relative[e[i].type];i++);return m(s>1&&h(f),s>1&&c(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(ae,"$1"),n,i>s&&g(e.slice(s,i)),r>i&&g(e=e.slice(i)),r>i&&c(e))}f.push(n)}return h(f)}function v(e,n){var r=n.length>0,a=e.length>0,o=function(i,o,s,l,u){var c,d,h,f=0,m="0",g=i&&[],v=[],y=D,_=i||a&&b.find.TAG("*",u),$=F+=null==y?1:Math.random()||.1,w=_.length;for(u&&(D=o===A||o||u);m!==w&&null!=(c=_[m]);m++){if(a&&c){for(d=0,o||c.ownerDocument===A||(E(c),s=!N);h=e[d++];)if(h(c,o||A,s)){l.push(c);break}u&&(F=$)}r&&((c=!h&&c)&&f--,i&&g.push(c))}if(f+=m,r&&m!==f){for(d=0;h=n[d++];)h(g,v,o,s);if(i){if(f>0)for(;m--;)g[m]||v[m]||(v[m]=G.call(l));v=p(v)}Z.apply(l,v),u&&!i&&v.length>0&&f+n.length>1&&t.uniqueSort(l)}return u&&(F=$,D=y),g};return r?i(o):o}var y,_,b,$,w,S,T,C,D,k,x,E,A,O,N,M,I,R,P,L="sizzle"+1*new Date,H=e.document,F=0,Y=0,V=n(),q=n(),j=n(),B=function(e,t){return e===t&&(x=!0),0},W=1<<31,U={}.hasOwnProperty,z=[],G=z.pop,X=z.push,Z=z.push,K=z.slice,Q=function(e,t){for(var n=0,i=e.length;i>n;n++)if(e[n]===t)return n;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ee="[\\x20\\t\\r\\n\\f]",te="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ne="\\["+ee+"*("+te+")(?:"+ee+"*([*^$|!~]?=)"+ee+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+te+"))|)"+ee+"*\\]",ie=":("+te+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ne+")*)|.*)\\)|)",re=new RegExp(ee+"+","g"),ae=new RegExp("^"+ee+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ee+"+$","g"),oe=new RegExp("^"+ee+"*,"+ee+"*"),se=new RegExp("^"+ee+"*([>+~]|"+ee+")"+ee+"*"),le=new RegExp("="+ee+"*([^\\]'\"]*?)"+ee+"*\\]","g"),ue=new RegExp(ie),ce=new RegExp("^"+te+"$"),de={ID:new RegExp("^#("+te+")"),CLASS:new RegExp("^\\.("+te+")"),TAG:new RegExp("^("+te+"|[*])"),ATTR:new RegExp("^"+ne),PSEUDO:new RegExp("^"+ie),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ee+"*(even|odd|(([+-]|)(\\d*)n|)"+ee+"*(?:([+-]|)"+ee+"*(\\d+)|))"+ee+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+ee+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ee+"*((?:-\\d)?\\d*)"+ee+"*\\)|)(?=[^-]|$)","i")},he=/^(?:input|select|textarea|button)$/i,fe=/^h\d$/i,pe=/^[^{]+\{\s*\[native \w/,me=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ge=/[+~]/,ve=/'|\\/g,ye=new RegExp("\\\\([\\da-f]{1,6}"+ee+"?|("+ee+")|.)","ig"),_e=function(e,t,n){var i="0x"+t-65536;return i!==i||n?t:0>i?String.fromCharCode(i+65536):String.fromCharCode(i>>10|55296,1023&i|56320)},be=function(){E()};try{Z.apply(z=K.call(H.childNodes),H.childNodes),z[H.childNodes.length].nodeType}catch(e){Z={apply:z.length?function(e,t){X.apply(e,K.call(t))}:function(e,t){for(var n=e.length,i=0;e[n++]=t[i++];);e.length=n-1}}}_=t.support={},w=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},E=t.setDocument=function(e){var t,n,i=e?e.ownerDocument||e:H;return i!==A&&9===i.nodeType&&i.documentElement?(A=i,O=A.documentElement,N=!w(A),(n=A.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",be,!1):n.attachEvent&&n.attachEvent("onunload",be)),_.attributes=r(function(e){return e.className="i",!e.getAttribute("className")}),_.getElementsByTagName=r(function(e){return e.appendChild(A.createComment("")),!e.getElementsByTagName("*").length}),_.getElementsByClassName=pe.test(A.getElementsByClassName),_.getById=r(function(e){return O.appendChild(e).id=L,!A.getElementsByName||!A.getElementsByName(L).length}),_.getById?(b.find.ID=function(e,t){if(void 0!==t.getElementById&&N){var n=t.getElementById(e);return n?[n]:[]}},b.filter.ID=function(e){var t=e.replace(ye,_e);return function(e){return e.getAttribute("id")===t}}):(delete b.find.ID,b.filter.ID=function(e){var t=e.replace(ye,_e);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),b.find.TAG=_.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):_.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,i=[],r=0,a=t.getElementsByTagName(e);if("*"===e){for(;n=a[r++];)1===n.nodeType&&i.push(n);return i}return a},b.find.CLASS=_.getElementsByClassName&&function(e,t){return void 0!==t.getElementsByClassName&&N?t.getElementsByClassName(e):void 0},I=[],M=[],(_.qsa=pe.test(A.querySelectorAll))&&(r(function(e){O.appendChild(e).innerHTML="<a id='"+L+"'></a><select id='"+L+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+ee+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+ee+"*(?:value|"+J+")"),e.querySelectorAll("[id~="+L+"-]").length||M.push("~="),e.querySelectorAll(":checked").length||M.push(":checked"),e.querySelectorAll("a#"+L+"+*").length||M.push(".#.+[+~]")}),r(function(e){var t=A.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+ee+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(_.matchesSelector=pe.test(R=O.matches||O.webkitMatchesSelector||O.mozMatchesSelector||O.oMatchesSelector||O.msMatchesSelector))&&r(function(e){_.disconnectedMatch=R.call(e,"div"),R.call(e,"[s!='']:x"),I.push("!=",ie)}),M=M.length&&new RegExp(M.join("|")),I=I.length&&new RegExp(I.join("|")),t=pe.test(O.compareDocumentPosition),P=t||pe.test(O.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},B=t?function(e,t){if(e===t)return x=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!_.sortDetached&&t.compareDocumentPosition(e)===n?e===A||e.ownerDocument===H&&P(H,e)?-1:t===A||t.ownerDocument===H&&P(H,t)?1:k?Q(k,e)-Q(k,t):0:4&n?-1:1)}:function(e,t){if(e===t)return x=!0,0;var n,i=0,r=e.parentNode,a=t.parentNode,s=[e],l=[t];if(!r||!a)return e===A?-1:t===A?1:r?-1:a?1:k?Q(k,e)-Q(k,t):0;if(r===a)return o(e,t);for(n=e;n=n.parentNode;)s.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;s[i]===l[i];)i++;return i?o(s[i],l[i]):s[i]===H?-1:l[i]===H?1:0},A):A},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==A&&E(e),n=n.replace(le,"='$1']"),_.matchesSelector&&N&&!j[n+" "]&&(!I||!I.test(n))&&(!M||!M.test(n)))try{var i=R.call(e,n);if(i||_.disconnectedMatch||e.document&&11!==e.document.nodeType)return i}catch(e){}return t(n,A,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==A&&E(e),P(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==A&&E(e);var n=b.attrHandle[t.toLowerCase()],i=n&&U.call(b.attrHandle,t.toLowerCase())?n(e,t,!N):void 0;return void 0!==i?i:_.attributes||!N?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],i=0,r=0;if(x=!_.detectDuplicates,k=!_.sortStable&&e.slice(0),e.sort(B),x){for(;t=e[r++];)t===e[r]&&(i=n.push(r));for(;i--;)e.splice(n[i],1)}return k=null,e},$=t.getText=function(e){var t,n="",i=0,r=e.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=$(e)}else if(3===r||4===r)return e.nodeValue}else for(;t=e[i++];)n+=$(t);return n},b=t.selectors={cacheLength:50,createPseudo:i,match:de,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(ye,_e),e[3]=(e[3]||e[4]||e[5]||"").replace(ye,_e),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return de.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ue.test(n)&&(t=S(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(ye,_e).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=V[e+" "];return t||(t=new RegExp("(^|"+ee+")"+e+"("+ee+"|$)"))&&V(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,i){return function(r){var a=t.attr(r,e);return null==a?"!="===n:!n||(a+="","="===n?a===i:"!="===n?a!==i:"^="===n?i&&0===a.indexOf(i):"*="===n?i&&a.indexOf(i)>-1:"$="===n?i&&a.slice(-i.length)===i:"~="===n?(" "+a.replace(re," ")+" ").indexOf(i)>-1:"|="===n&&(a===i||a.slice(0,i.length+1)===i+"-"))}},CHILD:function(e,t,n,i,r){var a="nth"!==e.slice(0,3),o="last"!==e.slice(-4),s="of-type"===t;return 1===i&&0===r?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,h,f,p,m=a!==o?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s,_=!1;if(g){if(a){for(;m;){for(h=t;h=h[m];)if(s?h.nodeName.toLowerCase()===v:1===h.nodeType)return!1;p=m="only"===e&&!p&&"nextSibling"}return!0}if(p=[o?g.firstChild:g.lastChild],o&&y){for(h=g,d=h[L]||(h[L]={}),c=d[h.uniqueID]||(d[h.uniqueID]={}),u=c[e]||[],f=u[0]===F&&u[1],_=f&&u[2],h=f&&g.childNodes[f];h=++f&&h&&h[m]||(_=f=0)||p.pop();)if(1===h.nodeType&&++_&&h===t){c[e]=[F,f,_];break}}else if(y&&(h=t,d=h[L]||(h[L]={}),c=d[h.uniqueID]||(d[h.uniqueID]={}),u=c[e]||[],f=u[0]===F&&u[1],_=f),!1===_)for(;(h=++f&&h&&h[m]||(_=f=0)||p.pop())&&((s?h.nodeName.toLowerCase()!==v:1!==h.nodeType)||!++_||(y&&(d=h[L]||(h[L]={}),c=d[h.uniqueID]||(d[h.uniqueID]={}),c[e]=[F,_]),h!==t)););return(_-=r)===i||_%i==0&&_/i>=0}}},PSEUDO:function(e,n){var r,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return a[L]?a(n):a.length>1?(r=[e,e,"",n],b.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,t){for(var i,r=a(e,n),o=r.length;o--;)i=Q(e,r[o]),e[i]=!(t[i]=r[o])}):function(e){return a(e,0,r)}):a}},pseudos:{not:i(function(e){var t=[],n=[],r=T(e.replace(ae,"$1"));return r[L]?i(function(e,t,n,i){
for(var a,o=r(e,null,i,[]),s=e.length;s--;)(a=o[s])&&(e[s]=!(t[s]=a))}):function(e,i,a){return t[0]=e,r(t,null,a,n),t[0]=null,!n.pop()}}),has:i(function(e){return function(n){return t(e,n).length>0}}),contains:i(function(e){return e=e.replace(ye,_e),function(t){return(t.textContent||t.innerText||$(t)).indexOf(e)>-1}}),lang:i(function(e){return ce.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(ye,_e).toLowerCase(),function(t){var n;do{if(n=N?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===O},focus:function(e){return e===A.activeElement&&(!A.hasFocus||A.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return!1===e.disabled},disabled:function(e){return!0===e.disabled},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return fe.test(e.nodeName)},input:function(e){return he.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:s(function(){return[0]}),last:s(function(e,t){return[t-1]}),eq:s(function(e,t,n){return[0>n?n+t:n]}),even:s(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:s(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:s(function(e,t,n){for(var i=0>n?n+t:n;--i>=0;)e.push(i);return e}),gt:s(function(e,t,n){for(var i=0>n?n+t:n;++i<t;)e.push(i);return e})}},b.pseudos.nth=b.pseudos.eq;for(y in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[y]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(y);for(y in{submit:!0,reset:!0})b.pseudos[y]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(y);return u.prototype=b.filters=b.pseudos,b.setFilters=new u,S=t.tokenize=function(e,n){var i,r,a,o,s,l,u,c=q[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=b.preFilter;s;){(!i||(r=oe.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(a=[])),i=!1,(r=se.exec(s))&&(i=r.shift(),a.push({value:i,type:r[0].replace(ae," ")}),s=s.slice(i.length));for(o in b.filter)!(r=de[o].exec(s))||u[o]&&!(r=u[o](r))||(i=r.shift(),a.push({value:i,type:o,matches:r}),s=s.slice(i.length));if(!i)break}return n?s.length:s?t.error(e):q(e,l).slice(0)},T=t.compile=function(e,t){var n,i=[],r=[],a=j[e+" "];if(!a){for(t||(t=S(e)),n=t.length;n--;)a=g(t[n]),a[L]?i.push(a):r.push(a);a=j(e,v(r,i)),a.selector=e}return a},C=t.select=function(e,t,n,i){var r,a,o,s,u,d="function"==typeof e&&e,h=!i&&S(e=d.selector||e);if(n=n||[],1===h.length){if(a=h[0]=h[0].slice(0),a.length>2&&"ID"===(o=a[0]).type&&_.getById&&9===t.nodeType&&N&&b.relative[a[1].type]){if(!(t=(b.find.ID(o.matches[0].replace(ye,_e),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}for(r=de.needsContext.test(e)?0:a.length;r--&&(o=a[r],!b.relative[s=o.type]);)if((u=b.find[s])&&(i=u(o.matches[0].replace(ye,_e),ge.test(a[0].type)&&l(t.parentNode)||t))){if(a.splice(r,1),!(e=i.length&&c(a)))return Z.apply(n,i),n;break}}return(d||T(e,h))(i,t,!N,n,!t||ge.test(e)&&l(t.parentNode)||t),n},_.sortStable=L.split("").sort(B).join("")===L,_.detectDuplicates=!!x,E(),_.sortDetached=r(function(e){return 1&e.compareDocumentPosition(A.createElement("div"))}),r(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||a("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),_.attributes&&r(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||a("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),r(function(e){return null==e.getAttribute("disabled")})||a(J,function(e,t,n){var i;return n?void 0:!0===e[t]?t.toLowerCase():(i=e.getAttributeNode(t))&&i.specified?i.value:null}),t}(e);fe.find=ye,fe.expr=ye.selectors,fe.expr[":"]=fe.expr.pseudos,fe.uniqueSort=fe.unique=ye.uniqueSort,fe.text=ye.getText,fe.isXMLDoc=ye.isXML,fe.contains=ye.contains;var _e=function(e,t,n){for(var i=[],r=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(r&&fe(e).is(n))break;i.push(e)}return i},be=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},$e=fe.expr.match.needsContext,we=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,Se=/^.[^:#\[\.,]*$/;fe.filter=function(e,t,n){var i=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===i.nodeType?fe.find.matchesSelector(i,e)?[i]:[]:fe.find.matches(e,fe.grep(t,function(e){return 1===e.nodeType}))},fe.fn.extend({find:function(e){var t,n=[],i=this,r=i.length;if("string"!=typeof e)return this.pushStack(fe(e).filter(function(){for(t=0;r>t;t++)if(fe.contains(i[t],this))return!0}));for(t=0;r>t;t++)fe.find(e,i[t],n);return n=this.pushStack(r>1?fe.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(i(this,e||[],!1))},not:function(e){return this.pushStack(i(this,e||[],!0))},is:function(e){return!!i(this,"string"==typeof e&&$e.test(e)?fe(e):e||[],!1).length}});var Te,Ce=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/;(fe.fn.init=function(e,t,n){var i,r;if(!e)return this;if(n=n||Te,"string"==typeof e){if(!(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:Ce.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof fe?t[0]:t,fe.merge(this,fe.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:ie,!0)),we.test(i[1])&&fe.isPlainObject(t))for(i in t)fe.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}if((r=ie.getElementById(i[2]))&&r.parentNode){if(r.id!==i[2])return Te.find(e);this.length=1,this[0]=r}return this.context=ie,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):fe.isFunction(e)?void 0!==n.ready?n.ready(e):e(fe):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),fe.makeArray(e,this))}).prototype=fe.fn,Te=fe(ie);var De=/^(?:parents|prev(?:Until|All))/,ke={children:!0,contents:!0,next:!0,prev:!0};fe.fn.extend({has:function(e){var t,n=fe(e,this),i=n.length;return this.filter(function(){for(t=0;i>t;t++)if(fe.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,i=0,r=this.length,a=[],o=$e.test(e)||"string"!=typeof e?fe(e,t||this.context):0;r>i;i++)for(n=this[i];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(o?o.index(n)>-1:1===n.nodeType&&fe.find.matchesSelector(n,e))){a.push(n);break}return this.pushStack(a.length>1?fe.uniqueSort(a):a)},index:function(e){return e?"string"==typeof e?fe.inArray(this[0],fe(e)):fe.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(fe.uniqueSort(fe.merge(this.get(),fe(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),fe.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return _e(e,"parentNode")},parentsUntil:function(e,t,n){return _e(e,"parentNode",n)},next:function(e){return r(e,"nextSibling")},prev:function(e){return r(e,"previousSibling")},nextAll:function(e){return _e(e,"nextSibling")},prevAll:function(e){return _e(e,"previousSibling")},nextUntil:function(e,t,n){return _e(e,"nextSibling",n)},prevUntil:function(e,t,n){return _e(e,"previousSibling",n)},siblings:function(e){return be((e.parentNode||{}).firstChild,e)},children:function(e){return be(e.firstChild)},contents:function(e){return fe.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:fe.merge([],e.childNodes)}},function(e,t){fe.fn[e]=function(n,i){var r=fe.map(this,t,n);return"Until"!==e.slice(-5)&&(i=n),i&&"string"==typeof i&&(r=fe.filter(i,r)),this.length>1&&(ke[e]||(r=fe.uniqueSort(r)),De.test(e)&&(r=r.reverse())),this.pushStack(r)}});var xe=/\S+/g;fe.Callbacks=function(e){e="string"==typeof e?a(e):fe.extend({},e);var t,n,i,r,o=[],s=[],l=-1,u=function(){for(r=e.once,i=t=!0;s.length;l=-1)for(n=s.shift();++l<o.length;)!1===o[l].apply(n[0],n[1])&&e.stopOnFalse&&(l=o.length,n=!1);e.memory||(n=!1),t=!1,r&&(o=n?[]:"")},c={add:function(){return o&&(n&&!t&&(l=o.length-1,s.push(n)),function t(n){fe.each(n,function(n,i){fe.isFunction(i)?e.unique&&c.has(i)||o.push(i):i&&i.length&&"string"!==fe.type(i)&&t(i)})}(arguments),n&&!t&&u()),this},remove:function(){return fe.each(arguments,function(e,t){for(var n;(n=fe.inArray(t,o,n))>-1;)o.splice(n,1),l>=n&&l--}),this},has:function(e){return e?fe.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return r=s=[],o=n="",this},disabled:function(){return!o},lock:function(){return r=!0,n||c.disable(),this},locked:function(){return!!r},fireWith:function(e,n){return r||(n=n||[],n=[e,n.slice?n.slice():n],s.push(n),t||u()),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!i}};return c},fe.extend({Deferred:function(e){var t=[["resolve","done",fe.Callbacks("once memory"),"resolved"],["reject","fail",fe.Callbacks("once memory"),"rejected"],["notify","progress",fe.Callbacks("memory")]],n="pending",i={state:function(){return n},always:function(){return r.done(arguments).fail(arguments),this},then:function(){var e=arguments;return fe.Deferred(function(n){fe.each(t,function(t,a){var o=fe.isFunction(e[t])&&e[t];r[a[1]](function(){var e=o&&o.apply(this,arguments);e&&fe.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[a[0]+"With"](this===i?n.promise():this,o?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?fe.extend(e,i):i}},r={};return i.pipe=i.then,fe.each(t,function(e,a){var o=a[2],s=a[3];i[a[1]]=o.add,s&&o.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),r[a[0]]=function(){return r[a[0]+"With"](this===r?i:this,arguments),this},r[a[0]+"With"]=o.fireWith}),i.promise(r),e&&e.call(r,r),r},when:function(e){var t,n,i,r=0,a=re.call(arguments),o=a.length,s=1!==o||e&&fe.isFunction(e.promise)?o:0,l=1===s?e:fe.Deferred(),u=function(e,n,i){return function(r){n[e]=this,i[e]=arguments.length>1?re.call(arguments):r,i===t?l.notifyWith(n,i):--s||l.resolveWith(n,i)}};if(o>1)for(t=new Array(o),n=new Array(o),i=new Array(o);o>r;r++)a[r]&&fe.isFunction(a[r].promise)?a[r].promise().progress(u(r,n,t)).done(u(r,i,a)).fail(l.reject):--s;return s||l.resolveWith(i,a),l.promise()}});var Ee;fe.fn.ready=function(e){return fe.ready.promise().done(e),this},fe.extend({isReady:!1,readyWait:1,holdReady:function(e){e?fe.readyWait++:fe.ready(!0)},ready:function(e){(!0===e?--fe.readyWait:fe.isReady)||(fe.isReady=!0,!0!==e&&--fe.readyWait>0||(Ee.resolveWith(ie,[fe]),fe.fn.triggerHandler&&(fe(ie).triggerHandler("ready"),fe(ie).off("ready"))))}}),fe.ready.promise=function(t){if(!Ee)if(Ee=fe.Deferred(),"complete"===ie.readyState||"loading"!==ie.readyState&&!ie.documentElement.doScroll)e.setTimeout(fe.ready);else if(ie.addEventListener)ie.addEventListener("DOMContentLoaded",s),e.addEventListener("load",s);else{ie.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&ie.documentElement}catch(e){}n&&n.doScroll&&function t(){if(!fe.isReady){try{n.doScroll("left")}catch(n){return e.setTimeout(t,50)}o(),fe.ready()}}()}return Ee.promise(t)},fe.ready.promise();var Ae;for(Ae in fe(de))break;de.ownFirst="0"===Ae,de.inlineBlockNeedsLayout=!1,fe(function(){var e,t,n,i;(n=ie.getElementsByTagName("body")[0])&&n.style&&(t=ie.createElement("div"),i=ie.createElement("div"),i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(i).appendChild(t),void 0!==t.style.zoom&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",de.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(i))}),function(){var e=ie.createElement("div");de.deleteExpando=!0;try{delete e.test}catch(e){de.deleteExpando=!1}e=null}();var Oe=function(e){var t=fe.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return(1===n||9===n)&&(!t||!0!==t&&e.getAttribute("classid")===t)},Ne=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Me=/([A-Z])/g;fe.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return!!(e=e.nodeType?fe.cache[e[fe.expando]]:e[fe.expando])&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),fe.fn.extend({data:function(e,t){var n,i,r,a=this[0],o=a&&a.attributes;if(void 0===e){if(this.length&&(r=fe.data(a),1===a.nodeType&&!fe._data(a,"parsedAttrs"))){for(n=o.length;n--;)o[n]&&(i=o[n].name,0===i.indexOf("data-")&&(i=fe.camelCase(i.slice(5)),l(a,i,r[i])));fe._data(a,"parsedAttrs",!0)}return r}return"object"==(void 0===e?"undefined":_typeof(e))?this.each(function(){fe.data(this,e)}):arguments.length>1?this.each(function(){fe.data(this,e,t)}):a?l(a,e,fe.data(a,e)):void 0},removeData:function(e){return this.each(function(){fe.removeData(this,e)})}}),fe.extend({queue:function(e,t,n){var i;return e?(t=(t||"fx")+"queue",i=fe._data(e,t),n&&(!i||fe.isArray(n)?i=fe._data(e,t,fe.makeArray(n)):i.push(n)),i||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=fe.queue(e,t),i=n.length,r=n.shift(),a=fe._queueHooks(e,t),o=function(){fe.dequeue(e,t)};"inprogress"===r&&(r=n.shift(),i--),r&&("fx"===t&&n.unshift("inprogress"),delete a.stop,r.call(e,o,a)),!i&&a&&a.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return fe._data(e,n)||fe._data(e,n,{empty:fe.Callbacks("once memory").add(function(){fe._removeData(e,t+"queue"),fe._removeData(e,n)})})}}),fe.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?fe.queue(this[0],e):void 0===t?this:this.each(function(){var n=fe.queue(this,e,t);fe._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&fe.dequeue(this,e)})},dequeue:function(e){return this.each(function(){fe.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,i=1,r=fe.Deferred(),a=this,o=this.length,s=function(){--i||r.resolveWith(a,[a])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";o--;)(n=fe._data(a[o],e+"queueHooks"))&&n.empty&&(i++,n.empty.add(s));return s(),r.promise(t)}}),function(){var e;de.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,i;return n=ie.getElementsByTagName("body")[0],n&&n.style?(t=ie.createElement("div"),i=ie.createElement("div"),i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(i).appendChild(t),void 0!==t.style.zoom&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ie.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(i),e):void 0}}();var Ie=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Re=new RegExp("^(?:([+-])=|)("+Ie+")([a-z%]*)$","i"),Pe=["Top","Right","Bottom","Left"],Le=function(e,t){return e=t||e,"none"===fe.css(e,"display")||!fe.contains(e.ownerDocument,e)},He=function e(t,n,i,r,a,o,s){var l=0,u=t.length,c=null==i;if("object"===fe.type(i)){a=!0;for(l in i)e(t,n,l,i[l],!0,o,s)}else if(void 0!==r&&(a=!0,fe.isFunction(r)||(s=!0),c&&(s?(n.call(t,r),n=null):(c=n,n=function(e,t,n){return c.call(fe(e),n)})),n))for(;u>l;l++)n(t[l],i,s?r:r.call(t[l],l,n(t[l],i)));return a?t:c?n.call(t):u?n(t[0],i):o},Fe=/^(?:checkbox|radio)$/i,Ye=/<([\w:-]+)/,Ve=/^$|\/(?:java|ecma)script/i,qe=/^\s+/,je="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";!function(){var e=ie.createElement("div"),t=ie.createDocumentFragment(),n=ie.createElement("input");e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",de.leadingWhitespace=3===e.firstChild.nodeType,de.tbody=!e.getElementsByTagName("tbody").length,de.htmlSerialize=!!e.getElementsByTagName("link").length,de.html5Clone="<:nav></:nav>"!==ie.createElement("nav").cloneNode(!0).outerHTML,n.type="checkbox",n.checked=!0,t.appendChild(n),de.appendChecked=n.checked,e.innerHTML="<textarea>x</textarea>",de.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue,t.appendChild(e),n=ie.createElement("input"),n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),e.appendChild(n),de.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,de.noCloneEvent=!!e.addEventListener,e[fe.expando]=1,de.attributes=!e.getAttribute(fe.expando)}();var Be={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:de.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};Be.optgroup=Be.option,Be.tbody=Be.tfoot=Be.colgroup=Be.caption=Be.thead,Be.th=Be.td;var We=/<|&#?\w+;/,Ue=/<tbody/i;!function(){var t,n,i=ie.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(de[t]=n in e)||(i.setAttribute(n,"t"),de[t]=!1===i.attributes[n].expando);i=null}();var ze=/^(?:input|select|textarea)$/i,Ge=/^key/,Xe=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ze=/^(?:focusinfocus|focusoutblur)$/,Ke=/^([^.]*)(?:\.(.+)|)/;fe.event={global:{},add:function(e,t,n,i,r){var a,o,s,l,u,c,d,h,f,p,m,g=fe._data(e);if(g){for(n.handler&&(l=n,n=l.handler,r=l.selector),n.guid||(n.guid=fe.guid++),(o=g.events)||(o=g.events={}),(c=g.handle)||(c=g.handle=function(e){return void 0===fe||e&&fe.event.triggered===e.type?void 0:fe.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(xe)||[""],s=t.length;s--;)a=Ke.exec(t[s])||[],f=m=a[1],p=(a[2]||"").split(".").sort(),f&&(u=fe.event.special[f]||{},f=(r?u.delegateType:u.bindType)||f,u=fe.event.special[f]||{},d=fe.extend({type:f,origType:m,data:i,handler:n,guid:n.guid,selector:r,needsContext:r&&fe.expr.match.needsContext.test(r),namespace:p.join(".")},l),(h=o[f])||(h=o[f]=[],h.delegateCount=0,u.setup&&!1!==u.setup.call(e,i,p,c)||(e.addEventListener?e.addEventListener(f,c,!1):e.attachEvent&&e.attachEvent("on"+f,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),r?h.splice(h.delegateCount++,0,d):h.push(d),fe.event.global[f]=!0);e=null}},remove:function(e,t,n,i,r){var a,o,s,l,u,c,d,h,f,p,m,g=fe.hasData(e)&&fe._data(e);if(g&&(c=g.events)){for(t=(t||"").match(xe)||[""],u=t.length;u--;)if(s=Ke.exec(t[u])||[],f=m=s[1],p=(s[2]||"").split(".").sort(),f){for(d=fe.event.special[f]||{},f=(i?d.delegateType:d.bindType)||f,h=c[f]||[],s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=a=h.length;a--;)o=h[a],!r&&m!==o.origType||n&&n.guid!==o.guid||s&&!s.test(o.namespace)||i&&i!==o.selector&&("**"!==i||!o.selector)||(h.splice(a,1),o.selector&&h.delegateCount--,d.remove&&d.remove.call(e,o));l&&!h.length&&(d.teardown&&!1!==d.teardown.call(e,p,g.handle)||fe.removeEvent(e,f,g.handle),delete c[f])}else for(f in c)fe.event.remove(e,f+t[u],n,i,!0);fe.isEmptyObject(c)&&(delete g.handle,fe._removeData(e,"events"))}},trigger:function(t,n,i,r){var a,o,s,l,u,c,d,h=[i||ie],f=ce.call(t,"type")?t.type:t,p=ce.call(t,"namespace")?t.namespace.split("."):[];if(s=c=i=i||ie,3!==i.nodeType&&8!==i.nodeType&&!Ze.test(f+fe.event.triggered)&&(f.indexOf(".")>-1&&(p=f.split("."),f=p.shift(),p.sort()),o=f.indexOf(":")<0&&"on"+f,t=t[fe.expando]?t:new fe.Event(f,"object"==(void 0===t?"undefined":_typeof(t))&&t),t.isTrigger=r?2:3,t.namespace=p.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:fe.makeArray(n,[t]),u=fe.event.special[f]||{},r||!u.trigger||!1!==u.trigger.apply(i,n))){if(!r&&!u.noBubble&&!fe.isWindow(i)){for(l=u.delegateType||f,Ze.test(l+f)||(s=s.parentNode);s;s=s.parentNode)h.push(s),c=s;c===(i.ownerDocument||ie)&&h.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=h[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||f,a=(fe._data(s,"events")||{})[t.type]&&fe._data(s,"handle"),a&&a.apply(s,n),(a=o&&s[o])&&a.apply&&Oe(s)&&(t.result=a.apply(s,n),!1===t.result&&t.preventDefault());if(t.type=f,!r&&!t.isDefaultPrevented()&&(!u._default||!1===u._default.apply(h.pop(),n))&&Oe(i)&&o&&i[f]&&!fe.isWindow(i)){c=i[o],c&&(i[o]=null),fe.event.triggered=f;try{i[f]()}catch(e){}fe.event.triggered=void 0,c&&(i[o]=c)}return t.result}},dispatch:function(e){e=fe.event.fix(e);var t,n,i,r,a,o=[],s=re.call(arguments),l=(fe._data(this,"events")||{})[e.type]||[],u=fe.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||!1!==u.preDispatch.call(this,e)){for(o=fe.event.handlers.call(this,e,l),t=0;(r=o[t++])&&!e.isPropagationStopped();)for(e.currentTarget=r.elem,n=0;(a=r.handlers[n++])&&!e.isImmediatePropagationStopped();)(!e.rnamespace||e.rnamespace.test(a.namespace))&&(e.handleObj=a,e.data=a.data,void 0!==(i=((fe.event.special[a.origType]||{}).handle||a.handler).apply(r.elem,s))&&!1===(e.result=i)&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,i,r,a,o=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&("click"!==e.type||isNaN(e.button)||e.button<1))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(!0!==l.disabled||"click"!==e.type)){for(i=[],n=0;s>n;n++)a=t[n],r=a.selector+" ",void 0===i[r]&&(i[r]=a.needsContext?fe(r,this).index(l)>-1:fe.find(r,this,null,[l]).length),i[r]&&i.push(a);i.length&&o.push({elem:l,handlers:i})}return s<t.length&&o.push({elem:this,handlers:t.slice(s)}),o},fix:function(e){if(e[fe.expando])return e;var t,n,i,r=e.type,a=e,o=this.fixHooks[r];for(o||(this.fixHooks[r]=o=Xe.test(r)?this.mouseHooks:Ge.test(r)?this.keyHooks:{}),i=o.props?this.props.concat(o.props):this.props,e=new fe.Event(a),t=i.length;t--;)n=i[t],e[n]=a[n];return e.target||(e.target=a.srcElement||ie),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,o.filter?o.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,i,r,a=t.button,o=t.fromElement;return null==e.pageX&&null!=t.clientX&&(i=e.target.ownerDocument||ie,r=i.documentElement,n=i.body,e.pageX=t.clientX+(r&&r.scrollLeft||n&&n.scrollLeft||0)-(r&&r.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||n&&n.scrollTop||0)-(r&&r.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&o&&(e.relatedTarget=o===e.target?t.toElement:o),e.which||void 0===a||(e.which=1&a?1:2&a?3:4&a?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==b()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===b()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return fe.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return fe.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n){var i=fe.extend(new fe.Event,n,{type:e,isSimulated:!0});fe.event.trigger(i,null,t),i.isDefaultPrevented()&&n.preventDefault()}},fe.removeEvent=ie.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)}:function(e,t,n){var i="on"+t;e.detachEvent&&(void 0===e[i]&&(e[i]=null),e.detachEvent(i,n))},fe.Event=function(e,t){return this instanceof fe.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?y:_):this.type=e,t&&fe.extend(this,t),this.timeStamp=e&&e.timeStamp||fe.now(),void(this[fe.expando]=!0)):new fe.Event(e,t)},fe.Event.prototype={constructor:fe.Event,isDefaultPrevented:_,isPropagationStopped:_,isImmediatePropagationStopped:_,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=y,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=y,e&&!this.isSimulated&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=y,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},fe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){fe.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,i=this,r=e.relatedTarget,a=e.handleObj;return(!r||r!==i&&!fe.contains(i,r))&&(e.type=a.origType,n=a.handler.apply(this,arguments),e.type=t),n}}}),de.submit||(fe.event.special.submit={setup:function(){return!fe.nodeName(this,"form")&&void fe.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=fe.nodeName(t,"input")||fe.nodeName(t,"button")?fe.prop(t,"form"):void 0;n&&!fe._data(n,"submit")&&(fe.event.add(n,"submit._submit",function(e){e._submitBubble=!0}),fe._data(n,"submit",!0))})},postDispatch:function(e){e._submitBubble&&(delete e._submitBubble,this.parentNode&&!e.isTrigger&&fe.event.simulate("submit",this.parentNode,e))},teardown:function(){return!fe.nodeName(this,"form")&&void fe.event.remove(this,"._submit")}}),de.change||(fe.event.special.change={setup:function(){return ze.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(fe.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._justChanged=!0)}),fe.event.add(this,"click._change",function(e){this._justChanged&&!e.isTrigger&&(this._justChanged=!1),fe.event.simulate("change",this,e)})),!1):void fe.event.add(this,"beforeactivate._change",function(e){var t=e.target;ze.test(t.nodeName)&&!fe._data(t,"change")&&(fe.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||fe.event.simulate("change",this.parentNode,e)}),fe._data(t,"change",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return fe.event.remove(this,"._change"),!ze.test(this.nodeName)}}),de.focusin||fe.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){fe.event.simulate(t,e.target,fe.event.fix(e))};fe.event.special[t]={setup:function(){var i=this.ownerDocument||this,r=fe._data(i,t);r||i.addEventListener(e,n,!0),fe._data(i,t,(r||0)+1)},teardown:function(){var i=this.ownerDocument||this,r=fe._data(i,t)-1;r?fe._data(i,t,r):(i.removeEventListener(e,n,!0),fe._removeData(i,t))}}}),fe.fn.extend({on:function(e,t,n,i){return $(this,e,t,n,i)},one:function(e,t,n,i){return $(this,e,t,n,i,1)},off:function(e,t,n){var i,r;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,fe(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==(void 0===e?"undefined":_typeof(e))){for(r in e)this.off(r,t,e[r]);return this}return(!1===t||"function"==typeof t)&&(n=t,t=void 0),!1===n&&(n=_),this.each(function(){fe.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){fe.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?fe.event.trigger(e,t,n,!0):void 0}});var Qe=/ jQuery\d+="(?:null|\d+)"/g,Je=new RegExp("<(?:"+je+")[\\s/>]","i"),et=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,tt=/<script|<style|<link/i,nt=/checked\s*(?:[^=]|=\s*.checked.)/i,it=/^true\/(.*)/,rt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,at=f(ie),ot=at.appendChild(ie.createElement("div"));fe.extend({htmlPrefilter:function(e){return e.replace(et,"<$1></$2>")},clone:function(e,t,n){var i,r,a,o,s,l=fe.contains(e.ownerDocument,e);if(de.html5Clone||fe.isXMLDoc(e)||!Je.test("<"+e.nodeName+">")?a=e.cloneNode(!0):(ot.innerHTML=e.outerHTML,ot.removeChild(a=ot.firstChild)),!(de.noCloneEvent&&de.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||fe.isXMLDoc(e)))for(i=p(a),s=p(e),o=0;null!=(r=s[o]);++o)i[o]&&D(r,i[o]);if(t)if(n)for(s=s||p(e),i=i||p(a),o=0;null!=(r=s[o]);o++)C(r,i[o]);else C(e,a);return i=p(a,"script"),i.length>0&&m(i,!l&&p(e,"script")),i=s=r=null,a},cleanData:function(e,t){for(var n,i,r,a,o=0,s=fe.expando,l=fe.cache,u=de.attributes,c=fe.event.special;null!=(n=e[o]);o++)if((t||Oe(n))&&(r=n[s],a=r&&l[r])){if(a.events)for(i in a.events)c[i]?fe.event.remove(n,i):fe.removeEvent(n,i,a.handle);l[r]&&(delete l[r],u||void 0===n.removeAttribute?n[s]=void 0:n.removeAttribute(s),ne.push(r))}}}),fe.fn.extend({domManip:k,detach:function(e){return x(this,e,!0)},remove:function(e){return x(this,e)},text:function(e){return He(this,function(e){return void 0===e?fe.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ie).createTextNode(e))},null,e,arguments.length)},append:function(){return k(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){w(this,e).appendChild(e)}})},prepend:function(){return k(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=w(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return k(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return k(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&fe.cleanData(p(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&fe.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return fe.clone(this,e,t)})},html:function(e){return He(this,function(e){var t=this[0]||{},n=0,i=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Qe,""):void 0;if("string"==typeof e&&!tt.test(e)&&(de.htmlSerialize||!Je.test(e))&&(de.leadingWhitespace||!qe.test(e))&&!Be[(Ye.exec(e)||["",""])[1].toLowerCase()]){e=fe.htmlPrefilter(e);try{for(;i>n;n++)t=this[n]||{},1===t.nodeType&&(fe.cleanData(p(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return k(this,arguments,function(t){var n=this.parentNode;fe.inArray(this,e)<0&&(fe.cleanData(p(this)),n&&n.replaceChild(t,this))},e)}}),fe.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){fe.fn[e]=function(e){for(var n,i=0,r=[],a=fe(e),o=a.length-1;o>=i;i++)n=i===o?this:this.clone(!0),fe(a[i])[t](n),oe.apply(r,n.get());return this.pushStack(r)}});var st,lt={HTML:"block",BODY:"block"},ut=/^margin/,ct=new RegExp("^("+Ie+")(?!px)[a-z%]+$","i"),dt=function(e,t,n,i){var r,a,o={};for(a in t)o[a]=e.style[a],e.style[a]=t[a];r=n.apply(e,i||[]);for(a in t)e.style[a]=o[a];return r},ht=ie.documentElement;!function(){
var t,n,i,r,a,o,s=ie.createElement("div"),l=ie.createElement("div");if(l.style){var u=function(){var u,c,d=ie.documentElement;d.appendChild(s),l.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",t=i=o=!1,n=a=!0,e.getComputedStyle&&(c=e.getComputedStyle(l),t="1%"!==(c||{}).top,o="2px"===(c||{}).marginLeft,i="4px"===(c||{width:"4px"}).width,l.style.marginRight="50%",n="4px"===(c||{marginRight:"4px"}).marginRight,u=l.appendChild(ie.createElement("div")),u.style.cssText=l.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",u.style.marginRight=u.style.width="0",l.style.width="1px",a=!parseFloat((e.getComputedStyle(u)||{}).marginRight),l.removeChild(u)),l.style.display="none",r=0===l.getClientRects().length,r&&(l.style.display="",l.innerHTML="<table><tr><td></td><td>t</td></tr></table>",u=l.getElementsByTagName("td"),u[0].style.cssText="margin:0;border:0;padding:0;display:none",(r=0===u[0].offsetHeight)&&(u[0].style.display="",u[1].style.display="none",r=0===u[0].offsetHeight)),d.removeChild(s)};l.style.cssText="float:left;opacity:.5",de.opacity="0.5"===l.style.opacity,de.cssFloat=!!l.style.cssFloat,l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",de.clearCloneStyle="content-box"===l.style.backgroundClip,s=ie.createElement("div"),s.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",l.innerHTML="",s.appendChild(l),de.boxSizing=""===l.style.boxSizing||""===l.style.MozBoxSizing||""===l.style.WebkitBoxSizing,fe.extend(de,{reliableHiddenOffsets:function(){return null==t&&u(),r},boxSizingReliable:function(){return null==t&&u(),i},pixelMarginRight:function(){return null==t&&u(),n},pixelPosition:function(){return null==t&&u(),t},reliableMarginRight:function(){return null==t&&u(),a},reliableMarginLeft:function(){return null==t&&u(),o}})}}();var ft,pt,mt=/^(top|right|bottom|left)$/;e.getComputedStyle?(ft=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},pt=function(e,t,n){var i,r,a,o,s=e.style;return n=n||ft(e),o=n?n.getPropertyValue(t)||n[t]:void 0,""!==o&&void 0!==o||fe.contains(e.ownerDocument,e)||(o=fe.style(e,t)),n&&!de.pixelMarginRight()&&ct.test(o)&&ut.test(t)&&(i=s.width,r=s.minWidth,a=s.maxWidth,s.minWidth=s.maxWidth=s.width=o,o=n.width,s.width=i,s.minWidth=r,s.maxWidth=a),void 0===o?o:o+""}):ht.currentStyle&&(ft=function(e){return e.currentStyle},pt=function(e,t,n){var i,r,a,o,s=e.style;return n=n||ft(e),o=n?n[t]:void 0,null==o&&s&&s[t]&&(o=s[t]),ct.test(o)&&!mt.test(t)&&(i=s.left,r=e.runtimeStyle,a=r&&r.left,a&&(r.left=e.currentStyle.left),s.left="fontSize"===t?"1em":o,o=s.pixelLeft+"px",s.left=i,a&&(r.left=a)),void 0===o?o:o+""||"auto"});var gt=/alpha\([^)]*\)/i,vt=/opacity\s*=\s*([^)]*)/i,yt=/^(none|table(?!-c[ea]).+)/,_t=new RegExp("^("+Ie+")(.*)$","i"),bt={position:"absolute",visibility:"hidden",display:"block"},$t={letterSpacing:"0",fontWeight:"400"},wt=["Webkit","O","Moz","ms"],St=ie.createElement("div").style;fe.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=pt(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{float:de.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var r,a,o,s=fe.camelCase(t),l=e.style;if(t=fe.cssProps[s]||(fe.cssProps[s]=N(s)||s),o=fe.cssHooks[t]||fe.cssHooks[s],void 0===n)return o&&"get"in o&&void 0!==(r=o.get(e,!1,i))?r:l[t];if(a=void 0===n?"undefined":_typeof(n),"string"===a&&(r=Re.exec(n))&&r[1]&&(n=h(e,t,r),a="number"),null!=n&&n===n&&("number"===a&&(n+=r&&r[3]||(fe.cssNumber[s]?"":"px")),de.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(o&&"set"in o&&void 0===(n=o.set(e,n,i)))))try{l[t]=n}catch(e){}}},css:function(e,t,n,i){var r,a,o,s=fe.camelCase(t);return t=fe.cssProps[s]||(fe.cssProps[s]=N(s)||s),o=fe.cssHooks[t]||fe.cssHooks[s],o&&"get"in o&&(a=o.get(e,!0,n)),void 0===a&&(a=pt(e,t,i)),"normal"===a&&t in $t&&(a=$t[t]),""===n||n?(r=parseFloat(a),!0===n||isFinite(r)?r||0:a):a}}),fe.each(["height","width"],function(e,t){fe.cssHooks[t]={get:function(e,n,i){return n?yt.test(fe.css(e,"display"))&&0===e.offsetWidth?dt(e,bt,function(){return P(e,t,i)}):P(e,t,i):void 0},set:function(e,n,i){var r=i&&ft(e);return I(e,n,i?R(e,t,i,de.boxSizing&&"border-box"===fe.css(e,"boxSizing",!1,r),r):0)}}}),de.opacity||(fe.cssHooks.opacity={get:function(e,t){return vt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,i=e.currentStyle,r=fe.isNumeric(t)?"alpha(opacity="+100*t+")":"",a=i&&i.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===fe.trim(a.replace(gt,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||i&&!i.filter)||(n.filter=gt.test(a)?a.replace(gt,r):a+" "+r)}}),fe.cssHooks.marginRight=O(de.reliableMarginRight,function(e,t){return t?dt(e,{display:"inline-block"},pt,[e,"marginRight"]):void 0}),fe.cssHooks.marginLeft=O(de.reliableMarginLeft,function(e,t){return t?(parseFloat(pt(e,"marginLeft"))||(fe.contains(e.ownerDocument,e)?e.getBoundingClientRect().left-dt(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}):0))+"px":void 0}),fe.each({margin:"",padding:"",border:"Width"},function(e,t){fe.cssHooks[e+t]={expand:function(n){for(var i=0,r={},a="string"==typeof n?n.split(" "):[n];4>i;i++)r[e+Pe[i]+t]=a[i]||a[i-2]||a[0];return r}},ut.test(e)||(fe.cssHooks[e+t].set=I)}),fe.fn.extend({css:function(e,t){return He(this,function(e,t,n){var i,r,a={},o=0;if(fe.isArray(t)){for(i=ft(e),r=t.length;r>o;o++)a[t[o]]=fe.css(e,t[o],!1,i);return a}return void 0!==n?fe.style(e,t,n):fe.css(e,t)},e,t,arguments.length>1)},show:function(){return M(this,!0)},hide:function(){return M(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Le(this)?fe(this).show():fe(this).hide()})}}),fe.Tween=L,L.prototype={constructor:L,init:function(e,t,n,i,r,a){this.elem=e,this.prop=n,this.easing=r||fe.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=a||(fe.cssNumber[n]?"":"px")},cur:function(){var e=L.propHooks[this.prop];return e&&e.get?e.get(this):L.propHooks._default.get(this)},run:function(e){var t,n=L.propHooks[this.prop];return this.options.duration?this.pos=t=fe.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):L.propHooks._default.set(this),this}},L.prototype.init.prototype=L.prototype,L.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=fe.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){fe.fx.step[e.prop]?fe.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[fe.cssProps[e.prop]]&&!fe.cssHooks[e.prop]?e.elem[e.prop]=e.now:fe.style(e.elem,e.prop,e.now+e.unit)}}},L.propHooks.scrollTop=L.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},fe.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},fe.fx=L.prototype.init,fe.fx.step={};var Tt,Ct,Dt=/^(?:toggle|show|hide)$/,kt=/queueHooks$/;fe.Animation=fe.extend(j,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return h(n.elem,e,Re.exec(t),n),n}]},tweener:function(e,t){fe.isFunction(e)?(t=e,e=["*"]):e=e.match(xe);for(var n,i=0,r=e.length;r>i;i++)n=e[i],j.tweeners[n]=j.tweeners[n]||[],j.tweeners[n].unshift(t)},prefilters:[V],prefilter:function(e,t){t?j.prefilters.unshift(e):j.prefilters.push(e)}}),fe.speed=function(e,t,n){var i=e&&"object"==(void 0===e?"undefined":_typeof(e))?fe.extend({},e):{complete:n||!n&&t||fe.isFunction(e)&&e,duration:e,easing:n&&t||t&&!fe.isFunction(t)&&t};return i.duration=fe.fx.off?0:"number"==typeof i.duration?i.duration:i.duration in fe.fx.speeds?fe.fx.speeds[i.duration]:fe.fx.speeds._default,(null==i.queue||!0===i.queue)&&(i.queue="fx"),i.old=i.complete,i.complete=function(){fe.isFunction(i.old)&&i.old.call(this),i.queue&&fe.dequeue(this,i.queue)},i},fe.fn.extend({fadeTo:function(e,t,n,i){return this.filter(Le).css("opacity",0).show().end().animate({opacity:t},e,n,i)},animate:function(e,t,n,i){var r=fe.isEmptyObject(e),a=fe.speed(t,n,i),o=function(){var t=j(this,fe.extend({},e),a);(r||fe._data(this,"finish"))&&t.stop(!0)};return o.finish=o,r||!1===a.queue?this.each(o):this.queue(a.queue,o)},stop:function(e,t,n){var i=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&!1!==e&&this.queue(e||"fx",[]),this.each(function(){var t=!0,r=null!=e&&e+"queueHooks",a=fe.timers,o=fe._data(this);if(r)o[r]&&o[r].stop&&i(o[r]);else for(r in o)o[r]&&o[r].stop&&kt.test(r)&&i(o[r]);for(r=a.length;r--;)a[r].elem!==this||null!=e&&a[r].queue!==e||(a[r].anim.stop(n),t=!1,a.splice(r,1));(t||!n)&&fe.dequeue(this,e)})},finish:function(e){return!1!==e&&(e=e||"fx"),this.each(function(){var t,n=fe._data(this),i=n[e+"queue"],r=n[e+"queueHooks"],a=fe.timers,o=i?i.length:0;for(n.finish=!0,fe.queue(this,e,[]),r&&r.stop&&r.stop.call(this,!0),t=a.length;t--;)a[t].elem===this&&a[t].queue===e&&(a[t].anim.stop(!0),a.splice(t,1));for(t=0;o>t;t++)i[t]&&i[t].finish&&i[t].finish.call(this);delete n.finish})}}),fe.each(["toggle","show","hide"],function(e,t){var n=fe.fn[t];fe.fn[t]=function(e,i,r){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(F(t,!0),e,i,r)}}),fe.each({slideDown:F("show"),slideUp:F("hide"),slideToggle:F("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){fe.fn[e]=function(e,n,i){return this.animate(t,e,n,i)}}),fe.timers=[],fe.fx.tick=function(){var e,t=fe.timers,n=0;for(Tt=fe.now();n<t.length;n++)(e=t[n])()||t[n]!==e||t.splice(n--,1);t.length||fe.fx.stop(),Tt=void 0},fe.fx.timer=function(e){fe.timers.push(e),e()?fe.fx.start():fe.timers.pop()},fe.fx.interval=13,fe.fx.start=function(){Ct||(Ct=e.setInterval(fe.fx.tick,fe.fx.interval))},fe.fx.stop=function(){e.clearInterval(Ct),Ct=null},fe.fx.speeds={slow:600,fast:200,_default:400},fe.fn.delay=function(t,n){return t=fe.fx?fe.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,i){var r=e.setTimeout(n,t);i.stop=function(){e.clearTimeout(r)}})},function(){var e,t=ie.createElement("input"),n=ie.createElement("div"),i=ie.createElement("select"),r=i.appendChild(ie.createElement("option"));n=ie.createElement("div"),n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",e=n.getElementsByTagName("a")[0],t.setAttribute("type","checkbox"),n.appendChild(t),e=n.getElementsByTagName("a")[0],e.style.cssText="top:1px",de.getSetAttribute="t"!==n.className,de.style=/top/.test(e.getAttribute("style")),de.hrefNormalized="/a"===e.getAttribute("href"),de.checkOn=!!t.value,de.optSelected=r.selected,de.enctype=!!ie.createElement("form").enctype,i.disabled=!0,de.optDisabled=!r.disabled,t=ie.createElement("input"),t.setAttribute("value",""),de.input=""===t.getAttribute("value"),t.value="t",t.setAttribute("type","radio"),de.radioValue="t"===t.value}();var xt=/\r/g;fe.fn.extend({val:function(e){var t,n,i,r=this[0];return arguments.length?(i=fe.isFunction(e),this.each(function(n){var r;1===this.nodeType&&(r=i?e.call(this,n,fe(this).val()):e,null==r?r="":"number"==typeof r?r+="":fe.isArray(r)&&(r=fe.map(r,function(e){return null==e?"":e+""})),(t=fe.valHooks[this.type]||fe.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,r,"value")||(this.value=r))})):r?(t=fe.valHooks[r.type]||fe.valHooks[r.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(r,"value"))?n:(n=r.value,"string"==typeof n?n.replace(xt,""):null==n?"":n)):void 0}}),fe.extend({valHooks:{option:{get:function(e){var t=fe.find.attr(e,"value");return null!=t?t:fe.trim(fe.text(e))}},select:{get:function(e){for(var t,n,i=e.options,r=e.selectedIndex,a="select-one"===e.type||0>r,o=a?null:[],s=a?r+1:i.length,l=0>r?s:a?r:0;s>l;l++)if(n=i[l],(n.selected||l===r)&&(de.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!fe.nodeName(n.parentNode,"optgroup"))){if(t=fe(n).val(),a)return t;o.push(t)}return o},set:function(e,t){for(var n,i,r=e.options,a=fe.makeArray(t),o=r.length;o--;)if(i=r[o],fe.inArray(fe.valHooks.option.get(i),a)>=0)try{i.selected=n=!0}catch(e){i.scrollHeight}else i.selected=!1;return n||(e.selectedIndex=-1),r}}}}),fe.each(["radio","checkbox"],function(){fe.valHooks[this]={set:function(e,t){return fe.isArray(t)?e.checked=fe.inArray(fe(e).val(),t)>-1:void 0}},de.checkOn||(fe.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Et,At,Ot=fe.expr.attrHandle,Nt=/^(?:checked|selected)$/i,Mt=de.getSetAttribute,It=de.input;fe.fn.extend({attr:function(e,t){return He(this,fe.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){fe.removeAttr(this,e)})}}),fe.extend({attr:function(e,t,n){var i,r,a=e.nodeType;if(3!==a&&8!==a&&2!==a)return void 0===e.getAttribute?fe.prop(e,t,n):(1===a&&fe.isXMLDoc(e)||(t=t.toLowerCase(),r=fe.attrHooks[t]||(fe.expr.match.bool.test(t)?At:Et)),void 0!==n?null===n?void fe.removeAttr(e,t):r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=fe.find.attr(e,t),null==i?void 0:i))},attrHooks:{type:{set:function(e,t){if(!de.radioValue&&"radio"===t&&fe.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,i,r=0,a=t&&t.match(xe);if(a&&1===e.nodeType)for(;n=a[r++];)i=fe.propFix[n]||n,fe.expr.match.bool.test(n)?It&&Mt||!Nt.test(n)?e[i]=!1:e[fe.camelCase("default-"+n)]=e[i]=!1:fe.attr(e,n,""),e.removeAttribute(Mt?n:i)}}),At={set:function(e,t,n){return!1===t?fe.removeAttr(e,n):It&&Mt||!Nt.test(n)?e.setAttribute(!Mt&&fe.propFix[n]||n,n):e[fe.camelCase("default-"+n)]=e[n]=!0,n}},fe.each(fe.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Ot[t]||fe.find.attr;It&&Mt||!Nt.test(t)?Ot[t]=function(e,t,i){var r,a;return i||(a=Ot[t],Ot[t]=r,r=null!=n(e,t,i)?t.toLowerCase():null,Ot[t]=a),r}:Ot[t]=function(e,t,n){return n?void 0:e[fe.camelCase("default-"+t)]?t.toLowerCase():null}}),It&&Mt||(fe.attrHooks.value={set:function(e,t,n){return fe.nodeName(e,"input")?void(e.defaultValue=t):Et&&Et.set(e,t,n)}}),Mt||(Et={set:function(e,t,n){var i=e.getAttributeNode(n);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(n)),i.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Ot.id=Ot.name=Ot.coords=function(e,t,n){var i;return n?void 0:(i=e.getAttributeNode(t))&&""!==i.value?i.value:null},fe.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Et.set},fe.attrHooks.contenteditable={set:function(e,t,n){Et.set(e,""!==t&&t,n)}},fe.each(["width","height"],function(e,t){fe.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),de.style||(fe.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Rt=/^(?:input|select|textarea|button|object)$/i,Pt=/^(?:a|area)$/i;fe.fn.extend({prop:function(e,t){return He(this,fe.prop,e,t,arguments.length>1)},removeProp:function(e){return e=fe.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(e){}})}}),fe.extend({prop:function(e,t,n){var i,r,a=e.nodeType;if(3!==a&&8!==a&&2!==a)return 1===a&&fe.isXMLDoc(e)||(t=fe.propFix[t]||t,r=fe.propHooks[t]),void 0!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:e[t]=n:r&&"get"in r&&null!==(i=r.get(e,t))?i:e[t]},propHooks:{tabIndex:{get:function(e){var t=fe.find.attr(e,"tabindex");return t?parseInt(t,10):Rt.test(e.nodeName)||Pt.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),de.hrefNormalized||fe.each(["href","src"],function(e,t){fe.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),de.optSelected||(fe.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),fe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){fe.propFix[this.toLowerCase()]=this}),de.enctype||(fe.propFix.enctype="encoding");var Lt=/[\t\r\n\f]/g;fe.fn.extend({addClass:function(e){var t,n,i,r,a,o,s,l=0;if(fe.isFunction(e))return this.each(function(t){fe(this).addClass(e.call(this,t,B(this)))});if("string"==typeof e&&e)for(t=e.match(xe)||[];n=this[l++];)if(r=B(n),i=1===n.nodeType&&(" "+r+" ").replace(Lt," ")){for(o=0;a=t[o++];)i.indexOf(" "+a+" ")<0&&(i+=a+" ");s=fe.trim(i),r!==s&&fe.attr(n,"class",s)}return this},removeClass:function(e){var t,n,i,r,a,o,s,l=0;if(fe.isFunction(e))return this.each(function(t){fe(this).removeClass(e.call(this,t,B(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(xe)||[];n=this[l++];)if(r=B(n),i=1===n.nodeType&&(" "+r+" ").replace(Lt," ")){for(o=0;a=t[o++];)for(;i.indexOf(" "+a+" ")>-1;)i=i.replace(" "+a+" "," ");s=fe.trim(i),r!==s&&fe.attr(n,"class",s)}return this},toggleClass:function(e,t){var n=void 0===e?"undefined":_typeof(e);return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):fe.isFunction(e)?this.each(function(n){fe(this).toggleClass(e.call(this,n,B(this),t),t)}):this.each(function(){var t,i,r,a;if("string"===n)for(i=0,r=fe(this),a=e.match(xe)||[];t=a[i++];)r.hasClass(t)?r.removeClass(t):r.addClass(t);else(void 0===e||"boolean"===n)&&(t=B(this),t&&fe._data(this,"__className__",t),fe.attr(this,"class",t||!1===e?"":fe._data(this,"__className__")||""))})},hasClass:function(e){var t,n,i=0;for(t=" "+e+" ";n=this[i++];)if(1===n.nodeType&&(" "+B(n)+" ").replace(Lt," ").indexOf(t)>-1)return!0;return!1}}),fe.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){fe.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),fe.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}});var Ht=e.location,Ft=fe.now(),Yt=/\?/,Vt=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;fe.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,i=null,r=fe.trim(t+"");return r&&!fe.trim(r.replace(Vt,function(e,t,r,a){return n&&t&&(i=0),0===i?e:(n=r||t,i+=!a-!r,"")}))?Function("return "+r)():fe.error("Invalid JSON: "+t)},fe.parseXML=function(t){var n,i;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(i=new e.DOMParser,n=i.parseFromString(t,"text/xml")):(n=new e.ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(e){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||fe.error("Invalid XML: "+t),n};var qt=/#.*$/,jt=/([?&])_=[^&]*/,Bt=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Wt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ut=/^(?:GET|HEAD)$/,zt=/^\/\//,Gt=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Xt={},Zt={},Kt="*/".concat("*"),Qt=Ht.href,Jt=Gt.exec(Qt.toLowerCase())||[];fe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Qt,type:"GET",isLocal:Wt.test(Jt[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kt,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"},converters:{"* text":String,"text html":!0,"text json":fe.parseJSON,"text xml":fe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?z(z(e,fe.ajaxSettings),t):z(fe.ajaxSettings,e)},ajaxPrefilter:W(Xt),ajaxTransport:W(Zt),ajax:function(t,n){function i(t,n,i,r){var a,d,y,_,$,S=n;2!==b&&(b=2,l&&e.clearTimeout(l),c=void 0,s=r||"",w.readyState=t>0?4:0,a=t>=200&&300>t||304===t,i&&(_=G(h,w,i)),_=X(h,_,w,a),a?(h.ifModified&&($=w.getResponseHeader("Last-Modified"),$&&(fe.lastModified[o]=$),($=w.getResponseHeader("etag"))&&(fe.etag[o]=$)),204===t||"HEAD"===h.type?S="nocontent":304===t?S="notmodified":(S=_.state,d=_.data,y=_.error,a=!y)):(y=S,(t||!S)&&(S="error",0>t&&(t=0))),w.status=t,w.statusText=(n||S)+"",a?m.resolveWith(f,[d,S,w]):m.rejectWith(f,[w,S,y]),w.statusCode(v),v=void 0,u&&p.trigger(a?"ajaxSuccess":"ajaxError",[w,h,a?d:y]),g.fireWith(f,[w,S]),u&&(p.trigger("ajaxComplete",[w,h]),--fe.active||fe.event.trigger("ajaxStop")))}"object"==(void 0===t?"undefined":_typeof(t))&&(n=t,t=void 0),n=n||{};var r,a,o,s,l,u,c,d,h=fe.ajaxSetup({},n),f=h.context||h,p=h.context&&(f.nodeType||f.jquery)?fe(f):fe.event,m=fe.Deferred(),g=fe.Callbacks("once memory"),v=h.statusCode||{},y={},_={},b=0,$="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!d)for(d={};t=Bt.exec(s);)d[t[1].toLowerCase()]=t[2];t=d[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=_[n]=_[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)v[t]=[v[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||$;return c&&c.abort(t),i(0,t),this}};if(m.promise(w).complete=g.add,w.success=w.done,w.error=w.fail,h.url=((t||h.url||Qt)+"").replace(qt,"").replace(zt,Jt[1]+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=fe.trim(h.dataType||"*").toLowerCase().match(xe)||[""],null==h.crossDomain&&(r=Gt.exec(h.url.toLowerCase()),h.crossDomain=!(!r||r[1]===Jt[1]&&r[2]===Jt[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Jt[3]||("http:"===Jt[1]?"80":"443")))),h.data&&h.processData&&"string"!=typeof h.data&&(h.data=fe.param(h.data,h.traditional)),U(Xt,h,n,w),2===b)return w;u=fe.event&&h.global,u&&0==fe.active++&&fe.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Ut.test(h.type),o=h.url,h.hasContent||(h.data&&(o=h.url+=(Yt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(h.url=jt.test(o)?o.replace(jt,"$1_="+Ft++):o+(Yt.test(o)?"&":"?")+"_="+Ft++)),h.ifModified&&(fe.lastModified[o]&&w.setRequestHeader("If-Modified-Since",fe.lastModified[o]),fe.etag[o]&&w.setRequestHeader("If-None-Match",fe.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&w.setRequestHeader("Content-Type",h.contentType),w.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+Kt+"; q=0.01":""):h.accepts["*"]);for(a in h.headers)w.setRequestHeader(a,h.headers[a]);if(h.beforeSend&&(!1===h.beforeSend.call(f,w,h)||2===b))return w.abort();$="abort";for(a in{success:1,error:1,complete:1})w[a](h[a]);if(c=U(Zt,h,n,w)){if(w.readyState=1,u&&p.trigger("ajaxSend",[w,h]),2===b)return w;h.async&&h.timeout>0&&(l=e.setTimeout(function(){w.abort("timeout")},h.timeout));try{b=1,c.send(y,i)}catch(e){if(!(2>b))throw e;i(-1,e)}}else i(-1,"No Transport");return w},getJSON:function(e,t,n){return fe.get(e,t,n,"json")},getScript:function(e,t){return fe.get(e,void 0,t,"script")}}),fe.each(["get","post"],function(e,t){fe[t]=function(e,n,i,r){return fe.isFunction(n)&&(r=r||i,i=n,n=void 0),fe.ajax(fe.extend({url:e,type:t,dataType:r,data:n,success:i},fe.isPlainObject(e)&&e))}}),fe._evalUrl=function(e){return fe.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,throws:!0})},fe.fn.extend({wrapAll:function(e){if(fe.isFunction(e))return this.each(function(t){fe(this).wrapAll(e.call(this,t))});if(this[0]){var t=fe(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return fe.isFunction(e)?this.each(function(t){fe(this).wrapInner(e.call(this,t))}):this.each(function(){var t=fe(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=fe.isFunction(e);return this.each(function(n){fe(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){fe.nodeName(this,"body")||fe(this).replaceWith(this.childNodes)}).end()}}),fe.expr.filters.hidden=function(e){return de.reliableHiddenOffsets()?e.offsetWidth<=0&&e.offsetHeight<=0&&!e.getClientRects().length:K(e)},fe.expr.filters.visible=function(e){return!fe.expr.filters.hidden(e)};var en=/%20/g,tn=/\[\]$/,nn=/\r?\n/g,rn=/^(?:submit|button|image|reset|file)$/i,an=/^(?:input|select|textarea|keygen)/i;fe.param=function(e,t){var n,i=[],r=function(e,t){t=fe.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=fe.ajaxSettings&&fe.ajaxSettings.traditional),fe.isArray(e)||e.jquery&&!fe.isPlainObject(e))fe.each(e,function(){r(this.name,this.value)});else for(n in e)Q(n,e[n],t,r);return i.join("&").replace(en,"+")},fe.fn.extend({serialize:function(){return fe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=fe.prop(this,"elements");return e?fe.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!fe(this).is(":disabled")&&an.test(this.nodeName)&&!rn.test(e)&&(this.checked||!Fe.test(e))}).map(function(e,t){var n=fe(this).val();return null==n?null:fe.isArray(n)?fe.map(n,function(e){return{name:t.name,value:e.replace(nn,"\r\n")}}):{name:t.name,value:n.replace(nn,"\r\n")}}).get()}}),fe.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return this.isLocal?ee():ie.documentMode>8?J():/^(get|post|head|put|delete|options)$/i.test(this.type)&&J()||ee()}:J;var on=0,sn={},ln=fe.ajaxSettings.xhr();e.attachEvent&&e.attachEvent("onunload",function(){for(var e in sn)sn[e](void 0,!0)}),de.cors=!!ln&&"withCredentials"in ln,(ln=de.ajax=!!ln)&&fe.ajaxTransport(function(t){if(!t.crossDomain||de.cors){var n;return{send:function(i,r){var a,o=t.xhr(),s=++on;if(o.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)o[a]=t.xhrFields[a];t.mimeType&&o.overrideMimeType&&o.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)void 0!==i[a]&&o.setRequestHeader(a,i[a]+"");o.send(t.hasContent&&t.data||null),n=function(e,i){var a,l,u;if(n&&(i||4===o.readyState))if(delete sn[s],n=void 0,o.onreadystatechange=fe.noop,i)4!==o.readyState&&o.abort();else{u={},a=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(e){l=""}a||!t.isLocal||t.crossDomain?1223===a&&(a=204):a=u.text?200:404}u&&r(a,l,u,o.getAllResponseHeaders())},t.async?4===o.readyState?e.setTimeout(n):o.onreadystatechange=sn[s]=n:n()},abort:function(){n&&n(void 0,!0)}}}}),fe.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),fe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return fe.globalEval(e),e}}}),fe.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),fe.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=ie.head||fe("head")[0]||ie.documentElement;return{send:function(i,r){t=ie.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||r(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var un=[],cn=/(=)\?(?=&|$)|\?\?/;fe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=un.pop()||fe.expando+"_"+Ft++;return this[e]=!0,e}}),fe.ajaxPrefilter("json jsonp",function(t,n,i){var r,a,o,s=!1!==t.jsonp&&(cn.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&cn.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(r=t.jsonpCallback=fe.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(cn,"$1"+r):!1!==t.jsonp&&(t.url+=(Yt.test(t.url)?"&":"?")+t.jsonp+"="+r),t.converters["script json"]=function(){return o||fe.error(r+" was not called"),o[0]},t.dataTypes[0]="json",a=e[r],e[r]=function(){o=arguments},i.always(function(){void 0===a?fe(e).removeProp(r):e[r]=a,t[r]&&(t.jsonpCallback=n.jsonpCallback,un.push(r)),o&&fe.isFunction(a)&&a(o[0]),o=a=void 0}),"script"):void 0}),de.createHTMLDocument=function(){if(!ie.implementation.createHTMLDocument)return!1;var e=ie.implementation.createHTMLDocument("");return e.body.innerHTML="<form></form><form></form>",2===e.body.childNodes.length}(),fe.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||(de.createHTMLDocument?ie.implementation.createHTMLDocument(""):ie);var i=we.exec(e),r=!n&&[];return i?[t.createElement(i[1])]:(i=v([e],t,r),r&&r.length&&fe(r).remove(),fe.merge([],i.childNodes))};var dn=fe.fn.load;fe.fn.load=function(e,t,n){if("string"!=typeof e&&dn)return dn.apply(this,arguments);var i,r,a,o=this,s=e.indexOf(" ");return s>-1&&(i=fe.trim(e.slice(s,e.length)),e=e.slice(0,s)),fe.isFunction(t)?(n=t,t=void 0):t&&"object"==(void 0===t?"undefined":_typeof(t))&&(r="POST"),o.length>0&&fe.ajax({url:e,type:r||"GET",dataType:"html",data:t}).done(function(e){a=arguments,o.html(i?fe("<div>").append(fe.parseHTML(e)).find(i):e)}).always(n&&function(e,t){o.each(function(){n.apply(o,a||[e.responseText,t,e])})}),this},fe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){fe.fn[t]=function(e){return this.on(t,e)}}),fe.expr.filters.animated=function(e){return fe.grep(fe.timers,function(t){return e===t.elem}).length},fe.offset={setOffset:function(e,t,n){var i,r,a,o,s,l,u,c=fe.css(e,"position"),d=fe(e),h={};"static"===c&&(e.style.position="relative"),s=d.offset(),a=fe.css(e,"top"),l=fe.css(e,"left"),u=("absolute"===c||"fixed"===c)&&fe.inArray("auto",[a,l])>-1,u?(i=d.position(),o=i.top,r=i.left):(o=parseFloat(a)||0,r=parseFloat(l)||0),fe.isFunction(t)&&(t=t.call(e,n,fe.extend({},s))),null!=t.top&&(h.top=t.top-s.top+o),null!=t.left&&(h.left=t.left-s.left+r),"using"in t?t.using.call(e,h):d.css(h)}},fe.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){fe.offset.setOffset(this,e,t)});var t,n,i={top:0,left:0},r=this[0],a=r&&r.ownerDocument;return a?(t=a.documentElement,fe.contains(t,r)?(void 0!==r.getBoundingClientRect&&(i=r.getBoundingClientRect()),n=te(a),{top:i.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:i.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):i):void 0},position:function(){if(this[0]){var e,t,n={top:0,left:0},i=this[0];return"fixed"===fe.css(i,"position")?t=i.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),fe.nodeName(e[0],"html")||(n=e.offset()),n.top+=fe.css(e[0],"borderTopWidth",!0),n.left+=fe.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-fe.css(i,"marginTop",!0),left:t.left-n.left-fe.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&!fe.nodeName(e,"html")&&"static"===fe.css(e,"position");)e=e.offsetParent;return e||ht})}}),fe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){
var n=/Y/.test(t);fe.fn[e]=function(i){return He(this,function(e,i,r){var a=te(e);return void 0===r?a?t in a?a[t]:a.document.documentElement[i]:e[i]:void(a?a.scrollTo(n?fe(a).scrollLeft():r,n?r:fe(a).scrollTop()):e[i]=r)},e,i,arguments.length,null)}}),fe.each(["top","left"],function(e,t){fe.cssHooks[t]=O(de.pixelPosition,function(e,n){return n?(n=pt(e,t),ct.test(n)?fe(e).position()[t]+"px":n):void 0})}),fe.each({Height:"height",Width:"width"},function(e,t){fe.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,i){fe.fn[i]=function(i,r){var a=arguments.length&&(n||"boolean"!=typeof i),o=n||(!0===i||!0===r?"margin":"border");return He(this,function(t,n,i){var r;return fe.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(r=t.documentElement,Math.max(t.body["scroll"+e],r["scroll"+e],t.body["offset"+e],r["offset"+e],r["client"+e])):void 0===i?fe.css(t,n,o):fe.style(t,n,i,o)},t,a?i:void 0,a,null)}})}),fe.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,i){return this.on(t,e,n,i)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),fe.fn.size=function(){return this.length},fe.fn.andSelf=fe.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return fe});var hn=e.jQuery,fn=e.$;return fe.noConflict=function(t){return e.$===fe&&(e.$=fn),t&&e.jQuery===fe&&(e.jQuery=hn),fe},t||(e.jQuery=e.$=fe),fe}),function(e,t){"object"==("undefined"==typeof exports?"undefined":_typeof(exports))&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";function e(){return Xe.apply(null,arguments)}function t(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function i(e){return void 0===e}function r(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function a(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function o(e,t){var n,i=[];for(n=0;n<e.length;++n)i.push(t(e[n],n));return i}function s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function l(e,t){for(var n in t)s(t,n)&&(e[n]=t[n]);return s(t,"toString")&&(e.toString=t.toString),s(t,"valueOf")&&(e.valueOf=t.valueOf),e}function u(e,t,n,i){return me(e,t,n,i,!0).utc()}function c(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function d(e){if(null==e._isValid){var t=c(e),n=Ze.call(t.parsedDateParts,function(e){return null!=e}),i=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(i=i&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return i;e._isValid=i}return e._isValid}function h(e){var t=u(NaN);return null!=e?l(c(t),e):c(t).userInvalidated=!0,t}function f(e,t){var n,r,a;if(i(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),i(t._i)||(e._i=t._i),i(t._f)||(e._f=t._f),i(t._l)||(e._l=t._l),i(t._strict)||(e._strict=t._strict),i(t._tzm)||(e._tzm=t._tzm),i(t._isUTC)||(e._isUTC=t._isUTC),i(t._offset)||(e._offset=t._offset),i(t._pf)||(e._pf=c(t)),i(t._locale)||(e._locale=t._locale),0<Qe.length)for(n=0;n<Qe.length;n++)i(a=t[r=Qe[n]])||(e[r]=a);return e}function p(t){f(this,t),this._d=new Date(null!=t._d?t._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===Je&&(Je=!0,e.updateOffset(this),Je=!1)}function m(e){return e instanceof p||null!=e&&null!=e._isAMomentObject}function g(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function v(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=g(t)),n}function y(e,t,n){var i,r=Math.min(e.length,t.length),a=Math.abs(e.length-t.length),o=0;for(i=0;i<r;i++)(n&&e[i]!==t[i]||!n&&v(e[i])!==v(t[i]))&&o++;return o+a}function _(t){!1===e.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+t)}function b(t,n){var i=!0;return l(function(){if(null!=e.deprecationHandler&&e.deprecationHandler(null,t),i){for(var r,a=[],o=0;o<arguments.length;o++){if(r="","object"==_typeof(arguments[o])){for(var s in r+="\n["+o+"] ",arguments[0])r+=s+": "+arguments[0][s]+", ";r=r.slice(0,-2)}else r=arguments[o];a.push(r)}_(t+"\nArguments: "+Array.prototype.slice.call(a).join("")+"\n"+(new Error).stack),i=!1}return n.apply(this,arguments)},n)}function $(t,n){null!=e.deprecationHandler&&e.deprecationHandler(t,n),et[t]||(_(n),et[t]=!0)}function w(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function S(e,t){var i,r=l({},e);for(i in t)s(t,i)&&(n(e[i])&&n(t[i])?(r[i]={},l(r[i],e[i]),l(r[i],t[i])):null!=t[i]?r[i]=t[i]:delete r[i]);for(i in e)s(e,i)&&!s(t,i)&&n(e[i])&&(r[i]=l({},r[i]));return r}function T(e){null!=e&&this.set(e)}function C(e,t){var n=e.toLowerCase();tt[n]=tt[n+"s"]=tt[t]=e}function D(e){return"string"==typeof e?tt[e]||tt[e.toLowerCase()]:void 0}function k(e){var t,n,i={};for(n in e)s(e,n)&&(t=D(n))&&(i[t]=e[n]);return i}function x(e,t){nt[e]=t}function E(e,t,n){var i=""+Math.abs(e),r=t-i.length;return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,r)).toString().substr(1)+i}function A(e,t,n,i){var r=i;"string"==typeof i&&(r=function(){return this[i]()}),e&&(ot[e]=r),t&&(ot[t[0]]=function(){return E(r.apply(this,arguments),t[1],t[2])}),n&&(ot[n]=function(){return this.localeData().ordinal(r.apply(this,arguments),e)})}function O(e,t){return e.isValid()?(t=N(t,e.localeData()),at[t]=at[t]||function(e){var t,n,i,r=e.match(it);for(t=0,n=r.length;t<n;t++)ot[r[t]]?r[t]=ot[r[t]]:r[t]=(i=r[t]).match(/\[[\s\S]/)?i.replace(/^\[|\]$/g,""):i.replace(/\\/g,"");return function(t){var i,a="";for(i=0;i<n;i++)a+=w(r[i])?r[i].call(t,e):r[i];return a}}(t),at[t](e)):e.localeData().invalidDate()}function N(e,t){function n(e){return t.longDateFormat(e)||e}var i=5;for(rt.lastIndex=0;0<=i&&rt.test(e);)e=e.replace(rt,n),rt.lastIndex=0,i-=1;return e}function M(e,t,n){St[e]=w(t)?t:function(e,i){return e&&n?n:t}}function I(e,t){return s(St,e)?St[e](t._strict,t._locale):new RegExp(R(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,i,r){return t||n||i||r})))}function R(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function P(e,t){var n,i=t;for("string"==typeof e&&(e=[e]),r(t)&&(i=function(e,n){n[t]=v(e)}),n=0;n<e.length;n++)Tt[e[n]]=i}function L(e,t){P(e,function(e,n,i,r){i._w=i._w||{},t(e,i._w,i,r)})}function H(e){return F(e)?366:365}function F(e){return e%4==0&&e%100!=0||e%400==0}function Y(t,n){return function(i){return null!=i?(q(this,t,i),e.updateOffset(this,n),this):V(this,t)}}function V(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function q(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&F(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),j(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function j(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,i=(t%(n=12)+n)%n;return e+=(t-i)/12,1===i?F(e)?29:28:31-i%7%2}function B(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=v(t);else if(!r(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),j(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function W(t){return null!=t?(B(this,t),e.updateOffset(this,!0),this):V(this,"Month")}function U(){function e(e,t){return t.length-e.length}var t,n,i=[],r=[],a=[];for(t=0;t<12;t++)n=u([2e3,t]),i.push(this.monthsShort(n,"")),r.push(this.months(n,"")),a.push(this.months(n,"")),a.push(this.monthsShort(n,""));for(i.sort(e),r.sort(e),a.sort(e),t=0;t<12;t++)i[t]=R(i[t]),r[t]=R(r[t]);for(t=0;t<24;t++)a[t]=R(a[t]);this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+i.join("|")+")","i")}function z(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&0<=e&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function G(e,t,n){var i=7+t-n;return-(7+z(e,0,i).getUTCDay()-t)%7+i-1}function X(e,t,n,i,r){var a,o,s=1+7*(t-1)+(7+n-i)%7+G(e,i,r);return s<=0?o=H(a=e-1)+s:s>H(e)?(a=e+1,o=s-H(e)):(a=e,o=s),{year:a,dayOfYear:o}}function Z(e,t,n){var i,r,a=G(e.year(),t,n),o=Math.floor((e.dayOfYear()-a-1)/7)+1;return o<1?i=o+K(r=e.year()-1,t,n):o>K(e.year(),t,n)?(i=o-K(e.year(),t,n),r=e.year()+1):(r=e.year(),i=o),{week:i,year:r}}function K(e,t,n){var i=G(e,t,n),r=G(e+1,t,n);return(H(e)-i+r)/7}function Q(){function e(e,t){return t.length-e.length}var t,n,i,r,a,o=[],s=[],l=[],c=[];for(t=0;t<7;t++)n=u([2e3,1]).day(t),i=this.weekdaysMin(n,""),r=this.weekdaysShort(n,""),a=this.weekdays(n,""),o.push(i),s.push(r),l.push(a),c.push(i),c.push(r),c.push(a);for(o.sort(e),s.sort(e),l.sort(e),c.sort(e),t=0;t<7;t++)s[t]=R(s[t]),l[t]=R(l[t]),c[t]=R(c[t]);this._weekdaysRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+o.join("|")+")","i")}function J(){return this.hours()%12||12}function ee(e,t){A(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function te(e,t){return t._meridiemParse}function ne(e){return e?e.toLowerCase().replace("_","-"):e}function ie(e){var t=null;if(!Zt[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=zt._abbr,require("./locale/"+e),re(t)}catch(e){}return Zt[e]}function re(e,t){var n;return e&&((n=i(t)?oe(e):ae(e,t))?zt=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),zt._abbr}function ae(e,t){if(null!==t){var n,i=Xt;if(t.abbr=e,null!=Zt[e])$("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),i=Zt[e]._config;else if(null!=t.parentLocale)if(null!=Zt[t.parentLocale])i=Zt[t.parentLocale]._config;else{if(null==(n=ie(t.parentLocale)))return Kt[t.parentLocale]||(Kt[t.parentLocale]=[]),Kt[t.parentLocale].push({name:e,config:t}),null;i=n._config}return Zt[e]=new T(S(i,t)),Kt[e]&&Kt[e].forEach(function(e){ae(e.name,e.config)}),re(e),Zt[e]}return delete Zt[e],null}function oe(e){var n;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return zt;if(!t(e)){if(n=ie(e))return n;e=[e]}return function(e){for(var t,n,i,r,a=0;a<e.length;){for(t=(r=ne(e[a]).split("-")).length,n=(n=ne(e[a+1]))?n.split("-"):null;0<t;){if(i=ie(r.slice(0,t).join("-")))return i;if(n&&n.length>=t&&y(r,n,!0)>=t-1)break;t--}a++}return zt}(e)}function se(e){var t,n=e._a;return n&&-2===c(e).overflow&&(t=n[Dt]<0||11<n[Dt]?Dt:n[kt]<1||n[kt]>j(n[Ct],n[Dt])?kt:n[xt]<0||24<n[xt]||24===n[xt]&&(0!==n[Et]||0!==n[At]||0!==n[Ot])?xt:n[Et]<0||59<n[Et]?Et:n[At]<0||59<n[At]?At:n[Ot]<0||999<n[Ot]?Ot:-1,c(e)._overflowDayOfYear&&(t<Ct||kt<t)&&(t=kt),c(e)._overflowWeeks&&-1===t&&(t=Nt),c(e)._overflowWeekday&&-1===t&&(t=Mt),c(e).overflow=t),e}function le(e,t,n){return null!=e?e:null!=t?t:n}function ue(t){var n,i,r,a,o,s=[];if(!t._d){var l,u;for(l=t,u=new Date(e.now()),r=l._useUTC?[u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()]:[u.getFullYear(),u.getMonth(),u.getDate()],t._w&&null==t._a[kt]&&null==t._a[Dt]&&function(e){var t,n,i,r,a,o,s,l;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)a=1,o=4,n=le(t.GG,e._a[Ct],Z(ge(),1,4).year),i=le(t.W,1),((r=le(t.E,1))<1||7<r)&&(l=!0);else{a=e._locale._week.dow,o=e._locale._week.doy;var u=Z(ge(),a,o);n=le(t.gg,e._a[Ct],u.year),i=le(t.w,u.week),null!=t.d?((r=t.d)<0||6<r)&&(l=!0):null!=t.e?(r=t.e+a,(t.e<0||6<t.e)&&(l=!0)):r=a}i<1||i>K(n,a,o)?c(e)._overflowWeeks=!0:null!=l?c(e)._overflowWeekday=!0:(s=X(n,i,r,a,o),e._a[Ct]=s.year,e._dayOfYear=s.dayOfYear)}(t),null!=t._dayOfYear&&(o=le(t._a[Ct],r[Ct]),(t._dayOfYear>H(o)||0===t._dayOfYear)&&(c(t)._overflowDayOfYear=!0),i=z(o,0,t._dayOfYear),t._a[Dt]=i.getUTCMonth(),t._a[kt]=i.getUTCDate()),n=0;n<3&&null==t._a[n];++n)t._a[n]=s[n]=r[n];for(;n<7;n++)t._a[n]=s[n]=null==t._a[n]?2===n?1:0:t._a[n];24===t._a[xt]&&0===t._a[Et]&&0===t._a[At]&&0===t._a[Ot]&&(t._nextDay=!0,t._a[xt]=0),t._d=(t._useUTC?z:function(e,t,n,i,r,a,o){var s=new Date(e,t,n,i,r,a,o);return e<100&&0<=e&&isFinite(s.getFullYear())&&s.setFullYear(e),s}).apply(null,s),a=t._useUTC?t._d.getUTCDay():t._d.getDay(),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[xt]=24),t._w&&void 0!==t._w.d&&t._w.d!==a&&(c(t).weekdayMismatch=!0)}}function ce(e){var t,n,i,r,a,o,s=e._i,l=Qt.exec(s)||Jt.exec(s);if(l){for(c(e).iso=!0,t=0,n=tn.length;t<n;t++)if(tn[t][1].exec(l[1])){r=tn[t][0],i=!1!==tn[t][2];break}if(null==r)return void(e._isValid=!1);if(l[3]){for(t=0,n=nn.length;t<n;t++)if(nn[t][1].exec(l[3])){a=(l[2]||" ")+nn[t][0];break}if(null==a)return void(e._isValid=!1)}if(!i&&null!=a)return void(e._isValid=!1);if(l[4]){if(!en.exec(l[4]))return void(e._isValid=!1);o="Z"}e._f=r+(a||"")+(o||""),fe(e)}else e._isValid=!1}function de(e,t,n,i,r,a){var o=[function(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}(e),Ht.indexOf(t),parseInt(n,10),parseInt(i,10),parseInt(r,10)];return a&&o.push(parseInt(a,10)),o}function he(e){var t,n,i,r=an.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim());if(r){var a=de(r[4],r[3],r[2],r[5],r[6],r[7]);if(t=r[1],n=a,i=e,t&&qt.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(c(i).weekdayMismatch=!0,!(i._isValid=!1)))return;e._a=a,e._tzm=function(e,t,n){if(e)return on[e];if(t)return 0;var i=parseInt(n,10),r=i%100;return(i-r)/100*60+r}(r[8],r[9],r[10]),e._d=z.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),c(e).rfc2822=!0}else e._isValid=!1}function fe(t){if(t._f!==e.ISO_8601)if(t._f!==e.RFC_2822){t._a=[],c(t).empty=!0;var n,i,r,a,o,l,u,d,h=""+t._i,f=h.length,p=0;for(r=N(t._f,t._locale).match(it)||[],n=0;n<r.length;n++)a=r[n],(i=(h.match(I(a,t))||[])[0])&&(0<(o=h.substr(0,h.indexOf(i))).length&&c(t).unusedInput.push(o),h=h.slice(h.indexOf(i)+i.length),p+=i.length),ot[a]?(i?c(t).empty=!1:c(t).unusedTokens.push(a),l=a,d=t,null!=(u=i)&&s(Tt,l)&&Tt[l](u,d._a,d,l)):t._strict&&!i&&c(t).unusedTokens.push(a);c(t).charsLeftOver=f-p,0<h.length&&c(t).unusedInput.push(h),t._a[xt]<=12&&!0===c(t).bigHour&&0<t._a[xt]&&(c(t).bigHour=void 0),c(t).parsedDateParts=t._a.slice(0),c(t).meridiem=t._meridiem,t._a[xt]=function(e,t,n){var i;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):(null!=e.isPM&&((i=e.isPM(n))&&t<12&&(t+=12),i||12!==t||(t=0)),t)}(t._locale,t._a[xt],t._meridiem),ue(t),se(t)}else he(t);else ce(t)}function pe(s){var u,g,v,y,_=s._i,b=s._f;return s._locale=s._locale||oe(s._l),null===_||void 0===b&&""===_?h({nullInput:!0}):("string"==typeof _&&(s._i=_=s._locale.preparse(_)),m(_)?new p(se(_)):(a(_)?s._d=_:t(b)?function(e){var t,n,i,r,a;if(0===e._f.length)return c(e).invalidFormat=!0,e._d=new Date(NaN);for(r=0;r<e._f.length;r++)a=0,t=f({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[r],fe(t),d(t)&&(a+=c(t).charsLeftOver,a+=10*c(t).unusedTokens.length,c(t).score=a,(null==i||a<i)&&(i=a,n=t));l(e,n||t)}(s):b?fe(s):i(g=(u=s)._i)?u._d=new Date(e.now()):a(g)?u._d=new Date(g.valueOf()):"string"==typeof g?(v=u,null===(y=rn.exec(v._i))?(ce(v),!1===v._isValid&&(delete v._isValid,he(v),!1===v._isValid&&(delete v._isValid,e.createFromInputFallback(v)))):v._d=new Date(+y[1])):t(g)?(u._a=o(g.slice(0),function(e){return parseInt(e,10)}),ue(u)):n(g)?function(e){if(!e._d){var t=k(e._i);e._a=o([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ue(e)}}(u):r(g)?u._d=new Date(g):e.createFromInputFallback(u),d(s)||(s._d=null),s))}function me(e,i,r,a,o){var s,l={};return!0!==r&&!1!==r||(a=r,r=void 0),(n(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0}(e)||t(e)&&0===e.length)&&(e=void 0),l._isAMomentObject=!0,l._useUTC=l._isUTC=o,l._l=r,l._i=e,l._f=i,l._strict=a,(s=new p(se(pe(l))))._nextDay&&(s.add(1,"d"),s._nextDay=void 0),s}function ge(e,t,n,i){return me(e,t,n,i,!1)}function ve(e,n){var i,r;if(1===n.length&&t(n[0])&&(n=n[0]),!n.length)return ge();for(i=n[0],r=1;r<n.length;++r)n[r].isValid()&&!n[r][e](i)||(i=n[r]);return i}function ye(e){var t=k(e),n=t.year||0,i=t.quarter||0,r=t.month||0,a=t.week||0,o=t.day||0,s=t.hour||0,l=t.minute||0,u=t.second||0,c=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===It.call(un,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,i=0;i<un.length;++i)if(e[un[i]]){if(n)return!1;parseFloat(e[un[i]])!==v(e[un[i]])&&(n=!0)}return!0}(t),this._milliseconds=+c+1e3*u+6e4*l+1e3*s*60*60,this._days=+o+7*a,this._months=+r+3*i+12*n,this._data={},this._locale=oe(),this._bubble()}function _e(e){return e instanceof ye}function be(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function $e(e,t){A(e,0,0,function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+E(~~(e/60),2)+t+E(~~e%60,2)})}function we(e,t){var n=(t||"").match(e);if(null===n)return null;var i=((n[n.length-1]||[])+"").match(cn)||["-",0,0],r=60*i[1]+v(i[2]);return 0===r?0:"+"===i[0]?r:-r}function Se(t,n){var i,r;return n._isUTC?(i=n.clone(),r=(m(t)||a(t)?t.valueOf():ge(t).valueOf())-i.valueOf(),i._d.setTime(i._d.valueOf()+r),e.updateOffset(i,!1),i):ge(t).local()}function Te(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Ce(){return!!this.isValid()&&this._isUTC&&0===this._offset}function De(e,t){var n,i,a,o=e,l=null;return _e(e)?o={ms:e._milliseconds,d:e._days,M:e._months}:r(e)?(o={},t?o[t]=e:o.milliseconds=e):(l=dn.exec(e))?(n="-"===l[1]?-1:1,o={y:0,d:v(l[kt])*n,h:v(l[xt])*n,m:v(l[Et])*n,s:v(l[At])*n,ms:v(be(1e3*l[Ot]))*n}):(l=hn.exec(e))?(n="-"===l[1]?-1:(l[1],1),o={y:ke(l[2],n),M:ke(l[3],n),w:ke(l[4],n),d:ke(l[5],n),h:ke(l[6],n),m:ke(l[7],n),s:ke(l[8],n)}):null==o?o={}:"object"==(void 0===o?"undefined":_typeof(o))&&("from"in o||"to"in o)&&(a=function(e,t){var n;return e.isValid()&&t.isValid()?(t=Se(t,e),e.isBefore(t)?n=xe(e,t):((n=xe(t,e)).milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}(ge(o.from),ge(o.to)),(o={}).ms=a.milliseconds,o.M=a.months),i=new ye(o),_e(e)&&s(e,"_locale")&&(i._locale=e._locale),i}function ke(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function xe(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function Ee(e,t){return function(n,i){var r;return null===i||isNaN(+i)||($(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),r=n,n=i,i=r),Ae(this,De(n="string"==typeof n?+n:n,i),e),this}}function Ae(t,n,i,r){var a=n._milliseconds,o=be(n._days),s=be(n._months);t.isValid()&&(r=null==r||r,s&&B(t,V(t,"Month")+s*i),o&&q(t,"Date",V(t,"Date")+o*i),a&&t._d.setTime(t._d.valueOf()+a*i),r&&e.updateOffset(t,o||s))}function Oe(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),i=e.clone().add(n,"months");return-(n+(t-i<0?(t-i)/(i-e.clone().add(n-1,"months")):(t-i)/(e.clone().add(n+1,"months")-i)))||0}function Ne(e){var t;return void 0===e?this._locale._abbr:(null!=(t=oe(e))&&(this._locale=t),this)}function Me(){return this._locale}function Ie(e,t){A(0,[e,e.length],0,t)}function Re(e,t,n,i,r){var a;return null==e?Z(this,i,r).year:((a=K(e,i,r))<t&&(t=a),function(e,t,n,i,r){var a=X(e,t,n,i,r),o=z(a.year,0,a.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.getUTCDate()),this}.call(this,e,t,n,i,r))}function Pe(e,t){t[Ot]=v(1e3*("0."+e))}function Le(e){return e}function He(e,t,n,i){var r=oe(),a=u().set(i,t);return r[n](a,e)}function Fe(e,t,n){if(r(e)&&(t=e,e=void 0),e=e||"",null!=t)return He(e,t,n,"month");var i,a=[];for(i=0;i<12;i++)a[i]=He(e,i,n,"month");return a}function Ye(e,t,n,i){"boolean"==typeof e?r(t)&&(n=t,t=void 0):(t=e,e=!1,r(n=t)&&(n=t,t=void 0)),t=t||"";var a,o=oe(),s=e?o._week.dow:0;if(null!=n)return He(t,(n+s)%7,i,"day");var l=[];for(a=0;a<7;a++)l[a]=He(t,(a+s)%7,i,"day");return l}function Ve(e,t,n,i){var r=De(t,n);return e._milliseconds+=i*r._milliseconds,e._days+=i*r._days,e._months+=i*r._months,e._bubble()}function qe(e){return e<0?Math.floor(e):Math.ceil(e)}function je(e){return 4800*e/146097}function Be(e){return 146097*e/4800}function We(e){return function(){return this.as(e)}}function Ue(e){return function(){return this.isValid()?this._data[e]:NaN}}function ze(e){return(0<e)-(e<0)||+e}function Ge(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n=Vn(this._milliseconds)/1e3,i=Vn(this._days),r=Vn(this._months);t=g((e=g(n/60))/60),n%=60,e%=60;var a=g(r/12),o=r%=12,s=i,l=t,u=e,c=n?n.toFixed(3).replace(/\.?0+$/,""):"",d=this.asSeconds();if(!d)return"P0D";var h=d<0?"-":"",f=ze(this._months)!==ze(d)?"-":"",p=ze(this._days)!==ze(d)?"-":"",m=ze(this._milliseconds)!==ze(d)?"-":"";return h+"P"+(a?f+a+"Y":"")+(o?f+o+"M":"")+(s?p+s+"D":"")+(l||u||c?"T":"")+(l?m+l+"H":"")+(u?m+u+"M":"")+(c?m+c+"S":"")}var Xe,Ze;Ze=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,i=0;i<n;i++)if(i in t&&e.call(this,t[i],i,t))return!0;return!1};var Ke,Qe=e.momentProperties=[],Je=!1,et={};e.suppressDeprecationWarnings=!1,e.deprecationHandler=null,Ke=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)s(e,t)&&n.push(t);return n};var tt={},nt={},it=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,rt=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,at={},ot={},st=/\d/,lt=/\d\d/,ut=/\d{3}/,ct=/\d{4}/,dt=/[+-]?\d{6}/,ht=/\d\d?/,ft=/\d\d\d\d?/,pt=/\d\d\d\d\d\d?/,mt=/\d{1,3}/,gt=/\d{1,4}/,vt=/[+-]?\d{1,6}/,yt=/\d+/,_t=/[+-]?\d+/,bt=/Z|[+-]\d\d:?\d\d/gi,$t=/Z|[+-]\d\d(?::?\d\d)?/gi,wt=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,St={},Tt={},Ct=0,Dt=1,kt=2,xt=3,Et=4,At=5,Ot=6,Nt=7,Mt=8;A("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),A(0,["YY",2],0,function(){return this.year()%100}),A(0,["YYYY",4],0,"year"),A(0,["YYYYY",5],0,"year"),A(0,["YYYYYY",6,!0],0,"year"),C("year","y"),x("year",1),M("Y",_t),M("YY",ht,lt),M("YYYY",gt,ct),M("YYYYY",vt,dt),M("YYYYYY",vt,dt),P(["YYYYY","YYYYYY"],Ct),P("YYYY",function(t,n){n[Ct]=2===t.length?e.parseTwoDigitYear(t):v(t)}),P("YY",function(t,n){n[Ct]=e.parseTwoDigitYear(t)}),P("Y",function(e,t){t[Ct]=parseInt(e,10)}),e.parseTwoDigitYear=function(e){return v(e)+(68<v(e)?1900:2e3)};var It,Rt=Y("FullYear",!0);It=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},A("M",["MM",2],"Mo",function(){return this.month()+1}),A("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),A("MMMM",0,0,function(e){return this.localeData().months(this,e)}),C("month","M"),x("month",8),M("M",ht),M("MM",ht,lt),M("MMM",function(e,t){return t.monthsShortRegex(e)}),M("MMMM",function(e,t){return t.monthsRegex(e)}),P(["M","MM"],function(e,t){t[Dt]=v(e)-1}),P(["MMM","MMMM"],function(e,t,n,i){var r=n._locale.monthsParse(e,i,n._strict);null!=r?t[Dt]=r:c(n).invalidMonth=e});var Pt=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Lt="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Ht="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Ft=wt,Yt=wt;A("w",["ww",2],"wo","week"),A("W",["WW",2],"Wo","isoWeek"),C("week","w"),C("isoWeek","W"),x("week",5),x("isoWeek",5),M("w",ht),M("ww",ht,lt),M("W",ht),M("WW",ht,lt),L(["w","ww","W","WW"],function(e,t,n,i){t[i.substr(0,1)]=v(e)}),A("d",0,"do","day"),A("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),A("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),A("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),A("e",0,0,"weekday"),A("E",0,0,"isoWeekday"),C("day","d"),C("weekday","e"),C("isoWeekday","E"),x("day",11),x("weekday",11),x("isoWeekday",11),M("d",ht),M("e",ht),M("E",ht),M("dd",function(e,t){return t.weekdaysMinRegex(e)}),M("ddd",function(e,t){return t.weekdaysShortRegex(e)}),M("dddd",function(e,t){return t.weekdaysRegex(e)}),L(["dd","ddd","dddd"],function(e,t,n,i){var r=n._locale.weekdaysParse(e,i,n._strict);null!=r?t.d=r:c(n).invalidWeekday=e}),L(["d","e","E"],function(e,t,n,i){t[i]=v(e)});var Vt="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),qt="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),jt="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Bt=wt,Wt=wt,Ut=wt;A("H",["HH",2],0,"hour"),A("h",["hh",2],0,J),A("k",["kk",2],0,function(){return this.hours()||24}),A("hmm",0,0,function(){return""+J.apply(this)+E(this.minutes(),2)}),A("hmmss",0,0,function(){return""+J.apply(this)+E(this.minutes(),2)+E(this.seconds(),2)}),A("Hmm",0,0,function(){return""+this.hours()+E(this.minutes(),2)}),A("Hmmss",0,0,function(){return""+this.hours()+E(this.minutes(),2)+E(this.seconds(),2)}),ee("a",!0),ee("A",!1),C("hour","h"),x("hour",13),M("a",te),M("A",te),M("H",ht),M("h",ht),M("k",ht),M("HH",ht,lt),M("hh",ht,lt),M("kk",ht,lt),M("hmm",ft),M("hmmss",pt),M("Hmm",ft),M("Hmmss",pt),P(["H","HH"],xt),P(["k","kk"],function(e,t,n){var i=v(e);t[xt]=24===i?0:i}),P(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),P(["h","hh"],function(e,t,n){t[xt]=v(e),c(n).bigHour=!0}),P("hmm",function(e,t,n){var i=e.length-2;t[xt]=v(e.substr(0,i)),t[Et]=v(e.substr(i)),c(n).bigHour=!0}),P("hmmss",function(e,t,n){var i=e.length-4,r=e.length-2;t[xt]=v(e.substr(0,i)),t[Et]=v(e.substr(i,2)),t[At]=v(e.substr(r)),c(n).bigHour=!0}),P("Hmm",function(e,t,n){var i=e.length-2;t[xt]=v(e.substr(0,i)),t[Et]=v(e.substr(i))}),P("Hmmss",function(e,t,n){var i=e.length-4,r=e.length-2;t[xt]=v(e.substr(0,i)),t[Et]=v(e.substr(i,2)),t[At]=v(e.substr(r))});var zt,Gt=Y("Hours",!0),Xt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Lt,monthsShort:Ht,week:{dow:0,doy:6},weekdays:Vt,weekdaysMin:jt,weekdaysShort:qt,meridiemParse:/[ap]\.?m?\.?/i},Zt={},Kt={},Qt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Jt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,en=/Z|[+-]\d\d(?::?\d\d)?/,tn=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],nn=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],rn=/^\/?Date\((\-?\d+)/i,an=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,on={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};e.createFromInputFallback=b("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),e.ISO_8601=function(){},e.RFC_2822=function(){};var sn=b("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=ge.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:h()}),ln=b("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=ge.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:h()}),un=["year","quarter","month","week","day","hour","minute","second","millisecond"];$e("Z",":"),$e("ZZ",""),M("Z",$t),M("ZZ",$t),P(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=we($t,e)});var cn=/([\+\-]|\d\d)/gi;e.updateOffset=function(){};var dn=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,hn=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;De.fn=ye.prototype,De.invalid=function(){return De(NaN)};var fn=Ee(1,"add"),pn=Ee(-1,"subtract");e.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",e.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var mn=b("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});A(0,["gg",2],0,function(){return this.weekYear()%100}),A(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ie("gggg","weekYear"),Ie("ggggg","weekYear"),Ie("GGGG","isoWeekYear"),Ie("GGGGG","isoWeekYear"),C("weekYear","gg"),C("isoWeekYear","GG"),x("weekYear",1),x("isoWeekYear",1),M("G",_t),M("g",_t),M("GG",ht,lt),M("gg",ht,lt),M("GGGG",gt,ct),M("gggg",gt,ct),M("GGGGG",vt,dt),M("ggggg",vt,dt),L(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,i){t[i.substr(0,2)]=v(e)}),L(["gg","GG"],function(t,n,i,r){n[r]=e.parseTwoDigitYear(t)}),A("Q",0,"Qo","quarter"),C("quarter","Q"),x("quarter",7),M("Q",st),P("Q",function(e,t){t[Dt]=3*(v(e)-1)}),A("D",["DD",2],"Do","date"),C("date","D"),x("date",9),M("D",ht),M("DD",ht,lt),M("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),P(["D","DD"],kt),P("Do",function(e,t){t[kt]=v(e.match(ht)[0])});var gn=Y("Date",!0);A("DDD",["DDDD",3],"DDDo","dayOfYear"),C("dayOfYear","DDD"),x("dayOfYear",4),M("DDD",mt),M("DDDD",ut),P(["DDD","DDDD"],function(e,t,n){n._dayOfYear=v(e)}),A("m",["mm",2],0,"minute"),C("minute","m"),x("minute",14),M("m",ht),M("mm",ht,lt),P(["m","mm"],Et);var vn=Y("Minutes",!1);A("s",["ss",2],0,"second"),C("second","s"),x("second",15),M("s",ht),M("ss",ht,lt),P(["s","ss"],At);var yn,_n=Y("Seconds",!1);for(A("S",0,0,function(){return~~(this.millisecond()/100)}),A(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),A(0,["SSS",3],0,"millisecond"),A(0,["SSSS",4],0,function(){return 10*this.millisecond()}),A(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),A(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),A(0,["SSSSSSS",7],0,function(){
return 1e4*this.millisecond()}),A(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),A(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),C("millisecond","ms"),x("millisecond",16),M("S",mt,st),M("SS",mt,lt),M("SSS",mt,ut),yn="SSSS";yn.length<=9;yn+="S")M(yn,yt);for(yn="S";yn.length<=9;yn+="S")P(yn,Pe);var bn=Y("Milliseconds",!1);A("z",0,0,"zoneAbbr"),A("zz",0,0,"zoneName");var $n=p.prototype;$n.add=fn,$n.calendar=function(t,n){var i=t||ge(),r=Se(i,this).startOf("day"),a=e.calendarFormat(this,r)||"sameElse",o=n&&(w(n[a])?n[a].call(this,i):n[a]);return this.format(o||this.localeData().calendar(a,this,ge(i)))},$n.clone=function(){return new p(this)},$n.diff=function(e,t,n){var i,r,a;if(!this.isValid())return NaN;if(!(i=Se(e,this)).isValid())return NaN;switch(r=6e4*(i.utcOffset()-this.utcOffset()),t=D(t)){case"year":a=Oe(this,i)/12;break;case"month":a=Oe(this,i);break;case"quarter":a=Oe(this,i)/3;break;case"second":a=(this-i)/1e3;break;case"minute":a=(this-i)/6e4;break;case"hour":a=(this-i)/36e5;break;case"day":a=(this-i-r)/864e5;break;case"week":a=(this-i-r)/6048e5;break;default:a=this-i}return n?a:g(a)},$n.endOf=function(e){return void 0===(e=D(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},$n.format=function(t){t||(t=this.isUtc()?e.defaultFormatUtc:e.defaultFormat);var n=O(this,t);return this.localeData().postformat(n)},$n.from=function(e,t){return this.isValid()&&(m(e)&&e.isValid()||ge(e).isValid())?De({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},$n.fromNow=function(e){return this.from(ge(),e)},$n.to=function(e,t){return this.isValid()&&(m(e)&&e.isValid()||ge(e).isValid())?De({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},$n.toNow=function(e){return this.to(ge(),e)},$n.get=function(e){return w(this[e=D(e)])?this[e]():this},$n.invalidAt=function(){return c(this).overflow},$n.isAfter=function(e,t){var n=m(e)?e:ge(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=D(i(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},$n.isBefore=function(e,t){var n=m(e)?e:ge(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=D(i(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},$n.isBetween=function(e,t,n,i){return("("===(i=i||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===i[1]?this.isBefore(t,n):!this.isAfter(t,n))},$n.isSame=function(e,t){var n,i=m(e)?e:ge(e);return!(!this.isValid()||!i.isValid())&&("millisecond"===(t=D(t||"millisecond"))?this.valueOf()===i.valueOf():(n=i.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},$n.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},$n.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},$n.isValid=function(){return d(this)},$n.lang=mn,$n.locale=Ne,$n.localeData=Me,$n.max=ln,$n.min=sn,$n.parsingFlags=function(){return l({},c(this))},$n.set=function(e,t){if("object"==(void 0===e?"undefined":_typeof(e)))for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:nt[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=k(e)),i=0;i<n.length;i++)this[n[i].unit](e[n[i].unit]);else if(w(this[e=D(e)]))return this[e](t);return this},$n.startOf=function(e){switch(e=D(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},$n.subtract=pn,$n.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},$n.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},$n.toDate=function(){return new Date(this.valueOf())},$n.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||9999<n.year()?O(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):w(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",O(n,"Z")):O(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},$n.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',i=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",r=t+'[")]';return this.format(n+i+"-MM-DD[T]HH:mm:ss.SSS"+r)},$n.toJSON=function(){return this.isValid()?this.toISOString():null},$n.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},$n.unix=function(){return Math.floor(this.valueOf()/1e3)},$n.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},$n.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},$n.year=Rt,$n.isLeapYear=function(){return F(this.year())},$n.weekYear=function(e){return Re.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},$n.isoWeekYear=function(e){return Re.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},$n.quarter=$n.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},$n.month=W,$n.daysInMonth=function(){return j(this.year(),this.month())},$n.week=$n.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},$n.isoWeek=$n.isoWeeks=function(e){var t=Z(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},$n.weeksInYear=function(){var e=this.localeData()._week;return K(this.year(),e.dow,e.doy)},$n.isoWeeksInYear=function(){return K(this.year(),1,4)},$n.date=gn,$n.day=$n.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,i=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-i,"d")):i},$n.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},$n.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=(n=e,i=this.localeData(),"string"==typeof n?i.weekdaysParse(n)%7||7:isNaN(n)?null:n);return this.day(this.day()%7?t:t-7)}return this.day()||7;var n,i},$n.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},$n.hour=$n.hours=Gt,$n.minute=$n.minutes=vn,$n.second=$n.seconds=_n,$n.millisecond=$n.milliseconds=bn,$n.utcOffset=function(t,n,i){var r,a=this._offset||0;if(!this.isValid())return null!=t?this:NaN;if(null!=t){if("string"==typeof t){if(null===(t=we($t,t)))return this}else Math.abs(t)<16&&!i&&(t*=60);return!this._isUTC&&n&&(r=Te(this)),this._offset=t,this._isUTC=!0,null!=r&&this.add(r,"m"),a!==t&&(!n||this._changeInProgress?Ae(this,De(t-a,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,e.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?a:Te(this)},$n.utc=function(e){return this.utcOffset(0,e)},$n.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Te(this),"m")),this},$n.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=we(bt,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},$n.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?ge(e).utcOffset():0,(this.utcOffset()-e)%60==0)},$n.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},$n.isLocal=function(){return!!this.isValid()&&!this._isUTC},$n.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},$n.isUtc=Ce,$n.isUTC=Ce,$n.zoneAbbr=function(){return this._isUTC?"UTC":""},$n.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},$n.dates=b("dates accessor is deprecated. Use date instead.",gn),$n.months=b("months accessor is deprecated. Use month instead",W),$n.years=b("years accessor is deprecated. Use year instead",Rt),$n.zone=b("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),$n.isDSTShifted=b("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!i(this._isDSTShifted))return this._isDSTShifted;var e={};if(f(e,this),(e=pe(e))._a){var t=e._isUTC?u(e._a):ge(e._a);this._isDSTShifted=this.isValid()&&0<y(e._a,t.toArray())}else this._isDSTShifted=!1;return this._isDSTShifted});var wn=T.prototype;wn.calendar=function(e,t,n){var i=this._calendar[e]||this._calendar.sameElse;return w(i)?i.call(t,n):i},wn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},wn.invalidDate=function(){return this._invalidDate},wn.ordinal=function(e){return this._ordinal.replace("%d",e)},wn.preparse=Le,wn.postformat=Le,wn.relativeTime=function(e,t,n,i){var r=this._relativeTime[n];return w(r)?r(e,t,n,i):r.replace(/%d/i,e)},wn.pastFuture=function(e,t){var n=this._relativeTime[0<e?"future":"past"];return w(n)?n(t):n.replace(/%s/i,t)},wn.set=function(e){var t,n;for(n in e)w(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},wn.months=function(e,n){return e?t(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||Pt).test(n)?"format":"standalone"][e.month()]:t(this._months)?this._months:this._months.standalone},wn.monthsShort=function(e,n){return e?t(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[Pt.test(n)?"format":"standalone"][e.month()]:t(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},wn.monthsParse=function(e,t,n){var i,r,a;if(this._monthsParseExact)return function(e,t,n){var i,r,a,o=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],i=0;i<12;++i)a=u([2e3,i]),this._shortMonthsParse[i]=this.monthsShort(a,"").toLocaleLowerCase(),this._longMonthsParse[i]=this.months(a,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(r=It.call(this._shortMonthsParse,o))?r:null:-1!==(r=It.call(this._longMonthsParse,o))?r:null:"MMM"===t?-1!==(r=It.call(this._shortMonthsParse,o))?r:-1!==(r=It.call(this._longMonthsParse,o))?r:null:-1!==(r=It.call(this._longMonthsParse,o))?r:-1!==(r=It.call(this._shortMonthsParse,o))?r:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),i=0;i<12;i++){if(r=u([2e3,i]),n&&!this._longMonthsParse[i]&&(this._longMonthsParse[i]=new RegExp("^"+this.months(r,"").replace(".","")+"$","i"),this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(r,"").replace(".","")+"$","i")),n||this._monthsParse[i]||(a="^"+this.months(r,"")+"|^"+this.monthsShort(r,""),this._monthsParse[i]=new RegExp(a.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[i].test(e))return i;if(n&&"MMM"===t&&this._shortMonthsParse[i].test(e))return i;if(!n&&this._monthsParse[i].test(e))return i}},wn.monthsRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||U.call(this),e?this._monthsStrictRegex:this._monthsRegex):(s(this,"_monthsRegex")||(this._monthsRegex=Yt),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},wn.monthsShortRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||U.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(s(this,"_monthsShortRegex")||(this._monthsShortRegex=Ft),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},wn.week=function(e){return Z(e,this._week.dow,this._week.doy).week},wn.firstDayOfYear=function(){return this._week.doy},wn.firstDayOfWeek=function(){return this._week.dow},wn.weekdays=function(e,n){return e?t(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(n)?"format":"standalone"][e.day()]:t(this._weekdays)?this._weekdays:this._weekdays.standalone},wn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},wn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},wn.weekdaysParse=function(e,t,n){var i,r,a;if(this._weekdaysParseExact)return function(e,t,n){var i,r,a,o=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],i=0;i<7;++i)a=u([2e3,1]).day(i),this._minWeekdaysParse[i]=this.weekdaysMin(a,"").toLocaleLowerCase(),this._shortWeekdaysParse[i]=this.weekdaysShort(a,"").toLocaleLowerCase(),this._weekdaysParse[i]=this.weekdays(a,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(r=It.call(this._weekdaysParse,o))?r:null:"ddd"===t?-1!==(r=It.call(this._shortWeekdaysParse,o))?r:null:-1!==(r=It.call(this._minWeekdaysParse,o))?r:null:"dddd"===t?-1!==(r=It.call(this._weekdaysParse,o))?r:-1!==(r=It.call(this._shortWeekdaysParse,o))?r:-1!==(r=It.call(this._minWeekdaysParse,o))?r:null:"ddd"===t?-1!==(r=It.call(this._shortWeekdaysParse,o))?r:-1!==(r=It.call(this._weekdaysParse,o))?r:-1!==(r=It.call(this._minWeekdaysParse,o))?r:null:-1!==(r=It.call(this._minWeekdaysParse,o))?r:-1!==(r=It.call(this._weekdaysParse,o))?r:-1!==(r=It.call(this._shortWeekdaysParse,o))?r:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),i=0;i<7;i++){if(r=u([2e3,1]).day(i),n&&!this._fullWeekdaysParse[i]&&(this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(r,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(r,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(r,"").replace(".",".?")+"$","i")),this._weekdaysParse[i]||(a="^"+this.weekdays(r,"")+"|^"+this.weekdaysShort(r,"")+"|^"+this.weekdaysMin(r,""),this._weekdaysParse[i]=new RegExp(a.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[i].test(e))return i;if(n&&"ddd"===t&&this._shortWeekdaysParse[i].test(e))return i;if(n&&"dd"===t&&this._minWeekdaysParse[i].test(e))return i;if(!n&&this._weekdaysParse[i].test(e))return i}},wn.weekdaysRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Q.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(s(this,"_weekdaysRegex")||(this._weekdaysRegex=Bt),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},wn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Q.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(s(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Wt),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},wn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Q.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(s(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Ut),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},wn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},wn.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},re("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===v(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),e.lang=b("moment.lang is deprecated. Use moment.locale instead.",re),e.langData=b("moment.langData is deprecated. Use moment.localeData instead.",oe);var Sn=Math.abs,Tn=We("ms"),Cn=We("s"),Dn=We("m"),kn=We("h"),xn=We("d"),En=We("w"),An=We("M"),On=We("y"),Nn=Ue("milliseconds"),Mn=Ue("seconds"),In=Ue("minutes"),Rn=Ue("hours"),Pn=Ue("days"),Ln=Ue("months"),Hn=Ue("years"),Fn=Math.round,Yn={ss:44,s:45,m:45,h:22,d:26,M:11},Vn=Math.abs,qn=ye.prototype;return qn.isValid=function(){return this._isValid},qn.abs=function(){var e=this._data;return this._milliseconds=Sn(this._milliseconds),this._days=Sn(this._days),this._months=Sn(this._months),e.milliseconds=Sn(e.milliseconds),e.seconds=Sn(e.seconds),e.minutes=Sn(e.minutes),e.hours=Sn(e.hours),e.months=Sn(e.months),e.years=Sn(e.years),this},qn.add=function(e,t){return Ve(this,e,t,1)},qn.subtract=function(e,t){return Ve(this,e,t,-1)},qn.as=function(e){if(!this.isValid())return NaN;var t,n,i=this._milliseconds;if("month"===(e=D(e))||"year"===e)return t=this._days+i/864e5,n=this._months+je(t),"month"===e?n:n/12;switch(t=this._days+Math.round(Be(this._months)),e){case"week":return t/7+i/6048e5;case"day":return t+i/864e5;case"hour":return 24*t+i/36e5;case"minute":return 1440*t+i/6e4;case"second":return 86400*t+i/1e3;case"millisecond":return Math.floor(864e5*t)+i;default:throw new Error("Unknown unit "+e)}},qn.asMilliseconds=Tn,qn.asSeconds=Cn,qn.asMinutes=Dn,qn.asHours=kn,qn.asDays=xn,qn.asWeeks=En,qn.asMonths=An,qn.asYears=On,qn.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*v(this._months/12):NaN},qn._bubble=function(){var e,t,n,i,r,a=this._milliseconds,o=this._days,s=this._months,l=this._data;return 0<=a&&0<=o&&0<=s||a<=0&&o<=0&&s<=0||(a+=864e5*qe(Be(s)+o),s=o=0),l.milliseconds=a%1e3,e=g(a/1e3),l.seconds=e%60,t=g(e/60),l.minutes=t%60,n=g(t/60),l.hours=n%24,s+=r=g(je(o+=g(n/24))),o-=qe(Be(r)),i=g(s/12),s%=12,l.days=o,l.months=s,l.years=i,this},qn.clone=function(){return De(this)},qn.get=function(e){return e=D(e),this.isValid()?this[e+"s"]():NaN},qn.milliseconds=Nn,qn.seconds=Mn,qn.minutes=In,qn.hours=Rn,qn.days=Pn,qn.weeks=function(){return g(this.days()/7)},qn.months=Ln,qn.years=Hn,qn.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t,n,i,r,a,o,s,l,u,c,d,h=this.localeData(),f=(n=!e,i=h,r=De(t=this).abs(),a=Fn(r.as("s")),o=Fn(r.as("m")),s=Fn(r.as("h")),l=Fn(r.as("d")),u=Fn(r.as("M")),c=Fn(r.as("y")),(d=a<=Yn.ss&&["s",a]||a<Yn.s&&["ss",a]||o<=1&&["m"]||o<Yn.m&&["mm",o]||s<=1&&["h"]||s<Yn.h&&["hh",s]||l<=1&&["d"]||l<Yn.d&&["dd",l]||u<=1&&["M"]||u<Yn.M&&["MM",u]||c<=1&&["y"]||["yy",c])[2]=n,d[3]=0<+t,d[4]=i,function(e,t,n,i,r){return r.relativeTime(t||1,!!n,e,i)}.apply(null,d));return e&&(f=h.pastFuture(+this,f)),h.postformat(f)},qn.toISOString=Ge,qn.toString=Ge,qn.toJSON=Ge,qn.locale=Ne,qn.localeData=Me,qn.toIsoString=b("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Ge),qn.lang=mn,A("X",0,0,"unix"),A("x",0,0,"valueOf"),M("x",_t),M("X",/[+-]?\d+(\.\d{1,3})?/),P("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),P("x",function(e,t,n){n._d=new Date(v(e))}),e.version="2.22.1",Xe=ge,e.fn=$n,e.min=function(){return ve("isBefore",[].slice.call(arguments,0))},e.max=function(){return ve("isAfter",[].slice.call(arguments,0))},e.now=function(){return Date.now?Date.now():+new Date},e.utc=u,e.unix=function(e){return ge(1e3*e)},e.months=function(e,t){return Fe(e,t,"months")},e.isDate=a,e.locale=re,e.invalid=h,e.duration=De,e.isMoment=m,e.weekdays=function(e,t,n){return Ye(e,t,n,"weekdays")},e.parseZone=function(){return ge.apply(null,arguments).parseZone()},e.localeData=oe,e.isDuration=_e,e.monthsShort=function(e,t){return Fe(e,t,"monthsShort")},e.weekdaysMin=function(e,t,n){return Ye(e,t,n,"weekdaysMin")},e.defineLocale=ae,e.updateLocale=function(e,t){if(null!=t){var n,i,r=Xt;null!=(i=ie(e))&&(r=i._config),(n=new T(t=S(r,t))).parentLocale=Zt[e],Zt[e]=n,re(e)}else null!=Zt[e]&&(null!=Zt[e].parentLocale?Zt[e]=Zt[e].parentLocale:null!=Zt[e]&&delete Zt[e]);return Zt[e]},e.locales=function(){return Ke(Zt)},e.weekdaysShort=function(e,t,n){return Ye(e,t,n,"weekdaysShort")},e.normalizeUnits=D,e.relativeTimeRounding=function(e){return void 0===e?Fn:"function"==typeof e&&(Fn=e,!0)},e.relativeTimeThreshold=function(e,t){return void 0!==Yn[e]&&(void 0===t?Yn[e]:(Yn[e]=t,"s"===e&&(Yn.ss=t-1),!0))},e.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},e.prototype=$n,e.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"YYYY-[W]WW",MONTH:"YYYY-MM"},e}),function(e,t){"object"==("undefined"==typeof exports?"undefined":_typeof(exports))&&"undefined"!=typeof module?t(exports,require("jquery"),require("popper.js")):"function"==typeof define&&define.amd?define(["exports","jquery","popper.js"],t):t(e.bootstrap={},e.jQuery,e.Popper)}(this,function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function r(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}).apply(this,arguments)}t=t&&t.hasOwnProperty("default")?t.default:t,n=n&&n.hasOwnProperty("default")?n.default:n;var o,s,l,u,c,d,h,f,p,m,g,v,y,_,b,$,w,S,T,C,D,k,x,E,A,O,N=function(e){function t(t){var n=this,r=!1;return e(this).one(i.TRANSITION_END,function(){r=!0}),setTimeout(function(){r||i.triggerTransitionEnd(n)},t),this}var n=!1,i={TRANSITION_END:"bsTransitionEnd",getUID:function(e){do{e+=~~(1e6*Math.random())}while(document.getElementById(e));return e},getSelectorFromElement:function(t){var n,i=t.getAttribute("data-target");i&&"#"!==i||(i=t.getAttribute("href")||""),"#"===i.charAt(0)&&(n=i,i=n="function"==typeof e.escapeSelector?e.escapeSelector(n).substr(1):n.replace(/(:|\.|\[|\]|,|=|@)/g,"\\$1"));try{return e(document).find(i).length>0?i:null}catch(e){return null}},reflow:function(e){return e.offsetHeight},triggerTransitionEnd:function(t){e(t).trigger(n.end)},supportsTransitionEnd:function(){return Boolean(n)},isElement:function(e){return(e[0]||e).nodeType},typeCheckConfig:function(e,t,n){for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r)){var a=n[r],o=t[r],s=o&&i.isElement(o)?"element":(l=o,{}.toString.call(l).match(/\s([a-zA-Z]+)/)[1].toLowerCase());if(!new RegExp(a).test(s))throw new Error(e.toUpperCase()+': Option "'+r+'" provided type "'+s+'" but expected type "'+a+'".')}var l}};return n=("undefined"==typeof window||!window.QUnit)&&{end:"transitionend"},e.fn.emulateTransitionEnd=t,i.supportsTransitionEnd()&&(e.event.special[i.TRANSITION_END]={bindType:n.end,delegateType:n.end,handle:function(t){if(e(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}}),i}(t),M=(s="alert",u="."+(l="bs.alert"),c=(o=t).fn[s],d={CLOSE:"close"+u,CLOSED:"closed"+u,CLICK_DATA_API:"click"+u+".data-api"},h="alert",f="fade",p="show",m=function(){function e(e){this._element=e}var t=e.prototype;return t.close=function(e){e=e||this._element;var t=this._getRootElement(e);this._triggerCloseEvent(t).isDefaultPrevented()||this._removeElement(t)},t.dispose=function(){o.removeData(this._element,l),this._element=null},t._getRootElement=function(e){var t=N.getSelectorFromElement(e),n=!1;return t&&(n=o(t)[0]),n||(n=o(e).closest("."+h)[0]),n},t._triggerCloseEvent=function(e){var t=o.Event(d.CLOSE);return o(e).trigger(t),t},t._removeElement=function(e){var t=this;o(e).removeClass(p),N.supportsTransitionEnd()&&o(e).hasClass(f)?o(e).one(N.TRANSITION_END,function(n){return t._destroyElement(e,n)}).emulateTransitionEnd(150):this._destroyElement(e)},t._destroyElement=function(e){o(e).detach().trigger(d.CLOSED).remove()},e._jQueryInterface=function(t){return this.each(function(){var n=o(this),i=n.data(l);i||(i=new e(this),n.data(l,i)),"close"===t&&i[t](this)})},e._handleDismiss=function(e){return function(t){t&&t.preventDefault(),e.close(this)}},r(e,null,[{key:"VERSION",get:function(){return"4.0.0"}}]),e}(),o(document).on(d.CLICK_DATA_API,'[data-dismiss="alert"]',m._handleDismiss(new m)),o.fn[s]=m._jQueryInterface,o.fn[s].Constructor=m,o.fn[s].noConflict=function(){return o.fn[s]=c,m._jQueryInterface},m),I=(v="button",_="."+(y="bs.button"),b=".data-api",$=(g=t).fn[v],w="active",S="btn",T="focus",C='[data-toggle^="button"]',D='[data-toggle="buttons"]',k="input",x=".active",E=".btn",A={CLICK_DATA_API:"click"+_+b,FOCUS_BLUR_DATA_API:"focus"+_+b+" blur"+_+b},O=function(){function e(e){this._element=e}var t=e.prototype;return t.toggle=function(){var e=!0,t=!0,n=g(this._element).closest(D)[0];if(n){var i=g(this._element).find(k)[0];if(i){if("radio"===i.type)if(i.checked&&g(this._element).hasClass(w))e=!1;else{var r=g(n).find(x)[0];r&&g(r).removeClass(w)}if(e){if(i.hasAttribute("disabled")||n.hasAttribute("disabled")||i.classList.contains("disabled")||n.classList.contains("disabled"))return;i.checked=!g(this._element).hasClass(w),g(i).trigger("change")}i.focus(),t=!1}}t&&this._element.setAttribute("aria-pressed",!g(this._element).hasClass(w)),e&&g(this._element).toggleClass(w)},t.dispose=function(){g.removeData(this._element,y),this._element=null},e._jQueryInterface=function(t){return this.each(function(){var n=g(this).data(y);n||(n=new e(this),g(this).data(y,n)),"toggle"===t&&n[t]()})},r(e,null,[{key:"VERSION",get:function(){return"4.0.0"}}]),e}(),g(document).on(A.CLICK_DATA_API,C,function(e){e.preventDefault();var t=e.target;g(t).hasClass(S)||(t=g(t).closest(E)),O._jQueryInterface.call(g(t),"toggle")}).on(A.FOCUS_BLUR_DATA_API,C,function(e){var t=g(e.target).closest(E)[0];g(t).toggleClass(T,/^focus(in)?$/.test(e.type))}),g.fn[v]=O._jQueryInterface,g.fn[v].Constructor=O,g.fn[v].noConflict=function(){return g.fn[v]=$,O._jQueryInterface},O),R=function(e){var t="carousel",n="bs.carousel",i="."+n,o=e.fn[t],s={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0},l={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean"},u="next",c="prev",d={SLIDE:"slide"+i,SLID:"slid"+i,KEYDOWN:"keydown"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i,TOUCHEND:"touchend"+i,LOAD_DATA_API:"load"+i+".data-api",CLICK_DATA_API:"click"+i+".data-api"},h="active",f={ACTIVE:".active",ACTIVE_ITEM:".active.carousel-item",ITEM:".carousel-item",NEXT_PREV:".carousel-item-next, .carousel-item-prev",INDICATORS:".carousel-indicators",DATA_SLIDE:"[data-slide], [data-slide-to]",DATA_RIDE:'[data-ride="carousel"]'},p=function(){function o(t,n){this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this._config=this._getConfig(n),this._element=e(t)[0],this._indicatorsElement=e(this._element).find(f.INDICATORS)[0],this._addEventListeners()}var p=o.prototype;return p.next=function(){this._isSliding||this._slide(u)},p.nextWhenVisible=function(){!document.hidden&&e(this._element).is(":visible")&&"hidden"!==e(this._element).css("visibility")&&this.next()},p.prev=function(){this._isSliding||this._slide(c)},p.pause=function(t){t||(this._isPaused=!0),e(this._element).find(f.NEXT_PREV)[0]&&N.supportsTransitionEnd()&&(N.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null},p.cycle=function(e){e||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))},p.to=function(t){var n=this;this._activeElement=e(this._element).find(f.ACTIVE_ITEM)[0];var i=this._getItemIndex(this._activeElement);if(!(t>this._items.length-1||t<0))if(this._isSliding)e(this._element).one(d.SLID,function(){return n.to(t)});else{if(i===t)return this.pause(),void this.cycle();var r=t>i?u:c;this._slide(r,this._items[t])}},p.dispose=function(){e(this._element).off(i),e.removeData(this._element,n),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null},p._getConfig=function(e){return e=a({},s,e),N.typeCheckConfig(t,e,l),e},p._addEventListeners=function(){var t=this;this._config.keyboard&&e(this._element).on(d.KEYDOWN,function(e){return t._keydown(e)}),"hover"===this._config.pause&&(e(this._element).on(d.MOUSEENTER,function(e){return t.pause(e)}).on(d.MOUSELEAVE,function(e){return t.cycle(e)}),"ontouchstart"in document.documentElement&&e(this._element).on(d.TOUCHEND,function(){t.pause(),t.touchTimeout&&clearTimeout(t.touchTimeout),t.touchTimeout=setTimeout(function(e){return t.cycle(e)},500+t._config.interval)}))},p._keydown=function(e){if(!/input|textarea/i.test(e.target.tagName))switch(e.which){case 37:e.preventDefault(),this.prev();break;case 39:e.preventDefault(),this.next()}},p._getItemIndex=function(t){return this._items=e.makeArray(e(t).parent().find(f.ITEM)),this._items.indexOf(t)},p._getItemByDirection=function(e,t){var n=e===u,i=e===c,r=this._getItemIndex(t),a=this._items.length-1;if((i&&0===r||n&&r===a)&&!this._config.wrap)return t;var o=(r+(e===c?-1:1))%this._items.length;return-1===o?this._items[this._items.length-1]:this._items[o]},p._triggerSlideEvent=function(t,n){var i=this._getItemIndex(t),r=this._getItemIndex(e(this._element).find(f.ACTIVE_ITEM)[0]),a=e.Event(d.SLIDE,{relatedTarget:t,direction:n,from:r,to:i});return e(this._element).trigger(a),a},p._setActiveIndicatorElement=function(t){if(this._indicatorsElement){e(this._indicatorsElement).find(f.ACTIVE).removeClass(h);var n=this._indicatorsElement.children[this._getItemIndex(t)];n&&e(n).addClass(h)}},p._slide=function(t,n){var i,r,a,o=this,s=e(this._element).find(f.ACTIVE_ITEM)[0],l=this._getItemIndex(s),c=n||s&&this._getItemByDirection(t,s),p=this._getItemIndex(c),m=Boolean(this._interval);if(t===u?(i="carousel-item-left",r="carousel-item-next",a="left"):(i="carousel-item-right",r="carousel-item-prev",a="right"),c&&e(c).hasClass(h))this._isSliding=!1;else if(!this._triggerSlideEvent(c,a).isDefaultPrevented()&&s&&c){this._isSliding=!0,m&&this.pause(),this._setActiveIndicatorElement(c);var g=e.Event(d.SLID,{relatedTarget:c,direction:a,from:l,to:p});N.supportsTransitionEnd()&&e(this._element).hasClass("slide")?(e(c).addClass(r),N.reflow(c),e(s).addClass(i),e(c).addClass(i),e(s).one(N.TRANSITION_END,function(){e(c).removeClass(i+" "+r).addClass(h),e(s).removeClass(h+" "+r+" "+i),o._isSliding=!1,setTimeout(function(){return e(o._element).trigger(g)},0)}).emulateTransitionEnd(600)):(e(s).removeClass(h),e(c).addClass(h),this._isSliding=!1,e(this._element).trigger(g)),m&&this.cycle()}},o._jQueryInterface=function(t){return this.each(function(){var i=e(this).data(n),r=a({},s,e(this).data());"object"==(void 0===t?"undefined":_typeof(t))&&(r=a({},r,t));var l="string"==typeof t?t:r.slide;if(i||(i=new o(this,r),e(this).data(n,i)),"number"==typeof t)i.to(t);else if("string"==typeof l){if(void 0===i[l])throw new TypeError('No method named "'+l+'"');i[l]()}else r.interval&&(i.pause(),i.cycle())})},o._dataApiClickHandler=function(t){var i=N.getSelectorFromElement(this);if(i){var r=e(i)[0];if(r&&e(r).hasClass("carousel")){var s=a({},e(r).data(),e(this).data()),l=this.getAttribute("data-slide-to");l&&(s.interval=!1),o._jQueryInterface.call(e(r),s),l&&e(r).data(n).to(l),t.preventDefault()}}},r(o,null,[{key:"VERSION",
get:function(){return"4.0.0"}},{key:"Default",get:function(){return s}}]),o}();return e(document).on(d.CLICK_DATA_API,f.DATA_SLIDE,p._dataApiClickHandler),e(window).on(d.LOAD_DATA_API,function(){e(f.DATA_RIDE).each(function(){var t=e(this);p._jQueryInterface.call(t,t.data())})}),e.fn[t]=p._jQueryInterface,e.fn[t].Constructor=p,e.fn[t].noConflict=function(){return e.fn[t]=o,p._jQueryInterface},p}(t),P=function(e){var t="collapse",n="bs.collapse",i="."+n,o=e.fn[t],s={toggle:!0,parent:""},l={toggle:"boolean",parent:"(string|element)"},u={SHOW:"show"+i,SHOWN:"shown"+i,HIDE:"hide"+i,HIDDEN:"hidden"+i,CLICK_DATA_API:"click"+i+".data-api"},c="show",d="collapse",h="collapsing",f="collapsed",p="width",m={ACTIVES:".show, .collapsing",DATA_TOGGLE:'[data-toggle="collapse"]'},g=function(){function i(t,n){this._isTransitioning=!1,this._element=t,this._config=this._getConfig(n),this._triggerArray=e.makeArray(e('[data-toggle="collapse"][href="#'+t.id+'"],[data-toggle="collapse"][data-target="#'+t.id+'"]'));for(var i=e(m.DATA_TOGGLE),r=0;r<i.length;r++){var a=i[r],o=N.getSelectorFromElement(a);null!==o&&e(o).filter(t).length>0&&(this._selector=o,this._triggerArray.push(a))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}var o=i.prototype;return o.toggle=function(){e(this._element).hasClass(c)?this.hide():this.show()},o.show=function(){var t,r,a=this;if(!(this._isTransitioning||e(this._element).hasClass(c)||(this._parent&&0===(t=e.makeArray(e(this._parent).find(m.ACTIVES).filter('[data-parent="'+this._config.parent+'"]'))).length&&(t=null),t&&(r=e(t).not(this._selector).data(n))&&r._isTransitioning))){var o=e.Event(u.SHOW);if(e(this._element).trigger(o),!o.isDefaultPrevented()){t&&(i._jQueryInterface.call(e(t).not(this._selector),"hide"),r||e(t).data(n,null));var s=this._getDimension();e(this._element).removeClass(d).addClass(h),this._element.style[s]=0,this._triggerArray.length>0&&e(this._triggerArray).removeClass(f).attr("aria-expanded",!0),this.setTransitioning(!0);var l=function(){e(a._element).removeClass(h).addClass(d).addClass(c),a._element.style[s]="",a.setTransitioning(!1),e(a._element).trigger(u.SHOWN)};if(N.supportsTransitionEnd()){var p="scroll"+(s[0].toUpperCase()+s.slice(1));e(this._element).one(N.TRANSITION_END,l).emulateTransitionEnd(600),this._element.style[s]=this._element[p]+"px"}else l()}}},o.hide=function(){var t=this;if(!this._isTransitioning&&e(this._element).hasClass(c)){var n=e.Event(u.HIDE);if(e(this._element).trigger(n),!n.isDefaultPrevented()){var i=this._getDimension();if(this._element.style[i]=this._element.getBoundingClientRect()[i]+"px",N.reflow(this._element),e(this._element).addClass(h).removeClass(d).removeClass(c),this._triggerArray.length>0)for(var r=0;r<this._triggerArray.length;r++){var a=this._triggerArray[r],o=N.getSelectorFromElement(a);null!==o&&(e(o).hasClass(c)||e(a).addClass(f).attr("aria-expanded",!1))}this.setTransitioning(!0);var s=function(){t.setTransitioning(!1),e(t._element).removeClass(h).addClass(d).trigger(u.HIDDEN)};this._element.style[i]="",N.supportsTransitionEnd()?e(this._element).one(N.TRANSITION_END,s).emulateTransitionEnd(600):s()}}},o.setTransitioning=function(e){this._isTransitioning=e},o.dispose=function(){e.removeData(this._element,n),this._config=null,this._parent=null,this._element=null,this._triggerArray=null,this._isTransitioning=null},o._getConfig=function(e){return(e=a({},s,e)).toggle=Boolean(e.toggle),N.typeCheckConfig(t,e,l),e},o._getDimension=function(){return e(this._element).hasClass(p)?p:"height"},o._getParent=function(){var t=this,n=null;N.isElement(this._config.parent)?(n=this._config.parent,void 0!==this._config.parent.jquery&&(n=this._config.parent[0])):n=e(this._config.parent)[0];var r='[data-toggle="collapse"][data-parent="'+this._config.parent+'"]';return e(n).find(r).each(function(e,n){t._addAriaAndCollapsedClass(i._getTargetFromElement(n),[n])}),n},o._addAriaAndCollapsedClass=function(t,n){if(t){var i=e(t).hasClass(c);n.length>0&&e(n).toggleClass(f,!i).attr("aria-expanded",i)}},i._getTargetFromElement=function(t){var n=N.getSelectorFromElement(t);return n?e(n)[0]:null},i._jQueryInterface=function(t){return this.each(function(){var r=e(this),o=r.data(n),l=a({},s,r.data(),"object"==(void 0===t?"undefined":_typeof(t))&&t);if(!o&&l.toggle&&/show|hide/.test(t)&&(l.toggle=!1),o||(o=new i(this,l),r.data(n,o)),"string"==typeof t){if(void 0===o[t])throw new TypeError('No method named "'+t+'"');o[t]()}})},r(i,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return s}}]),i}();return e(document).on(u.CLICK_DATA_API,m.DATA_TOGGLE,function(t){"A"===t.currentTarget.tagName&&t.preventDefault();var i=e(this),r=N.getSelectorFromElement(this);e(r).each(function(){var t=e(this),r=t.data(n)?"toggle":i.data();g._jQueryInterface.call(t,r)})}),e.fn[t]=g._jQueryInterface,e.fn[t].Constructor=g,e.fn[t].noConflict=function(){return e.fn[t]=o,g._jQueryInterface},g}(t),L=function(e){var t="dropdown",i="bs.dropdown",o="."+i,s=".data-api",l=e.fn[t],u=new RegExp("38|40|27"),c={HIDE:"hide"+o,HIDDEN:"hidden"+o,SHOW:"show"+o,SHOWN:"shown"+o,CLICK:"click"+o,CLICK_DATA_API:"click"+o+s,KEYDOWN_DATA_API:"keydown"+o+s,KEYUP_DATA_API:"keyup"+o+s},d="disabled",h="show",f="dropup",p="dropdown-menu-right",m='[data-toggle="dropdown"]',g=".dropdown-menu",v={offset:0,flip:!0,boundary:"scrollParent"},y={offset:"(number|string|function)",flip:"boolean",boundary:"(string|element)"},_=function(){function s(e,t){this._element=e,this._popper=null,this._config=this._getConfig(t),this._menu=this._getMenuElement(),this._inNavbar=this._detectNavbar(),this._addEventListeners()}var l=s.prototype;return l.toggle=function(){if(!this._element.disabled&&!e(this._element).hasClass(d)){var t=s._getParentFromElement(this._element),i=e(this._menu).hasClass(h);if(s._clearMenus(),!i){var r={relatedTarget:this._element},a=e.Event(c.SHOW,r);if(e(t).trigger(a),!a.isDefaultPrevented()){if(!this._inNavbar){if(void 0===n)throw new TypeError("Bootstrap dropdown require Popper.js (https://popper.js.org)");var o=this._element;e(t).hasClass(f)&&(e(this._menu).hasClass("dropdown-menu-left")||e(this._menu).hasClass(p))&&(o=t),"scrollParent"!==this._config.boundary&&e(t).addClass("position-static"),this._popper=new n(o,this._menu,this._getPopperConfig())}"ontouchstart"in document.documentElement&&0===e(t).closest(".navbar-nav").length&&e("body").children().on("mouseover",null,e.noop),this._element.focus(),this._element.setAttribute("aria-expanded",!0),e(this._menu).toggleClass(h),e(t).toggleClass(h).trigger(e.Event(c.SHOWN,r))}}}},l.dispose=function(){e.removeData(this._element,i),e(this._element).off(o),this._element=null,this._menu=null,null!==this._popper&&(this._popper.destroy(),this._popper=null)},l.update=function(){this._inNavbar=this._detectNavbar(),null!==this._popper&&this._popper.scheduleUpdate()},l._addEventListeners=function(){var t=this;e(this._element).on(c.CLICK,function(e){e.preventDefault(),e.stopPropagation(),t.toggle()})},l._getConfig=function(n){return n=a({},this.constructor.Default,e(this._element).data(),n),N.typeCheckConfig(t,n,this.constructor.DefaultType),n},l._getMenuElement=function(){if(!this._menu){var t=s._getParentFromElement(this._element);this._menu=e(t).find(g)[0]}return this._menu},l._getPlacement=function(){var t=e(this._element).parent(),n="bottom-start";return t.hasClass(f)?(n="top-start",e(this._menu).hasClass(p)&&(n="top-end")):t.hasClass("dropright")?n="right-start":t.hasClass("dropleft")?n="left-start":e(this._menu).hasClass(p)&&(n="bottom-end"),n},l._detectNavbar=function(){return e(this._element).closest(".navbar").length>0},l._getPopperConfig=function(){var e=this,t={};return"function"==typeof this._config.offset?t.fn=function(t){return t.offsets=a({},t.offsets,e._config.offset(t.offsets)||{}),t}:t.offset=this._config.offset,{placement:this._getPlacement(),modifiers:{offset:t,flip:{enabled:this._config.flip},preventOverflow:{boundariesElement:this._config.boundary}}}},s._jQueryInterface=function(t){return this.each(function(){var n=e(this).data(i);if(n||(n=new s(this,"object"==(void 0===t?"undefined":_typeof(t))?t:null),e(this).data(i,n)),"string"==typeof t){if(void 0===n[t])throw new TypeError('No method named "'+t+'"');n[t]()}})},s._clearMenus=function(t){if(!t||3!==t.which&&("keyup"!==t.type||9===t.which))for(var n=e.makeArray(e(m)),r=0;r<n.length;r++){var a=s._getParentFromElement(n[r]),o=e(n[r]).data(i),l={relatedTarget:n[r]};if(o){var u=o._menu;if(e(a).hasClass(h)&&!(t&&("click"===t.type&&/input|textarea/i.test(t.target.tagName)||"keyup"===t.type&&9===t.which)&&e.contains(a,t.target))){var d=e.Event(c.HIDE,l);e(a).trigger(d),d.isDefaultPrevented()||("ontouchstart"in document.documentElement&&e("body").children().off("mouseover",null,e.noop),n[r].setAttribute("aria-expanded","false"),e(u).removeClass(h),e(a).removeClass(h).trigger(e.Event(c.HIDDEN,l)))}}}},s._getParentFromElement=function(t){var n,i=N.getSelectorFromElement(t);return i&&(n=e(i)[0]),n||t.parentNode},s._dataApiKeydownHandler=function(t){if((/input|textarea/i.test(t.target.tagName)?!(32===t.which||27!==t.which&&(40!==t.which&&38!==t.which||e(t.target).closest(g).length)):u.test(t.which))&&(t.preventDefault(),t.stopPropagation(),!this.disabled&&!e(this).hasClass(d))){var n=s._getParentFromElement(this),i=e(n).hasClass(h);if((i||27===t.which&&32===t.which)&&(!i||27!==t.which&&32!==t.which)){var r=e(n).find(".dropdown-menu .dropdown-item:not(.disabled)").get();if(0!==r.length){var a=r.indexOf(t.target);38===t.which&&a>0&&a--,40===t.which&&a<r.length-1&&a++,a<0&&(a=0),r[a].focus()}}else{if(27===t.which){var o=e(n).find(m)[0];e(o).trigger("focus")}e(this).trigger("click")}}},r(s,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return v}},{key:"DefaultType",get:function(){return y}}]),s}();return e(document).on(c.KEYDOWN_DATA_API,m,_._dataApiKeydownHandler).on(c.KEYDOWN_DATA_API,g,_._dataApiKeydownHandler).on(c.CLICK_DATA_API+" "+c.KEYUP_DATA_API,_._clearMenus).on(c.CLICK_DATA_API,m,function(t){t.preventDefault(),t.stopPropagation(),_._jQueryInterface.call(e(this),"toggle")}).on(c.CLICK_DATA_API,".dropdown form",function(e){e.stopPropagation()}),e.fn[t]=_._jQueryInterface,e.fn[t].Constructor=_,e.fn[t].noConflict=function(){return e.fn[t]=l,_._jQueryInterface},_}(t),H=function(e){var t="bs.modal",n="."+t,i=e.fn.modal,o={backdrop:!0,keyboard:!0,focus:!0,show:!0},s={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean",show:"boolean"},l={HIDE:"hide"+n,HIDDEN:"hidden"+n,SHOW:"show"+n,SHOWN:"shown"+n,FOCUSIN:"focusin"+n,RESIZE:"resize"+n,CLICK_DISMISS:"click.dismiss"+n,KEYDOWN_DISMISS:"keydown.dismiss"+n,MOUSEUP_DISMISS:"mouseup.dismiss"+n,MOUSEDOWN_DISMISS:"mousedown.dismiss"+n,CLICK_DATA_API:"click"+n+".data-api"},u="modal-open",c="fade",d="show",h={DIALOG:".modal-dialog",DATA_TOGGLE:'[data-toggle="modal"]',DATA_DISMISS:'[data-dismiss="modal"]',FIXED_CONTENT:".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",STICKY_CONTENT:".sticky-top",NAVBAR_TOGGLER:".navbar-toggler"},f=function(){function i(t,n){this._config=this._getConfig(n),this._element=t,this._dialog=e(t).find(h.DIALOG)[0],this._backdrop=null,this._isShown=!1,this._isBodyOverflowing=!1,this._ignoreBackdropClick=!1,this._originalBodyPadding=0,this._scrollbarWidth=0}var f=i.prototype;return f.toggle=function(e){return this._isShown?this.hide():this.show(e)},f.show=function(t){var n=this;if(!this._isTransitioning&&!this._isShown){N.supportsTransitionEnd()&&e(this._element).hasClass(c)&&(this._isTransitioning=!0);var i=e.Event(l.SHOW,{relatedTarget:t});e(this._element).trigger(i),this._isShown||i.isDefaultPrevented()||(this._isShown=!0,this._checkScrollbar(),this._setScrollbar(),this._adjustDialog(),e(document.body).addClass(u),this._setEscapeEvent(),this._setResizeEvent(),e(this._element).on(l.CLICK_DISMISS,h.DATA_DISMISS,function(e){return n.hide(e)}),e(this._dialog).on(l.MOUSEDOWN_DISMISS,function(){e(n._element).one(l.MOUSEUP_DISMISS,function(t){e(t.target).is(n._element)&&(n._ignoreBackdropClick=!0)})}),this._showBackdrop(function(){return n._showElement(t)}))}},f.hide=function(t){var n=this;if(t&&t.preventDefault(),!this._isTransitioning&&this._isShown){var i=e.Event(l.HIDE);if(e(this._element).trigger(i),this._isShown&&!i.isDefaultPrevented()){this._isShown=!1;var r=N.supportsTransitionEnd()&&e(this._element).hasClass(c);r&&(this._isTransitioning=!0),this._setEscapeEvent(),this._setResizeEvent(),e(document).off(l.FOCUSIN),e(this._element).removeClass(d),e(this._element).off(l.CLICK_DISMISS),e(this._dialog).off(l.MOUSEDOWN_DISMISS),r?e(this._element).one(N.TRANSITION_END,function(e){return n._hideModal(e)}).emulateTransitionEnd(300):this._hideModal()}}},f.dispose=function(){e.removeData(this._element,t),e(window,document,this._element,this._backdrop).off(n),this._config=null,this._element=null,this._dialog=null,this._backdrop=null,this._isShown=null,this._isBodyOverflowing=null,this._ignoreBackdropClick=null,this._scrollbarWidth=null},f.handleUpdate=function(){this._adjustDialog()},f._getConfig=function(e){return e=a({},o,e),N.typeCheckConfig("modal",e,s),e},f._showElement=function(t){var n=this,i=N.supportsTransitionEnd()&&e(this._element).hasClass(c);this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.scrollTop=0,i&&N.reflow(this._element),e(this._element).addClass(d),this._config.focus&&this._enforceFocus();var r=e.Event(l.SHOWN,{relatedTarget:t}),a=function(){n._config.focus&&n._element.focus(),n._isTransitioning=!1,e(n._element).trigger(r)};i?e(this._dialog).one(N.TRANSITION_END,a).emulateTransitionEnd(300):a()},f._enforceFocus=function(){var t=this;e(document).off(l.FOCUSIN).on(l.FOCUSIN,function(n){document!==n.target&&t._element!==n.target&&0===e(t._element).has(n.target).length&&t._element.focus()})},f._setEscapeEvent=function(){var t=this;this._isShown&&this._config.keyboard?e(this._element).on(l.KEYDOWN_DISMISS,function(e){27===e.which&&(e.preventDefault(),t.hide())}):this._isShown||e(this._element).off(l.KEYDOWN_DISMISS)},f._setResizeEvent=function(){var t=this;this._isShown?e(window).on(l.RESIZE,function(e){return t.handleUpdate(e)}):e(window).off(l.RESIZE)},f._hideModal=function(){var t=this;this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._isTransitioning=!1,this._showBackdrop(function(){e(document.body).removeClass(u),t._resetAdjustments(),t._resetScrollbar(),e(t._element).trigger(l.HIDDEN)})},f._removeBackdrop=function(){this._backdrop&&(e(this._backdrop).remove(),this._backdrop=null)},f._showBackdrop=function(t){var n=this,i=e(this._element).hasClass(c)?c:"";if(this._isShown&&this._config.backdrop){var r=N.supportsTransitionEnd()&&i;if(this._backdrop=document.createElement("div"),this._backdrop.className="modal-backdrop",i&&e(this._backdrop).addClass(i),e(this._backdrop).appendTo(document.body),e(this._element).on(l.CLICK_DISMISS,function(e){n._ignoreBackdropClick?n._ignoreBackdropClick=!1:e.target===e.currentTarget&&("static"===n._config.backdrop?n._element.focus():n.hide())}),r&&N.reflow(this._backdrop),e(this._backdrop).addClass(d),!t)return;if(!r)return void t();e(this._backdrop).one(N.TRANSITION_END,t).emulateTransitionEnd(150)}else if(!this._isShown&&this._backdrop){e(this._backdrop).removeClass(d);var a=function(){n._removeBackdrop(),t&&t()};N.supportsTransitionEnd()&&e(this._element).hasClass(c)?e(this._backdrop).one(N.TRANSITION_END,a).emulateTransitionEnd(150):a()}else t&&t()},f._adjustDialog=function(){var e=this._element.scrollHeight>document.documentElement.clientHeight;!this._isBodyOverflowing&&e&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!e&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},f._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},f._checkScrollbar=function(){var e=document.body.getBoundingClientRect();this._isBodyOverflowing=e.left+e.right<window.innerWidth,this._scrollbarWidth=this._getScrollbarWidth()},f._setScrollbar=function(){var t=this;if(this._isBodyOverflowing){e(h.FIXED_CONTENT).each(function(n,i){var r=e(i)[0].style.paddingRight,a=e(i).css("padding-right");e(i).data("padding-right",r).css("padding-right",parseFloat(a)+t._scrollbarWidth+"px")}),e(h.STICKY_CONTENT).each(function(n,i){var r=e(i)[0].style.marginRight,a=e(i).css("margin-right");e(i).data("margin-right",r).css("margin-right",parseFloat(a)-t._scrollbarWidth+"px")}),e(h.NAVBAR_TOGGLER).each(function(n,i){var r=e(i)[0].style.marginRight,a=e(i).css("margin-right");e(i).data("margin-right",r).css("margin-right",parseFloat(a)+t._scrollbarWidth+"px")});var n=document.body.style.paddingRight,i=e("body").css("padding-right");e("body").data("padding-right",n).css("padding-right",parseFloat(i)+this._scrollbarWidth+"px")}},f._resetScrollbar=function(){e(h.FIXED_CONTENT).each(function(t,n){var i=e(n).data("padding-right");void 0!==i&&e(n).css("padding-right",i).removeData("padding-right")}),e(h.STICKY_CONTENT+", "+h.NAVBAR_TOGGLER).each(function(t,n){var i=e(n).data("margin-right");void 0!==i&&e(n).css("margin-right",i).removeData("margin-right")});var t=e("body").data("padding-right");void 0!==t&&e("body").css("padding-right",t).removeData("padding-right")},f._getScrollbarWidth=function(){var e=document.createElement("div");e.className="modal-scrollbar-measure",document.body.appendChild(e);var t=e.getBoundingClientRect().width-e.clientWidth;return document.body.removeChild(e),t},i._jQueryInterface=function(n,r){return this.each(function(){var o=e(this).data(t),s=a({},i.Default,e(this).data(),"object"==(void 0===n?"undefined":_typeof(n))&&n);if(o||(o=new i(this,s),e(this).data(t,o)),"string"==typeof n){if(void 0===o[n])throw new TypeError('No method named "'+n+'"');o[n](r)}else s.show&&o.show(r)})},r(i,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return o}}]),i}();return e(document).on(l.CLICK_DATA_API,h.DATA_TOGGLE,function(n){var i,r=this,o=N.getSelectorFromElement(this);o&&(i=e(o)[0]);var s=e(i).data(t)?"toggle":a({},e(i).data(),e(this).data());"A"!==this.tagName&&"AREA"!==this.tagName||n.preventDefault();var u=e(i).one(l.SHOW,function(t){t.isDefaultPrevented()||u.one(l.HIDDEN,function(){e(r).is(":visible")&&r.focus()})});f._jQueryInterface.call(e(i),s,this)}),e.fn.modal=f._jQueryInterface,e.fn.modal.Constructor=f,e.fn.modal.noConflict=function(){return e.fn.modal=i,f._jQueryInterface},f}(t),F=function(e){var t="tooltip",i="bs.tooltip",o="."+i,s=e.fn[t],l=new RegExp("(^|\\s)bs-tooltip\\S+","g"),u={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(number|string)",container:"(string|element|boolean)",fallbackPlacement:"(string|array)",boundary:"(string|element)"},c={AUTO:"auto",TOP:"top",RIGHT:"right",BOTTOM:"bottom",LEFT:"left"},d={animation:!0,template:'<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent"},h="show",f="out",p={HIDE:"hide"+o,HIDDEN:"hidden"+o,SHOW:"show"+o,SHOWN:"shown"+o,INSERTED:"inserted"+o,CLICK:"click"+o,FOCUSIN:"focusin"+o,FOCUSOUT:"focusout"+o,MOUSEENTER:"mouseenter"+o,MOUSELEAVE:"mouseleave"+o},m="fade",g="show",v="hover",y="focus",_=function(){function s(e,t){if(void 0===n)throw new TypeError("Bootstrap tooltips require Popper.js (https://popper.js.org)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=e,this.config=this._getConfig(t),this.tip=null,this._setListeners()}var _=s.prototype;return _.enable=function(){this._isEnabled=!0},_.disable=function(){this._isEnabled=!1},_.toggleEnabled=function(){this._isEnabled=!this._isEnabled},_.toggle=function(t){if(this._isEnabled)if(t){var n=this.constructor.DATA_KEY,i=e(t.currentTarget).data(n);i||(i=new this.constructor(t.currentTarget,this._getDelegateConfig()),e(t.currentTarget).data(n,i)),i._activeTrigger.click=!i._activeTrigger.click,i._isWithActiveTrigger()?i._enter(null,i):i._leave(null,i)}else{if(e(this.getTipElement()).hasClass(g))return void this._leave(null,this);this._enter(null,this)}},_.dispose=function(){clearTimeout(this._timeout),e.removeData(this.element,this.constructor.DATA_KEY),e(this.element).off(this.constructor.EVENT_KEY),e(this.element).closest(".modal").off("hide.bs.modal"),this.tip&&e(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,null!==this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},_.show=function(){var t=this;if("none"===e(this.element).css("display"))throw new Error("Please use show on visible elements");var i=e.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){e(this.element).trigger(i);var r=e.contains(this.element.ownerDocument.documentElement,this.element);if(i.isDefaultPrevented()||!r)return;var a=this.getTipElement(),o=N.getUID(this.constructor.NAME);a.setAttribute("id",o),this.element.setAttribute("aria-describedby",o),this.setContent(),this.config.animation&&e(a).addClass(m);var l="function"==typeof this.config.placement?this.config.placement.call(this,a,this.element):this.config.placement,u=this._getAttachment(l);this.addAttachmentClass(u);var c=!1===this.config.container?document.body:e(this.config.container);e(a).data(this.constructor.DATA_KEY,this),e.contains(this.element.ownerDocument.documentElement,this.tip)||e(a).appendTo(c),e(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new n(this.element,a,{placement:u,modifiers:{offset:{offset:this.config.offset},flip:{behavior:this.config.fallbackPlacement},arrow:{element:".arrow"},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(e){e.originalPlacement!==e.placement&&t._handlePopperPlacementChange(e)},onUpdate:function(e){t._handlePopperPlacementChange(e)}}),e(a).addClass(g),"ontouchstart"in document.documentElement&&e("body").children().on("mouseover",null,e.noop);var d=function(){t.config.animation&&t._fixTransition();var n=t._hoverState;t._hoverState=null,e(t.element).trigger(t.constructor.Event.SHOWN),n===f&&t._leave(null,t)};N.supportsTransitionEnd()&&e(this.tip).hasClass(m)?e(this.tip).one(N.TRANSITION_END,d).emulateTransitionEnd(s._TRANSITION_DURATION):d()}},_.hide=function(t){var n=this,i=this.getTipElement(),r=e.Event(this.constructor.Event.HIDE),a=function(){n._hoverState!==h&&i.parentNode&&i.parentNode.removeChild(i),n._cleanTipClass(),n.element.removeAttribute("aria-describedby"),e(n.element).trigger(n.constructor.Event.HIDDEN),null!==n._popper&&n._popper.destroy(),t&&t()};e(this.element).trigger(r),r.isDefaultPrevented()||(e(i).removeClass(g),"ontouchstart"in document.documentElement&&e("body").children().off("mouseover",null,e.noop),this._activeTrigger.click=!1,this._activeTrigger[y]=!1,this._activeTrigger[v]=!1,N.supportsTransitionEnd()&&e(this.tip).hasClass(m)?e(i).one(N.TRANSITION_END,a).emulateTransitionEnd(150):a(),this._hoverState="")},_.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},_.isWithContent=function(){return Boolean(this.getTitle())},_.addAttachmentClass=function(t){e(this.getTipElement()).addClass("bs-tooltip-"+t)},_.getTipElement=function(){return this.tip=this.tip||e(this.config.template)[0],this.tip},_.setContent=function(){var t=e(this.getTipElement());this.setElementContent(t.find(".tooltip-inner"),this.getTitle()),t.removeClass(m+" "+g)},_.setElementContent=function(t,n){var i=this.config.html;"object"==(void 0===n?"undefined":_typeof(n))&&(n.nodeType||n.jquery)?i?e(n).parent().is(t)||t.empty().append(n):t.text(e(n).text()):t[i?"html":"text"](n)},_.getTitle=function(){var e=this.element.getAttribute("data-original-title");return e||(e="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),e},_._getAttachment=function(e){return c[e.toUpperCase()]},_._setListeners=function(){var t=this;this.config.trigger.split(" ").forEach(function(n){if("click"===n)e(t.element).on(t.constructor.Event.CLICK,t.config.selector,function(e){return t.toggle(e)});else if("manual"!==n){var i=n===v?t.constructor.Event.MOUSEENTER:t.constructor.Event.FOCUSIN,r=n===v?t.constructor.Event.MOUSELEAVE:t.constructor.Event.FOCUSOUT;e(t.element).on(i,t.config.selector,function(e){return t._enter(e)}).on(r,t.config.selector,function(e){return t._leave(e)})}e(t.element).closest(".modal").on("hide.bs.modal",function(){return t.hide()})}),this.config.selector?this.config=a({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},_._fixTitle=function(){var e=_typeof(this.element.getAttribute("data-original-title"));(this.element.getAttribute("title")||"string"!==e)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},_._enter=function(t,n){var i=this.constructor.DATA_KEY;(n=n||e(t.currentTarget).data(i))||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),e(t.currentTarget).data(i,n)),t&&(n._activeTrigger["focusin"===t.type?y:v]=!0),e(n.getTipElement()).hasClass(g)||n._hoverState===h?n._hoverState=h:(clearTimeout(n._timeout),n._hoverState=h,n.config.delay&&n.config.delay.show?n._timeout=setTimeout(function(){n._hoverState===h&&n.show()},n.config.delay.show):n.show())},_._leave=function(t,n){var i=this.constructor.DATA_KEY;(n=n||e(t.currentTarget).data(i))||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),e(t.currentTarget).data(i,n)),t&&(n._activeTrigger["focusout"===t.type?y:v]=!1),n._isWithActiveTrigger()||(clearTimeout(n._timeout),n._hoverState=f,n.config.delay&&n.config.delay.hide?n._timeout=setTimeout(function(){n._hoverState===f&&n.hide()},n.config.delay.hide):n.hide())},_._isWithActiveTrigger=function(){for(var e in this._activeTrigger)if(this._activeTrigger[e])return!0;return!1},_._getConfig=function(n){return"number"==typeof(n=a({},this.constructor.Default,e(this.element).data(),n)).delay&&(n.delay={show:n.delay,hide:n.delay}),"number"==typeof n.title&&(n.title=n.title.toString()),"number"==typeof n.content&&(n.content=n.content.toString()),N.typeCheckConfig(t,n,this.constructor.DefaultType),n},_._getDelegateConfig=function(){var e={};if(this.config)for(var t in this.config)this.constructor.Default[t]!==this.config[t]&&(e[t]=this.config[t]);return e},_._cleanTipClass=function(){var t=e(this.getTipElement()),n=t.attr("class").match(l);null!==n&&n.length>0&&t.removeClass(n.join(""))},_._handlePopperPlacementChange=function(e){this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(e.placement))},_._fixTransition=function(){var t=this.getTipElement(),n=this.config.animation;null===t.getAttribute("x-placement")&&(e(t).removeClass(m),this.config.animation=!1,this.hide(),this.show(),this.config.animation=n)},s._jQueryInterface=function(t){return this.each(function(){var n=e(this).data(i),r="object"==(void 0===t?"undefined":_typeof(t))&&t;if((n||!/dispose|hide/.test(t))&&(n||(n=new s(this,r),e(this).data(i,n)),"string"==typeof t)){if(void 0===n[t])throw new TypeError('No method named "'+t+'"');n[t]()}})},r(s,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return d}},{key:"NAME",get:function(){return t}},{key:"DATA_KEY",get:function(){return i}},{key:"Event",get:function(){return p}},{key:"EVENT_KEY",get:function(){return o}},{key:"DefaultType",get:function(){return u}}]),s}();return e.fn[t]=_._jQueryInterface,e.fn[t].Constructor=_,e.fn[t].noConflict=function(){return e.fn[t]=s,_._jQueryInterface},_}(t),Y=function(e){var t="popover",n="bs.popover",i="."+n,o=e.fn[t],s=new RegExp("(^|\\s)bs-popover\\S+","g"),l=a({},F.Default,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'}),u=a({},F.DefaultType,{content:"(string|element|function)"}),c={HIDE:"hide"+i,HIDDEN:"hidden"+i,SHOW:"show"+i,SHOWN:"shown"+i,INSERTED:"inserted"+i,CLICK:"click"+i,FOCUSIN:"focusin"+i,FOCUSOUT:"focusout"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i},d=function(a){function o(){return a.apply(this,arguments)||this}var d,h;h=a,(d=o).prototype=Object.create(h.prototype),d.prototype.constructor=d,d.__proto__=h;var f=o.prototype;return f.isWithContent=function(){return this.getTitle()||this._getContent()},f.addAttachmentClass=function(t){e(this.getTipElement()).addClass("bs-popover-"+t)},f.getTipElement=function(){return this.tip=this.tip||e(this.config.template)[0],this.tip},f.setContent=function(){var t=e(this.getTipElement());this.setElementContent(t.find(".popover-header"),this.getTitle());var n=this._getContent();"function"==typeof n&&(n=n.call(this.element)),this.setElementContent(t.find(".popover-body"),n),t.removeClass("fade show")},f._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},f._cleanTipClass=function(){var t=e(this.getTipElement()),n=t.attr("class").match(s);null!==n&&n.length>0&&t.removeClass(n.join(""))},o._jQueryInterface=function(t){return this.each(function(){var i=e(this).data(n),r="object"==(void 0===t?"undefined":_typeof(t))?t:null;if((i||!/destroy|hide/.test(t))&&(i||(i=new o(this,r),e(this).data(n,i)),"string"==typeof t)){if(void 0===i[t])throw new TypeError('No method named "'+t+'"');i[t]()}})},r(o,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return l}},{key:"NAME",get:function(){return t}},{key:"DATA_KEY",get:function(){return n}},{key:"Event",get:function(){return c}},{key:"EVENT_KEY",get:function(){return i}},{key:"DefaultType",get:function(){return u}}]),o}(F);return e.fn[t]=d._jQueryInterface,e.fn[t].Constructor=d,e.fn[t].noConflict=function(){return e.fn[t]=o,d._jQueryInterface},d}(t),V=function(e){var t="scrollspy",n="bs.scrollspy",i="."+n,o=e.fn[t],s={offset:10,method:"auto",target:""},l={offset:"number",method:"string",target:"(string|element)"},u={ACTIVATE:"activate"+i,SCROLL:"scroll"+i,LOAD_DATA_API:"load"+i+".data-api"},c="active",d={DATA_SPY:'[data-spy="scroll"]',ACTIVE:".active",NAV_LIST_GROUP:".nav, .list-group",NAV_LINKS:".nav-link",NAV_ITEMS:".nav-item",LIST_ITEMS:".list-group-item",DROPDOWN:".dropdown",DROPDOWN_ITEMS:".dropdown-item",DROPDOWN_TOGGLE:".dropdown-toggle"},h="position",f=function(){function o(t,n){var i=this;this._element=t,this._scrollElement="BODY"===t.tagName?window:t,this._config=this._getConfig(n),this._selector=this._config.target+" "+d.NAV_LINKS+","+this._config.target+" "+d.LIST_ITEMS+","+this._config.target+" "+d.DROPDOWN_ITEMS,this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,e(this._scrollElement).on(u.SCROLL,function(e){return i._process(e)}),this.refresh(),this._process()}var f=o.prototype;return f.refresh=function(){var t=this,n=this._scrollElement===this._scrollElement.window?"offset":h,i="auto"===this._config.method?n:this._config.method,r=i===h?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),e.makeArray(e(this._selector)).map(function(t){var n,a=N.getSelectorFromElement(t);if(a&&(n=e(a)[0]),n){var o=n.getBoundingClientRect();if(o.width||o.height)return[e(n)[i]().top+r,a]}return null}).filter(function(e){return e}).sort(function(e,t){return e[0]-t[0]}).forEach(function(e){t._offsets.push(e[0]),t._targets.push(e[1])})},f.dispose=function(){e.removeData(this._element,n),
e(this._scrollElement).off(i),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},f._getConfig=function(n){if("string"!=typeof(n=a({},s,n)).target){var i=e(n.target).attr("id");i||(i=N.getUID(t),e(n.target).attr("id",i)),n.target="#"+i}return N.typeCheckConfig(t,n,l),n},f._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop},f._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},f._getOffsetHeight=function(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height},f._process=function(){var e=this._getScrollTop()+this._config.offset,t=this._getScrollHeight(),n=this._config.offset+t-this._getOffsetHeight();if(this._scrollHeight!==t&&this.refresh(),e>=n){var i=this._targets[this._targets.length-1];this._activeTarget!==i&&this._activate(i)}else{if(this._activeTarget&&e<this._offsets[0]&&this._offsets[0]>0)return this._activeTarget=null,void this._clear();for(var r=this._offsets.length;r--;)this._activeTarget!==this._targets[r]&&e>=this._offsets[r]&&(void 0===this._offsets[r+1]||e<this._offsets[r+1])&&this._activate(this._targets[r])}},f._activate=function(t){this._activeTarget=t,this._clear();var n=this._selector.split(",");n=n.map(function(e){return e+'[data-target="'+t+'"],'+e+'[href="'+t+'"]'});var i=e(n.join(","));i.hasClass("dropdown-item")?(i.closest(d.DROPDOWN).find(d.DROPDOWN_TOGGLE).addClass(c),i.addClass(c)):(i.addClass(c),i.parents(d.NAV_LIST_GROUP).prev(d.NAV_LINKS+", "+d.LIST_ITEMS).addClass(c),i.parents(d.NAV_LIST_GROUP).prev(d.NAV_ITEMS).children(d.NAV_LINKS).addClass(c)),e(this._scrollElement).trigger(u.ACTIVATE,{relatedTarget:t})},f._clear=function(){e(this._selector).filter(d.ACTIVE).removeClass(c)},o._jQueryInterface=function(t){return this.each(function(){var i=e(this).data(n);if(i||(i=new o(this,"object"==(void 0===t?"undefined":_typeof(t))&&t),e(this).data(n,i)),"string"==typeof t){if(void 0===i[t])throw new TypeError('No method named "'+t+'"');i[t]()}})},r(o,null,[{key:"VERSION",get:function(){return"4.0.0"}},{key:"Default",get:function(){return s}}]),o}();return e(window).on(u.LOAD_DATA_API,function(){for(var t=e.makeArray(e(d.DATA_SPY)),n=t.length;n--;){var i=e(t[n]);f._jQueryInterface.call(i,i.data())}}),e.fn[t]=f._jQueryInterface,e.fn[t].Constructor=f,e.fn[t].noConflict=function(){return e.fn[t]=o,f._jQueryInterface},f}(t),q=function(e){var t="bs.tab",n="."+t,i=e.fn.tab,a={HIDE:"hide"+n,HIDDEN:"hidden"+n,SHOW:"show"+n,SHOWN:"shown"+n,CLICK_DATA_API:"click.bs.tab.data-api"},o="active",s="show",l=".active",u="> li > .active",c=function(){function n(e){this._element=e}var i=n.prototype;return i.show=function(){var t=this;if(!(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&e(this._element).hasClass(o)||e(this._element).hasClass("disabled"))){var n,i,r=e(this._element).closest(".nav, .list-group")[0],s=N.getSelectorFromElement(this._element);if(r){var c="UL"===r.nodeName?u:l;i=(i=e.makeArray(e(r).find(c)))[i.length-1]}var d=e.Event(a.HIDE,{relatedTarget:this._element}),h=e.Event(a.SHOW,{relatedTarget:i});if(i&&e(i).trigger(d),e(this._element).trigger(h),!h.isDefaultPrevented()&&!d.isDefaultPrevented()){s&&(n=e(s)[0]),this._activate(this._element,r);var f=function(){var n=e.Event(a.HIDDEN,{relatedTarget:t._element}),r=e.Event(a.SHOWN,{relatedTarget:i});e(i).trigger(n),e(t._element).trigger(r)};n?this._activate(n,n.parentNode,f):f()}}},i.dispose=function(){e.removeData(this._element,t),this._element=null},i._activate=function(t,n,i){var r=this,a=("UL"===n.nodeName?e(n).find(u):e(n).children(l))[0],o=i&&N.supportsTransitionEnd()&&a&&e(a).hasClass("fade"),s=function(){return r._transitionComplete(t,a,i)};a&&o?e(a).one(N.TRANSITION_END,s).emulateTransitionEnd(150):s()},i._transitionComplete=function(t,n,i){if(n){e(n).removeClass(s+" "+o);var r=e(n.parentNode).find("> .dropdown-menu .active")[0];r&&e(r).removeClass(o),"tab"===n.getAttribute("role")&&n.setAttribute("aria-selected",!1)}if(e(t).addClass(o),"tab"===t.getAttribute("role")&&t.setAttribute("aria-selected",!0),N.reflow(t),e(t).addClass(s),t.parentNode&&e(t.parentNode).hasClass("dropdown-menu")){var a=e(t).closest(".dropdown")[0];a&&e(a).find(".dropdown-toggle").addClass(o),t.setAttribute("aria-expanded",!0)}i&&i()},n._jQueryInterface=function(i){return this.each(function(){var r=e(this),a=r.data(t);if(a||(a=new n(this),r.data(t,a)),"string"==typeof i){if(void 0===a[i])throw new TypeError('No method named "'+i+'"');a[i]()}})},r(n,null,[{key:"VERSION",get:function(){return"4.0.0"}}]),n}();return e(document).on(a.CLICK_DATA_API,'[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',function(t){t.preventDefault(),c._jQueryInterface.call(e(this),"show")}),e.fn.tab=c._jQueryInterface,e.fn.tab.Constructor=c,e.fn.tab.noConflict=function(){return e.fn.tab=i,c._jQueryInterface},c}(t);!function(e){if(void 0===e)throw new TypeError("Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.");var t=e.fn.jquery.split(" ")[0].split(".");if(t[0]<2&&t[1]<9||1===t[0]&&9===t[1]&&t[2]<1||t[0]>=4)throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}(t),e.Util=N,e.Alert=M,e.Button=I,e.Carousel=R,e.Collapse=P,e.Dropdown=L,e.Modal=H,e.Popover=Y,e.Scrollspy=V,e.Tab=q,e.Tooltip=F,Object.defineProperty(e,"__esModule",{value:!0})}),function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e("object"==("undefined"==typeof exports?"undefined":_typeof(exports))?require("jquery"):jQuery)}(function(e,t){function n(){return new Date(Date.UTC.apply(Date,arguments))}function i(){var e=new Date;return n(e.getFullYear(),e.getMonth(),e.getDate())}function r(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function a(n,i){return function(){return i!==t&&e.fn.datepicker.deprecated(i),this[n].apply(this,arguments)}}function o(e){return e&&!isNaN(e.getTime())}function s(t,n){function i(e,t){return t.toLowerCase()}var r,a=e(t).data(),o={},s=new RegExp("^"+n.toLowerCase()+"([A-Z])");n=new RegExp("^"+n.toLowerCase());for(var l in a)n.test(l)&&(r=l.replace(s,i),o[r]=a[l]);return o}function l(t){var n={};if(g[t]||(t=t.split("-")[0],g[t])){var i=g[t];return e.each(m,function(e,t){t in i&&(n[t]=i[t])}),n}}var u=function(){var t={get:function(e){return this.slice(e)[0]},contains:function(e){for(var t=e&&e.valueOf(),n=0,i=this.length;n<i;n++)if(0<=this[n].valueOf()-t&&this[n].valueOf()-t<864e5)return n;return-1},remove:function(e){this.splice(e,1)},replace:function(t){t&&(e.isArray(t)||(t=[t]),this.clear(),this.push.apply(this,t))},clear:function(){this.length=0},copy:function(){var e=new u;return e.replace(this),e}};return function(){var n=[];return n.push.apply(n,arguments),e.extend(n,t),n}}(),c=function(t,n){e.data(t,"datepicker",this),this._process_options(n),this.dates=new u,this.viewDate=this.o.defaultViewDate,this.focusDate=null,this.element=e(t),this.isInput=this.element.is("input"),this.inputField=this.isInput?this.element:this.element.find("input"),this.component=!!this.element.hasClass("date")&&this.element.find(".add-on, .input-group-addon, .btn"),this.component&&0===this.component.length&&(this.component=!1),this.isInline=!this.component&&this.element.is("div"),this.picker=e(v.template),this._check_template(this.o.templates.leftArrow)&&this.picker.find(".prev").html(this.o.templates.leftArrow),this._check_template(this.o.templates.rightArrow)&&this.picker.find(".next").html(this.o.templates.rightArrow),this._buildEvents(),this._attachEvents(),this.isInline?this.picker.addClass("datepicker-inline").appendTo(this.element):this.picker.addClass("datepicker-dropdown dropdown-menu"),this.o.rtl&&this.picker.addClass("datepicker-rtl"),this.o.calendarWeeks&&this.picker.find(".datepicker-days .datepicker-switch, thead .datepicker-title, tfoot .today, tfoot .clear").attr("colspan",function(e,t){return Number(t)+1}),this._process_options({startDate:this._o.startDate,endDate:this._o.endDate,daysOfWeekDisabled:this.o.daysOfWeekDisabled,daysOfWeekHighlighted:this.o.daysOfWeekHighlighted,datesDisabled:this.o.datesDisabled}),this._allow_update=!1,this.setViewMode(this.o.startView),this._allow_update=!0,this.fillDow(),this.fillMonths(),this.update(),this.isInline&&this.show()};c.prototype={constructor:c,_resolveViewName:function(t){return e.each(v.viewModes,function(n,i){if(t===n||-1!==e.inArray(t,i.names))return t=n,!1}),t},_resolveDaysOfWeek:function(t){return e.isArray(t)||(t=t.split(/[,\s]*/)),e.map(t,Number)},_check_template:function(n){try{if(n===t||""===n)return!1;if((n.match(/[<>]/g)||[]).length<=0)return!0;return e(n).length>0}catch(e){return!1}},_process_options:function(t){this._o=e.extend({},this._o,t);var r=this.o=e.extend({},this._o),a=r.language;g[a]||(a=a.split("-")[0],g[a]||(a=p.language)),r.language=a,r.startView=this._resolveViewName(r.startView),r.minViewMode=this._resolveViewName(r.minViewMode),r.maxViewMode=this._resolveViewName(r.maxViewMode),r.startView=Math.max(this.o.minViewMode,Math.min(this.o.maxViewMode,r.startView)),!0!==r.multidate&&(r.multidate=Number(r.multidate)||!1,!1!==r.multidate&&(r.multidate=Math.max(0,r.multidate))),r.multidateSeparator=String(r.multidateSeparator),r.weekStart%=7,r.weekEnd=(r.weekStart+6)%7;var o=v.parseFormat(r.format);r.startDate!==-1/0&&(r.startDate?r.startDate instanceof Date?r.startDate=this._local_to_utc(this._zero_time(r.startDate)):r.startDate=v.parseDate(r.startDate,o,r.language,r.assumeNearbyYear):r.startDate=-1/0),r.endDate!==1/0&&(r.endDate?r.endDate instanceof Date?r.endDate=this._local_to_utc(this._zero_time(r.endDate)):r.endDate=v.parseDate(r.endDate,o,r.language,r.assumeNearbyYear):r.endDate=1/0),r.daysOfWeekDisabled=this._resolveDaysOfWeek(r.daysOfWeekDisabled||[]),r.daysOfWeekHighlighted=this._resolveDaysOfWeek(r.daysOfWeekHighlighted||[]),r.datesDisabled=r.datesDisabled||[],e.isArray(r.datesDisabled)||(r.datesDisabled=r.datesDisabled.split(",")),r.datesDisabled=e.map(r.datesDisabled,function(e){return v.parseDate(e,o,r.language,r.assumeNearbyYear)});var s=String(r.orientation).toLowerCase().split(/\s+/g),l=r.orientation.toLowerCase();if(s=e.grep(s,function(e){return/^auto|left|right|top|bottom$/.test(e)}),r.orientation={x:"auto",y:"auto"},l&&"auto"!==l)if(1===s.length)switch(s[0]){case"top":case"bottom":r.orientation.y=s[0];break;case"left":case"right":r.orientation.x=s[0]}else l=e.grep(s,function(e){return/^left|right$/.test(e)}),r.orientation.x=l[0]||"auto",l=e.grep(s,function(e){return/^top|bottom$/.test(e)}),r.orientation.y=l[0]||"auto";if(r.defaultViewDate instanceof Date||"string"==typeof r.defaultViewDate)r.defaultViewDate=v.parseDate(r.defaultViewDate,o,r.language,r.assumeNearbyYear);else if(r.defaultViewDate){var u=r.defaultViewDate.year||(new Date).getFullYear(),c=r.defaultViewDate.month||0,d=r.defaultViewDate.day||1;r.defaultViewDate=n(u,c,d)}else r.defaultViewDate=i()},_events:[],_secondaryEvents:[],_applyEvents:function(e){for(var n,i,r,a=0;a<e.length;a++)n=e[a][0],2===e[a].length?(i=t,r=e[a][1]):3===e[a].length&&(i=e[a][1],r=e[a][2]),n.on(r,i)},_unapplyEvents:function(e){for(var n,i,r,a=0;a<e.length;a++)n=e[a][0],2===e[a].length?(r=t,i=e[a][1]):3===e[a].length&&(r=e[a][1],i=e[a][2]),n.off(i,r)},_buildEvents:function(){var t={keyup:e.proxy(function(t){-1===e.inArray(t.keyCode,[27,37,39,38,40,32,13,9])&&this.update()},this),keydown:e.proxy(this.keydown,this),paste:e.proxy(this.paste,this)};!0===this.o.showOnFocus&&(t.focus=e.proxy(this.show,this)),this.isInput?this._events=[[this.element,t]]:this.component&&this.inputField.length?this._events=[[this.inputField,t],[this.component,{click:e.proxy(this.show,this)}]]:this._events=[[this.element,{click:e.proxy(this.show,this),keydown:e.proxy(this.keydown,this)}]],this._events.push([this.element,"*",{blur:e.proxy(function(e){this._focused_from=e.target},this)}],[this.element,{blur:e.proxy(function(e){this._focused_from=e.target},this)}]),this.o.immediateUpdates&&this._events.push([this.element,{"changeYear changeMonth":e.proxy(function(e){this.update(e.date)},this)}]),this._secondaryEvents=[[this.picker,{click:e.proxy(this.click,this)}],[this.picker,".prev, .next",{click:e.proxy(this.navArrowsClick,this)}],[this.picker,".day:not(.disabled)",{click:e.proxy(this.dayCellClick,this)}],[e(window),{resize:e.proxy(this.place,this)}],[e(document),{"mousedown touchstart":e.proxy(function(e){this.element.is(e.target)||this.element.find(e.target).length||this.picker.is(e.target)||this.picker.find(e.target).length||this.isInline||this.hide()},this)}]]},_attachEvents:function(){this._detachEvents(),this._applyEvents(this._events)},_detachEvents:function(){this._unapplyEvents(this._events)},_attachSecondaryEvents:function(){this._detachSecondaryEvents(),this._applyEvents(this._secondaryEvents)},_detachSecondaryEvents:function(){this._unapplyEvents(this._secondaryEvents)},_trigger:function(t,n){var i=n||this.dates.get(-1),r=this._utc_to_local(i);this.element.trigger({type:t,date:r,viewMode:this.viewMode,dates:e.map(this.dates,this._utc_to_local),format:e.proxy(function(e,t){0===arguments.length?(e=this.dates.length-1,t=this.o.format):"string"==typeof e&&(t=e,e=this.dates.length-1),t=t||this.o.format;var n=this.dates.get(e);return v.formatDate(n,t,this.o.language)},this)})},show:function(){if(!(this.inputField.prop("disabled")||this.inputField.prop("readonly")&&!1===this.o.enableOnReadonly))return this.isInline||this.picker.appendTo(this.o.container),this.place(),this.picker.show(),this._attachSecondaryEvents(),this._trigger("show"),(window.navigator.msMaxTouchPoints||"ontouchstart"in document)&&this.o.disableTouchKeyboard&&e(this.element).blur(),this},hide:function(){return this.isInline||!this.picker.is(":visible")?this:(this.focusDate=null,this.picker.hide().detach(),this._detachSecondaryEvents(),this.setViewMode(this.o.startView),this.o.forceParse&&this.inputField.val()&&this.setValue(),this._trigger("hide"),this)},destroy:function(){return this.hide(),this._detachEvents(),this._detachSecondaryEvents(),this.picker.remove(),delete this.element.data().datepicker,this.isInput||delete this.element.data().date,this},paste:function(t){var n;if(t.originalEvent.clipboardData&&t.originalEvent.clipboardData.types&&-1!==e.inArray("text/plain",t.originalEvent.clipboardData.types))n=t.originalEvent.clipboardData.getData("text/plain");else{if(!window.clipboardData)return;n=window.clipboardData.getData("Text")}this.setDate(n),this.update(),t.preventDefault()},_utc_to_local:function(e){if(!e)return e;var t=new Date(e.getTime()+6e4*e.getTimezoneOffset());return t.getTimezoneOffset()!==e.getTimezoneOffset()&&(t=new Date(e.getTime()+6e4*t.getTimezoneOffset())),t},_local_to_utc:function(e){return e&&new Date(e.getTime()-6e4*e.getTimezoneOffset())},_zero_time:function(e){return e&&new Date(e.getFullYear(),e.getMonth(),e.getDate())},_zero_utc_time:function(e){return e&&n(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())},getDates:function(){return e.map(this.dates,this._utc_to_local)},getUTCDates:function(){return e.map(this.dates,function(e){return new Date(e)})},getDate:function(){return this._utc_to_local(this.getUTCDate())},getUTCDate:function(){var e=this.dates.get(-1);return e!==t?new Date(e):null},clearDates:function(){this.inputField.val(""),this.update(),this._trigger("changeDate"),this.o.autoclose&&this.hide()},setDates:function(){var t=e.isArray(arguments[0])?arguments[0]:arguments;return this.update.apply(this,t),this._trigger("changeDate"),this.setValue(),this},setUTCDates:function(){var t=e.isArray(arguments[0])?arguments[0]:arguments;return this.setDates.apply(this,e.map(t,this._utc_to_local)),this},setDate:a("setDates"),setUTCDate:a("setUTCDates"),remove:a("destroy","Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead"),setValue:function(){var e=this.getFormattedDate();return this.inputField.val(e),this},getFormattedDate:function(n){n===t&&(n=this.o.format);var i=this.o.language;return e.map(this.dates,function(e){return v.formatDate(e,n,i)}).join(this.o.multidateSeparator)},getStartDate:function(){return this.o.startDate},setStartDate:function(e){return this._process_options({startDate:e}),this.update(),this.updateNavArrows(),this},getEndDate:function(){return this.o.endDate},setEndDate:function(e){return this._process_options({endDate:e}),this.update(),this.updateNavArrows(),this},setDaysOfWeekDisabled:function(e){return this._process_options({daysOfWeekDisabled:e}),this.update(),this},setDaysOfWeekHighlighted:function(e){return this._process_options({daysOfWeekHighlighted:e}),this.update(),this},setDatesDisabled:function(e){return this._process_options({datesDisabled:e}),this.update(),this},place:function(){if(this.isInline)return this;var t=this.picker.outerWidth(),n=this.picker.outerHeight(),i=e(this.o.container),r=i.width(),a="body"===this.o.container?e(document).scrollTop():i.scrollTop(),o=i.offset(),s=[0];this.element.parents().each(function(){var t=e(this).css("z-index");"auto"!==t&&0!==Number(t)&&s.push(Number(t))});var l=Math.max.apply(Math,s)+this.o.zIndexOffset,u=this.component?this.component.parent().offset():this.element.offset(),c=this.component?this.component.outerHeight(!0):this.element.outerHeight(!1),d=this.component?this.component.outerWidth(!0):this.element.outerWidth(!1),h=u.left-o.left,f=u.top-o.top;"body"!==this.o.container&&(f+=a),this.picker.removeClass("datepicker-orient-top datepicker-orient-bottom datepicker-orient-right datepicker-orient-left"),"auto"!==this.o.orientation.x?(this.picker.addClass("datepicker-orient-"+this.o.orientation.x),"right"===this.o.orientation.x&&(h-=t-d)):u.left<0?(this.picker.addClass("datepicker-orient-left"),h-=u.left-10):h+t>r?(this.picker.addClass("datepicker-orient-right"),h+=d-t):this.o.rtl?this.picker.addClass("datepicker-orient-right"):this.picker.addClass("datepicker-orient-left");var p,m=this.o.orientation.y;if("auto"===m&&(p=-a+f-n,m=p<0?"bottom":"top"),this.picker.addClass("datepicker-orient-"+m),"top"===m?f-=n+parseInt(this.picker.css("padding-top")):f+=c,this.o.rtl){var g=r-(h+d);this.picker.css({top:f,right:g,zIndex:l})}else this.picker.css({top:f,left:h,zIndex:l});return this},_allow_update:!0,update:function(){if(!this._allow_update)return this;var t=this.dates.copy(),n=[],i=!1;return arguments.length?(e.each(arguments,e.proxy(function(e,t){t instanceof Date&&(t=this._local_to_utc(t)),n.push(t)},this)),i=!0):(n=this.isInput?this.element.val():this.element.data("date")||this.inputField.val(),n=n&&this.o.multidate?n.split(this.o.multidateSeparator):[n],delete this.element.data().date),n=e.map(n,e.proxy(function(e){return v.parseDate(e,this.o.format,this.o.language,this.o.assumeNearbyYear)},this)),n=e.grep(n,e.proxy(function(e){return!this.dateWithinRange(e)||!e},this),!0),this.dates.replace(n),this.o.updateViewDate&&(this.dates.length?this.viewDate=new Date(this.dates.get(-1)):this.viewDate<this.o.startDate?this.viewDate=new Date(this.o.startDate):this.viewDate>this.o.endDate?this.viewDate=new Date(this.o.endDate):this.viewDate=this.o.defaultViewDate),i?(this.setValue(),this.element.change()):this.dates.length&&String(t)!==String(this.dates)&&i&&(this._trigger("changeDate"),this.element.change()),!this.dates.length&&t.length&&(this._trigger("clearDate"),this.element.change()),this.fill(),this},fillDow:function(){if(this.o.showWeekDays){var t=this.o.weekStart,n="<tr>";for(this.o.calendarWeeks&&(n+='<th class="cw"> </th>');t<this.o.weekStart+7;)n+='<th class="dow',-1!==e.inArray(t,this.o.daysOfWeekDisabled)&&(n+=" disabled"),n+='">'+g[this.o.language].daysMin[t++%7]+"</th>";n+="</tr>",this.picker.find(".datepicker-days thead").append(n)}},fillMonths:function(){for(var e,t=this._utc_to_local(this.viewDate),n="",i=0;i<12;i++)e=t&&t.getMonth()===i?" focused":"",n+='<span class="month'+e+'">'+g[this.o.language].monthsShort[i]+"</span>";this.picker.find(".datepicker-months td").html(n)},setRange:function(t){t&&t.length?this.range=e.map(t,function(e){return e.valueOf()}):delete this.range,this.fill()},getClassNames:function(t){var n=[],a=this.viewDate.getUTCFullYear(),o=this.viewDate.getUTCMonth(),s=i();return t.getUTCFullYear()<a||t.getUTCFullYear()===a&&t.getUTCMonth()<o?n.push("old"):(t.getUTCFullYear()>a||t.getUTCFullYear()===a&&t.getUTCMonth()>o)&&n.push("new"),this.focusDate&&t.valueOf()===this.focusDate.valueOf()&&n.push("focused"),this.o.todayHighlight&&r(t,s)&&n.push("today"),-1!==this.dates.contains(t)&&n.push("active"),this.dateWithinRange(t)||n.push("disabled"),this.dateIsDisabled(t)&&n.push("disabled","disabled-date"),-1!==e.inArray(t.getUTCDay(),this.o.daysOfWeekHighlighted)&&n.push("highlighted"),this.range&&(t>this.range[0]&&t<this.range[this.range.length-1]&&n.push("range"),-1!==e.inArray(t.valueOf(),this.range)&&n.push("selected"),t.valueOf()===this.range[0]&&n.push("range-start"),t.valueOf()===this.range[this.range.length-1]&&n.push("range-end")),n},_fill_yearsView:function(n,i,r,a,o,s,l){for(var u,c,d,h="",f=r/10,p=this.picker.find(n),m=Math.floor(a/r)*r,g=m+9*f,v=Math.floor(this.viewDate.getFullYear()/f)*f,y=e.map(this.dates,function(e){return Math.floor(e.getUTCFullYear()/f)*f}),_=m-f;_<=g+f;_+=f)u=[i],c=null,_===m-f?u.push("old"):_===g+f&&u.push("new"),-1!==e.inArray(_,y)&&u.push("active"),(_<o||_>s)&&u.push("disabled"),_===v&&u.push("focused"),l!==e.noop&&(d=l(new Date(_,0,1)),d===t?d={}:"boolean"==typeof d?d={enabled:d}:"string"==typeof d&&(d={classes:d}),!1===d.enabled&&u.push("disabled"),d.classes&&(u=u.concat(d.classes.split(/\s+/))),d.tooltip&&(c=d.tooltip)),h+='<span class="'+u.join(" ")+'"'+(c?' title="'+c+'"':"")+">"+_+"</span>";p.find(".datepicker-switch").text(m+"-"+g),p.find("td").html(h)},fill:function(){var i,r,a=new Date(this.viewDate),o=a.getUTCFullYear(),s=a.getUTCMonth(),l=this.o.startDate!==-1/0?this.o.startDate.getUTCFullYear():-1/0,u=this.o.startDate!==-1/0?this.o.startDate.getUTCMonth():-1/0,c=this.o.endDate!==1/0?this.o.endDate.getUTCFullYear():1/0,d=this.o.endDate!==1/0?this.o.endDate.getUTCMonth():1/0,h=g[this.o.language].today||g.en.today||"",f=g[this.o.language].clear||g.en.clear||"",p=g[this.o.language].titleFormat||g.en.titleFormat;if(!isNaN(o)&&!isNaN(s)){this.picker.find(".datepicker-days .datepicker-switch").text(v.formatDate(a,p,this.o.language)),this.picker.find("tfoot .today").text(h).css("display",!0===this.o.todayBtn||"linked"===this.o.todayBtn?"table-cell":"none"),this.picker.find("tfoot .clear").text(f).css("display",!0===this.o.clearBtn?"table-cell":"none"),this.picker.find("thead .datepicker-title").text(this.o.title).css("display","string"==typeof this.o.title&&""!==this.o.title?"table-cell":"none"),this.updateNavArrows(),this.fillMonths();var m=n(o,s,0),y=m.getUTCDate();m.setUTCDate(y-(m.getUTCDay()-this.o.weekStart+7)%7);var _=new Date(m);m.getUTCFullYear()<100&&_.setUTCFullYear(m.getUTCFullYear()),_.setUTCDate(_.getUTCDate()+42),_=_.valueOf();for(var b,$,w=[];m.valueOf()<_;){if((b=m.getUTCDay())===this.o.weekStart&&(w.push("<tr>"),this.o.calendarWeeks)){var S=new Date(+m+(this.o.weekStart-b-7)%7*864e5),T=new Date(Number(S)+(11-S.getUTCDay())%7*864e5),C=new Date(Number(C=n(T.getUTCFullYear(),0,1))+(11-C.getUTCDay())%7*864e5),D=(T-C)/864e5/7+1;w.push('<td class="cw">'+D+"</td>")}$=this.getClassNames(m),$.push("day");var k=m.getUTCDate();this.o.beforeShowDay!==e.noop&&(r=this.o.beforeShowDay(this._utc_to_local(m)),r===t?r={}:"boolean"==typeof r?r={enabled:r}:"string"==typeof r&&(r={classes:r}),!1===r.enabled&&$.push("disabled"),r.classes&&($=$.concat(r.classes.split(/\s+/))),r.tooltip&&(i=r.tooltip),r.content&&(k=r.content)),$=e.isFunction(e.uniqueSort)?e.uniqueSort($):e.unique($),w.push('<td class="'+$.join(" ")+'"'+(i?' title="'+i+'"':"")+' data-date="'+m.getTime().toString()+'">'+k+"</td>"),i=null,b===this.o.weekEnd&&w.push("</tr>"),m.setUTCDate(m.getUTCDate()+1)}this.picker.find(".datepicker-days tbody").html(w.join(""));var x=g[this.o.language].monthsTitle||g.en.monthsTitle||"Months",E=this.picker.find(".datepicker-months").find(".datepicker-switch").text(this.o.maxViewMode<2?x:o).end().find("tbody span").removeClass("active");if(e.each(this.dates,function(e,t){t.getUTCFullYear()===o&&E.eq(t.getUTCMonth()).addClass("active")}),(o<l||o>c)&&E.addClass("disabled"),o===l&&E.slice(0,u).addClass("disabled"),o===c&&E.slice(d+1).addClass("disabled"),this.o.beforeShowMonth!==e.noop){var A=this;e.each(E,function(n,i){var r=new Date(o,n,1),a=A.o.beforeShowMonth(r);a===t?a={}:"boolean"==typeof a?a={enabled:a}:"string"==typeof a&&(a={classes:a}),!1!==a.enabled||e(i).hasClass("disabled")||e(i).addClass("disabled"),a.classes&&e(i).addClass(a.classes),a.tooltip&&e(i).prop("title",a.tooltip)})}this._fill_yearsView(".datepicker-years","year",10,o,l,c,this.o.beforeShowYear),this._fill_yearsView(".datepicker-decades","decade",100,o,l,c,this.o.beforeShowDecade),this._fill_yearsView(".datepicker-centuries","century",1e3,o,l,c,this.o.beforeShowCentury)}},updateNavArrows:function(){if(this._allow_update){var e,t,n=new Date(this.viewDate),i=n.getUTCFullYear(),r=n.getUTCMonth(),a=this.o.startDate!==-1/0?this.o.startDate.getUTCFullYear():-1/0,o=this.o.startDate!==-1/0?this.o.startDate.getUTCMonth():-1/0,s=this.o.endDate!==1/0?this.o.endDate.getUTCFullYear():1/0,l=this.o.endDate!==1/0?this.o.endDate.getUTCMonth():1/0,u=1;switch(this.viewMode){case 0:e=i<=a&&r<=o,t=i>=s&&r>=l;break;case 4:u*=10;case 3:u*=10;case 2:u*=10;case 1:e=Math.floor(i/u)*u<=a,t=Math.floor(i/u)*u+u>=s}this.picker.find(".prev").toggleClass("disabled",e),this.picker.find(".next").toggleClass("disabled",t)}},click:function(t){t.preventDefault(),t.stopPropagation();var r,a,o,s;r=e(t.target),r.hasClass("datepicker-switch")&&this.viewMode!==this.o.maxViewMode&&this.setViewMode(this.viewMode+1),r.hasClass("today")&&!r.hasClass("day")&&(this.setViewMode(0),this._setDate(i(),"linked"===this.o.todayBtn?null:"view")),r.hasClass("clear")&&this.clearDates(),r.hasClass("disabled")||(r.hasClass("month")||r.hasClass("year")||r.hasClass("decade")||r.hasClass("century"))&&(this.viewDate.setUTCDate(1),a=1,1===this.viewMode?(s=r.parent().find("span").index(r),o=this.viewDate.getUTCFullYear(),this.viewDate.setUTCMonth(s)):(s=0,o=Number(r.text()),this.viewDate.setUTCFullYear(o)),this._trigger(v.viewModes[this.viewMode-1].e,this.viewDate),this.viewMode===this.o.minViewMode?this._setDate(n(o,s,a)):(this.setViewMode(this.viewMode-1),this.fill())),this.picker.is(":visible")&&this._focused_from&&this._focused_from.focus(),delete this._focused_from},dayCellClick:function(t){var n=e(t.currentTarget),i=n.data("date"),r=new Date(i);this.o.updateViewDate&&(r.getUTCFullYear()!==this.viewDate.getUTCFullYear()&&this._trigger("changeYear",this.viewDate),r.getUTCMonth()!==this.viewDate.getUTCMonth()&&this._trigger("changeMonth",this.viewDate)),this._setDate(r)},navArrowsClick:function(t){var n=e(t.currentTarget),i=n.hasClass("prev")?-1:1;0!==this.viewMode&&(i*=12*v.viewModes[this.viewMode].navStep),this.viewDate=this.moveMonth(this.viewDate,i),this._trigger(v.viewModes[this.viewMode].e,this.viewDate),this.fill()},_toggle_multidate:function(e){var t=this.dates.contains(e);if(e||this.dates.clear(),-1!==t?(!0===this.o.multidate||this.o.multidate>1||this.o.toggleActive)&&this.dates.remove(t):!1===this.o.multidate?(this.dates.clear(),this.dates.push(e)):this.dates.push(e),"number"==typeof this.o.multidate)for(;this.dates.length>this.o.multidate;)this.dates.remove(0)},_setDate:function(e,t){t&&"date"!==t||this._toggle_multidate(e&&new Date(e)),(!t&&this.o.updateViewDate||"view"===t)&&(this.viewDate=e&&new Date(e)),this.fill(),this.setValue(),t&&"view"===t||this._trigger("changeDate"),this.inputField.trigger("change"),!this.o.autoclose||t&&"date"!==t||this.hide()},moveDay:function(e,t){var n=new Date(e);return n.setUTCDate(e.getUTCDate()+t),n},moveWeek:function(e,t){return this.moveDay(e,7*t)},moveMonth:function(e,t){if(!o(e))return this.o.defaultViewDate;if(!t)return e;var n,i,r=new Date(e.valueOf()),a=r.getUTCDate(),s=r.getUTCMonth(),l=Math.abs(t);if(t=t>0?1:-1,1===l)i=-1===t?function(){return r.getUTCMonth()===s}:function(){return r.getUTCMonth()!==n},n=s+t,r.setUTCMonth(n),n=(n+12)%12;else{for(var u=0;u<l;u++)r=this.moveMonth(r,t);n=r.getUTCMonth(),r.setUTCDate(a),i=function(){return n!==r.getUTCMonth()}}for(;i();)r.setUTCDate(--a),r.setUTCMonth(n);return r},moveYear:function(e,t){return this.moveMonth(e,12*t)},moveAvailableDate:function(e,t,n){do{if(e=this[n](e,t),!this.dateWithinRange(e))return!1;n="moveDay"}while(this.dateIsDisabled(e));return e},weekOfDateIsDisabled:function(t){return-1!==e.inArray(t.getUTCDay(),this.o.daysOfWeekDisabled)},dateIsDisabled:function(t){return this.weekOfDateIsDisabled(t)||e.grep(this.o.datesDisabled,function(e){return r(t,e)}).length>0},dateWithinRange:function(e){return e>=this.o.startDate&&e<=this.o.endDate},keydown:function(e){if(!this.picker.is(":visible"))return void(40!==e.keyCode&&27!==e.keyCode||(this.show(),e.stopPropagation()));var t,n,i=!1,r=this.focusDate||this.viewDate;switch(e.keyCode){case 27:this.focusDate?(this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill()):this.hide(),e.preventDefault(),e.stopPropagation();break;case 37:case 38:case 39:case 40:if(!this.o.keyboardNavigation||7===this.o.daysOfWeekDisabled.length)break;t=37===e.keyCode||38===e.keyCode?-1:1,0===this.viewMode?e.ctrlKey?(n=this.moveAvailableDate(r,t,"moveYear"))&&this._trigger("changeYear",this.viewDate):e.shiftKey?(n=this.moveAvailableDate(r,t,"moveMonth"))&&this._trigger("changeMonth",this.viewDate):37===e.keyCode||39===e.keyCode?n=this.moveAvailableDate(r,t,"moveDay"):this.weekOfDateIsDisabled(r)||(n=this.moveAvailableDate(r,t,"moveWeek")):1===this.viewMode?(38!==e.keyCode&&40!==e.keyCode||(t*=4),n=this.moveAvailableDate(r,t,"moveMonth")):2===this.viewMode&&(38!==e.keyCode&&40!==e.keyCode||(t*=4),n=this.moveAvailableDate(r,t,"moveYear")),n&&(this.focusDate=this.viewDate=n,this.setValue(),this.fill(),e.preventDefault());break;case 13:if(!this.o.forceParse)break;r=this.focusDate||this.dates.get(-1)||this.viewDate,this.o.keyboardNavigation&&(this._toggle_multidate(r),i=!0),this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.setValue(),this.fill(),this.picker.is(":visible")&&(e.preventDefault(),e.stopPropagation(),this.o.autoclose&&this.hide());break;case 9:this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill(),this.hide()}i&&(this.dates.length?this._trigger("changeDate"):this._trigger("clearDate"),this.inputField.trigger("change"))},setViewMode:function(e){this.viewMode=e,this.picker.children("div").hide().filter(".datepicker-"+v.viewModes[this.viewMode].clsName).show(),this.updateNavArrows(),this._trigger("changeViewMode",new Date(this.viewDate))}};var d=function(t,n){e.data(t,"datepicker",this),this.element=e(t),this.inputs=e.map(n.inputs,function(e){return e.jquery?e[0]:e}),delete n.inputs,this.keepEmptyValues=n.keepEmptyValues,delete n.keepEmptyValues,f.call(e(this.inputs),n).on("changeDate",e.proxy(this.dateUpdated,this)),this.pickers=e.map(this.inputs,function(t){return e.data(t,"datepicker")}),this.updateDates()};d.prototype={updateDates:function(){this.dates=e.map(this.pickers,function(e){return e.getUTCDate()}),this.updateRanges()},updateRanges:function(){var t=e.map(this.dates,function(e){return e.valueOf()});e.each(this.pickers,function(e,n){n.setRange(t)})},dateUpdated:function(n){if(!this.updating){this.updating=!0;var i=e.data(n.target,"datepicker");if(i!==t){var r=i.getUTCDate(),a=this.keepEmptyValues,o=e.inArray(n.target,this.inputs),s=o-1,l=o+1,u=this.inputs.length;if(-1!==o){if(e.each(this.pickers,function(e,t){
t.getUTCDate()||t!==i&&a||t.setUTCDate(r)}),r<this.dates[s])for(;s>=0&&r<this.dates[s];)this.pickers[s--].setUTCDate(r);else if(r>this.dates[l])for(;l<u&&r>this.dates[l];)this.pickers[l++].setUTCDate(r);this.updateDates(),delete this.updating}}}},destroy:function(){e.map(this.pickers,function(e){e.destroy()}),e(this.inputs).off("changeDate",this.dateUpdated),delete this.element.data().datepicker},remove:a("destroy","Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead")};var h=e.fn.datepicker,f=function(n){var i=Array.apply(null,arguments);i.shift();var r;if(this.each(function(){var t=e(this),a=t.data("datepicker"),o="object"==(void 0===n?"undefined":_typeof(n))&&n;if(!a){var u=s(this,"date"),h=e.extend({},p,u,o),f=l(h.language),m=e.extend({},p,f,u,o);t.hasClass("input-daterange")||m.inputs?(e.extend(m,{inputs:m.inputs||t.find("input").toArray()}),a=new d(this,m)):a=new c(this,m),t.data("datepicker",a)}"string"==typeof n&&"function"==typeof a[n]&&(r=a[n].apply(a,i))}),r===t||r instanceof c||r instanceof d)return this;if(this.length>1)throw new Error("Using only allowed for the collection of a single element ("+n+" function)");return r};e.fn.datepicker=f;var p=e.fn.datepicker.defaults={assumeNearbyYear:!1,autoclose:!1,beforeShowDay:e.noop,beforeShowMonth:e.noop,beforeShowYear:e.noop,beforeShowDecade:e.noop,beforeShowCentury:e.noop,calendarWeeks:!1,clearBtn:!1,toggleActive:!1,daysOfWeekDisabled:[],daysOfWeekHighlighted:[],datesDisabled:[],endDate:1/0,forceParse:!0,format:"mm/dd/yyyy",keepEmptyValues:!1,keyboardNavigation:!0,language:"en",minViewMode:0,maxViewMode:4,multidate:!1,multidateSeparator:",",orientation:"auto",rtl:!1,startDate:-1/0,startView:0,todayBtn:!1,todayHighlight:!1,updateViewDate:!0,weekStart:0,disableTouchKeyboard:!1,enableOnReadonly:!0,showOnFocus:!0,zIndexOffset:10,container:"body",immediateUpdates:!1,title:"",templates:{leftArrow:"«",rightArrow:"»"},showWeekDays:!0},m=e.fn.datepicker.locale_opts=["format","rtl","weekStart"];e.fn.datepicker.Constructor=c;var g=e.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear",titleFormat:"MM yyyy"}},v={viewModes:[{names:["days","month"],clsName:"days",e:"changeMonth"},{names:["months","year"],clsName:"months",e:"changeYear",navStep:1},{names:["years","decade"],clsName:"years",e:"changeDecade",navStep:10},{names:["decades","century"],clsName:"decades",e:"changeCentury",navStep:100},{names:["centuries","millennium"],clsName:"centuries",e:"changeMillennium",navStep:1e3}],validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,parseFormat:function(e){if("function"==typeof e.toValue&&"function"==typeof e.toDisplay)return e;var t=e.replace(this.validParts,"\0").split("\0"),n=e.match(this.validParts);if(!t||!t.length||!n||0===n.length)throw new Error("Invalid date format.");return{separators:t,parts:n}},parseDate:function(n,r,a,o){function s(e,t){return!0===t&&(t=10),e<100&&(e+=2e3)>(new Date).getFullYear()+t&&(e-=100),e}function l(){var e=this.slice(0,u[f].length),t=u[f].slice(0,e.length);return e.toLowerCase()===t.toLowerCase()}if(!n)return t;if(n instanceof Date)return n;if("string"==typeof r&&(r=v.parseFormat(r)),r.toValue)return r.toValue(n,r,a);var u,d,h,f,p,m={d:"moveDay",m:"moveMonth",w:"moveWeek",y:"moveYear"},y={yesterday:"-1d",today:"+0d",tomorrow:"+1d"};if(n in y&&(n=y[n]),/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/i.test(n)){for(u=n.match(/([\-+]\d+)([dmwy])/gi),n=new Date,f=0;f<u.length;f++)d=u[f].match(/([\-+]\d+)([dmwy])/i),h=Number(d[1]),p=m[d[2].toLowerCase()],n=c.prototype[p](n,h);return c.prototype._zero_utc_time(n)}u=n&&n.match(this.nonpunctuation)||[];var _,b,$={},w=["yyyy","yy","M","MM","m","mm","d","dd"],S={yyyy:function(e,t){return e.setUTCFullYear(o?s(t,o):t)},m:function(e,t){if(isNaN(e))return e;for(t-=1;t<0;)t+=12;for(t%=12,e.setUTCMonth(t);e.getUTCMonth()!==t;)e.setUTCDate(e.getUTCDate()-1);return e},d:function(e,t){return e.setUTCDate(t)}};S.yy=S.yyyy,S.M=S.MM=S.mm=S.m,S.dd=S.d,n=i();var T=r.parts.slice();if(u.length!==T.length&&(T=e(T).filter(function(t,n){return-1!==e.inArray(n,w)}).toArray()),u.length===T.length){var C;for(f=0,C=T.length;f<C;f++){if(_=parseInt(u[f],10),d=T[f],isNaN(_))switch(d){case"MM":b=e(g[a].months).filter(l),_=e.inArray(b[0],g[a].months)+1;break;case"M":b=e(g[a].monthsShort).filter(l),_=e.inArray(b[0],g[a].monthsShort)+1}$[d]=_}var D,k;for(f=0;f<w.length;f++)(k=w[f])in $&&!isNaN($[k])&&(D=new Date(n),S[k](D,$[k]),isNaN(D)||(n=D))}return n},formatDate:function(t,n,i){if(!t)return"";if("string"==typeof n&&(n=v.parseFormat(n)),n.toDisplay)return n.toDisplay(t,n,i);var r={d:t.getUTCDate(),D:g[i].daysShort[t.getUTCDay()],DD:g[i].days[t.getUTCDay()],m:t.getUTCMonth()+1,M:g[i].monthsShort[t.getUTCMonth()],MM:g[i].months[t.getUTCMonth()],yy:t.getUTCFullYear().toString().substring(2),yyyy:t.getUTCFullYear()};r.dd=(r.d<10?"0":"")+r.d,r.mm=(r.m<10?"0":"")+r.m,t=[];for(var a=e.extend([],n.separators),o=0,s=n.parts.length;o<=s;o++)a.length&&t.push(a.shift()),t.push(r[n.parts[o]]);return t.join("")},headTemplate:'<thead><tr><th colspan="7" class="datepicker-title"></th></tr><tr><th class="prev">'+p.templates.leftArrow+'</th><th colspan="5" class="datepicker-switch"></th><th class="next">'+p.templates.rightArrow+"</th></tr></thead>",contTemplate:'<tbody><tr><td colspan="7"></td></tr></tbody>',footTemplate:'<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'};v.template='<div class="datepicker"><div class="datepicker-days"><table class="table-condensed">'+v.headTemplate+"<tbody></tbody>"+v.footTemplate+'</table></div><div class="datepicker-months"><table class="table-condensed">'+v.headTemplate+v.contTemplate+v.footTemplate+'</table></div><div class="datepicker-years"><table class="table-condensed">'+v.headTemplate+v.contTemplate+v.footTemplate+'</table></div><div class="datepicker-decades"><table class="table-condensed">'+v.headTemplate+v.contTemplate+v.footTemplate+'</table></div><div class="datepicker-centuries"><table class="table-condensed">'+v.headTemplate+v.contTemplate+v.footTemplate+"</table></div></div>",e.fn.datepicker.DPGlobal=v,e.fn.datepicker.noConflict=function(){return e.fn.datepicker=h,this},e.fn.datepicker.version="1.7.1",e.fn.datepicker.deprecated=function(e){var t=window.console;t&&t.warn&&t.warn("DEPRECATED: "+e)},e(document).on("focus.datepicker.data-api click.datepicker.data-api",'[data-provide="datepicker"]',function(t){var n=e(this);n.data("datepicker")||(t.preventDefault(),f.call(n,"show"))}),e(function(){f.call(e('[data-provide="datepicker-inline"]'))})}),function(e){e.fn.datepicker.dates.de={days:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],daysShort:["Son","Mon","Die","Mit","Don","Fre","Sam"],daysMin:["So","Mo","Di","Mi","Do","Fr","Sa"],months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],monthsShort:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],today:"Heute",monthsTitle:"Monate",clear:"Löschen",weekStart:1,format:"dd.mm.yyyy"}}(jQuery),function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==("undefined"==typeof module?"undefined":_typeof(module))&&module.exports?module.exports=e(require("jquery")):e(jQuery)}(function(e){e.extend(e.fn,{validate:function(t){if(!this.length)return void(t&&t.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var n=e.data(this[0],"validator");return n||(this.attr("novalidate","novalidate"),n=new e.validator(t,this[0]),e.data(this[0],"validator",n),n.settings.onsubmit&&(this.on("click.validate",":submit",function(t){n.submitButton=t.currentTarget,e(this).hasClass("cancel")&&(n.cancelSubmit=!0),void 0!==e(this).attr("formnovalidate")&&(n.cancelSubmit=!0)}),this.on("submit.validate",function(t){function i(){var i,r;return n.submitButton&&(n.settings.submitHandler||n.formSubmitted)&&(i=e("<input type='hidden'/>").attr("name",n.submitButton.name).val(e(n.submitButton).val()).appendTo(n.currentForm)),!n.settings.submitHandler||(r=n.settings.submitHandler.call(n,n.currentForm,t),i&&i.remove(),void 0!==r&&r)}return n.settings.debug&&t.preventDefault(),n.cancelSubmit?(n.cancelSubmit=!1,i()):n.form()?n.pendingRequest?(n.formSubmitted=!0,!1):i():(n.focusInvalid(),!1)})),n)},valid:function(){var t,n,i;return e(this[0]).is("form")?t=this.validate().form():(i=[],t=!0,n=e(this[0].form).validate(),this.each(function(){(t=n.element(this)&&t)||(i=i.concat(n.errorList))}),n.errorList=i),t},rules:function(t,n){var i,r,a,o,s,l,u=this[0];if(null!=u&&(!u.form&&u.hasAttribute("contenteditable")&&(u.form=this.closest("form")[0],u.name=this.attr("name")),null!=u.form)){if(t)switch(i=e.data(u.form,"validator").settings,r=i.rules,a=e.validator.staticRules(u),t){case"add":e.extend(a,e.validator.normalizeRule(n)),delete a.messages,r[u.name]=a,n.messages&&(i.messages[u.name]=e.extend(i.messages[u.name],n.messages));break;case"remove":return n?(l={},e.each(n.split(/\s/),function(e,t){l[t]=a[t],delete a[t]}),l):(delete r[u.name],a)}return o=e.validator.normalizeRules(e.extend({},e.validator.classRules(u),e.validator.attributeRules(u),e.validator.dataRules(u),e.validator.staticRules(u)),u),o.required&&(s=o.required,delete o.required,o=e.extend({required:s},o)),o.remote&&(s=o.remote,delete o.remote,o=e.extend(o,{remote:s})),o}}}),e.extend(e.expr.pseudos||e.expr[":"],{blank:function(t){return!e.trim(""+e(t).val())},filled:function(t){var n=e(t).val();return null!==n&&!!e.trim(""+n)},unchecked:function(t){return!e(t).prop("checked")}}),e.validator=function(t,n){this.settings=e.extend(!0,{},e.validator.defaults,t),this.currentForm=n,this.init()},e.validator.format=function(t,n){return 1===arguments.length?function(){var n=e.makeArray(arguments);return n.unshift(t),e.validator.format.apply(this,n)}:void 0===n?t:(arguments.length>2&&n.constructor!==Array&&(n=e.makeArray(arguments).slice(1)),n.constructor!==Array&&(n=[n]),e.each(n,function(e,n){t=t.replace(new RegExp("\\{"+e+"\\}","g"),function(){return n})}),t)},e.extend(e.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:e([]),errorLabelContainer:e([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(e){this.lastActive=e,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,e,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(e)))},onfocusout:function(e){this.checkable(e)||!(e.name in this.submitted)&&this.optional(e)||this.element(e)},onkeyup:function(t,n){var i=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===n.which&&""===this.elementValue(t)||-1!==e.inArray(n.keyCode,i)||(t.name in this.submitted||t.name in this.invalid)&&this.element(t)},onclick:function(e){e.name in this.submitted?this.element(e):e.parentNode.name in this.submitted&&this.element(e.parentNode)},highlight:function(t,n,i){"radio"===t.type?this.findByName(t.name).addClass(n).removeClass(i):e(t).addClass(n).removeClass(i)},unhighlight:function(t,n,i){"radio"===t.type?this.findByName(t.name).removeClass(n).addClass(i):e(t).removeClass(n).addClass(i)}},setDefaults:function(t){e.extend(e.validator.defaults,t)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:e.validator.format("Please enter no more than {0} characters."),minlength:e.validator.format("Please enter at least {0} characters."),rangelength:e.validator.format("Please enter a value between {0} and {1} characters long."),range:e.validator.format("Please enter a value between {0} and {1}."),max:e.validator.format("Please enter a value less than or equal to {0}."),min:e.validator.format("Please enter a value greater than or equal to {0}."),step:e.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function t(t){!this.form&&this.hasAttribute("contenteditable")&&(this.form=e(this).closest("form")[0],this.name=e(this).attr("name"));var n=e.data(this.form,"validator"),i="on"+t.type.replace(/^validate/,""),r=n.settings;r[i]&&!e(this).is(r.ignore)&&r[i].call(n,this,t)}this.labelContainer=e(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||e(this.currentForm),this.containers=e(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var n,i=this.groups={};e.each(this.settings.groups,function(t,n){"string"==typeof n&&(n=n.split(/\s/)),e.each(n,function(e,n){i[n]=t})}),n=this.settings.rules,e.each(n,function(t,i){n[t]=e.validator.normalizeRule(i)}),e(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",t).on("click.validate","select, option, [type='radio'], [type='checkbox']",t),this.settings.invalidHandler&&e(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),e.extend(this.submitted,this.errorMap),this.invalid=e.extend({},this.errorMap),this.valid()||e(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var e=0,t=this.currentElements=this.elements();t[e];e++)this.check(t[e]);return this.valid()},element:function(t){var n,i,r=this.clean(t),a=this.validationTargetFor(r),o=this,s=!0;return void 0===a?delete this.invalid[r.name]:(this.prepareElement(a),this.currentElements=e(a),i=this.groups[a.name],i&&e.each(this.groups,function(e,t){t===i&&e!==a.name&&(r=o.validationTargetFor(o.clean(o.findByName(e))))&&r.name in o.invalid&&(o.currentElements.push(r),s=o.check(r)&&s)}),n=!1!==this.check(a),s=s&&n,this.invalid[a.name]=!n,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),e(t).attr("aria-invalid",!n)),s},showErrors:function(t){if(t){var n=this;e.extend(this.errorMap,t),this.errorList=e.map(this.errorMap,function(e,t){return{message:e,element:n.findByName(t)[0]}}),this.successList=e.grep(this.successList,function(e){return!(e.name in t)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){e.fn.resetForm&&e(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var t=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(t)},resetElements:function(e){var t;if(this.settings.unhighlight)for(t=0;e[t];t++)this.settings.unhighlight.call(this,e[t],this.settings.errorClass,""),this.findByName(e[t].name).removeClass(this.settings.validClass);else e.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(e){var t,n=0;for(t in e)void 0!==e[t]&&null!==e[t]&&!1!==e[t]&&n++;return n},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(e){e.not(this.containers).text(""),this.addWrapper(e).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{e(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(e){}},findLastActive:function(){var t=this.lastActive;return t&&1===e.grep(this.errorList,function(e){return e.element.name===t.name}).length&&t},elements:function(){var t=this,n={};return e(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var i=this.name||e(this).attr("name");return!i&&t.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.hasAttribute("contenteditable")&&(this.form=e(this).closest("form")[0],this.name=i),!(i in n||!t.objectLength(e(this).rules())||(n[i]=!0,0))})},clean:function(t){return e(t)[0]},errors:function(){var t=this.settings.errorClass.split(" ").join(".");return e(this.settings.errorElement+"."+t,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=e([]),this.toHide=e([])},reset:function(){this.resetInternals(),this.currentElements=e([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(e){this.reset(),this.toHide=this.errorsFor(e)},elementValue:function(t){var n,i,r=e(t),a=t.type;return"radio"===a||"checkbox"===a?this.findByName(t.name).filter(":checked").val():"number"===a&&void 0!==t.validity?t.validity.badInput?"NaN":r.val():(n=t.hasAttribute("contenteditable")?r.text():r.val(),"file"===a?"C:\\fakepath\\"===n.substr(0,12)?n.substr(12):(i=n.lastIndexOf("/"),i>=0?n.substr(i+1):(i=n.lastIndexOf("\\"),i>=0?n.substr(i+1):n)):"string"==typeof n?n.replace(/\r/g,""):n)},check:function(t){t=this.validationTargetFor(this.clean(t));var n,i,r,a,o=e(t).rules(),s=e.map(o,function(e,t){return t}).length,l=!1,u=this.elementValue(t);if("function"==typeof o.normalizer?a=o.normalizer:"function"==typeof this.settings.normalizer&&(a=this.settings.normalizer),a){if("string"!=typeof(u=a.call(t,u)))throw new TypeError("The normalizer should return a string value.");delete o.normalizer}for(i in o){r={method:i,parameters:o[i]};try{if("dependency-mismatch"===(n=e.validator.methods[i].call(this,u,t,r.parameters))&&1===s){l=!0;continue}if(l=!1,"pending"===n)return void(this.toHide=this.toHide.not(this.errorsFor(t)));if(!n)return this.formatAndAdd(t,r),!1}catch(e){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+t.id+", check the '"+r.method+"' method.",e),e instanceof TypeError&&(e.message+=". Exception occurred when checking element "+t.id+", check the '"+r.method+"' method."),e}}if(!l)return this.objectLength(o)&&this.successList.push(t),!0},customDataMessage:function(t,n){return e(t).data("msg"+n.charAt(0).toUpperCase()+n.substring(1).toLowerCase())||e(t).data("msg")},customMessage:function(e,t){var n=this.settings.messages[e];return n&&(n.constructor===String?n:n[t])},findDefined:function(){for(var e=0;e<arguments.length;e++)if(void 0!==arguments[e])return arguments[e]},defaultMessage:function(t,n){"string"==typeof n&&(n={method:n});var i=this.findDefined(this.customMessage(t.name,n.method),this.customDataMessage(t,n.method),!this.settings.ignoreTitle&&t.title||void 0,e.validator.messages[n.method],"<strong>Warning: No message defined for "+t.name+"</strong>"),r=/\$?\{(\d+)\}/g;return"function"==typeof i?i=i.call(this,n.parameters,t):r.test(i)&&(i=e.validator.format(i.replace(r,"{$1}"),n.parameters)),i},formatAndAdd:function(e,t){var n=this.defaultMessage(e,t);this.errorList.push({message:n,element:e,method:t.method}),this.errorMap[e.name]=n,this.submitted[e.name]=n},addWrapper:function(e){return this.settings.wrapper&&(e=e.add(e.parent(this.settings.wrapper))),e},defaultShowErrors:function(){var e,t,n;for(e=0;this.errorList[e];e++)n=this.errorList[e],this.settings.highlight&&this.settings.highlight.call(this,n.element,this.settings.errorClass,this.settings.validClass),this.showLabel(n.element,n.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(e=0;this.successList[e];e++)this.showLabel(this.successList[e]);if(this.settings.unhighlight)for(e=0,t=this.validElements();t[e];e++)this.settings.unhighlight.call(this,t[e],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return e(this.errorList).map(function(){return this.element})},showLabel:function(t,n){var i,r,a,o,s=this.errorsFor(t),l=this.idOrName(t),u=e(t).attr("aria-describedby");s.length?(s.removeClass(this.settings.validClass).addClass(this.settings.errorClass),s.html(n)):(s=e("<"+this.settings.errorElement+">").attr("id",l+"-error").addClass(this.settings.errorClass).html(n||""),i=s,this.settings.wrapper&&(i=s.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(i):this.settings.errorPlacement?this.settings.errorPlacement.call(this,i,e(t)):i.insertAfter(t),s.is("label")?s.attr("for",l):0===s.parents("label[for='"+this.escapeCssMeta(l)+"']").length&&(a=s.attr("id"),u?u.match(new RegExp("\\b"+this.escapeCssMeta(a)+"\\b"))||(u+=" "+a):u=a,e(t).attr("aria-describedby",u),(r=this.groups[t.name])&&(o=this,e.each(o.groups,function(t,n){n===r&&e("[name='"+o.escapeCssMeta(t)+"']",o.currentForm).attr("aria-describedby",s.attr("id"))})))),!n&&this.settings.success&&(s.text(""),"string"==typeof this.settings.success?s.addClass(this.settings.success):this.settings.success(s,t)),this.toShow=this.toShow.add(s)},errorsFor:function(t){var n=this.escapeCssMeta(this.idOrName(t)),i=e(t).attr("aria-describedby"),r="label[for='"+n+"'], label[for='"+n+"'] *";return i&&(r=r+", #"+this.escapeCssMeta(i).replace(/\s+/g,", #")),this.errors().filter(r)},escapeCssMeta:function(e){return e.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(e){return this.groups[e.name]||(this.checkable(e)?e.name:e.id||e.name)},validationTargetFor:function(t){return this.checkable(t)&&(t=this.findByName(t.name)),e(t).not(this.settings.ignore)[0]},checkable:function(e){return/radio|checkbox/i.test(e.type)},findByName:function(t){return e(this.currentForm).find("[name='"+this.escapeCssMeta(t)+"']")},getLength:function(t,n){switch(n.nodeName.toLowerCase()){case"select":return e("option:selected",n).length;case"input":if(this.checkable(n))return this.findByName(n.name).filter(":checked").length}return t.length},depend:function(e,t){return!this.dependTypes[void 0===e?"undefined":_typeof(e)]||this.dependTypes[void 0===e?"undefined":_typeof(e)](e,t)},dependTypes:{boolean:function(e){return e},string:function(t,n){return!!e(t,n.form).length},function:function(e,t){return e(t)}},optional:function(t){var n=this.elementValue(t);return!e.validator.methods.required.call(this,n,t)&&"dependency-mismatch"},startRequest:function(t){this.pending[t.name]||(this.pendingRequest++,e(t).addClass(this.settings.pendingClass),this.pending[t.name]=!0)},stopRequest:function(t,n){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[t.name],e(t).removeClass(this.settings.pendingClass),n&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(e(this.currentForm).submit(),this.submitButton&&e("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove(),this.formSubmitted=!1):!n&&0===this.pendingRequest&&this.formSubmitted&&(e(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(t,n){return n="string"==typeof n&&n||"remote",e.data(t,"previousValue")||e.data(t,"previousValue",{old:null,valid:!0,message:this.defaultMessage(t,{method:n})})},destroy:function(){this.resetForm(),e(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(t,n){t.constructor===String?this.classRuleSettings[t]=n:e.extend(this.classRuleSettings,t)},classRules:function(t){var n={},i=e(t).attr("class");return i&&e.each(i.split(" "),function(){this in e.validator.classRuleSettings&&e.extend(n,e.validator.classRuleSettings[this])}),n},normalizeAttributeRule:function(e,t,n,i){/min|max|step/.test(n)&&(null===t||/number|range|text/.test(t))&&(i=Number(i),isNaN(i)&&(i=void 0)),i||0===i?e[n]=i:t===n&&"range"!==t&&(e[n]=!0)},attributeRules:function(t){var n,i,r={},a=e(t),o=t.getAttribute("type");for(n in e.validator.methods)"required"===n?(i=t.getAttribute(n),""===i&&(i=!0),i=!!i):i=a.attr(n),this.normalizeAttributeRule(r,o,n,i);return r.maxlength&&/-1|2147483647|524288/.test(r.maxlength)&&delete r.maxlength,r},dataRules:function(t){var n,i,r={},a=e(t),o=t.getAttribute("type");for(n in e.validator.methods)i=a.data("rule"+n.charAt(0).toUpperCase()+n.substring(1).toLowerCase()),this.normalizeAttributeRule(r,o,n,i);return r},staticRules:function(t){var n={},i=e.data(t.form,"validator");return i.settings.rules&&(n=e.validator.normalizeRule(i.settings.rules[t.name])||{}),n},normalizeRules:function(t,n){return e.each(t,function(i,r){if(!1===r)return void delete t[i];if(r.param||r.depends){var a=!0;switch(_typeof(r.depends)){case"string":a=!!e(r.depends,n.form).length;break;case"function":a=r.depends.call(n,n)}a?t[i]=void 0===r.param||r.param:(e.data(n.form,"validator").resetElements(e(n)),delete t[i])}}),e.each(t,function(i,r){t[i]=e.isFunction(r)&&"normalizer"!==i?r(n):r}),e.each(["minlength","maxlength"],function(){t[this]&&(t[this]=Number(t[this]))}),e.each(["rangelength","range"],function(){var n;t[this]&&(e.isArray(t[this])?t[this]=[Number(t[this][0]),Number(t[this][1])]:"string"==typeof t[this]&&(n=t[this].replace(/[\[\]]/g,"").split(/[\s,]+/),t[this]=[Number(n[0]),Number(n[1])]))}),e.validator.autoCreateRanges&&(null!=t.min&&null!=t.max&&(t.range=[t.min,t.max],delete t.min,delete t.max),null!=t.minlength&&null!=t.maxlength&&(t.rangelength=[t.minlength,t.maxlength],delete t.minlength,delete t.maxlength)),t},normalizeRule:function(t){if("string"==typeof t){var n={};e.each(t.split(/\s/),function(){n[this]=!0}),t=n}return t},addMethod:function(t,n,i){e.validator.methods[t]=n,e.validator.messages[t]=void 0!==i?i:e.validator.messages[t],n.length<3&&e.validator.addClassRules(t,e.validator.normalizeRule(t))},methods:{required:function(t,n,i){if(!this.depend(i,n))return"dependency-mismatch";if("select"===n.nodeName.toLowerCase()){var r=e(n).val();return r&&r.length>0}return this.checkable(n)?this.getLength(t,n)>0:t.length>0},email:function(e,t){return this.optional(t)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e)},url:function(e,t){return this.optional(t)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(e)},date:function(e,t){return this.optional(t)||!/Invalid|NaN/.test(new Date(e).toString())},dateISO:function(e,t){return this.optional(t)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(e)},number:function(e,t){return this.optional(t)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(e)},digits:function(e,t){return this.optional(t)||/^\d+$/.test(e)},minlength:function(t,n,i){var r=e.isArray(t)?t.length:this.getLength(t,n);return this.optional(n)||r>=i},maxlength:function(t,n,i){var r=e.isArray(t)?t.length:this.getLength(t,n);return this.optional(n)||r<=i},rangelength:function(t,n,i){var r=e.isArray(t)?t.length:this.getLength(t,n);return this.optional(n)||r>=i[0]&&r<=i[1]},min:function(e,t,n){return this.optional(t)||e>=n},max:function(e,t,n){return this.optional(t)||e<=n},range:function(e,t,n){return this.optional(t)||e>=n[0]&&e<=n[1]},step:function(t,n,i){var r,a=e(n).attr("type"),o="Step attribute on input type "+a+" is not supported.",s=["text","number","range"],l=new RegExp("\\b"+a+"\\b"),u=a&&!l.test(s.join()),c=function(e){var t=(""+e).match(/(?:\.(\d+))?$/);return t&&t[1]?t[1].length:0},d=function(e){return Math.round(e*Math.pow(10,r))},h=!0;if(u)throw new Error(o);return r=c(i),(c(t)>r||d(t)%d(i)!=0)&&(h=!1),this.optional(n)||h},equalTo:function(t,n,i){var r=e(i);return this.settings.onfocusout&&r.not(".validate-equalTo-blur").length&&r.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){e(n).valid()}),t===r.val()},remote:function(t,n,i,r){if(this.optional(n))return"dependency-mismatch";r="string"==typeof r&&r||"remote";var a,o,s,l=this.previousValue(n,r);return this.settings.messages[n.name]||(this.settings.messages[n.name]={}),l.originalMessage=l.originalMessage||this.settings.messages[n.name][r],this.settings.messages[n.name][r]=l.message,i="string"==typeof i&&{url:i}||i,s=e.param(e.extend({data:t},i.data)),l.old===s?l.valid:(l.old=s,a=this,this.startRequest(n),o={},o[n.name]=t,e.ajax(e.extend(!0,{mode:"abort",port:"validate"+n.name,dataType:"json",data:o,context:a.currentForm,success:function(e){var i,o,s,u=!0===e||"true"===e;a.settings.messages[n.name][r]=l.originalMessage,u?(s=a.formSubmitted,a.resetInternals(),a.toHide=a.errorsFor(n),a.formSubmitted=s,a.successList.push(n),a.invalid[n.name]=!1,a.showErrors()):(i={},o=e||a.defaultMessage(n,{method:r,parameters:t}),i[n.name]=l.message=o,a.invalid[n.name]=!0,a.showErrors(i)),l.valid=u,a.stopRequest(n,u)}},i)),"pending")}}});var t,n={};return e.ajaxPrefilter?e.ajaxPrefilter(function(e,t,i){var r=e.port;"abort"===e.mode&&(n[r]&&n[r].abort(),n[r]=i)}):(t=e.ajax,e.ajax=function(i){var r=("mode"in i?i:e.ajaxSettings).mode,a=("port"in i?i:e.ajaxSettings).port;return"abort"===r?(n[a]&&n[a].abort(),n[a]=t.apply(this,arguments),n[a]):t.apply(this,arguments)}),e}),function(e,t,n,i,r,o,s){function l(){function t(e,t){l.push({Kb:e,gc:t})}function n(e,t){h.c(l,function(n,i){n.Kb==e&&n.gc===t&&l.splice(i,1)})}function i(){l=[]}function a(){h.c(u,function(e){h.$RemoveEvent(e.Nd,e.Kb,e.gc,e.Md)}),u=[]}var o,s=this,l=[],u=[];s.bd=function(){return o},s.a=function(e,t,n,i){h.$AddEvent(e,t,n,i),u.push({Nd:e,Kb:t,gc:n,Md:i})},s.T=function(e,t,n,i){h.c(u,function(r,a){r.Nd===e&&r.Kb==t&&r.gc===n&&r.Md==i&&(h.$RemoveEvent(e,t,n,i),u.splice(a,1))})},s.Rd=a,s.$On=s.addEventListener=t,s.$Off=s.removeEventListener=n,s.j=function(t){var n=[].slice.call(arguments,1);h.c(l,function(i){i.Kb==t&&i.gc.apply(e,n)})},s.$Destroy=function(){o||(o=r,a(),i())}}function u(e,t,n){var i=this;h.V(i,l),f.call(i,0,n.$Idle),i.jc=0,i.rd=n.$Idle}new function(){};var c={E:n.PI,m:n.max,k:n.min,K:n.ceil,P:n.floor,F:n.abs,sb:n.sin,dc:n.cos,Ee:n.tan,yf:n.atan,Yb:n.sqrt,q:n.pow,ke:n.random,$Round:n.round},d=e.$Jease$={$Swing:function(e){return-c.dc(e*c.E)/2+.5},$Linear:function(e){return e},$InQuad:function(e){return e*e},$OutQuad:function(e){return-e*(e-2)},$InOutQuad:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)},$InCubic:function(e){return e*e*e},$OutCubic:function(e){return(e-=1)*e*e+1},$InOutCubic:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)},
$InQuart:function(e){return e*e*e*e},$OutQuart:function(e){return-((e-=1)*e*e*e-1)},$InOutQuart:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)},$InQuint:function(e){return e*e*e*e*e},$OutQuint:function(e){return(e-=1)*e*e*e*e+1},$InOutQuint:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)},$InSine:function(e){return 1-c.dc(c.E/2*e)},$OutSine:function(e){return c.sb(c.E/2*e)},$InOutSine:function(e){return-.5*(c.dc(c.E*e)-1)},$InExpo:function(e){return 0==e?0:c.q(2,10*(e-1))},$OutExpo:function(e){return 1==e?1:1-c.q(2,-10*e)},$InOutExpo:function(e){return 0==e||1==e?e:(e*=2)<1?.5*c.q(2,10*(e-1)):.5*(2-c.q(2,-10*--e))},$InCirc:function(e){return-(c.Yb(1-e*e)-1)},$OutCirc:function(e){return c.Yb(1-(e-=1)*e)},$InOutCirc:function(e){return(e*=2)<1?-.5*(c.Yb(1-e*e)-1):.5*(c.Yb(1-(e-=2)*e)+1)},$InElastic:function(e){if(!e||1==e)return e;return-c.q(2,10*(e-=1))*c.sb(2*(e-.075)*c.E/.3)},$OutElastic:function(e){if(!e||1==e)return e;return c.q(2,-10*e)*c.sb(2*(e-.075)*c.E/.3)+1},$InOutElastic:function(e){if(!e||1==e)return e;return(e*=2)<1?-.5*c.q(2,10*(e-=1))*c.sb(2*(e-.1125)*c.E/.45):c.q(2,-10*(e-=1))*c.sb(2*(e-.1125)*c.E/.45)*.5+1},$InBack:function(e){var t=1.70158;return e*e*((t+1)*e-t)},$OutBack:function(e){var t=1.70158;return(e-=1)*e*((t+1)*e+t)+1},$InOutBack:function(e){var t=1.70158;return(e*=2)<1?.5*e*e*((1+(t*=1.525))*e-t):.5*((e-=2)*e*((1+(t*=1.525))*e+t)+2)},$InBounce:function(e){return 1-d.$OutBounce(1-e)},$OutBounce:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},$InOutBounce:function(e){return e<.5?.5*d.$InBounce(2*e):.5*d.$OutBounce(2*e-1)+.5},$GoBack:function(e){return 1-c.F(1)},$InWave:function(e){return 1-c.dc(e*c.E*2)},$OutWave:function(e){return c.sb(e*c.E*2)},$OutJump:function(e){return 1-((e*=2)<1?(e=1-e)*e*e:(e-=1)*e*e)},$InJump:function(e){return(e*=2)<1?e*e*e:(e=2-e)*e*e},$Early:c.K,$Late:c.P},h=e.$Jssor$=new function(){function n(){if(!ne){ne={Vc:"ontouchstart"in e||"createTouch"in t};var n;(fe.pointerEnabled||(n=fe.msPointerEnabled))&&(ne.ie=n?"msTouchAction":"touchAction")}return ne}function u(t){if(!ce)if(ce=-1,"Microsoft Internet Explorer"==pe&&e.attachEvent&&e.ActiveXObject){var n=me.indexOf("MSIE");ce=ae,de=ge(me.substring(n+5,me.indexOf(";",n)))}else if("Netscape"==pe&&e.addEventListener){var i=me.indexOf("Firefox"),r=me.indexOf("Safari"),a=me.indexOf("Chrome"),o=me.indexOf("AppleWebKit");if(i>=0)ce=oe,de=ge(me.substring(i+8));else if(r>=0){var s=me.substring(0,r).lastIndexOf("/");ce=a>=0?le:se,de=ge(me.substring(s+1,r))}else{var l=/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/i.exec(me);l&&(ce=ae,de=ge(l[1]))}o>=0&&(he=ge(me.substring(o+12)))}else{var l=/(opera)(?:.*version|)[ \/]([\w.]+)/i.exec(me);l&&(ce=ue,de=ge(l[2]))}return t==ce}function f(){return u(ae)}function p(){return u(oe)}function m(){return u(se)}function g(){return u(ue)}function v(){return m()&&he>534&&he<535}function y(){return u(),he>537||de>42||ce==ae&&de>=11}function _(e){var t,n;return function(i){if(!t){t=r;var a=e.substr(0,1).toUpperCase()+e.substr(1);w([e].concat(["WebKit","ms","Moz","O","webkit"]),function(t,r){var o=e;if(r&&(o=t+a),i.style[o]!=s)return n=o})}return n}}function b(e){var t;return function(n){return t=t||_(e)(n)||e}}function $(e){return{}.toString.call(e)}function w(e,t){var n,i;if("[object Array]"==$(e)){for(n=0;n<e.length;n++)if(i=t(e[n],n,e))return i}else for(n in e)if(i=t(e[n],n,e))return i}function S(e){return e==i?String(e):ye[$(e)]||"object"}function T(e){for(var t in e)return r}function C(e){try{return"object"==S(e)&&!e.nodeType&&e!=e.window&&(!e.constructor||{}.hasOwnProperty.call(e.constructor.prototype,"isPrototypeOf"))}catch(e){}}function D(e,t){setTimeout(e,t||0)}function k(e,t,n){var i=e&&"inherit"!=e?e:"";return w(t,function(e){var t=e.exec(i);if(t){var n=i.substr(0,t.index),r=i.substr(t.index+t[0].length+1,i.length-1);i=n+r}}),i&&(n+=(i.indexOf(" ")?" ":"")+i),n}function x(e,t){return e===s&&(e=t),e}function E(e){e.constructor===E.caller&&e.A&&e.A.apply(e,E.caller.arguments)}function A(t){return t||e.event}function O(t,n,r){if(r===s){var a=t.currentStyle||t.style;return r=a[n],""==r&&e.getComputedStyle&&(a=t.ownerDocument.defaultView.getComputedStyle(t,i))&&(r=a.getPropertyValue(n)||a[n]),r}t.style[n]=r==s?"":r}function N(e,t,n,r){if(n===s)return n=ge(O(e,t)),isNaN(n)&&(n=i),n;n==i?n="":r&&(n+="px"),O(e,t,n)}function M(e,t){var n,i=t?N:O;return 4&t&&(n=b(e)),function(r,a){return i(r,n?n(r):e,a,2&t)}}function I(e){return ge(e.style.opacity||"1")}function R(e,t){e.style.opacity=1==t?"":c.$Round(100*t)/100}function P(e,t){var n="";t&&(f()&&de&&de<10&&(delete t.$RotateX,delete t.$RotateY,delete t.$TranslateZ),w(t,function(e,t){var i=_e[t];if(i){var r=i[1]||0;we[t]!=e&&(n+=" "+i[0]+"("+e+["deg","px",""][r]+")")}}),y()&&((t.$TranslateX||t.$TranslateY||t.$TranslateZ!=s)&&(n+=" translate3d("+(t.$TranslateX||0)+"px,"+(t.$TranslateY||0)+"px,"+(t.$TranslateZ||0)+"px)"),t.$ScaleX==s&&(t.$ScaleX=1),t.$ScaleY==s&&(t.$ScaleY=1),1==t.$ScaleX&&1==t.$ScaleY||(n+=" scale3d("+t.$ScaleX+", "+t.$ScaleY+", 1)"))),e.style[ve(e)]=n}function L(e,t,n,r){for(r=r||"u",e=e?e.firstChild:i;e;e=e.nextSibling)if(1==e.nodeType){if(j(e,r)==t)return e;if(!n){var a=L(e,t,n,r);if(a)return a}}}function H(e,t,n,r){r=r||"u";var a=[];for(e=e?e.firstChild:i;e;e=e.nextSibling)if(1==e.nodeType&&(j(e,r)==t&&a.push(e),!n)){var o=H(e,t,n,r);o.length&&(a=a.concat(o))}return a}function F(){var e,t,n,i,r=arguments,a=1&r[0],o=1+a;for(e=r[o-1]||{};o<r.length;o++)if(t=r[o])for(n in t)if((i=t[n])!==s){i=t[n];var l=e[n];e[n]=a&&(C(l)||C(i))?F(a,{},l,i):i}return e}function Y(e,t){var n,i,r,a={};for(n in e)if(i=e[n],r=t[n],i!==r){var o;C(i)&&C(r)&&(i=Y(i,r),o=!T(i)),!o&&(a[n]=i)}return a}function V(e){return t.createElement(e)}function q(e,t,n){if(n==s)return e.getAttribute(t);e.setAttribute(t,n)}function j(e,t){return q(e,t)||q(e,"data-"+t)}function B(e,t){return q(e,"class",t)||""}function W(e){var t={};return w(e,function(e){e!=s&&(t[e]=e)}),t}function U(e,t){return e.match(t||re)}function z(e,t){return W(U(e||"",t))}function G(e,t){var n="";return w(t,function(t){n&&(n+=e),n+=t}),n}function X(e,t,n){B(e,G(" ",F(Y(z(B(e)),z(t)),z(n))))}function Z(){w([].slice.call(arguments,0),function(e){ie.ne(e)?Z.apply(i,e):e&&e.$Destroy()})}function K(e,t,n){var i=e.cloneNode(!t);return!n&&ie.Gg(i,"id"),i}function Q(){function n(){X(o,u,(f[g||2&m||m]||"")+" "+(f[p]||"")),ie.zc(o,g?"none":"")}function i(){p=0,a.T(e,"mouseup",i),a.T(t,"mouseup",i),a.T(t,"touchend",i),a.T(t,"touchcancel",i),a.T(e,"blur",i),n()}function r(r){g?ie.$CancelEvent(r):(p=4,n(),a.a(e,"mouseup",i),a.a(t,"mouseup",i),a.a(t,"touchend",i),a.a(t,"touchcancel",i),a.a(e,"blur",i))}var a=this;h.V(a,l);var o,u,c="",d=["av","pv","ds","dn"],f=[],p=0,m=0,g=0;a.ae=function(e){if(e===s)return m;m=2&e||1&e,n()},a.$Enable=function(e){if(e===s)return!g;g=e?0:3,n()},a.A=function(e){a.$Elmt=o=ie.$GetElement(e),q(o,"data-jssor-button","1");var t=h.Tg(B(o));t&&(c=t.shift()),w(d,function(e){f.push(c+e)}),u=G(" ",f),f.unshift(""),a.a(o,"mousedown",r),a.a(o,"touchstart",r)},h.A(a)}function J(e,t){function n(e,t){t=t||{};var n=t.$TranslateZ||0,i=(t.$RotateX||0)%360,r=(t.$RotateY||0)%360,a=(t.$Rotate||0)%360,l=t.$ScaleX,u=t.$ScaleY,c=t.Mh;l==s&&(l=1),u==s&&(u=1),c==s&&(c=1);var d=new ee(t.$TranslateX,t.$TranslateY,n);d.$Scale(l,u,c),d.Zg(t.$SkewX,t.$SkewY),d.$RotateX(i),d.$RotateY(r),d.Yg(a),d.$Move(t.N,t.J),e.style[o]=d.ah()}var r=y(),a=v(),o=ve(e);J=function(e,t){t=t||{};var o,l=t.N,u=t.J;w($e,function(n,i){(o=t[i])!==s&&n(e,o)}),ie.Lg(e,t.$Clip),ie.ig(e,t.vb),r||(l!=s&&ie.Q(e,(t.Fd||0)+l),u!=s&&ie.ab(e,(t.Pd||0)+u)),t.dh&&(a?D(ie.S(i,P,e,t)):r?n(e,t):P(e,t))},ie.Z=J,J(e,t)}function ee(e,t,n){function r(e){return e*c.E/180}function o(e,t,n,i,r,a,o,s,l,u,c,d,h,f,p,m,g,v,y,_,b,$,w,S,T,C,D,k,x,E,A,O){return[e*g+t*b+n*T+i*x,e*v+t*$+n*C+i*E,e*y+t*w+n*D+i*A,e*_+t*S+n*k+i*O,r*g+a*b+o*T+s*x,r*v+a*$+o*C+s*E,r*y+a*w+o*D+s*A,r*_+a*S+o*k+s*O,l*g+u*b+c*T+d*x,l*v+u*$+c*C+d*E,l*y+u*w+c*D+d*A,l*_+u*S+c*k+d*O,h*g+f*b+p*T+m*x,h*v+f*$+p*C+m*E,h*y+f*w+p*D+m*A,h*_+f*S+p*k+m*O]}function s(e,t){return o.apply(i,(t||u).concat(e))}var l=this,u=[1,0,0,0,0,1,0,0,0,0,1,0,e||0,t||0,n||0,1],d=c.sb,h=c.dc,f=c.Ee;l.$Scale=function(e,t,n){1==e&&1==t&&1==n||(u=s([e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]))},l.$Move=function(e,t,n){u[12]+=e||0,u[13]+=t||0,u[14]+=n||0},l.$RotateX=function(e){if(e){a=r(e);var t=h(a),n=d(a);u=s([1,0,0,0,0,t,n,0,0,-n,t,0,0,0,0,1])}},l.$RotateY=function(e){if(e){a=r(e);var t=h(a),n=d(a);u=s([t,0,-n,0,0,1,0,0,n,0,t,0,0,0,0,1])}},l.Yg=function(e){if(e){a=r(e);var t=h(a),n=d(a);u=s([t,n,0,0,-n,t,0,0,0,0,1,0,0,0,0,1])}},l.Zg=function(n,i){(n||i)&&(e=r(n),t=r(i),u=s([1,f(t),0,0,f(e),1,0,0,0,0,1,0,0,0,0,1]))},l.ah=function(){return"matrix3d("+u.join(",")+")"}}function te(e,t){var n={};return w(e,function(e,i){var r=e;t[i]!=s&&(r=ie.oc(e)?e+t[i]:te(e,t[i])),n[i]=r}),n}var ne,ie=this,re=/\S+/g,ae=1,oe=2,se=3,le=4,ue=5,ce=0,de=0,he=0,fe=navigator,pe=fe.appName,me=fe.userAgent,ge=parseFloat,ve=b("transform"),ye={};w(["Boolean","Number","String","Function","Array","Date","RegExp","Object"],function(e){ye["[object "+e+"]"]=e.toLowerCase()}),ie.Sc=n,ie.te=f,ie.bh=p,ie.Vg=m,ie.Xg=y,_("transform"),ie.id=function(){return de},ie.jg=function(){return u(),he},ie.$Delay=D,ie.W=x,ie.V=function(e,t){return t.call(e),F({},e)},ie.A=E,ie.$GetElement=function(e){return ie.kg(e)&&(e=t.getElementById(e)),e},ie.Xf=A,ie.$EvtSrc=function(e){e=A(e);var n=e.target||e.srcElement||t;return 3==n.nodeType&&(n=ie.sd(n)),n},ie.qe=function(e){return e=A(e),e.relatedTarget||e.toElement},ie.re=function(e){return e=A(e),e.which||[0,1,3,0,2][e.button]||e.charCode||e.keyCode},ie.jd=function(e){return e=A(e),{x:e.clientX||0,y:e.clientY||0}},ie.Yf=function(e,t){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h},ie.oe=function(e,t){var n=h.Ig(t),i=h.jd(e);return ie.Yf(i,n)};var _e={$Rotate:["rotate"],$RotateX:["rotateX"],$RotateY:["rotateY"],$SkewX:["skewX"],$SkewY:["skewY"]};y()||(_e=F(_e,{$ScaleX:["scaleX",2],$ScaleY:["scaleY",2],$TranslateZ:["translateZ",1]})),ie.Zf=M("transformOrigin",4),ie.dg=M("backfaceVisibility",4),M("transformStyle",4),ie.bg=M("perspective",6),ie.xg=M("perspectiveOrigin",4),ie.yg=function(e,t){if(f()&&de<9)e.style.zoom=1==t?"":t;else{var n=ve(e),i=1==t?"":"scale("+t+")",r=e.style[n],a=new RegExp(/[\s]*scale\(.*?\)/g),o=k(r,[a],i);e.style[n]=o}},ie.$AddEvent=function(e,t,n,i){e=ie.$GetElement(e),e.addEventListener?("mousewheel"==t&&e.addEventListener("DOMMouseScroll",n,i),e.addEventListener(t,n,i)):e.attachEvent&&(e.attachEvent("on"+t,n),i&&e.setCapture&&e.setCapture())},ie.$RemoveEvent=function(e,t,n,i){e=ie.$GetElement(e),e.removeEventListener?("mousewheel"==t&&e.removeEventListener("DOMMouseScroll",n,i),e.removeEventListener(t,n,i)):e.detachEvent&&(e.detachEvent("on"+t,n),i&&e.releaseCapture&&e.releaseCapture())},ie.$CancelEvent=function(e){e=A(e),e.preventDefault&&e.preventDefault(),e.cancel=r,e.returnValue=o},ie.$StopEvent=function(e){e=A(e),e.stopPropagation&&e.stopPropagation(),e.cancelBubble=r},ie.S=function(e,t){var n=[].slice.call(arguments,2);return function(){var i=n.concat([].slice.call(arguments,0));return t.apply(e,i)}},ie.Ag=function(e,n){if(n==s)return e.textContent||e.innerText;var i=t.createTextNode(n);ie.Xb(e),e.appendChild(i)},ie.Ig=function(e){var t=e.getBoundingClientRect();return{x:t.left,y:t.top,w:t.right-t.left,h:t.bottom-t.top}},ie.Eb=function(e,t){for(var n=[],i=e.firstChild;i;i=i.nextSibling)(t||1==i.nodeType)&&n.push(i);return n},ie.$FindChild=L,ie.qg=function(e,t){return e.getElementsByTagName(t)},ie.tb=function(e,n,i,r){i=i||"u";var a;do{if(1==e.nodeType){var o;if(i&&(o=j(e,i)),o&&o==x(n,o)||r==e.tagName){a=e;break}}e=h.sd(e)}while(e&&e!=t.body);return a},ie.ug=function(e){return W(["INPUT","TEXTAREA","SELECT"])[e.tagName]},ie.G=F,ie.me=function(e){return"function"==S(e)},ie.ne=function(e){return"array"==S(e)},ie.kg=function(e){return"string"==S(e)},ie.oc=function(e){return!isNaN(ge(e))&&isFinite(e)},ie.c=w,ie.Ae=C,ie.Tb=function(){return V("DIV")},ie.Cg=function(){return V("SPAN")},ie.Vf=function(){},ie.z=q,ie.X=j,ie.B=function(e,t,n){var i=ie.Ce(j(e,t));return isNaN(i)&&(i=n),i},ie.ye=W,ie.Tg=U,ie.Me=function(e){return e&&(e=e.toLowerCase()),e},ie.Be=G,ie.sd=function(e){return e.parentNode},ie.Cb=function(e){ie.Bb(e,"none")},ie.eb=function(e,t){ie.Bb(e,t?"none":"")},ie.Gg=function(e,t){e.removeAttribute(t)},ie.Lg=function(e,t){if(t)e.style.clip="rect("+c.$Round(t.$Top||t.J||0)+"px "+c.$Round(t.$Right)+"px "+c.$Round(t.$Bottom)+"px "+c.$Round(t.$Left||t.N||0)+"px)";else if(t!==s){var n=e.style.cssText,i=[new RegExp(/[\s]*clip: rect\(.*?\)[;]?/i),new RegExp(/[\s]*cliptop: .*?[;]?/i),new RegExp(/[\s]*clipright: .*?[;]?/i),new RegExp(/[\s]*clipbottom: .*?[;]?/i),new RegExp(/[\s]*clipleft: .*?[;]?/i)],r=k(n,i,"");h.zd(e,r)}},ie.ig=function(e,t){t&&(e.style.backgroundColor="rgba("+c.$Round(t.xd)+","+c.$Round(t.wd)+","+c.$Round(t.Bd)+","+t.$Opacity+")")},ie.Ab=function(){return+new Date},ie.bb=function(e,t){e.appendChild(t)},ie.sg=function(e,t){w(t,function(t){ie.bb(e,t)})},ie.Ib=function(e,t,n){(n||t.parentNode).insertBefore(e,t)},ie.rg=function(e,t,n){e.insertAdjacentHTML(t,n)},ie.nb=function(e,t){(t=t||e.parentNode)&&t.removeChild(e)},ie.tg=function(e,t){w(e,function(e){ie.nb(e,t)})},ie.Xb=function(e){ie.tg(ie.Eb(e,r),e)},ie.$Destroy=Z,ie.nd=function(e,t){var n=ie.sd(e);1&t&&(ie.Q(e,(ie.C(n)-ie.C(e))/2),ie.Xd(e,i)),2&t&&(ie.ab(e,(ie.D(n)-ie.D(e))/2),ie.Vd(e,i))};var be={$Top:i,$Right:i,$Bottom:i,$Left:i,H:i,I:i};ie.wg=function(e){var t=ie.Tb();J(t,{Sd:"block",Ob:ie.rb(e),$Top:0,$Left:0,H:0,I:0});var n=ie.Ud(e,be);ie.Ib(t,e),ie.bb(t,e);var i=ie.Ud(e,be),r={};return w(n,function(e,t){e==i[t]&&(r[t]=e)}),J(t,be),J(t,r),J(e,{$Top:0,$Left:0}),r},ie.Ce=ge,ie.ve=function(e,n){for(var i=t.body;n&&e!==n&&i!==n;)n=n.parentNode;return e===n},ie.gb=K,ie.Nb=function(e,t){function n(e,r){ie.$RemoveEvent(a,"load",n),ie.$RemoveEvent(a,"abort",i),ie.$RemoveEvent(a,"error",i),t&&t(a,r)}function i(e){n(e,r)}var a=new Image;g()&&de<11.6||!e?n(!e):(ie.$AddEvent(a,"load",n),ie.$AddEvent(a,"abort",i),ie.$AddEvent(a,"error",i),a.src=e)},ie.cg=function(e,t,n){function i(e){r--,t&&e&&e.src==t.src&&(t=e),!r&&n&&n(t)}var r=e.length+1;w(e,function(e){ie.Nb(e.src,i)}),i()},ie.fe=function(e,t,n,i){i&&(e=K(e));var r=H(e,t);r.length||(r=h.qg(e,t));for(var a=r.length-1;a>-1;a--){var o=r[a],s=K(n);B(s,B(o)),h.zd(s,o.style.cssText),h.Ib(s,o),h.nb(o)}return e},ie.qc=function(e){return new Q(e)},ie.Rb=O,ie.Lb=M("overflow"),ie.zc=M("pointerEvents"),ie.ab=M("top",2),ie.Xd=M("right",2),ie.Vd=M("bottom",2),ie.Q=M("left",2),ie.C=M("width",2),ie.D=M("height",2),M("marginLeft",2),M("marginTop",2),ie.rb=M("position"),ie.Bb=M("display"),ie.Y=M("zIndex",1),ie.hg=function(e,t,n){if(t==s)return I(e);R(e,t)},ie.zd=function(e,t){if(t==s)return e.style.cssText;e.style.cssText=t},ie.gg=function(e,t){if(t===s){t=O(e,"backgroundImage")||"";return(/\burl\s*\(\s*["']?([^"'\r\n,]+)["']?\s*\)/gi.exec(t)||[])[1]}O(e,"backgroundImage",t?"url('"+t+"')":"")};var $e;ie.Eg=$e={$Opacity:ie.hg,$Top:ie.ab,$Right:ie.Xd,$Bottom:ie.Vd,$Left:ie.Q,H:ie.C,I:ie.D,Ob:ie.rb,Sd:ie.Bb,$ZIndex:ie.Y},ie.Ud=function(e,t){var n={};return w(t,function(t,i){$e[i]&&(n[i]=$e[i](e))}),n},ie.fh=P,ie.Z=J;var we={Fd:0,Pd:0,N:0,J:0,$Zoom:1,$ScaleX:1,$ScaleY:1,$Rotate:0,$RotateX:0,$RotateY:0,$TranslateX:0,$TranslateY:0,$TranslateZ:0,$SkewX:0,$SkewY:0};ie.ad=function(e,t){var n=e||{};return e&&(h.me(e)?n={W:n}:h.me(e.$Clip)&&(n.$Clip={W:e.$Clip})),n.W=n.W||t,n.$Clip&&(n.$Clip.W=n.$Clip.W||t),n.vb&&(n.vb.W=n.vb.W||t),n},ie.Sg=te,ie.Ld=function(e,t,n,a,o,l,u){var p=t;if(e){p={};for(var m in t){var g=l[m]||1,v=o[m]||[0,1],y=(n-v[0])/v[1];y=c.k(c.m(y,0),1),y*=g;var _=c.P(y);y!=_&&(y-=_);var b,$=a.W||d.$Linear,S=e[m],T=t[m];if(h.oc(T)){$=a[m]||$;var C=$(y);b=S+T*C}else{b=F({kc:{}},e[m]);var D=a[m]||{};w(T.kc||T,function(e,t){$=D[t]||D.W||$;var n=$(y),i=e*n;b.kc[t]=i,b[t]+=i})}p[m]=b}var k=w(t,function(e,t){return we[t]!=s});k&&w(we,function(t,n){p[n]==s&&e[n]!==s&&(p[n]=e[n])}),k&&(p.$Zoom&&(p.$ScaleX=p.$ScaleY=p.$Zoom),p.$OriginalWidth=u.$OriginalWidth,p.$OriginalHeight=u.$OriginalHeight,f()&&de>=11&&(t.N||t.J)&&0!=n&&1!=n&&(p.$Rotate=p.$Rotate||1e-8),p.dh=r)}if(t.$Clip&&u.$Move){var x=p.$Clip.kc,E=(x.$Top||0)+(x.$Bottom||0),A=(x.$Left||0)+(x.$Right||0);p.$Left=(p.$Left||0)+A,p.$Top=(p.$Top||0)+E,p.$Clip.$Left-=A,p.$Clip.$Right-=A,p.$Clip.$Top-=E,p.$Clip.$Bottom-=E}return!p.$Clip||p.$Clip.$Top||p.$Clip.$Left||p.$Clip.J||p.$Clip.N||p.$Clip.$Right!=u.$OriginalWidth||p.$Clip.$Bottom!=u.$OriginalHeight||(p.$Clip=i),p}},f=function(t,n,i,a,l,u){function d(e){x+=e,E+=e,k+=e,H+=e,F+=e,L+=e}function f(e){var t=e;if(A&&(!O&&(t>=E||t<x)||O&&t>=x)&&(t=((t-x)%A+A)%A+x),!D||$||H!=t){var o=c.k(t,E);if(o=c.m(o,x),i.$Reverse&&(o=E-o+x),!D||$||o!=F){if(u){var d=(o-k)/(n||1),f=h.Ld(l,u,d,w,T,S,i);N?h.c(f,function(e,t){N[t]&&N[t](a,e)}):h.Z(a,f);var p;if(M&&(toDisablePointerEventsByAnimation=o>x&&o<E,toDisablePointerEventsByAnimation!=q&&(p=q=toDisablePointerEventsByAnimation)),!p&&f.$Opacity!=s){var m=f.$Opacity<.001;m!=V&&(p=V=m)}p!=s&&(p&&h.zc(a,"none"),!p&&h.zc(a,h.z(a,"data-events")))}var g=F,v=F=o;h.c(Y,function(e,n){(!D&&O||t<=H?Y[Y.length-n-1]:e).M(o-L)}),H=t,D=r,I.Tc(g-k,v-k),I.ec(g,v)}}}function p(e,t,n){t&&e.$Shift(E),n||(x=c.k(x,e.mc()+L),E=c.m(E,e.ub()+L)),Y.push(e)}function m(){if(y){var e=h.Ab(),t=c.k(e-R,i.Hd),n=H+t*b*P;R=e,n*b>=_*b&&(n=_),f(n),!$&&n*b>=_*b?v(C):j(m)}}function g(e,t,n){y||(y=r,$=n,C=t,e=c.m(e,x),e=c.k(e,E),_=e,b=_<H?-1:1,I.pd(),R=h.Ab(),j(m))}function v(e){y&&($=y=C=o,I.qd(),e&&e())}t=t||0;var y,_,b,$,w,S,T,C,D,k,x,E,A,O,N,M,I=this,R=0,P=1,L=0,H=0,F=0,Y=[],V=o,q=o,j=e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.msRequestAnimationFrame;(h.Vg()&&h.id()<7||!j)&&(j=function(e){h.$Delay(e,i.$Interval)}),I.$Play=function(e,t,n){g(e?H+e:E,t,n)},I.sc=g,I.Se=function(e,t){g(E,e,t)},I.O=v,I.Jd=function(){return H},I.Id=function(){return _},I.n=function(){return F},I.M=f,I.ef=function(){f(E,r)},I.$IsPlaying=function(){return y},I.Zd=function(e){P=e},I.$Shift=d,I.Be=p,I.U=function(e,t){p(e,0,t)},I.Gc=function(e){p(e,1)},I.Hc=function(e){E+=e},I.mc=function(){return x},I.ub=function(){return E},I.ec=I.pd=I.qd=I.Tc=h.Vf,I.Pc=h.Ab(),i=h.G({$Interval:16,Hd:50},i),a&&(M=h.z(a,"data-inactive")),A=i.pc,O=i.Oe,N=i.Ne,x=k=t,E=t+n,S=i.$Round||{},T=i.$During||{},w=h.ad(i.$Easing)},p={Hf:"data-scale",yb:"data-autocenter",Qc:"data-nofreeze",Td:"data-nodrag"},m=new function(){var e=this;e.Ac=function(e,t,n,i){(i||!h.z(e,t))&&h.z(e,t,n)},e.Cc=function(e){var t=h.B(e,p.yb);h.nd(e,t)}},g=e.$JssorSlideshowFormations$=new function(){function e(e){return(e&a)==a}function t(e){return(e&o)==o}function n(e,t,n){n.push(t),e[t]=e[t]||[],e[t].push(n)}var i=this,a=2,o=4,s=2049,l=2048+a,u=513,d=512+a,h=256+o,f=264,p=1024+o,m=1032;i.$FormationStraight=function(e){for(var t,i=e.$Cols,r=e.$Rows,a=e.$Assembly,o=e.Fc,c=[],m=0,g=0,v=i-1,y=r-1,_=o-1,g=0;g<r;g++)for(m=0;m<i;m++){switch(a){case s:t=_-(m*r+(y-g));break;case p:t=_-(g*i+(v-m));break;case u:t=_-(m*r+g);case h:t=_-(g*i+m);break;case l:t=m*r+g;break;case f:t=g*i+(v-m);break;case d:t=m*r+(y-g);break;default:t=g*i+m}n(c,t,[g,m])}return c},i.$FormationSwirl=function(e){var t,i,a=e.$Cols,o=e.$Rows,c=e.$Assembly,m=e.Fc,g=[],v=[],y=0,_=0,b=0,$=a-1,w=o-1,S=0;switch(c){case s:_=$,b=0,i=[2,1,3,0];break;case p:_=0,b=w,i=[0,3,1,2];break;case u:_=$,b=w,i=[3,1,2,0];break;case h:_=$,b=w,i=[1,3,0,2];break;case l:_=0,b=0,i=[2,0,3,1];break;case f:_=$,b=0,i=[1,2,0,3];break;case d:_=0,b=w,i=[3,0,2,1];break;default:_=0,b=0,i=[0,2,1,3]}for(y=0;y<m;){if(t=b+","+_,_>=0&&_<a&&b>=0&&b<o&&!v[t])v[t]=r,n(g,y++,[b,_]);else switch(i[S++%i.length]){case 0:_--;break;case 2:b--;break;case 1:_++;break;case 3:b++}switch(i[S%i.length]){case 0:_++;break;case 2:b++;break;case 1:_--;break;case 3:b--}}return g},i.$FormationZigZag=function(e){var t,i,r=e.$Cols,a=e.$Rows,o=e.$Assembly,c=e.Fc,m=[],g=0,v=0,y=0,_=r-1,b=a-1,$=0;switch(o){case s:v=_,y=0,i=[2,1,3,1];break;case p:v=0,y=b,i=[0,3,1,3];break;case u:v=_,y=b,i=[3,1,2,1];break;case h:v=_,y=b,i=[1,3,0,3];break;case l:v=0,y=0,i=[2,0,3,0];break;case f:v=_,y=0,i=[1,2,0,2];break;case d:v=0,y=b,i=[3,0,2,0];break;default:v=0,y=0,i=[0,2,1,2]}for(g=0;g<c;)if(t=y+","+v,v>=0&&v<r&&y>=0&&y<a&&void 0===m[t])switch(n(m,g++,[y,v]),i[$%i.length]){case 0:v++;break;case 2:y++;break;case 1:v--;break;case 3:y--}else{switch(i[$++%i.length]){case 0:v--;break;case 2:y--;break;case 1:v++;break;case 3:y++}switch(i[$++%i.length]){case 0:v++;break;case 2:y++;break;case 1:v--;break;case 3:y--}}return m},i.$FormationStraightStairs=function(i){var r=i.$Cols,a=i.$Rows,o=i.$Assembly,c=i.Fc,g=[],v=0,y=0,_=0,b=r-1,$=a-1,w=c-1;switch(o){case s:case d:case u:case l:var S=0,T=0;break;case f:case p:case h:case m:var S=b,T=0;break;default:o=m;var S=b,T=0}for(y=S,_=T;v<c;){switch(t(o)||e(o)?n(g,w-v++,[_,y]):n(g,v++,[_,y]),o){case s:case d:y--,_++;break;case u:case l:y++,_--;break;case f:case p:y--,_--;break;case m:case h:default:y++,_++}if(y<0||_<0||y>b||_>$){switch(o){case s:case d:S++;break;case f:case p:case u:case l:T++;break;case m:case h:default:S--}if(S<0||T<0||S>b||T>$){switch(o){case s:case d:S=b,T++;break;case u:case l:T=$,S++;break;case f:case p:T=$,S--;break;case m:case h:default:S=0,T++}T>$?T=$:T<0?T=0:S>b?S=b:S<0&&(S=0)}_=T,y=S}}return g},i.$FormationRectangle=function(e){var t,i,r,a=e.$Cols||1,o=e.$Rows||1,s=[];for(r=c.$Round(c.k(a/2,o/2))+1,t=0;t<a;t++)for(i=0;i<o;i++)n(s,r-c.k(t+1,i+1,a-t,o-i),[i,t]);return s},i.$FormationRandom=function(e){for(var t,i=[],r=0;r<e.$Rows;r++)for(t=0;t<e.$Cols;t++)n(i,c.K(1e5*c.ke())%13,[r,t]);return i},i.$FormationCircle=function(e){for(var t,i=e.$Cols||1,r=e.$Rows||1,a=[],o=i/2-.5,s=r/2-.5,l=0;l<i;l++)for(t=0;t<r;t++)n(a,c.$Round(c.Yb(c.q(l-o,2)+c.q(t-s,2))),[t,l]);return a},i.$FormationCross=function(e){for(var t,i=e.$Cols||1,r=e.$Rows||1,a=[],o=i/2-.5,s=r/2-.5,l=0;l<i;l++)for(t=0;t<r;t++)n(a,c.$Round(c.k(c.F(l-o),c.F(t-s))),[t,l]);return a},i.$FormationRectangleCross=function(e){for(var t,i=e.$Cols||1,r=e.$Rows||1,a=[],o=i/2-.5,s=r/2-.5,l=c.m(o,s)+1,u=0;u<i;u++)for(t=0;t<r;t++)n(a,c.$Round(l-c.m(o-c.F(u-o),s-c.F(t-s)))-1,[t,u]);return a}};e.$JssorSlideshowRunner$=function(e,t,n,a,s,u){function p(e){e.$Top&&(e.J=e.$Top),e.$Left&&(e.N=e.$Left),h.c(e,function(e){h.Ae(e)&&p(e)})}function m(e,t,n){var i={$Interval:t,$Duration:1,$Delay:0,$Cols:1,$Rows:1,$Opacity:0,$Zoom:0,$Clip:0,$Move:o,$SlideOut:o,$Reverse:o,$Formation:g.$FormationRandom,$Assembly:1032,$ChessMode:{$Column:0,$Row:0},$Easing:d.$Linear,$Round:{},vc:[],$During:{}};return h.G(i,e),0==i.$Rows&&(i.$Rows=c.$Round(i.$Cols*n)),p(i),i.Fc=i.$Cols*i.$Rows,i.$Easing=h.ad(i.$Easing,d.$Linear),i.mf=c.K(i.$Duration/i.$Interval),i.zf=function(e,t){e/=i.$Cols,t/=i.$Rows;var n=e+"x"+t;if(!i.vc[n]){i.vc[n]={H:e,I:t};for(var r=0;r<i.$Cols;r++)for(var a=0;a<i.$Rows;a++)i.vc[n][a+","+r]={$Top:a*t,$Right:r*e+e,$Bottom:a*t+t,$Left:r*e}}return i.vc[n]},i.$Brother&&(i.$Brother=m(i.$Brother,t,n),i.$SlideOut=r),i}function v(e,t,n,i,a,s){var l,d,f,p,m,g=this,v={},y={},_=[],b=n.$ChessMode.$Column||0,$=n.$ChessMode.$Row||0,w=n.zf(a,s),S=function(e){var t=e.$Formation(e);return e.$Reverse?t.reverse():t}(n),T=S.length-1,C=n.$Duration+n.$Delay*T,D=i+C,k=n.$SlideOut;D+=50,g.Cd=D,g.rc=function(e){e-=i;var t=e<C;if(t||m){m=t,k||(e=C-e);var r=c.K(e/n.$Interval);h.c(y,function(e,t){var n=c.m(r,e.k);n=c.k(n,e.length-1),e.yd!=n&&(e.yd||k?n==e.m&&k&&h.Cb(_[t]):h.eb(_[t]),e.yd=n,h.Z(_[t],e[n]))})}},t=h.gb(t),u(t,0,0),h.c(S,function(e,t){h.c(e,function(e){var i=e[0],u=e[1],m=i+","+u,g=o,_=o,S=o;b&&u%2&&(3&b&&(g=!g),12&b&&(_=!_),16&b&&(S=!S)),$&&i%2&&(3&$&&(g=!g),12&$&&(_=!_),16&$&&(S=!S)),n.$Top=n.$Top||4&n.$Clip,n.$Bottom=n.$Bottom||8&n.$Clip,n.$Left=n.$Left||1&n.$Clip,n.$Right=n.$Right||2&n.$Clip;var T=_?n.$Bottom:n.$Top,C=_?n.$Top:n.$Bottom,D=g?n.$Right:n.$Left,x=g?n.$Left:n.$Right;n.$Clip=T||C||D||x,p={},f={J:0,N:0,$Opacity:1,H:a,I:s},d=h.G({},f),l=h.G({},w[m]),n.$Opacity&&(f.$Opacity=2-n.$Opacity),n.$ZIndex&&(f.$ZIndex=n.$ZIndex,d.$ZIndex=0);var E=n.$Cols*n.$Rows>1||n.$Clip;if(n.$Zoom||n.$Rotate){if(r){f.$Zoom=n.$Zoom?n.$Zoom-1:1,d.$Zoom=1;var A=n.$Rotate||0;f.$Rotate=360*A*(S?-1:1),d.$Rotate=0}}if(E){var O=l.kc={};if(n.$Clip){var N=n.$ScaleClip||1;T&&C?(O.$Top=w.I/2*N,O.$Bottom=-O.$Top):T?O.$Bottom=-w.I*N:C&&(O.$Top=w.I*N),D&&x?(O.$Left=w.H/2*N,O.$Right=-O.$Left):D?O.$Right=-w.H*N:x&&(O.$Left=w.H*N)}p.$Clip=l,d.$Clip=w[m]}var M=g?1:-1,I=_?1:-1;n.x&&(f.N+=a*n.x*M),n.y&&(f.J+=s*n.y*I),h.c(f,function(e,t){h.oc(e)&&e!=d[t]&&(p[t]=e-d[t])}),v[m]=k?d:f;var R=n.mf,P=c.$Round(t*n.$Delay/n.$Interval);y[m]=new Array(P),y[m].k=P,y[m].m=P+R-1;for(var L=0;L<=R;L++){var H=h.Ld(d,p,L/R,n.$Easing,n.$During,n.$Round,{$Move:n.$Move,$OriginalWidth:a,$OriginalHeight:s});H.$ZIndex=H.$ZIndex||1,y[m].push(H)}})}),S.reverse(),h.c(S,function(n){h.c(n,function(n){var i=n[0],r=n[1],a=i+","+r,o=t;(r||i)&&(o=h.gb(t)),h.Z(o,v[a]),h.Lb(o,"hidden"),h.rb(o,"absolute"),e.Af(o),_[a]=o,h.eb(o,!k)})})}function y(){var e=this,t=0;f.call(e,0,_),e.ec=function(e,n){n-t>D&&(t=n,$&&$.rc(n),b&&b.rc(n))},e.Xc=w}var _,b,$,w,S=this,T=0,C=a.$TransitionsOrder,D=8;S.xf=function(){var e=0,t=a.$Transitions,n=t.length;return e=C?T++%n:c.P(c.ke()*n),t[e]&&(t[e].Zb=e),t[e]},S.tf=function(i,r,a,o,s,l){S.zb(),w=s,s=m(s,D,l);var u=o.Ad,d=a.Ad;u["no-image"]=!o.Uc,d["no-image"]=!a.Uc;var h=u,f=d,p=s,g=s.$Brother||m({},D,l);s.$SlideOut||(h=d,f=u);var y=g.$Shift||0;b=new v(e,f,g,c.m(y-g.$Interval,0),t,n),$=new v(e,h,p,c.m(g.$Interval-y,0),t,n),b.rc(0),$.rc(0),_=c.m(b.Cd,$.Cd),S.Zb=i},S.zb=function(){e.zb(),b=i,$=i},S.Pe=function(){var e=i;return $&&(e=new y),e},s&&h.jg()<537&&(D=16),l.call(S),f.call(S,-1e7,1e7)};var v={yc:1};e.$JssorBulletNavigator$=function(){function e(e){D[e]&&D[e].ae(e==E)}function t(e){k.j(v.yc,e*g)}var n,a,o,u,d,f,g,y,_,b,$,w,S,T,C,D,k=this,x=h.V(k,l),E=0;k.cd=function(t){if(t!=d){var n=E,i=c.P(t/g);E=i,d=t,e(n),e(i)}},k.dd=function(e){h.eb(n,e)},k.hd=function(e){h.$Destroy(D),d=s,k.Rd(),C=[],D=[],h.Xb(n),a=c.K(e/g),E=0;var l=S+_,p=T+b,v=c.K(a/y)-1;o=S+l*($?y-1:v),u=T+p*($?v:y-1),h.C(n,o),h.D(n,u);for(var x=0;x<a;x++){var A=h.Cg();h.Ag(A,x+1);var O=h.fe(w,"numbertemplate",A,r);h.rb(O,"absolute");var N=x%(v+1),M=c.P(x/(v+1)),I=f.cc&&!$?v-N:N;h.Q(O,($?M:I)*l),h.ab(O,($?I:M)*p),h.bb(n,O),C[x]=O,1&f.$ActionMode&&k.a(O,"click",h.S(i,t,x)),2&f.$ActionMode&&k.a(O,"mouseenter",h.S(i,t,x)),D[x]=h.qc(O)}m.Cc(n)},k.A=function(e,t){k.$Elmt=n=h.$GetElement(e),k.Jc=f=h.G({$SpacingX:10,$SpacingY:10,$ActionMode:1},t),w=h.$FindChild(n,"prototype"),S=h.C(w),T=h.D(w),h.nb(w,n),g=f.$Steps||1,y=f.$Rows||1,_=f.$SpacingX,b=f.$SpacingY,$=2&f.$Orientation,f.$AutoCenter&&m.Ac(n,p.yb,f.$AutoCenter)},k.$Destroy=function(){h.$Destroy(D,x)},h.A(k)},e.$JssorArrowNavigator$=function(){function e(e){b.j(v.yc,e,r)}function t(e){h.eb(a,e),h.eb(o,e)}function n(){y.$Enable((s.$Loop||!u.Ef(f))&&d>1),_.$Enable((s.$Loop||!u.Ff(f))&&d>1)}var a,o,s,u,c,d,f,g,y,_,b=this,$=h.V(b,l);b.cd=function(e,t,i){f=t,!i&&n()},b.dd=t,b.hd=function(t){d=t,f=0,c||(b.a(a,"click",h.S(i,e,-g)),b.a(o,"click",h.S(i,e,g)),y=h.qc(a),_=h.qc(o),h.z(a,p.Qc,1),h.z(o,p.Qc,1),c=r)},b.A=function(e,t,n,i){b.Jc=s=h.G({$Steps:1},n),a=e,o=t,s.cc&&(a=t,o=e),g=s.$Steps,u=i,s.$AutoCenter&&(m.Ac(a,p.yb,s.$AutoCenter),m.Ac(o,p.yb,s.$AutoCenter)),m.Cc(a),m.Cc(o)},b.$Destroy=function(){h.$Destroy(y,_,$)},h.A(b)},e.$JssorThumbnailNavigator$=function(){function e(){function e(){p.ae(f==s)}function t(e){if(e||!D.$LastDragSucceeded()){var t=b-s%b,n=D.de((s+t)/b-1),i=n*b+b-t;n<0&&(i+=u%b),n>=d&&(i-=u%b),x.j(v.yc,i,o,r)}}var n=this;h.V(n,l);var s,c,p,m;n.ce=e,n.A=function(e,o){n.Zb=s=o,m=e.Fe||e.Uc||h.Tb(),n.ld=c=h.fe(k,"thumbnailtemplate",m,r),p=h.qc(c),1&a.$ActionMode&&n.a(c,"click",h.S(i,t,0)),2&a.$ActionMode&&n.a(c,"mouseenter",h.S(i,t,1))},h.A(n)}var t,n,a,u,d,f,g,y,b,$,w,S,T,C,D,k,x=this,E=h.V(x,l),A=[];x.cd=function(e,t,n){if(e!=f){var i=f;f=e,-1!=i&&A[i].ce(),A[e]&&A[e].ce()}!n&&D.$PlayTo(D.de(c.P(e/b)))},x.dd=function(e){h.eb(t,e)},x.hd=function(i,l){h.$Destroy(D,A),f=s,A=[];var p=h.gb(n);h.Xb(t),a.cc&&h.z(t,"dir","rtl"),h.sg(t,h.Eb(p));var v=h.$FindChild(t,"slides",r);u=i,d=c.K(u/b),f=-1;var k=1&a.$Orientation,x=S+(S+$)*(b-1)*(1-k),E=T+(T+w)*(b-1)*k,O=(k?c.m:c.k)(g,x),N=(k?c.k:c.m)(y,E);C=c.K((g-$)/(S+$)*k+(y-w)/(T+w)*(1-k));var M=x+(x+$)*(C-1)*k,I=E+(E+w)*(C-1)*(1-k);O=c.k(O,M),N=c.k(N,I),h.C(v,O),h.D(v,N),h.nd(v,3);var R=[];h.c(l,function(t,n){var i=new e(t,n),r=i.ld,a=c.P(n/b),o=n%b;h.Q(r,(S+$)*o*(1-k)),h.ab(r,(T+w)*o*k),R[a]||(R[a]=h.Tb(),h.bb(v,R[a])),h.bb(R[a],r),A.push(i)});var P=h.G({$AutoPlay:0,$NaviQuitDrag:o,$SlideWidth:x,$SlideHeight:E,$SlideSpacing:$*k+w*(1-k),$MinDragOffsetToSlide:12,$SlideDuration:200,$PauseOnHover:1,$Cols:C,$PlayOrientation:a.$Orientation,$DragOrientation:a.$NoDrag||a.$DisableDrag?0:a.$Orientation},a);D=new _(t,P),m.Cc(t)},x.A=function(e,i,o){t=e,x.Jc=a=h.G({$SpacingX:0,$SpacingY:0,$Orientation:1,$ActionMode:1},i),g=h.C(t),y=h.D(t);var s=h.$FindChild(t,"slides",r);k=h.$FindChild(s,"prototype"),o=h.gb(o),h.Ib(o,s),S=h.C(k),T=h.D(k),h.nb(k,s),h.rb(s,"absolute"),h.Lb(s,"hidden"),b=a.$Rows||1,$=a.$SpacingX,w=a.$SpacingY,a.$AutoCenter&=a.$Orientation,a.$AutoCenter&&m.Ac(t,p.yb,a.$AutoCenter),n=h.gb(t)},x.$Destroy=function(){h.$Destroy(D,A,E)},h.A(x)},u.Rc=21,u.xc=24;var y=e.$JssorCaptionSlideo$=e.$JssorSlideo$=function(){function e(t,n){var i={};return h.c(t,function(t,r){var a=K[r];a&&(h.Ae(t)?t=e(t,n||"e"==r):n&&h.oc(t)&&(t=Z[t]),i[a]=t)}),i}function n(e,t){var i=[],r=h.B(e,"play");if(t&&r){var a=new y(e,P,{Fg:r});ie.push(a),M.a(a,u.Rc,O),M.a(a,u.xc,N)}else h.c(h.Eb(e),function(e){i=i.concat(n(e,t+1))});if(!t&&(!Y||16&Y)||t&&(!r||!(16&r))){var o=L[h.B(e,"t")];o&&i.push({$Elmt:e,Xc:o})}return i}function a(e,t){var n=J[e];if(n==i){n=J[e]={pb:e,gd:[],xe:[]};var r=0;!h.c(ee,function(t,n){return r=n,t.pb>e})&&r++,ee.splice(r,0,n)}return n}function s(t,n,o){var s,l;if(H){var u=H[h.B(t,"c")];u&&(s=a(u.r,0),s.eh=u.e||0)}if(h.c(n,function(n){var i=h.G(r,{},e(n)),u=h.ad(i.$Easing);delete i.$Easing,i.$Left&&(i.N=i.$Left,u.N=u.$Left,delete i.$Left),i.$Top&&(i.J=i.$Top,u.J=u.$Top,delete i.$Top);var d={$Easing:u,$OriginalWidth:o.H,$OriginalHeight:o.I},p=new f(n.b,n.d,d,t,o,i);if(te=c.m(te,n.b+n.d),s)l||(l=new f(n.b,0)),l.U(p);else{a(n.b,n.b+n.d).gd.push(p)}i.vb&&(o.vb={xd:0,wd:0,Bd:0,$Opacity:0}),o=h.Sg(o,i)}),s&&l){l.ef();var d,p=l,m=l.mc(),g=l.ub(),v=c.m(g,s.eh);s.pb<g&&(s.pb>m?(p=new f(m,s.pb-m),p.U(l,r)):p=i,d=new f(s.pb,v-m,{pc:v-s.pb,Oe:r}),d.U(l,r)),p&&s.gd.push(p),d&&s.xe.push(d)}return o}function p(e){h.c(e,function(e){var t=e.$Elmt,n=h.C(t),i=h.D(t),r={$Left:h.Q(t),$Top:h.ab(t),N:0,J:0,$Opacity:1,$ZIndex:h.Y(t)||0,$Rotate:0,$RotateX:0,$RotateY:0,$ScaleX:1,$ScaleY:1,$TranslateX:0,$TranslateY:0,$TranslateZ:0,$SkewX:0,$SkewY:0,H:n,I:i,$Clip:{$Top:0,$Right:n,$Bottom:i,$Left:0}};r.Fd=r.$Left,r.Pd=r.$Top,s(t,e.Xc,r)})}function m(e,t,n){var i=e.b-t;if(i){var a=new f(t,i);a.U(Q,r),a.$Shift(n),M.U(a)}return M.Hc(e.d),i}function g(e){var t=Q.mc(),n=0;h.c(e,function(e,i){e=h.G({d:3e3},e),m(e,t,n),t=e.b,n+=e.d,i&&2!=e.t||(M.jc=t,M.rd=t+e.d)})}function v(e,t,n){var i=t.length;if(i>4)for(var r=c.K(i/4),a=0;a<r;a++){var o=t.slice(4*a,c.k(4*a+4,i)),s=new f(o[0].pb,0);v(s,o,n),e.U(s)}else h.c(t,function(t){h.c(n?t.xe:t.gd,function(t){n&&t.Hc(te-t.ub()),e.U(t)})})}function _(e){return 2&e||4&e&&h.Sc().Vc}function b(){U||(8&q&&M.a(t,"keydown",D),32&q&&(M.a(t,"mousedown",x),M.a(t,"touchstart",x)),U=r)}function $(){M.T(t,"keydown",D),M.T(t,"mousedown",x),M.T(t,"touchstart",x),U=o}function w(e){z&&!e||(z=r,M.O(),e&&ne&&M.M(0),M.Zd(1),M.Se(),b(),M.j(u.Rc,M))}function S(){G||!z&&!M.n()||(G=r,M.O(),M.Jd()>M.jc&&M.M(M.jc),M.Zd(B||1),M.sc(0))}function T(){!X&&S()}function C(e){var t=e;e<0&&M.n()&&(t=1),t!=ne&&(ne=t,V&&M.j(u.xc,M,ne))}function D(e){8&q&&27==h.re(e)&&S()}function k(e){X&&h.qe(e)!==i&&(X=o,16&q&&h.$Delay(T,160))}function x(e){
32&q&&!h.ve(R,h.$EvtSrc(e))&&S()}function E(e){X||(X=r,1&Y&&h.oe(e,R)&&w())}function A(e){var t=h.$EvtSrc(e),n=h.tb(t,i,i,"A"),a=n&&(h.ug(n)||n===R||h.ve(R,n));z&&_(q)?!a&&S():_(Y)&&!a&&w(r)}function O(e){var t=e.Wg();childSlideoPlaying=re[t],childSlideoPlaying!==e&&re[t]&&re[t].pg(),re[t]=e}function N(e,t){M.j(u.xc,e,t)}var M=this,I=h.V(M,l);f.call(M,0,0);var R,P,L,H,F,Y,V,q,j,B,W,U,z,G,X,Z=[d.$Linear,d.$Swing,d.$InQuad,d.$OutQuad,d.$InOutQuad,d.$InCubic,d.$OutCubic,d.$InOutCubic,d.$InQuart,d.$OutQuart,d.$InOutQuart,d.$InQuint,d.$OutQuint,d.$InOutQuint,d.$InSine,d.$OutSine,d.$InOutSine,d.$InExpo,d.$OutExpo,d.$InOutExpo,d.$InCirc,d.$OutCirc,d.$InOutCirc,d.$InElastic,d.$OutElastic,d.$InOutElastic,d.$InBack,d.$OutBack,d.$InOutBack,d.$InBounce,d.$OutBounce,d.$InOutBounce,d.$Early,d.$Late],K={},Q=new f(0,0),J=[],ee=[],te=0,ne=0,ie=[],re=[];M.Wg=function(){return W||""},M.pg=S,M.pd=function(){C(1)},M.qd=function(){z=o,G=o,C(-1),!M.n()&&$()},M.ec=function(){!X&&j&&M.Jd()>M.rd&&S()},M.A=function(e,t,i){R=e,P=t,Y=i.Fg,F=i.ng,L=P.$Transitions,H=P.$Controls;var a={$Top:"y",$Left:"x",$Bottom:"m",$Right:"t",$Rotate:"r",$RotateX:"rX",$RotateY:"rY",$ScaleX:"sX",$ScaleY:"sY",$TranslateX:"tX",$TranslateY:"tY",$TranslateZ:"tZ",$SkewX:"kX",$SkewY:"kY",$Opacity:"o",$Easing:"e",$ZIndex:"i",$Clip:"c",vb:"bc",xd:"re",wd:"gr",Bd:"bl"};h.c(a,function(e,t){K[e]=t}),p(n(R,0)),v(Q,ee),Y&&(M.U(Q),F=r,j=h.B(R,"idle"),(_(Y)||_(q))&&M.a(R,"click",A),(1&Y||j)&&!h.Sc().Vc&&(M.a(R,"mouseenter",E),M.a(R,"mouseleave",k)),q=h.B(R,"rollback"),B=h.X(R,"speed")||"","x"==B.substr(0,1)&&(B=B.substr(1)),B=h.Ce(B),W=h.X(R,"group"),V=h.B(R,"pause"));var o=P.$Breaks||[],s=o[h.B(R,"b")]||[];s=s.concat({b:te,d:s.length?0:i.$Idle||j||0}),g(s),F&&M.Hc(1e8),te=M.ub(),v(M,ee,r),M.M(-1),M.M(h.B(R,"begin")||0)},M.$Destroy=function(){h.$Destroy(I,ie),M.O(),M.M(-1)},h.A(M)},_=e.$JssorSlider$=(e.module||{}).exports=function(){function n(){return!Gt&&12&rt}function a(){return Xt||!Gt&&3&rt}function m(){return!pt&&!n()&&!St.$IsPlaying()}function g(){return!a()&&m()}function y(){return ze||ge}function b(){return 2&y()?qe:Ve}function $(e,t,n){h.Q(e,t),h.ab(e,n)}function w(e,t){var n=y();$(e,(Ve*t+Bt)*(1&n),(qe*t+Bt)*(2&n)/2)}function S(e,t){if(pt&&!(1&ct)){var n,i=e;if(e<zt&&(i=zt,n=-1),e>Ut&&(i=Ut,n=1),n){var r=e-i;t?(r=2*c.yf(r)/c.E,r=c.q(r*n,1.6)):(r=c.q(r*n,.625),r=c.Ee(r*c.E/2)),e=i+r*n}}return e}function T(e){return S(e,r)}function C(e){return S(e)}function D(e,t){if(!(1&ct)){var n=e-Ut+(t||0),i=zt-e+(t||0);n>0&&n>i?e=Ut:i>0&&(e=zt)}return e}function k(e){return!(1&ct)&&e-zt<1e-4}function x(e){return!(1&ct)&&Ut-e<1e-4}function E(e){return!(1&ct)&&(e-zt<1e-4||Ut-e<1e-4)}function A(e,t,n){!Ot&&h.c(jt,function(i){i.cd(e,t,n)})}function O(e){var t=e;return E(e)?t=D(t):(e=F(e),t=e),t=c.P(t),t=c.m(t,0)}function N(e){e!=qt&&(Qt[qt],Re=qt,qt=e,Pe=Qt[qt])}function M(){ze=0;var e=bt.n(),t=O(e);A(t,e),(E(e)||e==c.P(e))&&(2&Je&&(it>0&&t==Le-1||it<0&&!t)&&(Je=0),N(t),Nt.j(_.$EVT_PARK,qt,Re))}function I(e,t){!Le||t&&St.$IsPlaying()||(St.O(),St.Kc(e,e))}function R(e){Le?(e=F(e),e=D(e),I(e)):A(0,0)}function P(){var e=_.je||0,t=dt;return _.je|=t,Ge=t&~e}function L(){Ge&&(_.je&=~dt,Ge=0)}function H(){var e=h.Tb();return h.Z(e,Ie),e}function F(e,t){return t=t||Le||1,(e%t+t)%t}function Y(e,t,n){8&Je&&(Je=0),U(e,ot,t,n)}function V(){h.c(jt,function(e){e.dd(e.Jc.$ChanceToShow<=Gt)})}function q(e){Gt||!h.qe(e)&&h.oe(e,pe)||(Gt=1,V(),pt||(12&rt&&ie(),Qt[qt]&&Qt[qt].uc()),Nt.j(_.$EVT_MOUSE_LEAVE))}function j(){Gt&&(Gt=0,V(),pt||!(12&rt)||ne()),Nt.j(_.$EVT_MOUSE_ENTER)}function B(){h.c(Vt,function(e){h.Z(e,Ie),h.Lb(e,"hidden"),h.Cb(e)}),h.Z(ke,Ie)}function W(e,t){U(e,t,r)}function U(e,t,i,a){if(Le&&(!pt||me.$NaviQuitDrag)&&!n()){var l=bt.n(),u=e;i&&(u=l+e,2&ct&&(k(l)&&e<0&&(u=Ut),x(l)&&e>0&&(u=zt))),1&ct||(u=a?F(u):D(u,.5)),i&&!E(u)&&(u=c.$Round(u));var d=(u-l)%Le;u=l+d,t==s&&(t=ot);var h=c.F(d),f=0;if(h){if(h<1&&(h=c.q(h,.5)),h>1){var p=b(),m=(1&ge?Ne:Me)/p;h=c.k(h,1.5*m)}f=t*h}Ot=r,St.O(),Ot=o,St.Kc(l,u,f)}}function z(e,t,n){var i,a,o,s,l=this,u={$Top:2,$Right:1,$Bottom:2,$Left:1},d={$Top:"top",$Right:"right",$Bottom:"bottom",$Left:"left"},f={};l.$Elmt=e,l.$ScaleSize=function(l,m,g){var v,y=l,_=m;if(o||(o=h.wg(e),i=e.parentNode,s={$Scale:h.B(e,p.Hf,1),$AutoCenter:h.B(e,p.yb)},h.c(d,function(t,n){f[n]=h.B(e,"data-scale-"+t,1)}),a=e,t&&(a=h.gb(i,r),h.Z(a,{$Top:0,$Left:0}),h.bb(a,e),h.bb(i,a))),n){if(v=c.m(l,m),t&&g>=0&&g<1){var b=c.k(l,m);v=c.k(v/b,1/(1-g))*b}}else y=_=v=c.q(we<Se?m:l,s.$Scale);var $=t?1.001:1,w=v*$;t&&(Ft=w),h.yg(a,w),h.C(i,o.H*y),h.D(i,o.I*_);var S=h.te()&&h.id()<9?w:1,T=(y-S)*o.H/2,C=(_-S)*o.I/2;h.Q(a,T),h.ab(a,C),h.c(o,function(e,t){if(u[t]&&e){var n=(1&u[t])*c.q(l,f[t])*e+(2&u[t])*c.q(m,f[t])*e/2;h.Eg[t](i,n)}}),h.nd(i,s.$AutoCenter)}}function G(){var e=this;f.call(e,0,0,{pc:Le}),h.c(Qt,function(t){e.Gc(t),t.$Shift(ut/je)})}function X(){var e=this,t=Tt.$Elmt;f.call(e,-1,2,{$Easing:d.$Linear,Ne:{Ob:w},pc:Le,$Reverse:tt},t,{Ob:1},{Ob:-2}),e.ld=t}function Z(){var e=this;f.call(e,-1e8,2e8),e.ec=function(e,t){if(c.F(t-e)>1e-5){var n=t,i=t;c.P(t)!=t&&t>e&&(1&ct||t>Wt)&&i++;A(O(i),n,r),Nt.j(_.$EVT_POSITION_CHANGE,F(n),F(e),t,e)}}}function K(e,t){var n,a,s,l,u,c=this;f.call(c,-1e8,2e8,{Hd:100}),c.pd=function(){ft=r,Nt.j(_.$EVT_SWIPE_START,F(bt.n()),$t.n())},c.qd=function(){ft=o,l=o,Nt.j(_.$EVT_SWIPE_END,F(bt.n()),$t.n()),!pt&&M()},c.ec=function(e,t){var i=t;if(l)i=u;else if(s){var r=t/s;i=me.$SlideEasing(r)*(a-n)+n}i=T(i),$t.M(i)},c.Kc=function(e,t,i,l){pt=o,s=i||1,n=e,a=t,Ot=r,$t.M(e),Ot=o,c.M(0),c.sc(s,l)},c.Wf=function(){(l=r)&&c.$Play(i,i,r)},c.lg=function(e){u=e},$t=new Z,$t.U(e),$t.U(t)}function Q(){var e=this,t=H();h.Y(t,0),e.$Elmt=t,e.Af=function(e){h.bb(t,e),h.eb(t)},e.zb=function(){h.Cb(t),h.Xb(t)}}function J(e,t){function n(t){D&&D.$Destroy(),Xt-=j,j=0,C(e,t,0),R=r,D=new ye.$Class(e,ye,{$Idle:h.B(e,"idle",at),ng:!Je}),D.$On(u.xc,d)}function a(){D.Pc<ye.Pc&&n()}function d(e,n){j+=n,Xt+=n,t==qt&&!j&&V.uc()}function p(e,n,i){if(!N&&(N=r,A&&i)){var a=i.width,s=i.height,l=a,u=s;if(a&&s&&U){if(3&U&&(!(4&U)||a>He||s>Fe)){var c=o,d=He/Fe*s/a;1&U?c=d>1:2&U&&(c=d<1),l=c?a*Fe/s:He,u=c?Fe:s*He/a}h.C(A,l),h.D(A,u),h.ab(A,(Fe-u)/2),h.Q(A,(He-l)/2)}h.rb(A,"absolute"),Nt.j(_.$EVT_LOAD_END,t)}n.ue(o),e&&e(V)}function v(e,n,i,a){if(a==H&&qt==t&&Je&&m()&&!V.bd()){var o=F(e);Ct.tf(o,t,n,V,i,Fe/He),n.gh(),wt.$Shift(o-wt.mc()-1),wt.M(o),I(o,r)}}function y(n){if(n==H&&qt==t&&m()&&!V.bd()){if(!P){var r=i;Ct&&(Ct.Zb==t?r=Ct.Pe():Ct.zb()),a(),P=new ee(e,t,r,D),P.ch(L)}!P.$IsPlaying()&&P.fd()}}function b(e,n,r){if(e==t)e!=n?Qt[n]&&Qt[n].he():!r&&P&&P.Jg(),L&&L.$Enable(),H=h.Ab(),V.Nb(h.S(i,y,H));else{var a=c.k(t,e),o=c.m(t,e),s=c.k(o-a,a+Le-o),l=Be+me.$LazyLoading-1;(!M||s<=l)&&V.Nb()}}function $(){qt==t&&P&&(P.O(),L&&L.$Quit(),L&&L.$Disable(),P.le())}function S(){qt==t&&P&&P.O()}function T(e){!ht&&Nt.j(_.$EVT_CLICK,t,e)}function C(e,t,n){if(!h.z(e,It)){if(!R){h.z(e,"data-events",h.zc(e)),h.z(e,"data-display",h.Bb(e)),h.Zf(e,h.X(e,"data-to")),h.dg(e,h.X(e,"data-bf")),h.bg(e,h.B(e,"data-p")),h.xg(e,h.X(e,"po")),"IMG"==e.tagName&&(z.push(e),h.z(e,"src")||(M=r,h.Cb(e)));var i=h.gg(e);if(i){var a=new Image;h.X(a,"src2",i),z.push(a)}n&&h.Y(e,(h.Y(e)||0)+1)}var o=h.Eb(e);h.c(o,function(i){n<2&&!A&&"image"==h.X(i,"u")&&(A=i,A.border=0,h.Z(A,Ie),h.Z(e,Ie)),C(i,t,n+1)})}}var D,k,x,A,O,N,M,R,P,L,H,Y,V=this,q=h.V(V,l),j=0,B=e,U=h.B(B,"data-fillmode",me.$FillMode),z=[];f.call(V,-Be,Be+1,{pc:1&ct?Le:s,$Reverse:tt}),V.ue=function(t){Y!=t&&(Y=t,t&&h.bb(e,x),!t&&h.nb(x))},V.Nb=function(e,n){n=n||V,z.length&&!N?(n.ue(r),O||(O=r,Nt.j(_.$EVT_LOAD_START,t),h.c(z,function(e){h.z(e,"src")||(e.src=h.X(e,"src2")||"",h.Bb(e,h.z(e,"data-display")))})),h.cg(z,A,h.S(i,p,e,n))):p(e,n)},V.Ng=function(){if(g())if(1==Le)V.he(),b(t,t);else{var e;if(Ct&&(e=Ct.xf(Le)),e){H=h.Ab();var n=t+it,r=Qt[F(n)];return r.Nb(h.S(i,v,n,r,e,H),V)}(ct||!E(bt.n())||!E(bt.n()+it))&&W(it)}},V.uc=function(){b(t,t,r)},V.he=function(){L&&L.$Quit(),L&&L.$Disable(),V.ze(),P&&P.Og(),P=i,n()},V.gh=function(){h.Cb(e)},V.ze=function(){h.eb(e)},V.Tc=function(e,t){w(k,Be-t)},V.Zb=t;var G=h.$FindChild(e,"thumb",r);G&&(V.Fe=h.gb(G),h.Cb(G)),h.eb(e),x=h.gb(ke),h.Y(x,1e3),V.a(e,"click",T),n(r),V.Uc=A,V.Ad=e,V.ld=k=e,V.a(Nt,203,b),V.a(Nt,28,S),V.a(Nt,24,$),V.$Destroy=function(){h.$Destroy(q,D,P)}}function ee(e,t,i,s){function c(){S.fd()}function d(e){w=e,S.O(),S.fd()}function p(){}var m,g,v,y,b,$,w,S=this,T=h.V(S,l),C=Qt[t];f.call(S,0,0),S.fd=function(){if(!(pt||ft||w||qt!=t||S.bd())){var e=S.n();if(e||m&&!b&&(b=r,S.le(r),Nt.j(_.$EVT_SLIDESHOW_START,t,0,0,0,m,y)),Nt.j(_.$EVT_STATE_CHANGE,t,e,0,g,v,y),!n()){var i;e==y?Je&&h.$Delay(C.Ng,20):(i=e==v?y:e?S.Id():v,(e!=v||!a())&&S.sc(i,c))}}},S.Jg=function(){v==y&&v==S.n()&&S.M(g)},S.Og=function(){Ct&&Ct.Zb==t&&Ct.zb();var e=S.n();e<y&&Nt.j(_.$EVT_STATE_CHANGE,t,-e-1,0,g,v,y)},S.le=function(e){i&&h.Lb(Ue,e&&i.Xc.$Outside?"":"hidden")},S.Tc=function(e,n){b&&n>=m&&(b=o,C.ze(),Ct.zb(),Nt.j(_.$EVT_SLIDESHOW_END,t,m,0,0,m,y)),Nt.j(_.$EVT_PROGRESS_CHANGE,t,n,0,g,v,y)},S.ch=function(e){e&&!$&&($=e,e.$On($JssorPlayer$.If,d))},S.a(s,u.Rc,p),i&&S.Gc(i),m=S.ub(),S.Gc(s),g=m+s.jc,y=S.ub(),v=Je?m+s.rd:y,S.$Destroy=function(){T.$Destroy(),S.O()}}function te(){xt=ft,Et=St.Id(),kt=bt.n(),Dt=C(kt)}function ne(){te(),(pt||n())&&(St.O(),Nt.j(_.hf))}function ie(e){if(m()){var t=bt.n(),n=Dt,i=0;e&&c.F(vt)>=me.$MinDragOffsetToSlide&&(n=t,i=_t),n=c.K(n),n=D(n+i,.5);var r=c.F(n-t);r<1&&me.$SlideEasing!=d.$Linear&&(r=c.q(r,.5)),ht&&e||!xt?t==n?Pe.uc():St.Kc(t,n,r*ot):St.sc(Et)}}function re(e){!h.tb(h.$EvtSrc(e),s,p.Td)&&h.$CancelEvent(e)}function ae(e){mt=o,pt=r,ne(),xt||(ze=0),Nt.j(_.$EVT_DRAG_START,F(kt),kt,e)}function oe(e){se(e,1)}function se(e,n){if(vt=0,yt=0,_t=0,Ht=Ft,n){var i=e.touches[0];gt={x:i.clientX,y:i.clientY}}else gt=h.jd(e);var r=h.$EvtSrc(e),a=h.tb(r,"1",Rt);a&&a!==pe||Ge||n&&1!=e.touches.length||(Xe=h.tb(r,s,p.Td)||!dt||!P(),Nt.a(t,n?"touchmove":"mousemove",le),!(mt=!Xe&&h.tb(r,s,p.Qc))&&!Xe&&ae(e,n))}function le(e){var t,n;if(e=h.Xf(e),"mousemove"!=e.type?1==e.touches.length?(n=e.touches[0],t={x:n.clientX,y:n.clientY}):ue():t=h.jd(e),t){var i=t.x-gt.x,a=t.y-gt.y,o=c.F(i),s=c.F(a);if(ze||o>1.5||s>1.5)if(mt)ae(e,n);else{c.P(Dt)!=Dt&&(ze=ze||ge&Ge),!i&&!a||ze||(ze=3==Ge?s>o?2:1:Ge,Kt&&1==ze&&s>2.4*o&&(Xe=r));var l=i,u=Ve;2==ze&&(l=a,u=qe),(vt-yt)*nt<-1.5&&(_t=0),(vt-yt)*nt>1.5&&(_t=-1),yt=vt,vt=l,At=Dt-vt*nt/u/Ht*me.$DragRatio,vt&&ze&&!Xe&&(h.$CancelEvent(e),St.Wf(r),St.lg(At))}}}function ue(){if(L(),Nt.T(t,"mousemove",le),Nt.T(t,"touchmove",le),ht=vt,pt){ht&&8&Je&&(Je=0),St.O(),pt=o;var e=bt.n();Nt.j(_.$EVT_DRAG_END,F(e),e,F(kt),kt),12&rt&&te(),ie(r)}}function ce(e){var t=h.$EvtSrc(e),n=h.tb(t,"1",It);if(pe===n)if(ht){h.$StopEvent(e);var i=h.tb(t,s,"data-jssor-button","A");i&&h.$CancelEvent(e)}else 4&Je&&(Je=0)}function de(){Zt.ie&&h.Rb(De,Zt.ie,[i,"pan-y","pan-x","auto"][dt]||""),Nt.a(pe,"click",ce,r),Nt.a(pe,"mouseleave",q),Nt.a(pe,"mouseenter",j),Nt.a(pe,"mousedown",se),Nt.a(pe,"touchstart",oe),Nt.a(pe,"dragstart",re),Nt.a(pe,"selectstart",re),Nt.a(e,"mouseup",ue),Nt.a(t,"mouseup",ue),Nt.a(t,"touchend",ue),Nt.a(t,"touchcancel",ue),Nt.a(e,"blur",ue),me.$ArrowKeyNavigation&&Nt.a(t,"keydown",function(e){var t=h.re(e);37!=t&&39!=t||(8&Je&&(Je=0),Y(me.$ArrowKeyNavigation*(t-38)*nt,r))})}function he(e){Mt.Rd(),Vt=[],Qt=[];var t=h.Eb(De),n=h.ye(["DIV","A","LI"]);if(h.c(t,function(e){n[e.tagName.toUpperCase()]&&!h.X(e,"u")&&"none"!=h.Bb(e)&&Vt.push(e),h.Y(e,(h.Y(e)||0)+1)}),Le=Vt.length){var i=1&ge?Ne:Me;B(),ut=me.$Align,ut==s&&(ut=(i-je+Ye)/2),We=i/je,Be=c.k(Le,me.$Cols||Le,c.K(We)),ct=Be<Le?me.$Loop:0,Le*je-Ye<=i&&(We=Le-Ye/je,ut=(i-je+Ye)/2,Bt=(i-je*Le+Ye)/2),ve&&(st=ve.$Class,lt=!ut&&1==Be&&Le>1&&st&&(!h.te()||h.id()>=9)),1&ct||(Wt=ut/je,Wt>Le-1&&(Wt=Le-1,ut=Wt*je),zt=Wt,Ut=zt+Le-We-Ye/je),dt=(Be>1||ut?ge:-1)&me.$DragOrientation,lt&&(Ct=new st(Tt,He,Fe,ve,Kt,$));for(var r=0;r<Vt.length;r++){var a=Vt[r],o=new J(a,r);Qt.push(o)}wt=new X,bt=new G,St=new K(bt,wt),de()}h.c(jt,function(t){t.hd(Le,Qt),e&&t.$On(v.yc,Y)})}function fe(e,t,n){h.ne(e)&&(e=h.Be("",e));var i,r;Le&&(t==s&&(t=Le),r="beforebegin",(i=Vt[t])||(r="afterend",i=Vt[Le-1])),h.$Destroy(Qt),e&&h.rg(i||De,r||"afterbegin",e),h.c(n,function(e){h.nb(e)}),he()}var pe,me,ge,ve,ye,_e,be,$e,we,Se,Te,Ce,De,ke,xe,Ee,Ae,Oe,Ne,Me,Ie,Re,Pe,Le,He,Fe,Ye,Ve,qe,je,Be,We,Ue,ze,Ge,Xe,Ze,Ke,Qe,Je,et,tt,nt,it,rt,at,ot,st,lt,ut,ct,dt,ht,ft,pt,mt,gt,vt,yt,_t,bt,$t,wt,St,Tt,Ct,Dt,kt,xt,Et,At,Ot,Nt=this,Mt=h.V(Nt,l),It="data-jssor-slider",Rt="data-jssor-thumb",Pt=1,Lt=1,Ht=1,Ft=1,Yt={},Vt=[],qt=-1,jt=[],Bt=0,Wt=0,Ut=Number.MAX_VALUE,zt=Number.MIN_VALUE,Gt=1,Xt=0,Zt=h.Sc(),Kt=Zt.Vc,Qt=[];Nt.$SlidesCount=function(){return Vt.length},Nt.$CurrentIndex=function(){return qt},Nt.$CurrentPosition=function(){return bt.n()},Nt.$AutoPlay=function(e){if(e==s)return Je;e!=Je&&(Je=e)&&Qt[qt]&&Qt[qt].uc()},Nt.$IsDragging=function(){return pt},Nt.$IsSliding=function(){return ft},Nt.$IsMouseOver=function(){return!Gt},Nt.$LastDragSucceeded=function(){return ht},Nt.$OriginalWidth=function(){return we},Nt.$OriginalHeight=function(){return Se},Nt.$ScaleHeight=function(e){if(e==s)return Ce||Se;Nt.$ScaleSize(e/Se*we,e)},Nt.$ScaleWidth=function(e){if(e==s)return Te||we;Nt.$ScaleSize(e,e/we*Se)},Nt.$ScaleSize=function(e,t,n){h.C(pe,e),h.D(pe,t),Pt=e/we,Lt=t/Se,h.c(Yt,function(e){e.$ScaleSize(Pt,Lt,n)}),Te||(h.Ib(Ue,De),h.ab(Ue,0),h.Q(Ue,0)),Te=e,Ce=t},Nt.Ef=k,Nt.Ff=x,Nt.$PlayTo=U,Nt.$GoTo=R,Nt.$Next=function(){W(1)},Nt.$Prev=function(){W(-1)},Nt.$Pause=function(){Je=0},Nt.$Play=function(){Nt.$AutoPlay(Je||1)},Nt.$SetSlideshowTransitions=function(e){me.$SlideshowOptions.$Transitions=e},Nt.$SetCaptionTransitions=function(e){ye.$Transitions=e,ye.Pc=h.Ab()},Nt.de=function(e){if(e=F(e),1&ct){var t=ut/je,n=F(bt.n()),i=F(e-n+t),r=F(c.F(e-n));i>=Be?r>Le/2&&(e>n?e-=Le:e+=Le):e>n&&i<t?e-=Le:e<n&&i>t&&(e+=Le)}return e},Nt.$AppendSlides=function(e,t){t==s&&(t=qt+1);var n=Vt[qt];fe(e,t);var i=0;h.c(Vt,function(e,t){e==n&&(i=t)}),R(i)},Nt.$ReloadSlides=function(e){fe(e,i,Vt),R(0)},Nt.$RemoveSlides=function(e){var t=qt,n=[];h.c(e,function(e){e<Le&&e>=0&&(n.push(Vt[e]),e<qt&&t--)}),fe(i,i,n),t=c.k(t,Le-1),R(t)},Nt.A=function(e,n){Nt.$Elmt=pe=h.$GetElement(e),we=h.C(pe),Se=h.D(pe),me=h.G({$FillMode:0,$LazyLoading:1,$ArrowKeyNavigation:1,$StartIndex:0,$AutoPlay:0,$Loop:1,$HWA:r,$NaviQuitDrag:r,$AutoPlaySteps:1,$AutoPlayInterval:3e3,$PauseOnHover:1,$SlideDuration:500,$SlideEasing:d.$OutQuad,$MinDragOffsetToSlide:20,$DragRatio:1,$SlideSpacing:0,$UISearchMode:1,$PlayOrientation:1,$DragOrientation:1},n),me.$HWA=me.$HWA&&h.Xg(),me.$Idle!=s&&(me.$AutoPlayInterval=me.$Idle),me.$DisplayPieces!=s&&(me.$Cols=me.$DisplayPieces),me.$ParkingPosition!=s&&(me.$Align=me.$ParkingPosition),Je=63&me.$AutoPlay,me.$UISearchMode,it=me.$AutoPlaySteps,rt=me.$PauseOnHover,rt&=Kt?10:5,at=me.$AutoPlayInterval,ot=me.$SlideDuration,ge=3&me.$PlayOrientation,et="rtl"==h.Me(h.z(pe,"dir")),tt=et&&(1==ge||1&me.$DragOrientation),nt=tt?-1:1,ve=me.$SlideshowOptions,ye=h.G({$Class:u},me.$CaptionSliderOptions),_e=me.$BulletNavigatorOptions,be=me.$ArrowNavigatorOptions,$e=me.$ThumbnailNavigatorOptions;var i=h.Eb(pe);h.c(i,function(e,t){var n=h.X(e,"u");"loading"==n?ke=e:("slides"==n&&(De=e,h.Rb(De,"margin",0),h.Rb(De,"padding",0)),"navigator"==n&&(xe=e),"arrowleft"==n&&(Ee=e),"arrowright"==n&&(Ae=e),"thumbnavigator"==n&&(Oe=e),"STYLE"!=e.tagName&&"SCRIPT"!=e.tagName&&(Yt[n||t]=new z(e,"slides"==n,h.ye(["slides","thumbnavigator"])[n])))}),ke&&h.nb(ke),ke=ke||h.Tb(t),Ne=h.C(De),Me=h.D(De),He=me.$SlideWidth||Ne,Fe=me.$SlideHeight||Me,Ie={H:He,I:Fe,$Top:0,$Left:0,Sd:"block",Ob:"absolute"},Ye=me.$SlideSpacing,Ve=He+Ye,qe=Fe+Ye,je=1&ge?Ve:qe,Tt=new Q,!me.$HWA||h.bh()&&!Kt||($=function(e,t,n){h.fh(e,{$TranslateX:t,$TranslateY:n})}),h.z(pe,It,"1"),h.Y(De,h.Y(De)||0),h.rb(De,"absolute"),Ue=h.gb(De,r),h.Rb(Ue,"pointerEvents","none"),h.Ib(Ue,De),h.bb(Ue,Tt.$Elmt),h.Lb(De,"hidden"),xe&&_e&&(_e.cc=et,Ze=new _e.$Class(xe,_e,we,Se),jt.push(Ze)),be&&Ee&&Ae&&(be.cc=et,be.$Loop=me.$Loop,Ke=new be.$Class(Ee,Ae,be,Nt),jt.push(Ke)),Oe&&$e&&($e.$StartIndex=me.$StartIndex,$e.$ArrowKeyNavigation=$e.$ArrowKeyNavigation||0,$e.cc=et,Qe=new $e.$Class(Oe,$e,ke),!$e.$NoDrag&&h.z(Oe,Rt,"1"),jt.push(Qe)),he(r),Nt.$ScaleSize(we,Se),V(),R(F(me.$StartIndex)),h.Rb(pe,"visibility","visible")},Nt.$Destroy=function(){Je=0,h.$Destroy(Qt,jt,Mt),h.Xb(pe)},h.A(Nt)};_.$EVT_CLICK=21,_.$EVT_DRAG_START=22,_.$EVT_DRAG_END=23,_.$EVT_SWIPE_START=24,_.$EVT_SWIPE_END=25,_.$EVT_LOAD_START=26,_.$EVT_LOAD_END=27,_.hf=28,_.$EVT_MOUSE_ENTER=31,_.$EVT_MOUSE_LEAVE=32,_.$EVT_POSITION_CHANGE=202,_.$EVT_PARK=203,_.$EVT_SLIDESHOW_START=206,_.$EVT_SLIDESHOW_END=207,_.$EVT_PROGRESS_CHANGE=208,_.$EVT_STATE_CHANGE=209}(window,document,Math,null,!0,!1);var br="https://www.meinweekend.ch/",offerType="alle",offerRegion="alle",offerDuration="alle",keyw="alle",vaucherCustom=100,activateEnter=!1,jssor1_slider=null,validator=null,scrollHistory=[];$(document).ready(function(){var e={};$(document).on("click",".g-recaptcha div",function(e){if(grecaptcha){grecaptcha.getResponse();$(".g-recaptcha").children().first().attr("style","width: 304px; height: 78px;border:1px solid red")}}),$(document).on("click","#confirmContact",function(t){grecaptcha.getResponse();cRules={user_name:"required",user_surname:"required",user_address:"required",user_postalCode:"required",user_postalPlace:"required",user_country:"required",user_telephone:"required",user_email:"required",user_comment:"required",andreOp:"required"},cMessages={user_name:{required:"Bitte um Ihre Angaben: Vorname"},user_surname:{required:"Bitte um Ihre Angaben: Nachname"},user_address:{required:"Bitte um Ihre Angaben: Adresse"},user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_country:{required:"Bitte um Ihre Angaben: Land"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"},user_comment:{required:"Bitte um Ihre Angaben: Mein Anliegen"},andreOp:{required:"Bitte um Ihre Angaben: Andrede"}},$("#contactForm").validate({errorClass:"bad-message",rules:cRules,messages:cMessages,submitHandler:function(t){var n=$("#user_surname").val(),i=$("#user_name").val(),r=$("#user_company").val(),a=$("#user_address").val(),o=$("#user_postalPlace").val(),s=$("#user_postalCode").val(),l=$("#user_telephone").val(),u=$("#user_email").val(),c=$("#user_comment").val(),d=($("#userRandomCode").val(),$("#user_offer").val()),h=$("input[name=_token]").val(),f=$("input[name='anredeOp']:checked").val();e={_token:h,andrede:f,name:i,vorname:n,strasse:a,ort:s,plz:o,telefon:l,email:u,company:r,message:c,offer:d};if(!validateCap())return!1;submitContact(e)},highlight:function(e,t){$(e).removeClass(t)}}),$("#contactForm").submit()}),$(document).on("click","#sendGroupOffer",function(t){cRules={user_postalCode:"required",user_postalPlace:"required",user_telephone:"required",user_email:"required"},cMessages={user_postalCode:{required:"Bitte um Ihre Angaben: PLZ"},user_postalPlace:{required:"Bitte um Ihre Angaben: Ort"},user_telephone:{required:"Bitte um Ihre Angaben: Telefon"},user_email:{required:"Bitte um Ihre Angaben: E-Mail"}},$("#groupOfferForm").validate({errorClass:"bad-message",rules:cRules,messages:cMessages,submitHandler:function(t){var n=$("#excursion_package").val(),i=$("#group_date").val(),r=$("#user_surname").val(),a=$("#user_name").val(),o=$("#user_company").val(),s=$("#user_address").val(),l=$("#user_postalPlace").val(),u=$("#user_postalCode").val(),c=$("#user_telephone").val(),d=$("#user_email").val(),h=$("#alternativ_Termine").val(),f=$("#desired_start_time").val(),p=$("#no_participants").val(),m=$("#remarks").val(),g=$("input[name=_token]").val();e={_token:g,offer:n,date:i,lastName:r,firstName:a,company:o,street:s,plz:l,ort:u,telefon:c,email:d,alternative:h,starttime:f,remarks:m,total_people:p},submitGroupOffer(e)},highlight:function(e,t){$(e).removeClass(t)}}),$("#groupOfferForm").submit()});var t="";$(document).on("click","#voucherStepb1,#voucherStepb2,#voucherStepb2Pay,#voucherStepb3",function(n){var i=$(n.target).attr("id");if("voucherStepb1"==i){var r=$("#vouchName").val(),a=$("#exampleTextarea").val().replace(/\n/g,"<br />"),o=$("#otherValue").val(),s=$("input[type=radio][name=optionsRadios]:checked");$("#voucherFor").text(r),$("#voucherFor1").text(r),$("#voucherText").html(a),$("#voucherText1").html(a),"other"==vaucherCustom?($("#voucherPrice").text(o),$("#voucherPrice1").text(o)):($("#voucherPrice").text(s.val()),$("#voucherPrice1").text(s.val())),validateVoucherOffer(2,1,"#VouchForm1",{})}else if("voucherStepb2"==i){var l=$("#user_name").val(),u=$("#user_surname").val(),c=$("#user_company").val(),d=$("#user_address").val(),h=$("#user_postalCode").val(),f=$("#user_postalPlace").val(),p=$("#user_country").val(),m=$("#user_telephone").val(),g=$("#user_email").val(),v=$("#user_message").val(),y=$("#user_payment").val(),_=$("#user_shipping").val(),b=$("#user_validFrom").val(),w=$("#voucherType").val();uStatus=$("input[name='anredeOp']:checked").val();var S=0,T=0,r=$("#vouchName").val(),a=$("#exampleTextarea").val(),o=$("#otherValue").val(),s=$("input[type=radio][name=optionsRadios]:checked");t=uStatus,T="other"==vaucherCustom?o:s.val(),"Rechnung"!=y?(S=1,$("#creditCardRules").show()):$("#creditCardRules").hide();var C=$("input[name=_token]").val();e={_token:C,vaucher_type:2,payment_id:S,offer:0,valid_from:b,vaucher_for:r,vaucher_text:a,items:"",payment_type:y,send_type:_,message:v,vaucher_template:w,total_price:T,user:{username:g,name:l+" "+u,first_name:l,last_name:u,address:d,telephone:m,fax:"",email:g,title:uStatus,zip:h,city:f,country:p,www:"",company:c,gender:uStatus}},$("#userFullnameHolder").text(l+" "+u),$("#userCompanyHolder").text(c),$("#userAddressHolder").text(d),$("#userPLZOrtHolder").text(h+", "+f),$("#userCountryHolder").text(p),$("#userTelephoneHolder").text(m),$("#userEmailHolder").text(g);var v=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(v),$("#userPaymentHolder").text(y),$("#userShippingHolder").text(_),$("#userStatusHolder").text(uStatus),$("input[name=AMOUNT]").val(T),$("input[name=CN]").val(l+" "+u),$("input[name=CURRENCY]").val("CHF"),$("input[name=EMAIL]").val(g),$("input[name=LANGUAGE]").val("de_DE");var D=new Date;$("input[name=ORDERID]").val(u+"/"+D),$("input[name=OWNERADDRESS]").val(p),$("input[name=OWNERTELNO]").val(m),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERZIP]").val(h),validateVoucherOffer(2,2,"#VouchForm2",e)}else if("voucherStepb2Pay"==i){var l=$("#user_name").val(),u=$("#user_surname").val(),c=$("#user_company").val(),d=$("#user_address").val(),h=$("#user_postalCode").val(),f=$("#user_postalPlace").val(),p=$("#user_country").val(),m=$("#user_telephone").val(),g=$("#user_email").val(),v=$("#user_message").val(),y=$("#user_payment").val(),_=$("#user_shipping").val(),b=$("#user_validFrom").val(),w=$("#voucherType").val();uStatus=$("input[name='anredeOp']:checked").val();var S=0,T=0,r=$("#vouchName").val(),a=$("#exampleTextarea").val(),o=$("#otherValue").val(),s=$("input[type=radio][name=optionsRadios]:checked");t=uStatus,T="other"==vaucherCustom?o:s.val(),"Rechnung"!=y?(S=1,$("#creditCardRules").show()):$("#creditCardRules").hide();var C=$("input[name=_token]").val();e={_token:C,vaucher_type:2,payment_id:S,offer:0,valid_from:b,vaucher_for:r,vaucher_text:a,items:"",payment_type:y,send_type:_,message:v,vaucher_template:w,total_price:T,user:{username:g,name:l+" "+u,first_name:l,last_name:u,address:d,telephone:m,fax:"",email:g,title:uStatus,zip:h,city:f,country:p,www:"",company:c,gender:uStatus}},$("#userFullnameHolder").text(l+" "+u),$("#userCompanyHolder").text(c),$("#userAddressHolder").text(d),$("#userPLZOrtHolder").text(h+", "+f),$("#userCountryHolder").text(p),$("#userTelephoneHolder").text(m),$("#userEmailHolder").text(g);var v=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(v),$("#userPaymentHolder").text(y),$("#userShippingHolder").text(_),$("#userStatusHolder").text(uStatus),$("input[name=AMOUNT]").val(T),$("input[name=CN]").val(l+" "+u),$("input[name=CURRENCY]").val("CHF"),$("input[name=EMAIL]").val(g),$("input[name=LANGUAGE]").val("de_DE");var D=new Date;$("input[name=ORDERID]").val(u+"/"+D),$("input[name=OWNERADDRESS]").val(p),$("input[name=OWNERTELNO]").val(m),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERZIP]").val(h),validateVoucherOffer(2,3,"#VouchForm2",e)}else if("voucherStepb3"==i){var l=$("#user_name").val(),u=$("#user_surname").val(),c=$("#user_company").val(),d=$("#user_address").val(),h=$("#user_postalCode").val(),f=$("#user_postalPlace").val(),p=$("#user_country").val(),m=$("#user_telephone").val(),g=$("#user_email").val(),v=$("#user_message").val(),y=$("#user_payment").val(),_=$("#user_shipping").val(),b=$("#user_validFrom").val(),w=$("#voucherType").val();uStatus=$("input[name='anredeOp']:checked").val();var S=0,T=0,r=$("#vouchName").val(),a=$("#exampleTextarea").val(),o=$("#otherValue").val(),s=$("input[type=radio][name=optionsRadios]:checked");t=uStatus,T="other"==vaucherCustom?o:s.val(),"Rechnung"!=y?(S=1,$("#creditCardRules").show()):$("#creditCardRules").hide();var C=$("input[name=_token]").val();e={_token:C,vaucher_type:2,payment_id:S,offer:0,valid_from:b,vaucher_for:r,vaucher_text:a,items:"",payment_type:y,send_type:_,message:v,vaucher_template:w,total_price:T,user:{username:g,name:l+" "+u,first_name:l,last_name:u,address:d,telephone:m,fax:"",email:g,title:uStatus,zip:h,city:f,country:p,www:"",company:c,gender:uStatus}},$("#userFullnameHolder").text(l+" "+u),$("#userCompanyHolder").text(c),$("#userAddressHolder").text(d),$("#userPLZOrtHolder").text(h+", "+f),$("#userCountryHolder").text(p),$("#userTelephoneHolder").text(m),$("#userEmailHolder").text(g);var v=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(v),$("#userPaymentHolder").text(y),$("#userShippingHolder").text(_),$("#userStatusHolder").text(uStatus),$("input[name=AMOUNT]").val(T),$("input[name=CN]").val(l+" "+u),$("input[name=CURRENCY]").val("CHF"),$("input[name=EMAIL]").val(g),$("input[name=LANGUAGE]").val("de_DE");var D=new Date;$("input[name=ORDERID]").val(u+"/"+D),$("input[name=OWNERADDRESS]").val(p),$("input[name=OWNERTELNO]").val(m),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERTOWN]").val(f),$("input[name=OWNERZIP]").val(h);var _=$("#user_shipping").val();"Postversand"!=_?($("#clientConfirmationEmail").text($("#userEmailHolder").text()),$("#printHome").attr("style","display:block;"),$("#postVersand").attr("style","display:none;")):($("#printHome").attr("style","display:none;"),$("#postVersand").attr("style","display:block;")),"Herr"==t?$("#senderName").text("R "+$("#userStatusHolder").text()+" "+$("#user_surname").val()):$("#senderName").text(" "+$("#userStatusHolder").text()+" "+$("#user_surname").val()),submitVoucher(e)}}),$(document).on("click","#voucherStepRet1,#voucherStepRet2,#voucherStepRet3",function(e){var t=$(e.target).attr("id");$(".voucherSteps").removeClass("stepShowVoucher"),"voucherStepRet1"==t||("voucherStepRet2"==t?window.history.back():"voucherStepRet3"==t&&window.history.back())}),$(document).on("click","#bookingStepb1,#bookingStepb2,#bookingStepb3",function(t){var n=$(t.target).attr("id");if("bookingStepb1"==n)$(".bookingSteps").removeClass("stepShowBooking"),$(".bookingSteps").removeClass("stepShowBookingSpecial"),$("#bookingStep2").addClass("stepShowBooking");else if("bookingStepb2"==n)validateVoucherOffer(1,1,"#bookingValid1",{});else if("bookingStepb3"==n){var i=$("#user_name").val(),r=$("#user_surname").val(),a=$("#user_company").val(),o=$("#user_address").val(),s=$("#user_postalCode").val(),l=$("#user_postalPlace").val(),u=$("#user_country").val(),c=$("#user_telephone").val(),d=$("#user_email").val(),h=$("#user_message").val(),f=$("#user_payment").val(),p=$("#user_shipping").val(),m=($("#user_validFrom").val(),$("#reservationgarantee_check")),g=$("#reservationgarantee_cardtype").val(),v=$("#reservationgarantee_cardno").val(),y=$("#reservationgarantee_exp_month").val(),_=$("#reservationgarantee_exp_year").val(),b=$("#reservationgarantee_name").val();m=m.is(":checked")?1:0;var w=$("#vouCode").val(),S=$("#marketingCode").val(),T=$("#totalBetrag").val(),C=$("input[name=andreOp]:checked").val(),D=($("#vouchName").val(),$("#exampleTextarea").val(),$("#otherValue").val()),k=$("input[type=radio][name=optionsRadios]:checked");"other"==vaucherCustom?D:k.val(),"Rechnung"!=f?(1,$("#creditCardRules").show()):$("#creditCardRules").hide();var x=$("input[name=_token]").val();e={_token:x,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,booking_date:bookingDate,reservationgarantee_nocard:m,reservationgarantee_cardno:v,reservationgarantee_cardtype:g,reservationgarantee_exp_month:y,reservationgarantee_exp_year:_,reservationgarantee_name:b,vaucher_code:w,marketing_code:S,message:h,vaucher_amount:T,saveUserContact:$("#step2row").html(),user:{username:d,name:i+" "+r,first_name:i,last_name:r,address:o,telephone:c,fax:"",email:d,title:C,zip:s,city:l,country:u,www:"",company:a,gender:C}},console.log(d),$("#userName").text(i),$("#userSurname").text(r),$("#uName").text(r),$("#userCompanyHolder").text(a),$("#userAddressHolder").text(o),$("#userPLZOrtHolder").text(s+", "+l),$("#userCountryHolder").text(u),$("#userTelephoneHolder").text(c),$("#userEmailHolder").text(d);var h=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(h),$("#userPaymentHolder").text(f),$("#userShippingHolder").text(p),$("#userStatusHolder").text(C),"Herr"==C?$("#uStatus").text("R "+C):$("#uStatus").text(" "+C),$(".stepsIndic").removeClass("step1"),$("#step4I").addClass("step1"),validateVoucherOffer(1,2,"#bookingContactForm",e)}}),$(document).on("click","#bookingStepRet1,#bookingStepRet2,#bookingStepRet3",function(e){var t=$(e.target).attr("id");"bookingStepRet1"==t||("bookingStepRet2"==t?window.history.back():"bookingStepRet3"==t&&window.history.back())}),$(document).on("click","#voucherOffersRet1,#voucherOffersRet2,#voucherOffersRet3",function(e){var t=$(e.target).attr("id");"voucherOffersRet1"==t||("voucherOffersRet2"==t?window.history.back():"voucherOffersRet3"==t&&window.history.back())}),$(document).on("click","#voucherOffers2,#voucherOffers3,#voucherOffers3Pay,#voucherOffers4",function(n){var i=$(n.target).attr("id");if("voucherOffers1"==i)$(".bookingSteps").removeClass("stepShowBookingSpecial"),$("#bookingVouchers2").addClass("stepShowBooking");else if("voucherOffers2"==i){var r=$("#vouchName").val(),a=$("#offerVaucherTextarea").val();$("#voucherFor").text(r),$("#voucherFor1").text(r),$("#voucherText").text(a),$("#voucherText1").text(a),validateVoucherOffer(3,1,"#offerVouchForm1",{})}else if("voucherOffers3"==i){var o=$("#user_name").val(),s=$("#user_surname").val(),l=$("#user_company").val(),u=$("#user_address").val(),c=$("#user_postalCode").val(),d=$("#user_postalPlace").val(),h=$("#user_country").val(),f=$("#user_telephone").val(),p=$("#user_email").val(),m=$("#user_message").val(),g=$("#user_payment").val(),v=$("#user_shipping").val(),y=$("#user_validFrom").val(),_=$("#reservationgarantee_cardtype").val(),b=$("#reservationgarantee_cardno").val(),w=$("#reservationgarantee_exp_month").val(),S=$("#reservationgarantee_exp_year").val(),T=$("#reservationgarantee_name").val(),C=$("#vouCode").val(),D=$("#marketingCode").val(),k=$("#totalBetrag").val(),x=$("input[name=andreOp]:checked").val(),r=$("#vouchName").val(),a=$("#offerVaucherTextarea").val(),E=$("#otherValue").val(),A=$("input[type=radio][name=optionsRadios]:checked");"other"==vaucherCustom?E:A.val(),"Rechnung"!=g?(1,$("#creditCardRules").show()):$("#creditCardRules").hide(),t=x;var O=$("input[name=_token]").val();e={_token:O,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,booking_date:bookingDate,payment_type:g,send_type:v,
reservationgarantee_cardno:b,reservationgarantee_cardtype:_,reservationgarantee_exp_month:w,reservationgarantee_exp_year:S,reservationgarantee_name:T,vaucher_code:C,marketing_code:D,vaucher_amount:k,valid_from:y,vaucher_for:r,message:m,vaucher_text:a,user:{username:p,name:o+" "+s,first_name:o,last_name:s,address:u,telephone:f,fax:"",email:p,title:x,zip:c,city:d,country:h,www:"",company:l,gender:x}},$("#userName").text(o),$("#userSurname").text(s),$("#uName").text(s),$("#userFullnameHolder").text(o+" "+s),$("#userCompanyHolder").text(l),$("#userAddressHolder").text(u),$("#userPLZOrtHolder").text(c+", "+d),$("#userCountryHolder").text(h),$("#userTelephoneHolder").text(f),$("#userEmailHolder").text(p);var m=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(m),$("#userPaymentHolder").text(g),$("#userShippingHolder").text(v),$("#userStatusHolder").text(x),"Herr"==x?$("#uStatus").text("R "+x):$("#uStatus").text(" "+x),validateVoucherOffer(3,2,"#offerVouchForm2",{})}else if("voucherOffers3Pay"==i){var o=$("#user_name").val(),s=$("#user_surname").val(),l=$("#user_company").val(),u=$("#user_address").val(),c=$("#user_postalCode").val(),d=$("#user_postalPlace").val(),h=$("#user_country").val(),f=$("#user_telephone").val(),p=$("#user_email").val(),m=$("#user_message").val(),g=$("#user_payment").val(),v=$("#user_shipping").val(),y=$("#user_validFrom").val(),_=$("#reservationgarantee_cardtype").val(),b=$("#reservationgarantee_cardno").val(),w=$("#reservationgarantee_exp_month").val(),S=$("#reservationgarantee_exp_year").val(),T=$("#reservationgarantee_name").val(),C=$("#vouCode").val(),D=$("#marketingCode").val(),k=$("#totalBetrag").val(),x=$("input[name=andreOp]:checked").val(),r=$("#vouchName").val(),a=$("#offerVaucherTextarea").val(),E=$("#otherValue").val(),A=$("input[type=radio][name=optionsRadios]:checked");"other"==vaucherCustom?E:A.val(),"Rechnung"!=g?(1,$("#creditCardRules").show()):$("#creditCardRules").hide(),t=x;var O=$("input[name=_token]").val();e={_token:O,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,booking_date:bookingDate,payment_type:g,send_type:v,reservationgarantee_cardno:b,reservationgarantee_cardtype:_,reservationgarantee_exp_month:w,reservationgarantee_exp_year:S,reservationgarantee_name:T,vaucher_code:C,marketing_code:D,vaucher_amount:k,valid_from:y,vaucher_for:r,message:m,vaucher_text:a,user:{username:p,name:o+" "+s,first_name:o,last_name:s,address:u,telephone:f,fax:"",email:p,title:x,zip:c,city:d,country:h,www:"",company:l,gender:x}},$("#userName").text(o),$("#userSurname").text(s),$("#uName").text(s),$("#userFullnameHolder").text(o+" "+s),$("#userCompanyHolder").text(l),$("#userAddressHolder").text(u),$("#userPLZOrtHolder").text(c+", "+d),$("#userCountryHolder").text(h),$("#userTelephoneHolder").text(f),$("#userEmailHolder").text(p);var m=$("#user_message").val().replace(/\n/g,"<br />");$("#userMessageHolder").html(m),$("#userPaymentHolder").text(g),$("#userShippingHolder").text(v),$("#userStatusHolder").text(x),"Herr"==x?$("#uStatus").text("R "+x):$("#uStatus").text(" "+x),validateVoucherOffer(3,3,"#offerVouchForm2",e)}else if("voucherOffers4"==i){var o=$("#user_name").val(),s=$("#user_surname").val(),l=$("#user_company").val(),u=$("#user_address").val(),c=$("#user_postalCode").val(),d=$("#user_postalPlace").val(),h=$("#user_country").val(),f=$("#user_telephone").val(),p=$("#user_email").val(),m=$("#user_message").val(),g=$("#user_payment").val(),v=$("#user_shipping").val(),y=$("#user_validFrom").val(),_=$("#reservationgarantee_cardtype").val(),b=$("#reservationgarantee_cardno").val(),w=$("#reservationgarantee_exp_month").val(),S=$("#reservationgarantee_exp_year").val(),T=$("#reservationgarantee_name").val(),C=$("#vouCode").val(),D=$("#marketingCode").val(),k=$("#totalBetrag").val(),x=$("input[name=andreOp]:checked").val(),r=$("#vouchName").val(),a=$("#offerVaucherTextarea").val(),E=$("#otherValue").val(),A=$("input[type=radio][name=optionsRadios]:checked"),N=$("#voucherType").val();"other"==vaucherCustom?E:A.val(),"Rechnung"!=g?(1,$("#creditCardRules").show()):$("#creditCardRules").hide(),t=x;var O=$("input[name=_token]").val();e={_token:O,offer:activeOffer,prices:pricesSelected,additionals:aditionalSelected,booking_date:bookingDate,payment_type:g,send_type:v,reservationgarantee_cardno:b,reservationgarantee_cardtype:_,reservationgarantee_exp_month:w,reservationgarantee_exp_year:S,reservationgarantee_name:T,vaucher_code:C,marketing_code:D,vaucher_amount:k,valid_from:y,vaucher_for:r,message:m,vaucher_template:N,vaucher_text:a,user:{username:p,name:o+" "+s,first_name:o,last_name:s,address:u,telephone:f,fax:"",email:p,title:x,zip:c,city:d,country:h,www:"",company:l,gender:x}};var v=$("#user_shipping").val();"Postversand"!=v?($("#clientConfirmationEmail").text($("#userEmailHolder").text()),$("#printHome").attr("style","display:block;"),$("#postVersand").attr("style","display:none;")):($("#printHome").attr("style","display:none;"),$("#postVersand").attr("style","display:block;")),"Herr"==t?$("#senderName").text("R "+$("#userStatusHolder").text()+" "+$("#user_surname").val()):$("#senderName").text(" "+$("#userStatusHolder").text()+" "+$("#user_surname").val()),$("#clientConfirmationEmail").text($("#userEmailHolder").text());var M=$("#vaucherConfirmationInfo").html();e.saveConfOffVau=M;var I=window.location.href,R=I.substr(I.indexOf("?")+1);I==window.location.href&&(R="");var P="";P=-1!==R.indexOf("step=3")?R.replace("step=3","step=4"):-1!==R.indexOf("step=4")?R:R+"?step=4",console.log("bookingVouchers4 ",P),window.history.pushState(null,null,P),submitOfferBooking(e)}}),$(window).resize(function(){$(window).width()>768&&$("#gMap1,#inLinks1,#toggle1,#toggle2,#toggle3",document).removeAttr("id")}),$(window).on("popstate",function(e){if(history.scrollRestoration="manual",end_l_of_c_s=!1,null!==e.state){var t=location.href,n=window.location.search;n=n.replace("?navigate=1",""),""!=n?"?"==n.charAt(0)&&(n=n.replace("?","?navigate=1&")):n="?navigate=1";if(t=window.location.pathname.replace("/","")+n,o_nav="",$("#pageDynamic").length){t.indexOf("?");navigateMaster(t,{urlCorrect:1,scrollBack:1,backPressed:1})}else window.location.href=window.location.host+"/"+t}}),$(document).on("click","a",function(e){var t=$(this),n=t.attr("class");if(n||(n=""),-1!==n.indexOf("linkPushNoAjax"));else{e.preventDefault();var i={},r=t.attr("href"),a=r.replace("https://www.meinweekend.ch/",""),o=a.replace("//","/"),s=o.replace(/^\/|\/$/g,""),l=s.replace(".html",""),u=t.attr("data-urlType");$(".navbar-nav").find(".active").removeClass("active"),$(this).parent().addClass("active"),$("#pageDynamic").length&&(u&&(i.gtype=u),navigateMaster(l,i))}}),$(document).on("click tap","#masterSearch",function(e){searchFilter()}),$(document).on("change","#offerType",function(e){var t=$(this),n=t.val();offerType=n}),$(document).on("change","#offerRegion",function(e){var t=$(this),n=t.val();offerRegion=n}),$(document).on("change","#offerDuration",function(e){var t=$(this),n=t.val();offerDuration=n}),$(document).on("keyup","#searchUser",function(e){var t=$(this),n=t.val();keyw=n})}),$(document).ready(function(){$(document).on("keyup",function(e){$("#homeindicator").length>0&&13==e.which&&searchFilter()}),$(".wrapEr").click(function(e){$(".wrapEr.active").removeClass("active"),$(this).parent().addClass("active"),e.preventDefault()})});var br="https://www.meinweekend.ch/",disDays=[],enableDays=[],totalBookingPrice=0,lastTotalBookingPrice=0,activeOffer=0,bookingDate=0,stTime=0,endTime=0,pricesSelected=[],aditionalSelected=[];$(document).ready(function(){$(document).on("change","#step2row input, #mainVaucherFormS1 input, #voucherStep2 input, #bookingVouchers1 input, #bookingVouchers2 input",function(e){var t=$(this);t.attr("value",t.val())}),$(document).on("change","#reservationgarantee_check",function(e){var t=$(this);"0"==t.attr("val")?t.attr("val","1"):t.attr("val","0")}),$(document).on("change","#step2row select, #voucherStep2 select, #bookingVouchers2 select",function(e){var t=$(this);if("user_country"==this.id)$("#"+t.context.id+" option").filter(function(e){e++;var n=1;n="Schweiz"==t.context.value?1:"Deutschland"==t.context.value?2:3,e==n?$("#"+t.context.id+" option[cost="+n+"]").attr("selected","selected"):$("#"+t.context.id+" option[cost="+e+"]").removeAttr("selected")});else if("user_payment"==this.id){var n=this;$("#"+this.id+" option").filter(function(e){if(this.value==n.value){if(console.log("this.value",this.value),"Kreditkarte/Postcard"==this.value){var t=$("#voucherStepb2Pay");console.log("chTypeRes.length",t.length),t.length>0&&$("#voucherStepb2").hide(),$("#voucherOffers3").hide(),$("#voucherStepb2Pay").show(),$("#voucherOffers3Pay").show()}else $("#voucherStepb2Pay").hide(),$("#voucherOffers3Pay").hide(),$("#voucherStepb2").show(),$("#voucherOffers3").show();$("#"+n.id+' option[value="'+this.value+'"]').attr("selected","selected")}else $("#"+n.id+' option[value="'+this.value+'"]').removeAttr("selected")})}else if("user_shipping"==this.id){var i=this;$("#"+this.id+" option").filter(function(e){this.value==i.value?$("#"+i.id+' option[value="'+this.value+'"]').attr("selected","selected"):$("#"+i.id+' option[value="'+this.value+'"]').removeAttr("selected")})}});document.getElementById("datetimepicker12")}),$(document).ready(function(){});
|
#ifndef __c21_Demo_EP_IdleRandMerg_h__
#define __c21_Demo_EP_IdleRandMerg_h__
/* Include files */
#include "sf_runtime/sfc_sf.h"
#include "sf_runtime/sfc_mex.h"
#include "rtwtypes.h"
#include "multiword_types.h"
/* Type Definitions */
#ifndef typedef_SFc21_Demo_EP_IdleRandMergInstanceStruct
#define typedef_SFc21_Demo_EP_IdleRandMergInstanceStruct
typedef struct {
SimStruct *S;
ChartInfoStruct chartInfo;
uint32_T chartNumber;
uint32_T instanceNumber;
int32_T c21_sfEvent;
boolean_T c21_isStable;
boolean_T c21_doneDoubleBufferReInit;
uint8_T c21_is_active_c21_Demo_EP_IdleRandMerg;
} SFc21_Demo_EP_IdleRandMergInstanceStruct;
#endif /*typedef_SFc21_Demo_EP_IdleRandMergInstanceStruct*/
/* Named Constants */
/* Variable Declarations */
/* Variable Definitions */
/* Function Declarations */
extern const mxArray
*sf_c21_Demo_EP_IdleRandMerg_get_eml_resolved_functions_info(void);
/* Function Definitions */
extern void sf_c21_Demo_EP_IdleRandMerg_get_check_sum(mxArray *plhs[]);
extern void c21_Demo_EP_IdleRandMerg_method_dispatcher(SimStruct *S, int_T
method, void *data);
#endif
|
import * as firebase from "firebase/app";
import "firebase/auth";
const app = firebase.initializeApp({
apiKey: "AIzaSyBLMSlM0gcFg3sO2cgRGZYFoPK00DvWSNY",
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID
});
export default app;
|
from flask import Flask, request
import os
import json
import socket
app = Flask(__name__)
@app.route('/dostep/<time>&<inputnames>&<inputvalues>&<outputnames>')
def step(time, inputnames, inputvalues, outputnames):
data = _parse_url(time, inputnames, inputvalues, outputnames)
outputs = [data['input1'] * data['time']
for i in range(0, len(data['outputnames']))]
return ','.join([str(output) for output in outputs])
def _parse_url(time, inputnames, inputvalues, outputnames):
"""
Ensure that inputs has the right type
"""
data = {str(key):float(value)
for key, value in
zip(inputnames.split(','), inputvalues.split(','))}
data['time'] = float(time)
data['outputnames'] = outputnames.split(',')
return data
@app.route('/shutdown')
def shutdown():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
return 'Server shutting down...'
@app.errorhandler(Exception)
def handle_error(e):
"""
Handle error message back to the FMU
"""
return 'ERROR: ' + str(e)
if __name__ == '__main__':
# Open the right port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = 'localhost'
sock.bind(('localhost', 0)) # Get a free port at random with '0'
port = sock.getsockname()[1] # Retrieve the port and address
sock.close() # Close the socket and use the port with Flask
# Write a file with port and address
path_to_server = os.path.dirname(__file__)
with open(os.path.join(path_to_server, "server_config.txt"), "w") as config:
config.write('address:' + address + ':port:' + str(port) + ':')
# Start the server
app.run(port=port, debug=True, use_reloader=False)
|
'''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
Created on Apr 22, 2011
@author: shreyas
@contact: dbratcher@gatech.edu
@summary: This is intended to be a collection of helper routines used by different QSTK modules
'''
import os
from functools import lru_cache
@lru_cache()
def cached_listdir(d):
return os.listdir(d)
def clean_paths (paths_to_clean):
'''
@summary: Removes any previous files in the list of paths.
'''
if (type(paths_to_clean) is str):
temp= paths_to_clean
paths_to_clean= list()
paths_to_clean.append(temp)
#endif
for path in paths_to_clean:
files_at_this_path = cached_listdir(str(path))
for _file in files_at_this_path:
if (os.path.isfile(path + _file)):
os.remove(path + _file)
#if ends
#for ends
#outer for ends
#clean_output_paths ends
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/sagemaker/model/InferenceSpecification.h>
#include <aws/sagemaker/model/SourceAlgorithmSpecification.h>
#include <aws/sagemaker/model/ModelPackageValidationSpecification.h>
#include <aws/sagemaker/model/ModelPackageStatus.h>
#include <aws/sagemaker/model/ModelPackageStatusDetails.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace SageMaker
{
namespace Model
{
class AWS_SAGEMAKER_API DescribeModelPackageResult
{
public:
DescribeModelPackageResult();
DescribeModelPackageResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeModelPackageResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The name of the model package being described.</p>
*/
inline const Aws::String& GetModelPackageName() const{ return m_modelPackageName; }
/**
* <p>The name of the model package being described.</p>
*/
inline void SetModelPackageName(const Aws::String& value) { m_modelPackageName = value; }
/**
* <p>The name of the model package being described.</p>
*/
inline void SetModelPackageName(Aws::String&& value) { m_modelPackageName = std::move(value); }
/**
* <p>The name of the model package being described.</p>
*/
inline void SetModelPackageName(const char* value) { m_modelPackageName.assign(value); }
/**
* <p>The name of the model package being described.</p>
*/
inline DescribeModelPackageResult& WithModelPackageName(const Aws::String& value) { SetModelPackageName(value); return *this;}
/**
* <p>The name of the model package being described.</p>
*/
inline DescribeModelPackageResult& WithModelPackageName(Aws::String&& value) { SetModelPackageName(std::move(value)); return *this;}
/**
* <p>The name of the model package being described.</p>
*/
inline DescribeModelPackageResult& WithModelPackageName(const char* value) { SetModelPackageName(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline const Aws::String& GetModelPackageArn() const{ return m_modelPackageArn; }
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline void SetModelPackageArn(const Aws::String& value) { m_modelPackageArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline void SetModelPackageArn(Aws::String&& value) { m_modelPackageArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline void SetModelPackageArn(const char* value) { m_modelPackageArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageArn(const Aws::String& value) { SetModelPackageArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageArn(Aws::String&& value) { SetModelPackageArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageArn(const char* value) { SetModelPackageArn(value); return *this;}
/**
* <p>A brief summary of the model package.</p>
*/
inline const Aws::String& GetModelPackageDescription() const{ return m_modelPackageDescription; }
/**
* <p>A brief summary of the model package.</p>
*/
inline void SetModelPackageDescription(const Aws::String& value) { m_modelPackageDescription = value; }
/**
* <p>A brief summary of the model package.</p>
*/
inline void SetModelPackageDescription(Aws::String&& value) { m_modelPackageDescription = std::move(value); }
/**
* <p>A brief summary of the model package.</p>
*/
inline void SetModelPackageDescription(const char* value) { m_modelPackageDescription.assign(value); }
/**
* <p>A brief summary of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageDescription(const Aws::String& value) { SetModelPackageDescription(value); return *this;}
/**
* <p>A brief summary of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageDescription(Aws::String&& value) { SetModelPackageDescription(std::move(value)); return *this;}
/**
* <p>A brief summary of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageDescription(const char* value) { SetModelPackageDescription(value); return *this;}
/**
* <p>A timestamp specifying when the model package was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; }
/**
* <p>A timestamp specifying when the model package was created.</p>
*/
inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTime = value; }
/**
* <p>A timestamp specifying when the model package was created.</p>
*/
inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTime = std::move(value); }
/**
* <p>A timestamp specifying when the model package was created.</p>
*/
inline DescribeModelPackageResult& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;}
/**
* <p>A timestamp specifying when the model package was created.</p>
*/
inline DescribeModelPackageResult& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;}
/**
* <p>Details about inference jobs that can be run with models based on this model
* package.</p>
*/
inline const InferenceSpecification& GetInferenceSpecification() const{ return m_inferenceSpecification; }
/**
* <p>Details about inference jobs that can be run with models based on this model
* package.</p>
*/
inline void SetInferenceSpecification(const InferenceSpecification& value) { m_inferenceSpecification = value; }
/**
* <p>Details about inference jobs that can be run with models based on this model
* package.</p>
*/
inline void SetInferenceSpecification(InferenceSpecification&& value) { m_inferenceSpecification = std::move(value); }
/**
* <p>Details about inference jobs that can be run with models based on this model
* package.</p>
*/
inline DescribeModelPackageResult& WithInferenceSpecification(const InferenceSpecification& value) { SetInferenceSpecification(value); return *this;}
/**
* <p>Details about inference jobs that can be run with models based on this model
* package.</p>
*/
inline DescribeModelPackageResult& WithInferenceSpecification(InferenceSpecification&& value) { SetInferenceSpecification(std::move(value)); return *this;}
/**
* <p>Details about the algorithm that was used to create the model package.</p>
*/
inline const SourceAlgorithmSpecification& GetSourceAlgorithmSpecification() const{ return m_sourceAlgorithmSpecification; }
/**
* <p>Details about the algorithm that was used to create the model package.</p>
*/
inline void SetSourceAlgorithmSpecification(const SourceAlgorithmSpecification& value) { m_sourceAlgorithmSpecification = value; }
/**
* <p>Details about the algorithm that was used to create the model package.</p>
*/
inline void SetSourceAlgorithmSpecification(SourceAlgorithmSpecification&& value) { m_sourceAlgorithmSpecification = std::move(value); }
/**
* <p>Details about the algorithm that was used to create the model package.</p>
*/
inline DescribeModelPackageResult& WithSourceAlgorithmSpecification(const SourceAlgorithmSpecification& value) { SetSourceAlgorithmSpecification(value); return *this;}
/**
* <p>Details about the algorithm that was used to create the model package.</p>
*/
inline DescribeModelPackageResult& WithSourceAlgorithmSpecification(SourceAlgorithmSpecification&& value) { SetSourceAlgorithmSpecification(std::move(value)); return *this;}
/**
* <p>Configurations for one or more transform jobs that Amazon SageMaker runs to
* test the model package.</p>
*/
inline const ModelPackageValidationSpecification& GetValidationSpecification() const{ return m_validationSpecification; }
/**
* <p>Configurations for one or more transform jobs that Amazon SageMaker runs to
* test the model package.</p>
*/
inline void SetValidationSpecification(const ModelPackageValidationSpecification& value) { m_validationSpecification = value; }
/**
* <p>Configurations for one or more transform jobs that Amazon SageMaker runs to
* test the model package.</p>
*/
inline void SetValidationSpecification(ModelPackageValidationSpecification&& value) { m_validationSpecification = std::move(value); }
/**
* <p>Configurations for one or more transform jobs that Amazon SageMaker runs to
* test the model package.</p>
*/
inline DescribeModelPackageResult& WithValidationSpecification(const ModelPackageValidationSpecification& value) { SetValidationSpecification(value); return *this;}
/**
* <p>Configurations for one or more transform jobs that Amazon SageMaker runs to
* test the model package.</p>
*/
inline DescribeModelPackageResult& WithValidationSpecification(ModelPackageValidationSpecification&& value) { SetValidationSpecification(std::move(value)); return *this;}
/**
* <p>The current status of the model package.</p>
*/
inline const ModelPackageStatus& GetModelPackageStatus() const{ return m_modelPackageStatus; }
/**
* <p>The current status of the model package.</p>
*/
inline void SetModelPackageStatus(const ModelPackageStatus& value) { m_modelPackageStatus = value; }
/**
* <p>The current status of the model package.</p>
*/
inline void SetModelPackageStatus(ModelPackageStatus&& value) { m_modelPackageStatus = std::move(value); }
/**
* <p>The current status of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageStatus(const ModelPackageStatus& value) { SetModelPackageStatus(value); return *this;}
/**
* <p>The current status of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageStatus(ModelPackageStatus&& value) { SetModelPackageStatus(std::move(value)); return *this;}
/**
* <p>Details about the current status of the model package.</p>
*/
inline const ModelPackageStatusDetails& GetModelPackageStatusDetails() const{ return m_modelPackageStatusDetails; }
/**
* <p>Details about the current status of the model package.</p>
*/
inline void SetModelPackageStatusDetails(const ModelPackageStatusDetails& value) { m_modelPackageStatusDetails = value; }
/**
* <p>Details about the current status of the model package.</p>
*/
inline void SetModelPackageStatusDetails(ModelPackageStatusDetails&& value) { m_modelPackageStatusDetails = std::move(value); }
/**
* <p>Details about the current status of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageStatusDetails(const ModelPackageStatusDetails& value) { SetModelPackageStatusDetails(value); return *this;}
/**
* <p>Details about the current status of the model package.</p>
*/
inline DescribeModelPackageResult& WithModelPackageStatusDetails(ModelPackageStatusDetails&& value) { SetModelPackageStatusDetails(std::move(value)); return *this;}
/**
* <p>Whether the model package is certified for listing on AWS Marketplace.</p>
*/
inline bool GetCertifyForMarketplace() const{ return m_certifyForMarketplace; }
/**
* <p>Whether the model package is certified for listing on AWS Marketplace.</p>
*/
inline void SetCertifyForMarketplace(bool value) { m_certifyForMarketplace = value; }
/**
* <p>Whether the model package is certified for listing on AWS Marketplace.</p>
*/
inline DescribeModelPackageResult& WithCertifyForMarketplace(bool value) { SetCertifyForMarketplace(value); return *this;}
private:
Aws::String m_modelPackageName;
Aws::String m_modelPackageArn;
Aws::String m_modelPackageDescription;
Aws::Utils::DateTime m_creationTime;
InferenceSpecification m_inferenceSpecification;
SourceAlgorithmSpecification m_sourceAlgorithmSpecification;
ModelPackageValidationSpecification m_validationSpecification;
ModelPackageStatus m_modelPackageStatus;
ModelPackageStatusDetails m_modelPackageStatusDetails;
bool m_certifyForMarketplace;
};
} // namespace Model
} // namespace SageMaker
} // namespace Aws
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-12-08 15:29
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('botmanager', '0002_auto_20161208_1406'),
]
operations = [
migrations.RenameField(
model_name='task',
old_name='retry_count',
new_name='attempt_count',
),
migrations.RemoveField(
model_name='task',
name='last_retry_dt',
),
migrations.RemoveField(
model_name='task',
name='max_retry_count',
),
migrations.RemoveField(
model_name='task',
name='retry_period',
),
migrations.AddField(
model_name='task',
name='attempt_period',
field=models.DurationField(default=datetime.timedelta(0, 3600), verbose_name='\u041f\u0435\u0440\u0438\u043e\u0434 \u043c\u0435\u0436\u0434\u0443 \u043f\u043e\u043f\u044b\u0442\u043a\u0430\u043c\u0438'),
),
migrations.AddField(
model_name='task',
name='last_attempt_dt',
field=models.DateTimeField(null=True, verbose_name='\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u044f\u044f \u043f\u043e\u043f\u044b\u0442\u043a\u0430 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f'),
),
migrations.AddField(
model_name='task',
name='max_attempt_count',
field=models.IntegerField(null=True, verbose_name='\u041c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043a\u043e\u043b-\u0432\u043e \u043f\u043e\u043f\u044b\u0442\u043e\u043a \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 (\u0435\u0441\u043b\u0438 None, \u0442\u043e \u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u043e)'),
),
]
|
# Delta Recurrent Neural Network (Delta-RNN) Framework
#
# This gives an implementation of the Delta-RNN framework given in Ororbia et al. 2017, arXiv:1703.08864 [cs.CL],
# https://arxiv.org/abs/1703.08864 using Python and Tensorflow.
#
# This code implements a variety of RNN models using the Delta-RNN Framework
#
# Stuart Hagler, 2017
# Imports
import tensorflow as tf
# Local imports
from delta_rnn import delta_rnn_graph
# Define derived Peephole LSTM TensorFlow graph class
class peephole_lstm_graph(delta_rnn_graph):
# Graph constructor
def __init__(self, num_gpus, alpha, c_size, h_size, vocabulary_size, num_training_unfoldings,
num_validation_unfoldings, training_batch_size, validation_batch_size, optimization_frequency):
# Feed remaining hyperparameters to delta RNN __init__
delta_rnn_graph.__init__(self, num_gpus, h_size, h_size, vocabulary_size, num_training_unfoldings,
num_validation_unfoldings, training_batch_size, validation_batch_size,
optimization_frequency)
# Peephole LSTM cell definition .
def _cell(self, x, c, h):
with tf.name_scope('i'):
i = tf.sigmoid(tf.matmul(x, self._Wi) + tf.matmul(h, self._Vi) + self._bi)
with tf.name_scope('f'):
f = tf.sigmoid(tf.matmul(x, self._Wf) + tf.matmul(h, self._Vf) + self._bf)
o = tf.sigmoid(tf.matmul(x, self._Wo) + tf.matmul(h, self._Vo) + self._bo)
with tf.name_scope('z'):
z = tf.sigmoid(tf.matmul(x, self._Wz) + tf.matmul(h, self._Vz) + self._bz)
with tf.name_scope('c'):
c = f*c + i*z
with tf.name_scope('h'):
h = o*tf.tanh(c)
with tf.name_scope('o'):
o = tf.nn.xw_plus_b(o, self._W, self._b)
return o, c, h
# Setup Peephole LSTM cell parameters
def _setup_cell_parameters(self):
with tf.name_scope('Wi'):
self._Wi = tf.Variable(tf.truncated_normal([self._vocabulary_size, self._h_size], -0.1, 0.1))
with tf.name_scope('Vi'):
self._Vi = tf.Variable(tf.truncated_normal([self._h_size, self._h_size], -0.1, 0.1))
with tf.name_scope('bi'):
self._bi = tf.Variable(tf.zeros([1, self._h_size]))
with tf.name_scope('Wf'):
self._Wf = tf.Variable(tf.truncated_normal([self._vocabulary_size, self._h_size], -0.1, 0.1))
with tf.name_scope('Vf'):
self._Vf = tf.Variable(tf.truncated_normal([self._h_size, self._h_size], -0.1, 0.1))
with tf.name_scope('bf'):
self._bf = tf.Variable(tf.zeros([1, self._h_size]))
with tf.name_scope('Wo'):
self._Wo = tf.Variable(tf.truncated_normal([self._vocabulary_size, self._h_size], -0.1, 0.1))
with tf.name_scope('Vo'):
self._Vo = tf.Variable(tf.truncated_normal([self._h_size, self._h_size], -0.1, 0.1))
with tf.name_scope('bo'):
self._bo = tf.Variable(tf.zeros([1, self._h_size]))
with tf.name_scope('Wz'):
self._Wz = tf.Variable(tf.truncated_normal([self._vocabulary_size, self._h_size], -0.1, 0.1))
with tf.name_scope('Vz'):
self._Vz = tf.Variable(tf.truncated_normal([self._h_size, self._h_size], -0.1, 0.1))
with tf.name_scope('bz'):
self._bz = tf.Variable(tf.zeros([1, self._h_size]))
with tf.name_scope('W'):
self._W = tf.Variable(tf.truncated_normal([self._h_size, self._vocabulary_size], -0.1, 0.1))
with tf.name_scope('b'):
self._b = tf.Variable(tf.zeros([self._vocabulary_size]))
|
"""Collect daisy tools into docs
================================
To use, type:
python collect.py
"""
import sys
import glob
import os
import re
import daisy.Experiment as E
import daisy.IOTools as IOTools
TEMPLATE_TOOL = """
========================================================
{tool_name}
========================================================
.. automodule:: daisy.tools.{tool_module}
Command line usage
==================
.. program-output:: daisy {tool_name} -?
"""
def main(argv=None):
parser = E.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"])
(options, args) = E.start(parser,
argv=argv, add_output_options=True)
tools = glob.glob(
os.path.join(os.path.dirname(__file__),
"..", "src", "daisy", "tools", "*.py"))
counter = E.Counter()
for tool in tools:
counter.found += 1
tool_module = re.sub(".py", "", os.path.basename(tool))
tool_name = re.sub("_", "-", tool_module)
if tool_name in ("__init__", "cli"):
c.ignored += 1
continue
dest = os.path.join("tools", "{}.rst".format(tool_name))
if os.path.exists(dest) and not options.output_force:
counter.skipped += 1
continue
with IOTools.openFile(dest, "w") as outf:
outf.write(TEMPLATE_TOOL.format(
**locals()))
counter.new += 1
E.info(counter)
E.stop()
if __name__ == "__main__":
sys.exit(main())
|
"""Transformer to parse and augment US zipcodes with info from zipcode database."""
from h2oaicore.transformer_utils import CustomTransformer
from h2oaicore.systemutils import make_experiment_logger, loggerinfo, loggerwarning
import datatable as dt
import numpy as np
_global_modules_needed_by_name = ['pycodestyle==2.6.0', 'uszipcode==0.2.4']
from uszipcode import SearchEngine
class USZipcodeDBTransformer(CustomTransformer):
_allow_transform_to_modify_output_feature_names = True
_numeric_output = True
@staticmethod
def do_acceptance_test():
return True
@staticmethod
def get_default_properties():
return dict(col_type="categorical", min_cols=1, max_cols=1, relative_importance=1)
@staticmethod
def to_dict_values(data, name):
result = dict()
data = data[name]
if data is None or len(data) == 0:
return result
for k in range(len(data)):
key = data[k]['key']
values = data[k]['values']
names = [d['x'] for d in values]
if len(data) > 1:
keys = [name + '_' + key + '_' + str(y) for y in names]
else:
keys = [name + '_' + str(y) for y in names]
vals = [d['y'] for d in values]
result = {**result, **dict(zip(keys, vals))}
return result
@staticmethod
def replaceBannedCharacters(str):
return str.replace('<', ' less ').replace('[', '(').replace(']', ')')
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.transformer_name = self.__class__.__name__
if self.transformer_name.endswith("Transformer"):
self.transformer_name = self.transformer_name[:-len("Transformer")]
search = SearchEngine(simple_zipcode=False)
def get_zipcode_features(self, value):
if value is None or not value:
return self.get_zipcode_null_features()
elif len(value) < 3:
# raise ValueError("Value '{}' too short for zip code.".format(value))
return self.get_zipcode_null_features()
elif value[:5] in ['000', '0000', '00000', ' ', ' ', ' ']:
return self.get_zipcode_null_features()
else:
lookup_value = value[:5] # US zipcode only
zip_data = self.search.by_zipcode(lookup_value)
if (zip_data.zipcode_type == None):
return self.get_zipcode_null_features()
# raise ValueError("Value '{}' not a zipcode.".format(value))
else:
zip_dict = zip_data.to_dict()
result = { # 'zip_key': value,
# 'zipcode_type': zip_dict['zipcode_type'],
# 'major_city': zip_dict['major_city'],
# 'post_office_city': zip_dict['post_office_city'],
# 'common_city_list': zip_dict['common_city_list'][0],
# 'county': zip_dict['county'],
# 'state': zip_dict['state'],
'lat': zip_dict['lat'],
'lng': zip_dict['lng'],
# 'timezone': zip_dict['timezone'],
'radius_in_miles': zip_dict['radius_in_miles'],
# 'area_code_list': ['469', '972'],
'population': zip_dict['population'],
'population_density': zip_dict['population_density'],
'land_area_in_sqmi': zip_dict['land_area_in_sqmi'],
'water_area_in_sqmi': zip_dict['water_area_in_sqmi'],
'housing_units': zip_dict['housing_units'],
'occupied_housing_units': zip_dict['occupied_housing_units'],
'median_home_value': zip_dict['median_home_value'],
'median_household_income': zip_dict['median_household_income'],
'bounds_west': zip_dict['bounds_west'],
'bounds_east': zip_dict['bounds_east'],
'bounds_north': zip_dict['bounds_north'],
'bounds_south': zip_dict['bounds_south'],
# 'zipcode': zip_dict['zipcode']
}
return {**result,
**self.to_dict_values(zip_dict, 'population_by_year'),
**self.to_dict_values(zip_dict, 'population_by_age'),
**self.to_dict_values(zip_dict, 'population_by_gender'),
**self.to_dict_values(zip_dict, 'population_by_race'),
**self.to_dict_values(zip_dict, 'head_of_household_by_age'),
**self.to_dict_values(zip_dict, 'families_vs_singles'),
**self.to_dict_values(zip_dict, 'households_with_kids'),
**self.to_dict_values(zip_dict, 'children_by_age'),
**self.to_dict_values(zip_dict, 'housing_type'),
**self.to_dict_values(zip_dict, 'year_housing_was_built'),
**self.to_dict_values(zip_dict, 'housing_occupancy'),
**self.to_dict_values(zip_dict, 'vancancy_reason'),
**self.to_dict_values(zip_dict, 'owner_occupied_home_values'),
**self.to_dict_values(zip_dict, 'rental_properties_by_number_of_rooms'),
**self.to_dict_values(zip_dict, 'monthly_rent_including_utilities_studio_apt'),
**self.to_dict_values(zip_dict, 'monthly_rent_including_utilities_1_b'),
**self.to_dict_values(zip_dict, 'monthly_rent_including_utilities_2_b'),
**self.to_dict_values(zip_dict, 'monthly_rent_including_utilities_3plus_b'),
**self.to_dict_values(zip_dict, 'employment_status'),
**self.to_dict_values(zip_dict, 'average_household_income_over_time'),
**self.to_dict_values(zip_dict, 'household_income'),
**self.to_dict_values(zip_dict, 'annual_individual_earnings'),
**self.to_dict_values(zip_dict,
'sources_of_household_income____percent_of_households_receiving_income'),
**self.to_dict_values(zip_dict,
'sources_of_household_income____average_income_per_household_by_income_source'),
**self.to_dict_values(zip_dict,
'household_investment_income____percent_of_households_receiving_investment_income'),
**self.to_dict_values(zip_dict,
'household_investment_income____average_income_per_household_by_income_source'),
**self.to_dict_values(zip_dict,
'household_retirement_income____percent_of_households_receiving_retirement_incom'),
**self.to_dict_values(zip_dict,
'household_retirement_income____average_income_per_household_by_income_source'),
**self.to_dict_values(zip_dict, 'source_of_earnings'),
**self.to_dict_values(zip_dict, 'means_of_transportation_to_work_for_workers_16_and_over'),
**self.to_dict_values(zip_dict, 'travel_time_to_work_in_minutes'),
**self.to_dict_values(zip_dict, 'educational_attainment_for_population_25_and_over'),
**self.to_dict_values(zip_dict, 'school_enrollment_age_3_to_17')
}
def get_zipcode_null_features(self):
null_dict = self.get_zipcode_features('79936')
for key, value in null_dict.items():
null_dict[key] = None
return null_dict
def get_zipcode_null_result(self, X, original_zip_column_name):
X[:, 'zip_key'] = '79936'
zip_list = ['79936']
zip_features = [self.get_zipcode_null_features() for x in zip_list]
X_g = dt.Frame({"zip_key": zip_list})
X_g.cbind(dt.Frame(zip_features))
X_g.key = 'zip_key'
X_result = X[:, :, dt.join(X_g)]
self._output_feature_names = ["{}:{}.{}".format(self.transformer_name,
original_zip_column_name, self.replaceBannedCharacters(f)) for f
in list(X_result[:, 1:].names)]
self._feature_desc = ["Property '{}' of zipcode column ['{}'] from US zipcode database (recipe '{}')".format(
f, original_zip_column_name, self.transformer_name) for f in list(X_result[:, 1:].names)]
return X_result[:, 1:]
def fit_transform(self, X: dt.Frame, y: np.array = None):
return self.transform(X)
def transform(self, X: dt.Frame):
logger = None
if self.context and self.context.experiment_id:
logger = make_experiment_logger(experiment_id=self.context.experiment_id,
tmp_dir=self.context.tmp_dir,
experiment_tmp_dir=self.context.experiment_tmp_dir)
X = dt.Frame(X)
original_zip_column_name = X.names[0]
X = X[:, dt.str64(dt.f[0])]
X.names = ['zip_key']
try:
zip_list = dt.unique(X[~dt.isna(dt.f.zip_key), 0]).to_list()[0] + ['79936']
zip_features = [self.get_zipcode_features(x) for x in zip_list]
X_g = dt.Frame({"zip_key": zip_list})
X_g.cbind(dt.Frame(zip_features))
X_g.key = 'zip_key'
X_result = X[:, :, dt.join(X_g)]
self._output_feature_names = ["{}:{}.{}".format(self.transformer_name,
original_zip_column_name, self.replaceBannedCharacters(f))
for f in list(X_result[:, 1:].names)]
self._feature_desc = [
"Property '{}' of zipcode column ['{}'] from US zipcode database (recipe '{}')".format(
f, original_zip_column_name, self.transformer_name) for f in list(X_result[:, 1:].names)]
return X_result[:, 1:]
except ValueError as ve:
loggerinfo(logger, "Column '{}' is not a zipcode: {}".format(original_zip_column_name, str(ve)))
return self.get_zipcode_null_result(X, original_zip_column_name)
except TypeError as te:
loggerwarning(logger, "Column '{}' triggered TypeError: {}".format(original_zip_column_name, str(te)))
raise te
|
import pandas as pd
from bokeh.io import output_file, show
from bokeh.models import BasicTicker, ColorBar, ColumnDataSource, LinearColorMapper, PrintfTickFormatter
from bokeh.plotting import figure
from bokeh.sampledata.unemployment1948 import data
from bokeh.transform import transform
output_file("unemploymemt.html")
data.Year = data.Year.astype(str)
data = data.set_index('Year')
data.drop('Annual', axis=1, inplace=True)
data.columns.name = 'Month'
# reshape to 1D array or rates with a month and year for each row.
df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()
source = ColumnDataSource(df)
# this is the colormap from the original NYTimes plot
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"]
mapper = LinearColorMapper(palette=colors, low=df.rate.min(), high=df.rate.max())
p = figure(plot_width=800, plot_height=300, title="US Unemployment 1948—2016",
x_range=list(data.index), y_range=list(reversed(data.columns)),
toolbar_location=None, tools="", x_axis_location="above")
p.rect(x="Year", y="Month", width=1, height=1, source=source,
line_color=None, fill_color=transform('rate', mapper))
color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
ticker=BasicTicker(desired_num_ticks=len(colors)),
formatter=PrintfTickFormatter(format="%d%%"))
p.add_layout(color_bar, 'right')
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "5pt"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = 1.0
show(p)
|
import React from 'react';
import { mount } from 'enzyme';
import { appealData } from '../../../data/appeals';
import { queueWrapper } from '../../../data/stores/queueStore';
import HearingTypeConversionModal from '../../../../app/hearings/components/HearingTypeConversionModal';
import Modal from '../../../../app/components/Modal';
import COPY from 'COPY';
describe('HearingTypeConversion', () => {
test('Displays convert to Video text when converting from Video', () => {
const hearingTypeConversion = mount(
<HearingTypeConversionModal
appeal={appealData}
hearingType="Video"
/>,
{
wrappingComponent: queueWrapper,
}
);
expect(hearingTypeConversion.exists(Modal)).toBeTruthy();
expect(hearingTypeConversion.find(Modal).text()).not.toContain('Central Office');
expect(hearingTypeConversion.find(Modal).text()).toContain(COPY.CONVERT_HEARING_TYPE_DEFAULT_REGIONAL_OFFICE_TEXT);
expect(hearingTypeConversion).toMatchSnapshot();
});
test('Displays convert to Central text when converting from Central', () => {
const hearingTypeConversion = mount(
<HearingTypeConversionModal
appeal={appealData}
hearingType="Central"
/>,
{
wrappingComponent: queueWrapper,
}
);
expect(hearingTypeConversion.exists(Modal)).toBeTruthy();
expect(hearingTypeConversion.find(Modal).text()).toContain('Central Office');
expect(hearingTypeConversion.find(Modal).text()).
not.toContain(COPY.CONVERT_HEARING_TYPE_DEFAULT_REGIONAL_OFFICE_TEXT);
expect(hearingTypeConversion).toMatchSnapshot();
});
});
|
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
nums.sort();
var ret = null;
var curNum = null, first = true;
for (var i = 0; i < nums.length; ++i) {
// console.log(nums, i, nums[i]);
if (first) {
curNum = nums[i];
first = false;
} else if (curNum != nums[i]) {
return curNum;
} else {
first = true;
}
}
return curNum;
};
|
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import unittest
import pytest
from . import util as test_util
import turicreate as tc
import tempfile
import numpy as np
import platform
import pytest
import sys
import os
from turicreate.toolkits._main import ToolkitError as _ToolkitError
from turicreate.toolkits._internal_utils import _raise_error_if_not_sarray, _mac_ver
from six import StringIO
import coremltools
_CLASSES = ["person", "cat", "dog", "chair"]
def _get_data(feature, annotations):
from PIL import Image as _PIL_Image
rs = np.random.RandomState(1234)
def from_pil_image(pil_img, image_format="png"):
# The above didn't work, so as a temporary fix write to temp files
if image_format == "raw":
image = np.array(pil_img)
FORMAT_RAW = 2
return tc.Image(
_image_data=image.tobytes(),
_width=image.shape[1],
_height=image.shape[0],
_channels=image.shape[2],
_format_enum=FORMAT_RAW,
_image_data_size=image.size,
)
else:
with tempfile.NamedTemporaryFile(
mode="w+b", suffix="." + image_format
) as f:
pil_img.save(f, format=image_format)
return tc.Image(f.name)
num_examples = 100
max_num_boxes_per_image = 10
classes = _CLASSES
images = []
anns = []
FORMATS = ["png", "jpeg", "raw"]
for i in range(num_examples):
# Randomly determine image size (should handle large and small)
img_shape = tuple(rs.randint(100, 1000, size=2)) + (3,)
img = rs.randint(255, size=img_shape)
pil_img = _PIL_Image.fromarray(img, mode="RGB")
# Randomly select image format
image_format = FORMATS[rs.randint(len(FORMATS))]
images.append(from_pil_image(pil_img, image_format=image_format))
ann = []
for j in range(rs.randint(max_num_boxes_per_image)):
left, right = np.sort(rs.randint(0, img_shape[1], size=2))
top, bottom = np.sort(rs.randint(0, img_shape[0], size=2))
x = (left + right) / 2
y = (top + bottom) / 2
width = max(right - left, 1)
height = max(bottom - top, 1)
label = {
"coordinates": {"x": x, "y": y, "width": width, "height": height,},
"label": classes[rs.randint(len(classes))],
"type": "rectangle",
}
ann.append(label)
anns.append(ann)
data = tc.SFrame({feature: tc.SArray(images), annotations: tc.SArray(anns),})
return data
class ObjectDetectorTest(unittest.TestCase):
@classmethod
def setUpClass(self):
"""
The setup class method for the basic test case with all default values.
"""
self.feature = "myimage"
self.annotations = "myannotations"
self.pre_trained_model = "darknet-yolo"
## Create the model
self.def_opts = {
"model": "darknet-yolo",
"max_iterations": 0,
}
# Model
self.sf = _get_data(feature=self.feature, annotations=self.annotations)
self.model = tc.object_detector.create(
self.sf,
feature=self.feature,
annotations=self.annotations,
batch_size=2,
max_iterations=1,
model=self.pre_trained_model,
)
## Answers
self.opts = self.def_opts.copy()
self.opts["max_iterations"] = 1
self.get_ans = {
"_model": lambda x: True,
"_class_to_index": lambda x: isinstance(x, dict),
"_training_time_as_string": lambda x: isinstance(x, str),
"_grid_shape": lambda x: tuple(x) == (13, 13),
"model": lambda x: x == self.pre_trained_model,
"anchors": lambda x: (
isinstance(x, (list, tuple, np.ndarray))
and len(x) > 0
and len(x[0]) == 2
),
"input_image_shape": lambda x: tuple(x) == (3, 416, 416),
"batch_size": lambda x: x == 2,
"classes": lambda x: x == sorted(_CLASSES),
"feature": lambda x: x == self.feature,
"max_iterations": lambda x: x >= 0,
"non_maximum_suppression_threshold": lambda x: 0 <= x <= 1,
"training_time": lambda x: x > 0,
"training_iterations": lambda x: x > 0,
"training_epochs": lambda x: x >= 0,
"num_bounding_boxes": lambda x: x > 0,
"num_examples": lambda x: x > 0,
"training_loss": lambda x: x > 0,
"annotations": lambda x: x == self.annotations,
"num_classes": lambda x: x == len(_CLASSES),
}
self.get_ans["annotation_position"] = lambda x: isinstance(x, str)
self.get_ans["annotation_scale"] = lambda x: isinstance(x, str)
self.get_ans["annotation_origin"] = lambda x: isinstance(x, str)
self.get_ans["grid_height"] = lambda x: x > 0
self.get_ans["grid_width"] = lambda x: x > 0
self.get_ans["random_seed"] = lambda x: isinstance(x, int)
self.get_ans["verbose"] = lambda x: True
del self.get_ans["_model"]
del self.get_ans["_class_to_index"]
del self.get_ans["_grid_shape"]
del self.get_ans["anchors"]
del self.get_ans["non_maximum_suppression_threshold"]
self.fields_ans = self.get_ans.keys()
def test_create_with_missing_value(self):
sf = self.sf.append(
tc.SFrame(
{
self.feature: tc.SArray([None], dtype=tc.Image),
self.annotations: [self.sf[self.annotations][0]],
}
)
)
with self.assertRaises(_ToolkitError):
tc.object_detector.create(
sf, feature=self.feature, annotations=self.annotations
)
def test_create_with_missing_feature(self):
with self.assertRaises(_ToolkitError):
tc.object_detector.create(
self.sf, feature="wrong_feature", annotations=self.annotations
)
def test_create_with_missing_annotations(self):
with self.assertRaises(_ToolkitError):
tc.object_detector.create(
self.sf, feature=self.feature, annotations="wrong_annotations"
)
def test_create_with_invalid_annotations_list_coord(self):
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: [{"label": _CLASSES[0], "coordinates": [100, 50, 20, 40]}]
)
tc.object_detector.create(sf)
def test_create_with_invalid_annotations_coordinate(self):
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: [
{
"label": _CLASSES[0],
"coordinates": {"x": None, "y": 1, "width": 1, "height": 1},
}
]
)
tc.object_detector.create(sf)
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: [
{
"label": _CLASSES[0],
"coordinates": {"x": 1, "y": [], "width": 1, "height": 1},
}
]
)
tc.object_detector.create(sf)
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: [
{
"label": _CLASSES[0],
"coordinates": {"x": 1, "y": 1, "width": {}, "height": 1},
}
]
)
tc.object_detector.create(sf)
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: [
{
"label": _CLASSES[0],
"coordinates": {"x": 1, "y": 1, "width": 1, "height": "1"},
}
]
)
tc.object_detector.create(sf)
def test_create_with_missing_annotations_label(self):
def create_missing_annotations_label(x):
for y in x:
y["label"] = None
return x
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: create_missing_annotations_label(x)
)
tc.object_detector.create(sf)
def test_create_with_invalid_annotations_not_dict(self):
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(lambda x: [1])
tc.object_detector.create(sf)
def test_create_with_invalid_user_define_classes(self):
sf = self.sf.head()
old_stdout = sys.stdout
result_out = StringIO()
sys.stdout = result_out
model = tc.object_detector.create(
sf,
feature=self.feature,
annotations=self.annotations,
classes=["invalid"],
max_iterations=1,
)
sys.stdout = old_stdout
self.assertTrue("Warning" in result_out.getvalue())
def test_create_with_empty_dataset(self):
with self.assertRaises(_ToolkitError):
tc.object_detector.create(self.sf[:0])
def test_create_with_verbose_False(self):
args = [self.sf, self.annotations, self.feature]
kwargs = {"max_iterations": 1, "model": self.pre_trained_model}
test_util.assert_longer_verbose_logs(tc.object_detector.create, args, kwargs)
def test_create_with_fixed_random_seed(self):
random_seed = 86
max_iterations = 3
model_1 = tc.object_detector.create(self.sf, max_iterations=max_iterations, random_seed=random_seed)
pred_1 = model_1.predict(self.sf)
model_2 = tc.object_detector.create(self.sf, max_iterations=max_iterations, random_seed=random_seed)
pred_2 = model_2.predict(self.sf)
self.assertEqual(len(pred_1), len(pred_2))
for i in range(len(pred_1)):
self.assertEqual(len(pred_1[i]),len(pred_2[i]))
for j in range(len(pred_1[i])):
self.assertEqual(pred_1[i][j], pred_2[i][j])
def test_dict_annotations(self):
sf_copy = self.sf[:]
sf_copy[self.annotations] = sf_copy[self.annotations].apply(
lambda x: x[0] if len(x) > 0 else None
)
dict_model = tc.object_detector.create(
sf_copy,
feature=self.feature,
annotations=self.annotations,
max_iterations=1,
model=self.pre_trained_model,
)
pred = dict_model.predict(sf_copy)
metrics = dict_model.evaluate(sf_copy)
annotated_img = tc.object_detector.util.draw_bounding_boxes(
sf_copy[self.feature], sf_copy[self.annotations]
)
def test_extra_classes(self):
# Create while the data has extra classes
model = tc.object_detector.create(
self.sf, classes=_CLASSES[:2], max_iterations=1
)
self.assertEqual(len(model.classes), 2)
# Evaluate while the data has extra classes
ret = model.evaluate(self.sf.head())
self.assertEqual(len(ret["average_precision_50"]), 2)
def test_different_grip_shape(self):
# Should able to give different input grip shape
shapes = [[1, 1], [5, 5], [26, 26], [10, 20], [7, 19]]
for shape in shapes:
model = tc.object_detector.create(
self.sf[:2], max_iterations=1, grid_shape=shape
)
pred = model.predict(self.sf[:2])
def test_predict(self):
sf = self.sf.head()
# Make sure this does not need the annotations column to work
del sf[self.annotations]
pred = self.model.predict(sf.head())
# Check the structure of the output
_raise_error_if_not_sarray(pred)
self.assertEqual(len(pred), len(sf))
# Make sure SFrame was not altered
self.assertEqual([col for col in sf.column_names() if col.startswith("_")], [])
# Predict should work on no input (and produce no predictions)
pred0 = self.model.predict(sf[:0])
self.assertEqual(len(pred0), 0)
def test_predict_with_invalid_annotation(self):
# predict function shouldn't throw exception when annotations column is invalid
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(lambda x: "invalid")
pred = self.model.predict(sf)
def test_single_image(self):
# Predict should work on a single image and product a list of dictionaries
# (we set confidene threshold to 0 to ensure predictions are returned)
pred = self.model.predict(self.sf[self.feature][0], confidence_threshold=0)
self.assertTrue(isinstance(pred, list))
self.assertTrue(isinstance(pred[0], dict))
def test_sarray(self):
sarray = self.sf.head()[self.feature]
pred = self.model.predict(sarray, confidence_threshold=0)
self.assertEqual(len(pred), len(sarray))
def test_confidence_threshold(self):
sf = self.sf.head()
pred = self.model.predict(sf.head(), confidence_threshold=1.0)
stacked = tc.object_detector.util.stack_annotations(pred)
# This should return no predictions, especially with an unconverged model
self.assertEqual(len(stacked), 0)
pred = self.model.predict(sf.head(), confidence_threshold=0.0)
stacked = tc.object_detector.util.stack_annotations(pred)
# This should return predictions
self.assertTrue(len(stacked) > 0)
def test_evaluate(self):
ret = self.model.evaluate(self.sf.head(), metric="average_precision")
self.assertTrue(set(ret), {"average_precision"})
self.assertEqual(set(ret["average_precision"].keys()), set(_CLASSES))
ret = self.model.evaluate(self.sf.head())
self.assertEqual(
set(ret), {"mean_average_precision_50", "average_precision_50"}
)
self.assertTrue(isinstance(ret["mean_average_precision_50"], float))
self.assertEqual(set(ret["average_precision_50"].keys()), set(_CLASSES))
# Empty dataset should not fail with error (although it should to 0
# metrics)
ret = self.model.evaluate(self.sf[:0])
self.assertEqual(ret["mean_average_precision_50"], 0.0)
def test_predict_invalid_threshold(self):
with self.assertRaises(_ToolkitError):
self.model.predict(self.sf.head(), confidence_threshold=-1)
with self.assertRaises(_ToolkitError):
self.model.predict(self.sf.head(), iou_threshold=-1)
def test_evaluate_invalid_threshold(self):
with self.assertRaises(_ToolkitError):
self.model.evaluate(self.sf.head(), confidence_threshold=-1)
with self.assertRaises(_ToolkitError):
self.model.evaluate(self.sf.head(), iou_threshold=-1)
def test_evaluate_sframe_format(self):
metrics = ["mean_average_precision_50", "mean_average_precision"]
for metric in metrics:
pred = self.model.evaluate(
self.sf.head(), metric=metric, output_type="sframe"
)
self.assertEqual(pred.column_names(), ["label"])
def test_evaluate_invalid_metric(self):
with self.assertRaises(_ToolkitError):
self.model.evaluate(self.sf.head(), metric="not-supported-metric")
def test_evaluate_invalid_format(self):
with self.assertRaises(_ToolkitError):
self.model.evaluate(self.sf.head(), output_type="not-supported-format")
def test_evaluate_missing_annotations(self):
with self.assertRaises(_ToolkitError):
sf = self.sf.copy()
del sf[self.annotations]
self.model.evaluate(sf.head())
def test_evaluate_with_missing_annotations_label(self):
def create_missing_annotations_label(x):
for y in x:
y["label"] = None
return x
with self.assertRaises(_ToolkitError):
sf = self.sf.head()
sf[self.annotations] = sf[self.annotations].apply(
lambda x: create_missing_annotations_label(x)
)
self.model.evaluate(sf)
def test_export_coreml(self):
from PIL import Image
import coremltools
import platform
filename = tempfile.NamedTemporaryFile(suffix=".mlmodel").name
self.model.export_coreml(filename, include_non_maximum_suppression=False)
coreml_model = coremltools.models.MLModel(filename)
self.assertDictEqual(
{
"com.github.apple.turicreate.version": tc.__version__,
"com.github.apple.os.platform": platform.platform(),
"annotations": self.annotations,
"type": "object_detector",
"classes": ",".join(sorted(_CLASSES)),
"feature": self.feature,
"include_non_maximum_suppression": "False",
"max_iterations": "1",
"model": "darknet-yolo",
"training_iterations": "1",
"version": "1",
},
dict(coreml_model.user_defined_metadata),
)
expected_result = "Object detector created by Turi Create (version %s)" % (
tc.__version__
)
self.assertEquals(expected_result, coreml_model.short_description)
img = self.sf[0:1][self.feature][0]
img_fixed = tc.image_analysis.resize(img, 416, 416, 3)
pil_img = Image.fromarray(img_fixed.pixel_data)
if _mac_ver() >= (10, 13):
ret = coreml_model.predict({self.feature: pil_img}, usesCPUOnly=True)
self.assertEqual(ret["coordinates"].shape[1], 4)
self.assertEqual(ret["confidence"].shape[1], len(_CLASSES))
self.assertEqual(ret["coordinates"].shape[0], ret["confidence"].shape[0])
# A numeric comparison of the resulting of top bounding boxes is
# not that meaningful unless the model has converged
# Also check if we can train a second model and export it.
filename2 = tempfile.NamedTemporaryFile(suffix=".mlmodel").name
# We also test at the same time if we can export a model with a single
# class
sf = tc.SFrame(
{
"image": [self.sf[self.feature][0]],
"ann": [self.sf[self.annotations][0][:1]],
}
)
model2 = tc.object_detector.create(sf, max_iterations=1)
model2.export_coreml(filename2, include_non_maximum_suppression=False)
@unittest.skipIf(
_mac_ver() < (10, 14),
"Non-maximum suppression is only supported on MacOS 10.14+.",
)
def test_export_coreml_with_non_maximum_suppression(self):
from PIL import Image
filename = tempfile.NamedTemporaryFile(suffix=".mlmodel").name
self.model.export_coreml(filename, include_non_maximum_suppression=True)
coreml_model = coremltools.models.MLModel(filename)
img = self.sf[0:1][self.feature][0]
img_fixed = tc.image_analysis.resize(img, 416, 416, 3)
pil_img = Image.fromarray(img_fixed.pixel_data)
if _mac_ver() >= (10, 13):
ret = coreml_model.predict({self.feature: pil_img}, usesCPUOnly=True)
self.assertEqual(ret["coordinates"].shape[1], 4)
self.assertEqual(ret["confidence"].shape[1], len(_CLASSES))
self.assertEqual(ret["coordinates"].shape[0], ret["confidence"].shape[0])
# A numeric comparison of the resulting of top bounding boxes is
# not that meaningful unless the model has converged
# Also check if we can train a second model and export it.
filename2 = tempfile.NamedTemporaryFile(suffix=".mlmodel").name
# We also test at the same time if we can export a model with a single
# class
sf = tc.SFrame(
{
"image": [self.sf[self.feature][0]],
"ann": [self.sf[self.annotations][0][:1]],
}
)
model2 = tc.object_detector.create(sf, max_iterations=1)
model2.export_coreml(filename2, include_non_maximum_suppression=True)
@pytest.mark.xfail
@unittest.skipIf(
sys.platform != "darwin" or _mac_ver() >= (10, 14),
"GPU selection should fail on macOS 10.13 or below",
)
def test_no_gpu_support_on_unsupported_macos(self):
num_gpus = tc.config.get_num_gpus()
tc.config.set_num_gpus(1)
with self.assertRaises(_ToolkitError):
tc.object_detector.create(self.sf, max_iterations=1)
tc.config.set_num_gpus(num_gpus)
def test__list_fields(self):
model = self.model
fields = model._list_fields()
self.assertEqual(set(fields), set(self.fields_ans))
def test_get(self):
model = self.model
for field in self.fields_ans:
ans = model._get(field)
self.assertTrue(
self.get_ans[field](ans),
"""Get failed in field {}. Output was {}.""".format(field, ans),
)
def test_summary(self):
model = self.model
model.summary()
def test_summary_str(self):
model = self.model
self.assertTrue(isinstance(model.summary("str"), str))
def test_summary_dict(self):
model = self.model
self.assertTrue(isinstance(model.summary("dict"), dict))
def test_summary_invalid_input(self):
model = self.model
with self.assertRaises(_ToolkitError):
model.summary(model.summary("invalid"))
with self.assertRaises(_ToolkitError):
model.summary(model.summary(0))
with self.assertRaises(_ToolkitError):
model.summary(model.summary({}))
def test_repr(self):
# Repr after fit
model = self.model
self.assertEqual(type(str(model)), str)
self.assertEqual(type(model.__repr__()), str)
def test_save_and_load(self):
with test_util.TempDirectory() as filename:
self.model.save(filename)
self.model = tc.load_model(filename)
self.test_predict()
print("Predict passed")
self.test_get()
print("Get passed")
self.test_summary()
print("Summary passed")
self.test__list_fields()
print("List fields passed")
@unittest.skipIf(tc.util._num_available_gpus() == 0, "Requires GPU")
@pytest.mark.gpu
class ObjectDetectorGPUTest(unittest.TestCase):
@classmethod
def setUpClass(self):
self.feature = "myimage"
self.annotations = "myannotations"
self.sf = _get_data(feature=self.feature, annotations=self.annotations)
def test_gpu_save_load_export(self):
old_num_gpus = tc.config.get_num_gpus()
gpu_options = set([old_num_gpus, 0, 1])
for in_gpus in gpu_options:
tc.config.set_num_gpus(in_gpus)
model = tc.object_detector.create(self.sf, max_iterations=1)
for out_gpus in gpu_options:
with test_util.TempDirectory() as path:
model.save(path)
tc.config.set_num_gpus(out_gpus)
model = tc.load_model(path)
model.export_coreml(os.path.join(path, "model.mlmodel"))
tc.config.set_num_gpus(old_num_gpus)
|
const Path = {
ADD_ARTICLE_PAGE: '/article-add-page',
LIST_ARTICLE_PAGE: '/article-list-page',
};
export default Path;
|
// Copyright 2008 The Closure Library 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.
/**
* @fileoverview Namespace with crypto related helper functions.
*/
goog.provide('goog.crypt');
goog.require('goog.array');
goog.require('goog.asserts');
/**
* Turns a string into an array of bytes; a "byte" being a JS number in the
* range 0-255.
* @param {string} str String value to arrify.
* @return {!Array.<number>} Array of numbers corresponding to the
* UCS character codes of each character in str.
*/
goog.crypt.stringToByteArray = function(str) {
var output = [], p = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
while (c > 0xff) {
output[p++] = c & 0xff;
c >>= 8;
}
output[p++] = c;
}
return output;
};
/**
* Turns an array of numbers into the string given by the concatenation of the
* characters to which the numbers correspond.
* @param {Array} array Array of numbers representing characters.
* @return {string} Stringification of the array.
*/
goog.crypt.byteArrayToString = function(array) {
return String.fromCharCode.apply(null, array);
};
/**
* Turns an array of numbers into the hex string given by the concatenation of
* the hex values to which the numbers correspond.
* @param {Uint8Array|Int8Array|Array.<number>} array Array of numbers
* representing characters.
* @return {string} Hex string.
*/
goog.crypt.byteArrayToHex = function(array) {
return goog.array.map(array, function(numByte) {
var hexByte = numByte.toString(16);
return hexByte.length > 1 ? hexByte : '0' + hexByte;
}).join('');
};
/**
* Converts a hex string into an integer array.
* @param {string} hexString Hex string of 16-bit integers (two characters
* per integer).
* @return {!Array.<number>} Array of {0,255} integers for the given string.
*/
goog.crypt.hexToByteArray = function(hexString) {
goog.asserts.assert(hexString.length % 2 == 0,
'Key string length must be multiple of 2');
var arr = [];
for (var i = 0; i < hexString.length; i += 2) {
arr.push(parseInt(hexString.substring(i, i + 2), 16));
}
return arr;
};
/**
* Converts a JS string to a UTF-8 "byte" array.
* @param {string} str 16-bit unicode string.
* @return {Array.<number>} UTF-8 byte array.
*/
goog.crypt.stringToUtf8ByteArray = function(str) {
// TODO(user): Use native implementations if/when available
str = str.replace(/\r\n/g, '\n');
var out = [], p = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c < 128) {
out[p++] = c;
} else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
} else {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return out;
};
/**
* Converts a UTF-8 byte array to JavaScript's 16-bit Unicode.
* @param {Uint8Array|Int8Array|Array.<number>} bytes UTF-8 byte array.
* @return {string} 16-bit Unicode string.
*/
goog.crypt.utf8ByteArrayToString = function(bytes) {
// TODO(user): Use native implementations if/when available
var out = [], pos = 0, c = 0;
while (pos < bytes.length) {
var c1 = bytes[pos++];
if (c1 < 128) {
out[c++] = String.fromCharCode(c1);
} else if (c1 > 191 && c1 < 224) {
var c2 = bytes[pos++];
out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
} else {
var c2 = bytes[pos++];
var c3 = bytes[pos++];
out[c++] = String.fromCharCode(
(c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
}
}
return out.join('');
};
/**
* XOR two byte arrays.
* @param {!ArrayBufferView|!Array.<number>} bytes1 Byte array 1.
* @param {!ArrayBufferView|!Array.<number>} bytes2 Byte array 2.
* @return {!Array.<number>} Resulting XOR of the two byte arrays.
*/
goog.crypt.xorByteArray = function(bytes1, bytes2) {
goog.asserts.assert(
bytes1.length == bytes2.length,
'XOR array lengths must match');
var result = [];
for (var i = 0; i < bytes1.length; i++) {
result.push(bytes1[i] ^ bytes2[i]);
}
return result;
};
|
import { all, fork } from "redux-saga/effects";
import postSaga from "./post";
import userSaga from "./user";
import scoreSaga from "./score";
import actionSaga from "./action";
export default function* rootSaga() {
yield all([
fork(postSaga),
fork(userSaga),
fork(scoreSaga),
fork(actionSaga),
]);
}
|
export default () => {
$('#blogTitle').after('<div class="nav-open"></div>')
$('#blogTitle').after('<div class="theme"></div>')
}
|
from brownie import OurToken, config, network
from scripts.helpful_scripts import get_account
from web3 import Web3
initial_supply = Web3.toWei(1000, "ether")
def main():
account = get_account()
our_token = OurToken.deploy(
initial_supply,
{"from": account},
publish_source=config["networks"][network.show_active()].get(
"verify", False)
)
print(our_token.name())
|
from libs import reaction
class Reaction(reaction.AdminReactionAddCommand):
'''Sets emojis to commands in servers
This works alongside `set_emoji`
**Usage**
React with an emoji to the message sent in response to `emoji_starter` to use that emoji
To learn how to use `emoji_starter`
```@Idea help emoji_starter ``` '''
def __init__(self, *args, **kwargs):
self.emoji=None
super().__init__(*args, **kwargs)
#print(self.emoji is None)
def matches(self, reaction, user):
return reaction.message.id in self.public_namespace.active_emoji_messages
def action(self, reaction, user, bot):
if isinstance(reaction.emoji, str):
emoji_id = reaction.emoji
else:
emoji_id = reaction.emoji.id
if isinstance(bot.reactions[self.public_namespace.active_emoji_messages[reaction.message.id]].emoji, dict):
bot.reactions[self.public_namespace.active_emoji_messages[reaction.message.id]].emoji[reaction.message.server.id]=emoji_id
else:
bot.reactions[self.public_namespace.active_emoji_messages[reaction.message.id]].emoji={reaction.message.server.id:emoji_id}
del(self.public_namespace.active_emoji_messages[reaction.message.id]) # remove message watch
yield from self.send_message(reaction.message.channel, "Success!")
|
"use strict";
/*-----------------------------------------
NoUiSlider - Property Fields
1. Price Range
2. Area Size
3. Lot Size
4. Year Built
------------------------------------------*/
// 1. Price Range
if ($('#property-price-range')[0]) {
var propertyPriceRange = document.getElementById('property-price-range');
var propertyPriceRangeValues = [
document.getElementById('property-price-upper'),
document.getElementById('property-price-lower')
]
noUiSlider.create (propertyPriceRange, {
start: [12000, 70000],
connect: true,
range: {
'min': 12000,
'max': 70000
}
});
propertyPriceRange.noUiSlider.on('update', function( values, handle ) {
propertyPriceRangeValues[handle].innerHTML = values[handle];
});
}
// 2. Property Area Size
if ($('#property-area-range')[0]) {
var propertyAreaRange = document.getElementById('property-area-range');
var propertyAreaRangeValues = [
document.getElementById('property-area-upper'),
document.getElementById('property-area-lower')
]
noUiSlider.create (propertyAreaRange, {
start: [3500, 10000],
connect: true,
range: {
'min': 3500,
'max': 10000
}
});
propertyAreaRange.noUiSlider.on('update', function( values, handle ) {
propertyAreaRangeValues[handle].innerHTML = values[handle];
});
}
// 3. Lot Size
if ($('#property-lot-range')[0]) {
var propertyLotRange = document.getElementById('property-lot-range');
var propertyLotRangeValues = [
document.getElementById('property-lot-upper'),
document.getElementById('property-lot-lower')
]
noUiSlider.create (propertyLotRange, {
start: [1000, 5000],
connect: true,
range: {
'min': 1000,
'max': 5000
}
});
propertyLotRange.noUiSlider.on('update', function( values, handle ) {
propertyLotRangeValues[handle].innerHTML = values[handle];
});
}
// 3. Year Built
if ($('#property-year-built')[0]) {
var propertyYbRange = document.getElementById('property-year-built');
var propertyYbRangeValues = [
document.getElementById('property-yb-upper'),
document.getElementById('property-yb-lower')
]
noUiSlider.create (propertyYbRange, {
start: [1990, 2019],
connect: true,
range: {
'min': 1990,
'max': 2019
}
});
propertyYbRange.noUiSlider.on('update', function( values, handle ) {
propertyYbRangeValues[handle].innerHTML = Math.round(values[handle]);
});
}
$(document).ready(function () {
/*-----------------------------------------------------
Submit property steps switch
- used in last form tab of 'submit-property.html'
------------------------------------------------------*/
$('body').on('shown.bs.tab', '.submit-property__button', function () {
var currentTab = $(this).attr('href');
$('.submit-property__steps > li').removeClass('active');
$('.submit-property__steps > li > a[href='+currentTab+']').parent().addClass('active');
})
/*-----------------------------------------------------
Calendar and Calendar Widget
- Used in dashboard index and calendar pages
------------------------------------------------------*/
if($('#calendar-widget')[0]) {
$('.calendar-widget__body').fullCalendar({
contentHeight: 'auto',
theme: false,
header: {
right: 'next',
center: 'title, ',
left: 'prev'
},
buttonIcons: {
prev: 'left',
next: 'right'
},
// defaultDate: '2016-08-12',
editable: true,
events: [
// {
// title: 'Dolor Pellentesque',
// start: '2016-08-01',
// className: 'fc-event--cyan'
// },
// {
// title: 'Purus Nibh',
// start: '2016-08-07',
// className: 'fc-event--amber'
// },
// {
// title: 'Amet Condimentum',
// start: '2016-08-09',
// className: 'fc-event--green'
// },
// {
// title: 'Tellus',
// start: '2016-08-12',
// className: 'fc-event--blue'
// },
// {
// title: 'Vestibulum',
// start: '2016-08-18',
// className: 'fc-event--cyan'
// },
// {
// title: 'Ipsum',
// start: '2016-08-24',
// className: 'fc-event--teal'
// },
// {
// title: 'Fringilla Sit',
// start: '2016-08-27',
// className: 'fc-event--blue'
// },
// {
// title: 'Amet Pharetra',
// url: 'http://google.com/',
// start: '2016-08-30',
// className: 'mdc-bg-amber-500'
// }
]
});
//Display Current Date as Calendar widget header
var mYear = moment().format('YYYY');
var mDay = moment().format('dddd, MMM D');
$('.calendar-widget__year').html(mYear);
$('.calendar-widget__day').html(mDay);
}
/*-----------------------------------------------------
Demo list delete
- Used in dashboaed/listings.html
------------------------------------------------------*/
if($('[data-demo-action="delete-listing"]')[0]) {
$('[data-demo-action="delete-listing"]').click(function (e) {
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function() {
swal(
'Deleted!',
'Your list has been deleted.',
'success'
);
})
});
}
});
|
from trezor import wire
from trezor.crypto import bip32
from apps.cardano import CURVE, SEED_NAMESPACE
from apps.common import cache, mnemonic, storage
from apps.common.request_passphrase import protect_by_passphrase
class Keychain:
def __init__(self, path: list, root: bip32.HDNode):
self.path = path
self.root = root
def validate_path(self, checked_path: list, checked_curve: str):
if checked_curve != CURVE or checked_path[:2] != SEED_NAMESPACE:
raise wire.DataError("Forbidden key path")
def derive(self, node_path: list) -> bip32.HDNode:
# check we are in the cardano namespace
prefix = node_path[: len(self.path)]
suffix = node_path[len(self.path) :]
if prefix != self.path:
raise wire.DataError("Forbidden key path")
# derive child node from the root
node = self.root.clone()
for i in suffix:
node.derive_cardano(i)
return node
async def get_keychain(ctx: wire.Context) -> Keychain:
if not storage.is_initialized():
raise wire.ProcessError("Device is not initialized")
# derive the root node from mnemonic and passphrase
passphrase = cache.get_passphrase()
if passphrase is None:
passphrase = await protect_by_passphrase(ctx)
cache.set_passphrase(passphrase)
root = bip32.from_mnemonic_cardano(mnemonic.restore(), passphrase)
# derive the namespaced root node
for i in SEED_NAMESPACE:
root.derive_cardano(i)
keychain = Keychain(SEED_NAMESPACE, root)
return keychain
|
/*
* Kendo UI v2014.2.716 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(e,define){define([],e)}(function(){return function(e){var t=e.kendo||(e.kendo={cultures:{}});t.cultures.fi={name:"fi",numberFormat:{pattern:["-n"],decimals:2,",":" ",".":",",groupSize:[3],percent:{pattern:["-n %","n %"],decimals:2,",":" ",".":",",groupSize:[3],symbol:"%"},currency:{pattern:["-n $","n $"],decimals:2,",":" ",".":",",groupSize:[3],symbol:"€"}},calendars:{standard:{days:{names:["sunnuntai","maanantai","tiistai","keskiviikko","torstai","perjantai","lauantai"],namesAbbr:["su","ma","ti","ke","to","pe","la"],namesShort:["su","ma","ti","ke","to","pe","la"]},months:{names:["tammikuu","helmikuu","maaliskuu","huhtikuu","toukokuu","kesäkuu","heinäkuu","elokuu","syyskuu","lokakuu","marraskuu","joulukuu",""],namesAbbr:["tammi","helmi","maalis","huhti","touko","kesä","heinä","elo","syys","loka","marras","joulu",""]},AM:[""],PM:[""],patterns:{d:"d.M.yyyy",D:"d. MMMM'ta 'yyyy",F:"d. MMMM'ta 'yyyy H:mm:ss",g:"d.M.yyyy H:mm",G:"d.M.yyyy H:mm:ss",m:"d. MMMM'ta'",M:"d. MMMM'ta'",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"H:mm",T:"H:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM yyyy",Y:"MMMM yyyy"},"/":".",":":":",firstDay:1}}}}(this),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()});
|
/* eslint-disable react/button-has-type */
/**
*
* ListBook
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
// import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';
import { useInjectSaga } from 'utils/injectSaga';
import { useInjectReducer } from 'utils/injectReducer';
import {
makeSelectIsCallApi,
makeSelectIsLoading,
makeSelectLimit,
makeSelectLoading,
makeSelectOffset,
makeSelectRepos,
makeSelectIsButton,
} from './selectors';
import reducer from './reducer';
import saga from './saga';
// import messages from './messages';
import { loadListBook } from './actions';
import Loading from '../loading';
export function ListBook({
getListBook,
listBook,
isLoadMore,
isCallApi,
isLoding,
offset,
limit,
isButton,
}) {
useInjectReducer({ key: 'listBook', reducer });
useInjectSaga({ key: 'listBook', saga });
React.useEffect(() => {
if (!isCallApi) getListBook(limit, offset, isLoadMore);
}, [isCallApi]);
// console.log(
// `limit ${limit} --- offset ${offset} --- isLoadMore ${isLoadMore}`,
// );
const [value, setValue] = React.useState('');
const handleSearch = e => {
e.preventDefault();
if (value !== undefined) {
getListBook(limit, offset, true, value);
} else {
getListBook(limit, 0);
}
};
const handleGetValue = e => {
setValue(e.target.value);
};
return (
<div>
<Helmet>
<title>ListBook</title>
<meta name="description" content="Description of ListBook" />
</Helmet>
{/* <FormattedMessage {...messages.header} /> */}
<br />
<form onSubmit={handleSearch} style={{ textAlign: 'center' }}>
<input
type="text"
name="search"
onChange={handleGetValue}
style={{ width: '500px' }}
/>
<button>Search</button>
</form>
<br />
{isLoding ? (
<div>
<table style={{ border: '1px solid black', width: '100%' }}>
{/* <tr style={{ border: '1px solid black' }}>
<td style={{ border: '1px solid black', width: '10%' }}>No</td>
<td style={{ border: '1px solid black', width: '30%' }}>Title</td>
<td style={{ border: '1px solid black', width: '50%' }}>
Description
</td>
<td style={{ border: '1px solid black', width: '10%' }}>Price</td>
</tr> */}
{listBook &&
listBook.length > 0 &&
listBook.map((item, idx) => (
<tr key={idx.toString()} style={{ border: '1px solid black' }}>
<td style={{ border: '1px solid black', width: '10%' }}>
{idx + 1}
</td>
<td style={{ border: '1px solid black', width: '30%' }}>
{item.title}
</td>
<td style={{ border: '1px solid black', width: '50%' }}>
{item.body}
</td>
<td style={{ border: '1px solid black', width: '10%' }}>
{item.price} $
</td>
</tr>
))}
</table>
<br />
{isButton ? (
''
) : (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{isLoadMore ? (
<Loading />
) : (
<button onClick={() => getListBook(limit, offset, true)}>
Load more
</button>
)}
</div>
)}
<br />
</div>
) : (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
}}
>
<Loading />
</div>
)}
</div>
);
}
ListBook.propTypes = {
// dispatch: PropTypes.func.isRequired,
getListBook: PropTypes.func,
listBook: PropTypes.any,
isLoadMore: PropTypes.bool,
isCallApi: PropTypes.bool,
isLoding: PropTypes.bool,
limit: PropTypes.number,
offset: PropTypes.number,
isButton: PropTypes.bool,
};
const mapStateToProps = createStructuredSelector({
// listBook: makeSelectListBook(),
listBook: makeSelectRepos(),
isLoadMore: makeSelectLoading(),
isCallApi: makeSelectIsCallApi(),
isLoding: makeSelectIsLoading(),
limit: makeSelectLimit(),
offset: makeSelectOffset(),
isButton: makeSelectIsButton(),
});
function mapDispatchToProps(dispatch) {
return {
getListBook: (limit, offset, isLoadMore, text) =>
dispatch(loadListBook(limit, offset, isLoadMore, text)),
isCall: () => dispatch(loadListBook()),
};
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
export default compose(withConnect)(ListBook);
|
'use strict';
exports.__esModule = true;
exports.default = {
el: {
colorpicker: {
confirm: 'جەزملەش',
clear: 'قۇرۇقداش'
},
datepicker: {
now: 'ھازىرقى ۋاقىت',
today: 'بۈگۈن',
cancel: 'بىكار قىلىش',
clear: 'قۇرۇقداش',
confirm: 'جەزملەش',
selectDate: 'چىسلا تاللاڭ',
selectTime: 'ۋاقىت تاللاڭ',
startDate: 'باشلانغان چىسلا',
startTime: 'باشلانغان ۋاقىت',
endDate: 'ئاخىرلاشقان چىسلا',
endTime: 'ئاخىرلاشقان ۋاقىت',
prevYear: 'ئالدىنقى يىل',
nextYear: 'كىيىنكى يىل',
prevMonth: 'ئالدىنقى ئاي',
nextMonth: 'كىيىنكى ئاي',
year: '- يىل',
month1: '1-ئاي',
month2: '2-ئاي',
month3: '3-ئاي',
month4: '4-ئاي',
month5: '5-ئاي',
month6: '6-ئاي',
month7: '7-ئاي',
month8: '8-ئاي',
month9: '9-ئاي',
month10: '10-ئاي',
month11: '11-ئاي',
month12: '12-ئاي',
// week: '周次',
weeks: {
sun: 'يەكشەنبە',
mon: 'دۈشەنبە',
tue: 'سەيشەنبە',
wed: 'چارشەنبە',
thu: 'پەيشەنبە',
fri: 'جۈمە',
sat: 'شەنبە'
},
months: {
jan: '1-ئاي',
feb: '2-ئاي',
mar: '3-ئاي',
apr: '4-ئاي',
may: '5-ئاي',
jun: '6-ئاي',
jul: '7-ئاي',
aug: '8-ئاي',
sep: '9-ئاي',
oct: '10-ئاي',
nov: '11-ئاي',
dec: '12-ئاي'
}
},
select: {
loading: 'يۈكلىنىۋاتىدۇ',
noMatch: 'ئۇچۇر تېپىلمىدى',
noData: 'ئۇچۇر يوق',
placeholder: 'تاللاڭ'
},
cascader: {
noMatch: 'ئۇچۇر تېپىلمىدى',
loading: 'يۈكلىنىۋاتىدۇ',
placeholder: 'تاللاڭ',
noData: 'ئۇچۇر يوق'
},
pagination: {
goto: 'كىيىنكى بەت',
pagesize: 'تال/بەت',
total: 'جەمئىي {total} تال',
pageClassifier: 'بەت'
},
messagebox: {
title: 'ئەسكەرتىش',
confirm: 'جەزملەش',
cancel: 'بىكار قىلىش',
error: 'كىرگۈزگەن ئۇچۇرىڭىزدا خاتالىق بار!'
},
upload: {
deleteTip: 'delete كۇنپكىسىنى بېسىپ ئۆچۈرەلەيسىز',
delete: 'ئۆچۈرۈش',
preview: 'رەسىمنى كۆرۈش',
continue: 'رەسىم يوللاش'
},
table: {
emptyText: 'ئۇچۇر يوق',
confirmFilter: 'سۈزگۈچ',
resetFilter: 'قايتا تولدۇرۇش',
clearFilter: 'ھەممە',
sumText: 'جەمئىي'
},
tree: {
emptyText: 'ئۇچۇر يوق'
},
transfer: {
noMatch: 'ئۇچۇر تېپىلمىدى',
noData: 'ئۇچۇر يوق',
titles: ['جەدۋەل 1', 'جەدۋەل 2'],
filterPlaceholder: 'ئىزدىمەكچى بولغان مەزمۇننى كىرگۈزۈڭ',
noCheckedFormat: 'جەمئىي {total} تۈر',
hasCheckedFormat: 'تاللانغىنى {checked}/{total} تۈر'
},
image: {
error: 'مەغلۇب بولدى'
},
pageHeader: {
title: 'قايتىش'
},
popconfirm: {
confirmButtonText: 'ھەئە',
cancelButtonText: 'ياق'
},
empty: {
description: 'ئۇچۇر يوق'
}
}
};
|
/**
* Copyright (c) 2015-present, Horcrux.
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "ABI36_0_0RNSVGRenderableManager.h"
@interface ABI36_0_0RNSVGRectManager : ABI36_0_0RNSVGRenderableManager
@end
|
const ciqlJson = require(".")
describe('Tester toute les fonctions du module ciql-json', () => {
test('La fonction Open', () => {
expect(ciqlJson.open("yarn.lock"))
expect(ciqlJson.open("packagef.jsn"))
expect(ciqlJson
.open("package.json")
.set('location', 'abidjan')
.set('adress.nom', '')
.extract('{name, location, scripts, adress}')
.getData())
})
test('Create ', () => {
expect(ciqlJson.create())
expect(ciqlJson.create({ nom: "edy" }).save())
const data = ciqlJson.create({ nom: 'edy', prenoms: 'koffi', age: 15 }).extract("{age}").getData()
expect(data).toEqual({ age: 15 })
});
test('extract and error catch', () => {
expect(ciqlJson.create({}).extract(""))
expect(ciqlJson.create({}).set())
expect(
ciqlJson
.create({ school: {} })
.set("school.name", "ESATIC")
.set("school.location", "Treichville")
.getData()
).toEqual({ school: { name: "ESATIC", location: "Treichville", } })
});
test('La fonction pushTo', () => {
expect(
ciqlJson
.create({ school: "ESATIC", courses: [] })
.pushTo("courses", "Data Sciences", "MERISE")
.getData()
).toEqual({ school: "ESATIC", courses: ["Data Sciences", "MERISE"] })
});
test('La fonction popTo', () => {
expect(
ciqlJson
.create({ school: "ESATIC", courses: ["Data Sciences", "MERISE"] })
.popTo("courses")
.getData()
).toEqual({ school: "ESATIC", courses: ["Data Sciences"] })
});
test('version', () => {
let t = ciqlJson.create({}).set("1.2.3", { name: "edy" }).getData()
expect(t).toEqual({ "1.2.3": { name: "edy" } })
});
test('getValues', () => {
let t = ciqlJson.create({}).set("1.2.3", { name: "edy" }).getValues()
expect(t).toEqual([{ name: "edy" }])
});
test('getKeys', () => {
let t = ciqlJson.create({}).set("1.2.3", { name: "edy" }).getKeys()
expect(t).toEqual(["1.2.3"])
});
test('save', () => {
expect(
ciqlJson
.create({})
.popTo("courses")
.pushTo("courses","edy","koffi")
.save()
)
});
test('remove', () => {
expect(
ciqlJson
.create({nom:"edy", age : 15})
.remove("age")
.getData()
)
});
})
|
def load(info):
import plugin_module
plugin_module.test()
|
# Copyright (c) 2021 ING Wholesale Banking Advanced Analytics
#
# 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.
# histogram and report functions
from histogrammar.dfinterface.make_histograms import (
get_bin_specs,
get_time_axes,
make_histograms,
)
# pandas/spark dataframe decorators
from popmon import decorators
from .pipeline.metrics import df_stability_metrics, stability_metrics
from .pipeline.report import df_stability_report, stability_report
from .stitching import stitch_histograms
from .version import version as __version__
|
'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 _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _Editor = require('../Editor');
var _Editor2 = _interopRequireDefault(_Editor);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint react/display-name: 0 */
var InsertModalBody = function (_Component) {
_inherits(InsertModalBody, _Component);
function InsertModalBody() {
_classCallCheck(this, InsertModalBody);
return _possibleConstructorReturn(this, (InsertModalBody.__proto__ || Object.getPrototypeOf(InsertModalBody)).apply(this, arguments));
}
_createClass(InsertModalBody, [{
key: 'getFieldValue',
value: function getFieldValue() {
var _this2 = this;
var newRow = {};
this.props.columns.forEach(function (column, i) {
var inputVal = void 0;
if (column.autoValue) {
// when you want same auto generate value and not allow edit, example ID field
var time = new Date().getTime();
inputVal = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time;
} else if (column.hiddenOnInsert || !column.field) {
inputVal = '';
} else {
var dom = _this2.refs[column.field + i];
inputVal = dom.value;
if (column.editable && column.editable.type === 'checkbox') {
var values = inputVal.split(':');
inputVal = dom.checked ? values[0] : values[1];
} else if (column.customInsertEditor) {
inputVal = inputVal || dom.getFieldValue();
}
}
newRow[column.field] = inputVal;
}, this);
return newRow;
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
columns = _props.columns,
validateState = _props.validateState,
ignoreEditable = _props.ignoreEditable;
return _react2.default.createElement(
'div',
{ className: 'modal-body' },
columns.map(function (column, i) {
var editable = column.editable,
format = column.format,
field = column.field,
name = column.name,
autoValue = column.autoValue,
hiddenOnInsert = column.hiddenOnInsert,
customInsertEditor = column.customInsertEditor;
var attr = {
ref: field + i,
placeholder: editable.placeholder ? editable.placeholder : name
};
var fieldElement = void 0;
var defaultValue = editable.defaultValue || undefined;
if (customInsertEditor) {
var getElement = customInsertEditor.getElement;
fieldElement = getElement(column, attr, 'form-control', ignoreEditable, defaultValue);
}
// fieldElement = false, means to use default editor when enable custom editor
// Becasuse some users want to have default editor based on some condition.
if (!customInsertEditor || fieldElement === false) {
fieldElement = (0, _Editor2.default)(editable, attr, format, '', defaultValue, ignoreEditable);
}
if (autoValue || hiddenOnInsert || !column.field) {
// when you want same auto generate value
// and not allow edit, for example ID field
return null;
}
var error = validateState[field] ? _react2.default.createElement(
'span',
{ className: 'help-block bg-danger' },
validateState[field]
) : null;
return _react2.default.createElement(
'div',
{ className: 'form-group', key: field },
_react2.default.createElement(
'label',
null,
name
),
fieldElement,
error
);
})
);
}
}]);
return InsertModalBody;
}(_react.Component);
InsertModalBody.propTypes = {
columns: _propTypes2.default.array,
validateState: _propTypes2.default.object,
ignoreEditable: _propTypes2.default.bool
};
InsertModalBody.defaultProps = {
validateState: {},
ignoreEditable: false
};
var _default = InsertModalBody;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(InsertModalBody, 'InsertModalBody', '/Users/pkalita/GitHub/react-bootstrap-table/src/toolbar/InsertModalBody.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/pkalita/GitHub/react-bootstrap-table/src/toolbar/InsertModalBody.js');
}();
;
|
# -*- coding: utf-8 -*-
'''
Support for hadoop
:maintainer: Yann Jouanin <yann.jouanin@intelunix.fr>
:maturity: new
:depends:
:platform: linux
'''
from __future__ import absolute_import
# Import salt libs
import salt.utils
__authorized_modules__ = ['namenode', 'dfsadmin', 'dfs', 'fs']
def __virtual__():
'''
Check if hadoop is present, then load the module
'''
if salt.utils.which('hadoop'):
return 'hadoop'
return False
def version():
'''
Return version from hadoop version
CLI Example:
.. code-block:: bash
salt '*' hadoop.version
'''
cmd = 'hadoop version'
out = __salt__['cmd.run'](cmd).split()
return out[1]
def _hadoop_cmd(module, command, *args):
'''
Hadoop command wrapper
In order to prevent random execution the module name is checked
Follows hadoop command template:
hadoop module -command args
E.g.: hadoop dfs -ls /
'''
out = None
if module and command:
if module in __authorized_modules__:
cmd = 'hadoop {0} -{1} {2}'.format(module, command, ' '.join(args))
out = __salt__['cmd.run'](cmd)
else:
return 'Error: Unknown module'
else:
return 'Error: Module and command not defined'
return out
def dfs(command=None, *args):
'''
Execute a command on DFS
CLI Example:
.. code-block:: bash
salt '*' hadoop.dfs ls /
'''
if command:
return _hadoop_cmd('dfs', command, *args)
else:
return 'Error: command must be provided'
def dfs_present(path):
'''
Check if a file or directory is present on the distributed FS.
CLI Example:
.. code-block:: bash
salt '*' hadoop.dfs_present /some_random_file
Returns True if the file is present
'''
cmd_return = _hadoop_cmd('dfs', 'stat', path)
if 'No such file or directory' in cmd_return:
return False
else:
return True
def dfs_absent(path):
'''
Check if a file or directory is absent on the distributed FS.
CLI Example:
.. code-block:: bash
salt '*' hadoop.dfs_absent /some_random_file
Returns True if the file is absent
'''
cmd_return = _hadoop_cmd('dfs', 'stat', path)
if 'No such file or directory' in cmd_return:
return True
else:
return False
def namenode_format(force=None):
'''
Format a name node
.. code-block:: bash
salt '*' hadoop.namenode_format force=True
'''
force_param = ''
if force:
force_param = '-force'
return _hadoop_cmd('namenode', 'format', '-nonInteractive', force_param)
|
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* monaco-languages version: 1.7.0(987f04155a65e564c5b8cc137f18c76785a3d814)
* Released under the MIT license
* https://github.com/Microsoft/monaco-languages/blob/master/LICENSE.md
*-----------------------------------------------------------------------------*/
define("vs/basic-languages/pgsql/pgsql",["require","exports"],function(_,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.conf={comments:{lineComment:"--",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}]},e.language={defaultToken:"",tokenPostfix:".sql",ignoreCase:!0,brackets:[{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"}],keywords:["A","ABORT","ABS","ABSENT","ABSOLUTE","ACCESS","ACCORDING","ACTION","ADA","ADD","ADMIN","AFTER","AGGREGATE","ALL","ALLOCATE","ALSO","ALTER","ALWAYS","ANALYSE","ANALYZE","AND","ANY","ARE","ARRAY","ARRAY_AGG","ARRAY_MAX_CARDINALITY","AS","ASC","ASENSITIVE","ASSERTION","ASSIGNMENT","ASYMMETRIC","AT","ATOMIC","ATTRIBUTE","ATTRIBUTES","AUTHORIZATION","AVG","BACKWARD","BASE64","BEFORE","BEGIN","BEGIN_FRAME","BEGIN_PARTITION","BERNOULLI","BETWEEN","BIGINT","BINARY","BIT","BIT_LENGTH","BLOB","BLOCKED","BOM","BOOLEAN","BOTH","BREADTH","BY","C","CACHE","CALL","CALLED","CARDINALITY","CASCADE","CASCADED","CASE","CAST","CATALOG","CATALOG_NAME","CEIL","CEILING","CHAIN","CHAR","CHARACTER","CHARACTERISTICS","CHARACTERS","CHARACTER_LENGTH","CHARACTER_SET_CATALOG","CHARACTER_SET_NAME","CHARACTER_SET_SCHEMA","CHAR_LENGTH","CHECK","CHECKPOINT","CLASS","CLASS_ORIGIN","CLOB","CLOSE","CLUSTER","COALESCE","COBOL","COLLATE","COLLATION","COLLATION_CATALOG","COLLATION_NAME","COLLATION_SCHEMA","COLLECT","COLUMN","COLUMNS","COLUMN_NAME","COMMAND_FUNCTION","COMMAND_FUNCTION_CODE","COMMENT","COMMENTS","COMMIT","COMMITTED","CONCURRENTLY","CONDITION","CONDITION_NUMBER","CONFIGURATION","CONFLICT","CONNECT","CONNECTION","CONNECTION_NAME","CONSTRAINT","CONSTRAINTS","CONSTRAINT_CATALOG","CONSTRAINT_NAME","CONSTRAINT_SCHEMA","CONSTRUCTOR","CONTAINS","CONTENT","CONTINUE","CONTROL","CONVERSION","CONVERT","COPY","CORR","CORRESPONDING","COST","COUNT","COVAR_POP","COVAR_SAMP","CREATE","CROSS","CSV","CUBE","CUME_DIST","CURRENT","CURRENT_CATALOG","CURRENT_DATE","CURRENT_DEFAULT_TRANSFORM_GROUP","CURRENT_PATH","CURRENT_ROLE","CURRENT_ROW","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TRANSFORM_GROUP_FOR_TYPE","CURRENT_USER","CURSOR","CURSOR_NAME","CYCLE","DATA","DATABASE","DATALINK","DATE","DATETIME_INTERVAL_CODE","DATETIME_INTERVAL_PRECISION","DAY","DB","DEALLOCATE","DEC","DECIMAL","DECLARE","DEFAULT","DEFAULTS","DEFERRABLE","DEFERRED","DEFINED","DEFINER","DEGREE","DELETE","DELIMITER","DELIMITERS","DENSE_RANK","DEPENDS","DEPTH","DEREF","DERIVED","DESC","DESCRIBE","DESCRIPTOR","DETERMINISTIC","DIAGNOSTICS","DICTIONARY","DISABLE","DISCARD","DISCONNECT","DISPATCH","DISTINCT","DLNEWCOPY","DLPREVIOUSCOPY","DLURLCOMPLETE","DLURLCOMPLETEONLY","DLURLCOMPLETEWRITE","DLURLPATH","DLURLPATHONLY","DLURLPATHWRITE","DLURLSCHEME","DLURLSERVER","DLVALUE","DO","DOCUMENT","DOMAIN","DOUBLE","DROP","DYNAMIC","DYNAMIC_FUNCTION","DYNAMIC_FUNCTION_CODE","EACH","ELEMENT","ELSE","EMPTY","ENABLE","ENCODING","ENCRYPTED","END","END-EXEC","END_FRAME","END_PARTITION","ENFORCED","ENUM","EQUALS","ESCAPE","EVENT","EVERY","EXCEPT","EXCEPTION","EXCLUDE","EXCLUDING","EXCLUSIVE","EXEC","EXECUTE","EXISTS","EXP","EXPLAIN","EXPRESSION","EXTENSION","EXTERNAL","EXTRACT","FALSE","FAMILY","FETCH","FILE","FILTER","FINAL","FIRST","FIRST_VALUE","FLAG","FLOAT","FLOOR","FOLLOWING","FOR","FORCE","FOREIGN","FORTRAN","FORWARD","FOUND","FRAME_ROW","FREE","FREEZE","FROM","FS","FULL","FUNCTION","FUNCTIONS","FUSION","G","GENERAL","GENERATED","GET","GLOBAL","GO","GOTO","GRANT","GRANTED","GREATEST","GROUP","GROUPING","GROUPS","HANDLER","HAVING","HEADER","HEX","HIERARCHY","HOLD","HOUR","ID","IDENTITY","IF","IGNORE","ILIKE","IMMEDIATE","IMMEDIATELY","IMMUTABLE","IMPLEMENTATION","IMPLICIT","IMPORT","IN","INCLUDING","INCREMENT","INDENT","INDEX","INDEXES","INDICATOR","INHERIT","INHERITS","INITIALLY","INLINE","INNER","INOUT","INPUT","INSENSITIVE","INSERT","INSTANCE","INSTANTIABLE","INSTEAD","INT","INTEGER","INTEGRITY","INTERSECT","INTERSECTION","INTERVAL","INTO","INVOKER","IS","ISNULL","ISOLATION","JOIN","K","KEY","KEY_MEMBER","KEY_TYPE","LABEL","LAG","LANGUAGE","LARGE","LAST","LAST_VALUE","LATERAL","LEAD","LEADING","LEAKPROOF","LEAST","LEFT","LENGTH","LEVEL","LIBRARY","LIKE","LIKE_REGEX","LIMIT","LINK","LISTEN","LN","LOAD","LOCAL","LOCALTIME","LOCALTIMESTAMP","LOCATION","LOCATOR","LOCK","LOCKED","LOGGED","LOWER","M","MAP","MAPPING","MATCH","MATCHED","MATERIALIZED","MAX","MAXVALUE","MAX_CARDINALITY","MEMBER","MERGE","MESSAGE_LENGTH","MESSAGE_OCTET_LENGTH","MESSAGE_TEXT","METHOD","MIN","MINUTE","MINVALUE","MOD","MODE","MODIFIES","MODULE","MONTH","MORE","MOVE","MULTISET","MUMPS","NAME","NAMES","NAMESPACE","NATIONAL","NATURAL","NCHAR","NCLOB","NESTING","NEW","NEXT","NFC","NFD","NFKC","NFKD","NIL","NO","NONE","NORMALIZE","NORMALIZED","NOT","NOTHING","NOTIFY","NOTNULL","NOWAIT","NTH_VALUE","NTILE","NULL","NULLABLE","NULLIF","NULLS","NUMBER","NUMERIC","OBJECT","OCCURRENCES_REGEX","OCTETS","OCTET_LENGTH","OF","OFF","OFFSET","OIDS","OLD","ON","ONLY","OPEN","OPERATOR","OPTION","OPTIONS","OR","ORDER","ORDERING","ORDINALITY","OTHERS","OUT","OUTER","OUTPUT","OVER","OVERLAPS","OVERLAY","OVERRIDING","OWNED","OWNER","P","PAD","PARALLEL","PARAMETER","PARAMETER_MODE","PARAMETER_NAME","PARAMETER_ORDINAL_POSITION","PARAMETER_SPECIFIC_CATALOG","PARAMETER_SPECIFIC_NAME","PARAMETER_SPECIFIC_SCHEMA","PARSER","PARTIAL","PARTITION","PASCAL","PASSING","PASSTHROUGH","PASSWORD","PATH","PERCENT","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","PERIOD","PERMISSION","PLACING","PLANS","PLI","POLICY","PORTION","POSITION","POSITION_REGEX","POWER","PRECEDES","PRECEDING","PRECISION","PREPARE","PREPARED","PRESERVE","PRIMARY","PRIOR","PRIVILEGES","PROCEDURAL","PROCEDURE","PROGRAM","PUBLIC","QUOTE","RANGE","RANK","READ","READS","REAL","REASSIGN","RECHECK","RECOVERY","RECURSIVE","REF","REFERENCES","REFERENCING","REFRESH","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","REINDEX","RELATIVE","RELEASE","RENAME","REPEATABLE","REPLACE","REPLICA","REQUIRING","RESET","RESPECT","RESTART","RESTORE","RESTRICT","RESULT","RETURN","RETURNED_CARDINALITY","RETURNED_LENGTH","RETURNED_OCTET_LENGTH","RETURNED_SQLSTATE","RETURNING","RETURNS","REVOKE","RIGHT","ROLE","ROLLBACK","ROLLUP","ROUTINE","ROUTINE_CATALOG","ROUTINE_NAME","ROUTINE_SCHEMA","ROW","ROWS","ROW_COUNT","ROW_NUMBER","RULE","SAVEPOINT","SCALE","SCHEMA","SCHEMA_NAME","SCOPE","SCOPE_CATALOG","SCOPE_NAME","SCOPE_SCHEMA","SCROLL","SEARCH","SECOND","SECTION","SECURITY","SELECT","SELECTIVE","SELF","SENSITIVE","SEQUENCE","SEQUENCES","SERIALIZABLE","SERVER","SERVER_NAME","SESSION","SESSION_USER","SET","SETOF","SETS","SHARE","SHOW","SIMILAR","SIMPLE","SIZE","SKIP","SMALLINT","SNAPSHOT","SOME","SOURCE","SPACE","SPECIFIC","SPECIFICTYPE","SPECIFIC_NAME","SQL","SQLCODE","SQLERROR","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQRT","STABLE","STANDALONE","START","STATE","STATEMENT","STATIC","STATISTICS","STDDEV_POP","STDDEV_SAMP","STDIN","STDOUT","STORAGE","STRICT","STRIP","STRUCTURE","STYLE","SUBCLASS_ORIGIN","SUBMULTISET","SUBSTRING","SUBSTRING_REGEX","SUCCEEDS","SUM","SYMMETRIC","SYSID","SYSTEM","SYSTEM_TIME","SYSTEM_USER","T","TABLE","TABLES","TABLESAMPLE","TABLESPACE","TABLE_NAME","TEMP","TEMPLATE","TEMPORARY","TEXT","THEN","TIES","TIME","TIMESTAMP","TIMEZONE_HOUR","TIMEZONE_MINUTE","TO","TOKEN","TOP_LEVEL_COUNT","TRAILING","TRANSACTION","TRANSACTIONS_COMMITTED","TRANSACTIONS_ROLLED_BACK","TRANSACTION_ACTIVE","TRANSFORM","TRANSFORMS","TRANSLATE","TRANSLATE_REGEX","TRANSLATION","TREAT","TRIGGER","TRIGGER_CATALOG","TRIGGER_NAME","TRIGGER_SCHEMA","TRIM","TRIM_ARRAY","TRUE","TRUNCATE","TRUSTED","TYPE","TYPES","UESCAPE","UNBOUNDED","UNCOMMITTED","UNDER","UNENCRYPTED","UNION","UNIQUE","UNKNOWN","UNLINK","UNLISTEN","UNLOGGED","UNNAMED","UNNEST","UNTIL","UNTYPED","UPDATE","UPPER","URI","USAGE","USER","USER_DEFINED_TYPE_CATALOG","USER_DEFINED_TYPE_CODE","USER_DEFINED_TYPE_NAME","USER_DEFINED_TYPE_SCHEMA","USING","VACUUM","VALID","VALIDATE","VALIDATOR","VALUE","VALUES","VALUE_OF","VARBINARY","VARCHAR","VARIADIC","VARYING","VAR_POP","VAR_SAMP","VERBOSE","VERSION","VERSIONING","VIEW","VIEWS","VOLATILE","WHEN","WHENEVER","WHERE","WHITESPACE","WIDTH_BUCKET","WINDOW","WITH","WITHIN","WITHOUT","WORK","WRAPPER","WRITE","XML","XMLAGG","XMLATTRIBUTES","XMLBINARY","XMLCAST","XMLCOMMENT","XMLCONCAT","XMLDECLARATION","XMLDOCUMENT","XMLELEMENT","XMLEXISTS","XMLFOREST","XMLITERATE","XMLNAMESPACES","XMLPARSE","XMLPI","XMLQUERY","XMLROOT","XMLSCHEMA","XMLSERIALIZE","XMLTABLE","XMLTEXT","XMLVALIDATE","YEAR","YES","ZONE"],operators:["AND","BETWEEN","IN","LIKE","NOT","OR","IS","NULL","INTERSECT","UNION","INNER","JOIN","LEFT","OUTER","RIGHT"],builtinFunctions:["abbrev","abs","acos","acosd","age","any","area","array_agg","array_append","array_cat","array_dims","array_fill","array_length","array_lower","array_ndims","array_position","array_positions","array_prepend","array_remove","array_replace","array_to_json","array_to_string","array_to_tsvector","array_upper","ascii","asin","asind","atan","atan2","atan2d","atand","avg","bit","bit_and","bit_length","bit_or","bool_and","bool_or","bound_box","box","brin_summarize_new_values","broadcast","btrim","cardinality","cbrt","ceil","ceiling","center","char_length","character_length","chr","circle","clock_timestamp","coalesce","col_description","concat","concat_ws","convert","convert_from","convert_to","corr","cos","cosd","cot","cotd","count","covar_pop","covar_samp","cume_dist","current_catalog","current_database","current_date","current_query","current_role","current_schema","current_schemas","current_setting","current_time","current_timestamp","current_user","currval","cursor_to_xml","date_part","date_trunc","decode","degrees","dense_rank","diameter","div","encode","enum_first","enum_last","enum_range","every","exp","extract","family","first_value","floor","format","format_type","generate_series","generate_subscripts","get_bit","get_byte","get_current_ts_config","gin_clean_pending_list","greatest","grouping","has_any_column_privilege","has_column_privilege","has_database_privilege","has_foreign_data_wrapper_privilege","has_function_privilege","has_language_privilege","has_schema_privilege","has_sequence_privilege","has_server_privilege","has_table_privilege","has_tablespace_privilege","has_type_privilege","height","host","hostmask","inet_client_addr","inet_client_port","inet_merge","inet_same_family","inet_server_addr","inet_server_port","initcap","isclosed","isempty","isfinite","isopen","json_agg","json_object","json_object_agg","json_populate_record","json_populate_recordset","json_to_record","json_to_recordset","jsonb_agg","jsonb_object_agg","justify_days","justify_hours","justify_interval","lag","last_value","lastval","lead","least","left","length","line","ln","localtime","localtimestamp","log","lower","lower_inc","lower_inf","lpad","lseg","ltrim","make_date","make_interval","make_time","make_timestamp","make_timestamptz","masklen","max","md5","min","mod","mode","netmask","network","nextval","now","npoints","nth_value","ntile","nullif","num_nonnulls","num_nulls","numnode","obj_description","octet_length","overlay","parse_ident","path","pclose","percent_rank","percentile_cont","percentile_disc","pg_advisory_lock","pg_advisory_lock_shared","pg_advisory_unlock","pg_advisory_unlock_all","pg_advisory_unlock_shared","pg_advisory_xact_lock","pg_advisory_xact_lock_shared","pg_backend_pid","pg_backup_start_time","pg_blocking_pids","pg_cancel_backend","pg_client_encoding","pg_collation_is_visible","pg_column_size","pg_conf_load_time","pg_control_checkpoint","pg_control_init","pg_control_recovery","pg_control_system","pg_conversion_is_visible","pg_create_logical_replication_slot","pg_create_physical_replication_slot","pg_create_restore_point","pg_current_xlog_flush_location","pg_current_xlog_insert_location","pg_current_xlog_location","pg_database_size","pg_describe_object","pg_drop_replication_slot","pg_export_snapshot","pg_filenode_relation","pg_function_is_visible","pg_get_constraintdef","pg_get_expr","pg_get_function_arguments","pg_get_function_identity_arguments","pg_get_function_result","pg_get_functiondef","pg_get_indexdef","pg_get_keywords","pg_get_object_address","pg_get_owned_sequence","pg_get_ruledef","pg_get_serial_sequence","pg_get_triggerdef","pg_get_userbyid","pg_get_viewdef","pg_has_role","pg_identify_object","pg_identify_object_as_address","pg_index_column_has_property","pg_index_has_property","pg_indexam_has_property","pg_indexes_size","pg_is_in_backup","pg_is_in_recovery","pg_is_other_temp_schema","pg_is_xlog_replay_paused","pg_last_committed_xact","pg_last_xact_replay_timestamp","pg_last_xlog_receive_location","pg_last_xlog_replay_location","pg_listening_channels","pg_logical_emit_message","pg_logical_slot_get_binary_changes","pg_logical_slot_get_changes","pg_logical_slot_peek_binary_changes","pg_logical_slot_peek_changes","pg_ls_dir","pg_my_temp_schema","pg_notification_queue_usage","pg_opclass_is_visible","pg_operator_is_visible","pg_opfamily_is_visible","pg_options_to_table","pg_postmaster_start_time","pg_read_binary_file","pg_read_file","pg_relation_filenode","pg_relation_filepath","pg_relation_size","pg_reload_conf","pg_replication_origin_create","pg_replication_origin_drop","pg_replication_origin_oid","pg_replication_origin_progress","pg_replication_origin_session_is_setup","pg_replication_origin_session_progress","pg_replication_origin_session_reset","pg_replication_origin_session_setup","pg_replication_origin_xact_reset","pg_replication_origin_xact_setup","pg_rotate_logfile","pg_size_bytes","pg_size_pretty","pg_sleep","pg_sleep_for","pg_sleep_until","pg_start_backup","pg_stat_file","pg_stop_backup","pg_switch_xlog","pg_table_is_visible","pg_table_size","pg_tablespace_databases","pg_tablespace_location","pg_tablespace_size","pg_terminate_backend","pg_total_relation_size","pg_trigger_depth","pg_try_advisory_lock","pg_try_advisory_lock_shared","pg_try_advisory_xact_lock","pg_try_advisory_xact_lock_shared","pg_ts_config_is_visible","pg_ts_dict_is_visible","pg_ts_parser_is_visible","pg_ts_template_is_visible","pg_type_is_visible","pg_typeof","pg_xact_commit_timestamp","pg_xlog_location_diff","pg_xlog_replay_pause","pg_xlog_replay_resume","pg_xlogfile_name","pg_xlogfile_name_offset","phraseto_tsquery","pi","plainto_tsquery","point","polygon","popen","position","power","pqserverversion","query_to_xml","querytree","quote_ident","quote_literal","quote_nullable","radians","radius","random","range_merge","rank","regexp_matches","regexp_replace","regexp_split_to_array","regexp_split_to_table","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","repeat","replace","reverse","right","round","row_number","row_security_active","row_to_json","rpad","rtrim","scale","session_user","set_bit","set_byte","set_config","set_masklen","setseed","setval","setweight","shobj_description","sign","sin","sind","split_part","sprintf","sqrt","statement_timestamp","stddev","stddev_pop","stddev_samp","string_agg","string_to_array","strip","strpos","substr","substring","sum","table_to_xml","table_to_xml_and_xmlschema","tan","tand","text","timeofday","timezone","to_ascii","to_char","to_date","to_hex","to_json","to_number","to_regclass","to_regnamespace","to_regoper","to_regoperator","to_regproc","to_regprocedure","to_regrole","to_regtype","to_timestamp","to_tsquery","to_tsvector","transaction_timestamp","translate","trim","trunc","ts_debug","ts_delete","ts_filter","ts_headline","ts_lexize","ts_parse","ts_rank","ts_rank_cd","ts_rewrite","ts_stat","ts_token_type","tsquery_phrase","tsvector_to_array","tsvector_update_trigger","tsvector_update_trigger_column","txid_current","txid_current_snapshot","txid_snapshot_xip","txid_snapshot_xmax","txid_snapshot_xmin","txid_visible_in_snapshot","unnest","upper","upper_inc","upper_inf","user","var_pop","var_samp","variance","version","width","width_bucket","xml_is_well_formed","xml_is_well_formed_content","xml_is_well_formed_document","xmlagg","xmlcomment","xmlconcat","xmlelement","xmlexists","xmlforest","xmlparse","xmlpi","xmlroot","xmlserialize","xpath","xpath_exists"],builtinVariables:[],pseudoColumns:[],tokenizer:{root:[{include:"@comments"},{include:"@whitespace"},{include:"@pseudoColumns"},{include:"@numbers"},{include:"@strings"},{include:"@complexIdentifiers"},{include:"@scopes"},[/[;,.]/,"delimiter"],[/[()]/,"@brackets"],[/[\w@#$]+/,{cases:{"@keywords":"keyword","@operators":"operator","@builtinVariables":"predefined","@builtinFunctions":"predefined","@default":"identifier"}}],[/[<>=!%&+\-*/|~^]/,"operator"]],whitespace:[[/\s+/,"white"]],comments:[[/--+.*/,"comment"],[/\/\*/,{token:"comment.quote",next:"@comment"}]],comment:[[/[^*/]+/,"comment"],[/\*\//,{token:"comment.quote",next:"@pop"}],[/./,"comment"]],pseudoColumns:[[/[$][A-Za-z_][\w@#$]*/,{cases:{"@pseudoColumns":"predefined","@default":"identifier"}}]],numbers:[[/0[xX][0-9a-fA-F]*/,"number"],[/[$][+-]*\d*(\.\d*)?/,"number"],[/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/,"number"]],strings:[[/'/,{token:"string",next:"@string"}]],string:[[/[^']+/,"string"],[/''/,"string"],[/'/,{token:"string",next:"@pop"}]],complexIdentifiers:[[/"/,{token:"identifier.quote",next:"@quotedIdentifier"}]],quotedIdentifier:[[/[^"]+/,"identifier"],[/""/,"identifier"],[/"/,{token:"identifier.quote",next:"@pop"}]],scopes:[]}}});
|
import { deprecate } from '../utils/deprecate';
import isArray from '../utils/is-array';
import { createLocal } from '../create/constructors';
import { createInvalid } from '../create/from-anything';
export var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
);
export var prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
export function min () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
export function max () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
|
/*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef CREDITSCOMMAND_H_
#define CREDITSCOMMAND_H_
#include "server/zone/objects/scene/SceneObject.h"
class CreditsCommand : public QueueCommand {
public:
CreditsCommand(const String& name, ZoneProcessServer* server)
: QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
try {
ManagedReference<SceneObject* > object =
server->getZoneServer()->getObject(target);
ManagedReference<CreatureObject*> player = nullptr;
StringTokenizer args(arguments.toString());
if(object == nullptr || !object->isPlayerCreature()) {
String firstName;
if(args.hasMoreTokens()) {
args.getStringToken(firstName);
player = server->getZoneServer()->getPlayerManager()->getPlayer(firstName);
}
} else {
player = cast<CreatureObject*>( object.get());
}
if (player == nullptr) {
creature->sendSystemMessage("invalid arguments for credits command: /credits <firstname> <add/subtract> <amount> <bank/cash>");
return GENERALERROR;
}
Locker clocker(player, creature);
String action;
args.getStringToken(action);
int amount;
amount = args.getIntToken();
String location;
args.getStringToken(location);
bool success = false;
if (action == "add") {
if (location.toLowerCase() == "cash") {
player->addCashCredits(amount);
success = true;
}
if (location.toLowerCase() == "bank") {
player->addBankCredits(amount);
success = true;
}
} else if (action == "subtract") {
if (location.toLowerCase() == "cash") {
if (player->verifyCashCredits(amount))
player->subtractCashCredits(amount);
else
player->setCashCredits(0, true);
success = true;
}
if (location.toLowerCase() == "bank") {
if (player->verifyBankCredits(amount))
player->subtractBankCredits(amount);
else
player->setBankCredits(0, true);
success = true;
}
}
if(success)
creature->sendSystemMessage("Credits have been deposited successfully for " + player->getFirstName());
else
creature->sendSystemMessage("invalid arguments for credits command: /credits <firstname> <add/subtract> <amount> <bank/cash>");
} catch (Exception& e) {
creature->sendSystemMessage("invalid arguments for credits command: /credits <firstname> <add/subtract> <amount> <bank/cash>");
}
return SUCCESS;
}
};
#endif //CREDITSCOMMAND_H_
|
"""
Django settings for docter_28901 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
from modules.manifest import get_modules
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
]
MODULES_APPS = get_modules()
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS + MODULES_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'docter_28901.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'docter_28901.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
#!/usr/bin/env python
from .common import *
from .version import *
from .cli_wrapper import *
from .extractor import *
|
/**
* Copyright IBM Corp. 2016, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
*/
var _20 = {
"elem": "svg",
"attrs": {
"xmlns": "http://www.w3.org/2000/svg",
"viewBox": "0 0 32 32",
"fill": "currentColor",
"width": 20,
"height": 20
},
"content": [{
"elem": "path",
"attrs": {
"d": "M28 12H30V15H28zM24 7H26V20H24zM20 11H22V16H20zM16 9H18V18H16zM12 12H14V15H12z"
}
}, {
"elem": "circle",
"attrs": {
"cx": "13.5",
"cy": "24.5",
"r": "1.5"
}
}, {
"elem": "path",
"attrs": {
"d": "M20,30H7a2.0023,2.0023,0,0,1-2-2V4A2.0023,2.0023,0,0,1,7,2H20V4H7V28H20V24h2v4A2.0023,2.0023,0,0,1,20,30Z"
}
}],
"name": "mobile--audio",
"size": 20
};
export default _20;
|
/**
* @module octokit
*/
const {request} = require("@octokit/request");
const log = require("../../util/log");
const digest = require("../digest");
/**
* Cryptographically anonymise the data of an issue body
* to ensure privacy of users.
* Anonymise the following parameters (if present):
* email, ip, name, reCAPTCHA response.
* The anonymised data can be used for reference by server
* admins with the possession of the server's secret.
* @param {Object} data
* @return {Object} anonymised data
*/
const anonymiseData = (data) => {
if (data.email) {
const anonId = digest.hashPassWithSaltInHex(
data.email,
process.env.SERVER_SECRET,
);
data.email = anonId;
}
if (data.ip) {
const anonIp = digest.hashPassWithSaltInHex(
data.ip,
process.env.SERVER_SECRET,
);
data.ip = anonIp;
}
if (data.name) {
const anonName = digest.hashPassWithSaltInHex(
data.name,
process.env.SERVER_SECRET,
);
data.name = anonName;
}
if (data['g-recaptcha-response']) {
const anonRes = digest.hashPassWithSaltInHex(
data['g-recaptcha-response'],
process.env.SERVER_SECRET,
);
data['g-recaptcha-response'] = anonRes;
}
if (data['_csrf']) {
const anonRes = digest.hashPassWithSaltInHex(
data['_csrf'],
process.env.SERVER_SECRET,
);
data['_csrf'] = anonRes;
}
return data;
};
/**
* Create markdown formatted issue body string
* from pretty printed issue data and metadata.
* @param {Object} data
* @return {String} markdown formatted issue body
*/
const createIssueBody = (data) => {
return `### ${data.subject ? data.subject : 'Route ' + data.originalUrl}\n\n` +
`${data.report ? data.report : data.message}\n\n` +
'Metadata:\n```yaml\n' +
JSON.stringify(data, null, 4) +
'\n```';
};
/**
* Create bugreport Github issue:
* Anonymise PII in bugreport, create
* formatted issue body and post the
* issue to Github via Github API.
* @param {Object} bugreport
*/
const createBugreportIssue = async (bugreport) => {
await createIssue(
`[bugreport] ${bugreport.subject ? bugreport.subject : 'Auto bugreport for route ' + bugreport.originalUrl}`,
createIssueBody(anonymiseData(bugreport)),
"bugreport",
);
};
/**
* Create feature request Github issue:
* Anonymise PII in feature request, create
* formatted issue body and post the
* issue to Github via Github API.
* @param {Object} featureRequest
*/
const createFeatureRequestIssue = async (featureRequest) => {
await createIssue(
`[feature request] ${featureRequest.subject}`,
createIssueBody(anonymiseData(featureRequest)),
"feature request",
);
};
/**
* Create an issue on Github via Github API
* with given issue title, body and label.
* @param {String} title
* @param {String} body
* @param {String} label
*/
const createIssue = async (title, body, label) => {
try {
if (process.env.CREATE_GITHUB_ISSUES === '0') {
log.info("Skipping creation of Github Issue - %s", title);
return;
}
log.info("Creating Github Issue - %s", title);
await request("POST /repos/almasen/rdf-mapped/issues", {
headers: {
authorization: `token ${process.env.GITHUB_TOKEN}`,
},
title,
body,
labels: [label],
});
log.info("Successfully created Github Issue - %s", title);
} catch (error) {
log.error("Github Issue creation FAILED, err: " + error.message);
};
};
module.exports = {
createBugreportIssue,
createFeatureRequestIssue,
};
|
from enum import Enum, unique
from typing import Dict, List, Optional
from pydantic import BaseModel, Field, validator
from astrobase.helpers.name import random_name
class EKSNodegroupScalingConfig(BaseModel):
minSize: int = 1
maxSize: int = 3
desiredSize: int = 1
@unique
class EKSNodegroupAmiType(str, Enum):
al2_x86_64 = "AL2_x86_64"
al2_x86_64_gpu = "AL2_x86_64_GPU"
al2_arm_64 = "AL2_ARM_64"
@unique
class EKSNodegroupCapacityType(str, Enum):
on_demand = "ON_DEMAND"
spot = "SPOT"
class EKSNodegroup(BaseModel):
clusterName: Optional[str]
nodegroupName: str
scalingConfig: EKSNodegroupScalingConfig
diskSize: int = 100
subnets: Optional[List[str]]
instanceTypes: List[str] = ["t3.medium"]
amiType: EKSNodegroupAmiType = EKSNodegroupAmiType.al2_x86_64
nodeRole: str
labels: Optional[Dict[str, str]] = {}
tags: Optional[Dict[str, str]] = {}
capacityType: EKSNodegroupCapacityType = EKSNodegroupCapacityType.spot
class ResourcesVpcConfig(BaseModel):
subnetIds: List[str]
securityGroupIds: List[str]
endpointPublicAccess: bool = True
endpointPrivateAccess: bool = True
publicAccessCidrs: List[str] = ["0.0.0.0/0"]
@unique
class ClusterLoggingType(str, Enum):
api = "api"
audit = "audit"
scheduler = "scheduler"
authenticator = "authenticator"
controllerManager = "controllerManager"
class ClusterLoggingConfig(BaseModel):
types: List[ClusterLoggingType] = []
enabled: bool = False
class ClusterLogging(BaseModel):
clusterLogging: List[ClusterLoggingConfig] = [ClusterLoggingConfig()]
class EKSBase(BaseModel):
name: Optional[str] = Field(default_factory=random_name)
region: str
roleArn: str
resourcesVpcConfig: ResourcesVpcConfig
tags: Optional[Dict[str, str]] = {}
logging: ClusterLogging = ClusterLogging()
nodegroups: List[EKSNodegroup]
@validator("nodegroups", pre=True, always=True)
def set_nodegroup_name_subnets(
cls: BaseModel, v: List[dict], values: dict
) -> List[dict]:
for nodegroup in v:
if not nodegroup.get("clusterName"):
nodegroup["clusterName"] = values["name"]
if not nodegroup.get("subnets"):
nodegroup["subnets"] = values["resourcesVpcConfig"].subnetIds
return v
class EKSCreate(EKSBase):
pass
class EKSCreateAPIFilter(BaseModel):
name: str
roleArn: str
resourcesVpcConfig: ResourcesVpcConfig
tags: Optional[Dict[str, str]] = {}
logging: Optional[ClusterLogging] = ClusterLogging()
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _ApiClient = _interopRequireDefault(require("../ApiClient"));
var _GADShape = _interopRequireDefault(require("./GADShape"));
var _GeographicalCoordinates = _interopRequireDefault(require("./GeographicalCoordinates"));
var _PointUncertaintyCircleAllOf = _interopRequireDefault(require("./PointUncertaintyCircleAllOf"));
var _SupportedGADShapes = _interopRequireDefault(require("./SupportedGADShapes"));
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"); } }
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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
/**
* The PointUncertaintyCircle model module.
* @module model/PointUncertaintyCircle
* @version 1.1.0-alpha.4
*/
var PointUncertaintyCircle = /*#__PURE__*/function () {
/**
* Constructs a new <code>PointUncertaintyCircle</code>.
* Ellipsoid point with uncertainty circle.
* @alias module:model/PointUncertaintyCircle
* @extends module:model/GADShape
* @implements module:model/GADShape
* @implements module:model/PointUncertaintyCircleAllOf
* @param shape {module:model/SupportedGADShapes}
* @param point {module:model/GeographicalCoordinates}
* @param uncertainty {Number} Indicates value of uncertainty.
*/
function PointUncertaintyCircle(shape, point, uncertainty) {
_classCallCheck(this, PointUncertaintyCircle);
_GADShape["default"].initialize(this, shape);
_PointUncertaintyCircleAllOf["default"].initialize(this, point, uncertainty);
PointUncertaintyCircle.initialize(this, shape, point, uncertainty);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
_createClass(PointUncertaintyCircle, null, [{
key: "initialize",
value: function initialize(obj, shape, point, uncertainty) {
obj['point'] = point;
obj['uncertainty'] = uncertainty;
}
/**
* Constructs a <code>PointUncertaintyCircle</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PointUncertaintyCircle} obj Optional instance to populate.
* @return {module:model/PointUncertaintyCircle} The populated <code>PointUncertaintyCircle</code> instance.
*/
}, {
key: "constructFromObject",
value: function constructFromObject(data, obj) {
if (data) {
obj = obj || new PointUncertaintyCircle();
_GADShape["default"].constructFromObject(data, obj);
_GADShape["default"].constructFromObject(data, obj);
_PointUncertaintyCircleAllOf["default"].constructFromObject(data, obj);
if (data.hasOwnProperty('point')) {
obj['point'] = _GeographicalCoordinates["default"].constructFromObject(data['point']);
}
if (data.hasOwnProperty('uncertainty')) {
obj['uncertainty'] = _ApiClient["default"].convertToType(data['uncertainty'], 'Number');
}
}
return obj;
}
}]);
return PointUncertaintyCircle;
}();
/**
* @member {module:model/GeographicalCoordinates} point
*/
PointUncertaintyCircle.prototype['point'] = undefined;
/**
* Indicates value of uncertainty.
* @member {Number} uncertainty
*/
PointUncertaintyCircle.prototype['uncertainty'] = undefined; // Implement GADShape interface:
/**
* @member {module:model/SupportedGADShapes} shape
*/
_GADShape["default"].prototype['shape'] = undefined; // Implement PointUncertaintyCircleAllOf interface:
/**
* @member {module:model/GeographicalCoordinates} point
*/
_PointUncertaintyCircleAllOf["default"].prototype['point'] = undefined;
/**
* Indicates value of uncertainty.
* @member {Number} uncertainty
*/
_PointUncertaintyCircleAllOf["default"].prototype['uncertainty'] = undefined;
var _default = PointUncertaintyCircle;
exports["default"] = _default;
|
#! ../env/bin/python
# -*- coding: utf-8 -*-
from appname import create_app
from appname.models import db, User
class TestForm:
def setup(self):
app = create_app('appname.settings.DevConfig', env='dev')
self.app = app.test_client()
db.app = app
db.create_all()
admin = User('admin', 'supersafepassword')
db.session.add(admin)
db.session.commit()
def teardown(self):
db.session.remove()
db.drop_all()
def test_user_login(self):
rv = self.app.post('/login', data=dict(
username='admin',
password="supersafepassword"
), follow_redirects=True)
assert rv.status_code == 200
assert 'Logged in successfully.' in rv.data
|
nome = str (input ('DIGITE O NOME DO ALUNO: '))
nota1 = float (input ('DIGITE A PRIMEIRA NOTA: '))
nota2 = float (input ('DIGITE A SEGUNDA NOTA: '))
media =(( nota1 + nota2 ) / 2)
if media < 5.0:
print ('O ALUNO {} FOI REPROVADO COM A MÉDIA {:.2F}.'.format (nome , media))
elif media == 5.0 or media <= 6.9:
print ('O ALUNO {} ESTÁ EM RECUPERAÇÃO COM A MÉDIA {:.2F}.'.format (nome , media))
elif media >= 7.0:
print('O ALUNO {} ESTÁ APROVADO COM A MÉDIA {:.2F}, PARABENS.'.format(nome, media))
|
#include <kernel.h>
#include <stdint.h>
#include <cio.h>
void map_PIC(uint8_t PIC0Offset, uint8_t PIC1Offset) {
uint8_t mask0;
uint8_t mask1;
mask0 = get_PIC0_mask(); // save PIC 0 and 1's masks
mask1 = get_PIC1_mask();
port_out_b(0x20, 0x11); // initialise
port_out_b(0xA0, 0x11);
port_out_b(0x21, PIC0Offset); // set offsets
port_out_b(0xA1, PIC1Offset);
port_out_b(0x21, 0x04); // PIC wiring info
port_out_b(0xA1, 0x02);
port_out_b(0x21, 0x01); // environment info
port_out_b(0xA1, 0x01);
set_PIC0_mask(mask0); // restore masks
set_PIC1_mask(mask1);
}
void set_PIC0_mask(uint8_t mask) {
port_out_b(0x21, mask);
return;
}
void set_PIC1_mask(uint8_t mask) {
port_out_b(0xA1, mask);
return;
}
uint8_t get_PIC0_mask(void) {
return port_in_b(0x21);
}
uint8_t get_PIC1_mask(void) {
return port_in_b(0xA1);
}
int pic_io_wrapper(uint32_t dev, uint64_t loc, int type, uint8_t payload) {
switch (type) {
case DF_GET_MASK:
if (dev) {
return get_PIC1_mask();
} else {
return get_PIC0_mask();
}
case DF_SET_MASK:
if (dev) {
set_PIC1_mask(payload);
} else {
set_PIC0_mask(payload);
}
return 0;
}
}
void init_pic(void) {
kernel_add_device("i8259:0", 0, 0, &pic_io_wrapper);
kernel_add_device("i8259:1", 1, 0, &pic_io_wrapper);
}
|
import pymongo
from app.daos.dao import Dao
from app.daos.mongo import MongoDatabase
from app.models.github_repository import GithubRepository
class GithubRepositoryDao(Dao):
def __init__(self, mongo_database: MongoDatabase):
super().__init__(mongo_database, 'github_repositories')
def find_all(self, *, query: dict = None) -> list:
results = [result for result in
self._mongo_database.find(self.collection, query).sort("updated_at", pymongo.DESCENDING)]
return results
def _to_json(self, object_record: dict) -> GithubRepository:
github_repo_model = GithubRepository(object_record)
return github_repo_model
|
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
def sqrt(a):
return a ** 0.5
def pow(a, b):
return a**b
|
var data = {
"body": "<g fill-rule=\"nonzero\" fill=\"none\"><path fill=\"#F7DF1E\" d=\"M1.853 1.833h201.094v199H1.853z\"/><path d=\"M204.8 202.667H0V0h204.8v202.667zm-200.954-3.83h197.105V3.83H3.846v195.008z\" fill=\"#EEE\"/><path d=\"M137.16 158.025c4.06 6.63 9.342 11.502 18.686 11.502c7.849 0 12.862-3.923 12.862-9.341c0-6.494-5.15-8.796-13.79-12.574l-4.733-2.031c-13.669-5.822-22.748-13.118-22.748-28.54c0-14.206 10.822-25.02 27.74-25.02c12.042 0 20.701 4.192 26.94 15.166l-14.75 9.47c-3.248-5.824-6.75-8.117-12.19-8.117c-5.55 0-9.065 3.52-9.065 8.117c0 5.681 3.52 7.983 11.646 11.503l4.736 2.029c16.094 6.901 25.18 13.937 25.18 29.756c0 17.051-13.396 26.395-31.388 26.395c-17.592 0-28.956-8.382-34.517-19.368c0-.005 15.392-8.947 15.392-8.947zm68.33 0c4.059 6.63 9.34 11.502 18.685 11.502c7.848 0 12.862-3.923 12.862-9.341c0-6.494-5.15-8.796-13.79-12.574l-4.734-2.031c-13.668-5.822-22.748-13.118-22.748-28.54c0-14.206 10.823-25.02 27.74-25.02c12.043 0 20.702 4.192 26.94 15.166l-14.75 9.47c-3.247-5.824-6.75-8.117-12.19-8.117c-5.549 0-9.064 3.52-9.064 8.117c0 5.681 3.52 7.983 11.645 11.503l4.736 2.029C246.914 137.088 256 144.124 256 159.942c0 17.052-13.395 26.396-31.388 26.396c-17.591 0-28.955-8.382-34.517-19.368l15.394-8.945zm-135.24 1.642c2.977 5.28 5.684 9.743 12.19 9.743c6.223 0 10.149-2.434 10.149-11.902V93.101h18.94v64.661c0 19.612-11.5 28.54-28.284 28.54c-15.166 0-23.949-7.849-28.416-17.301l15.422-9.334c0-.002 0 0 0 0z\" fill=\"#000\"/></g>",
"width": 256,
"height": 203
};
export default data;
|
export const SET_LOADING = 'SET_LOADING';
export const SET_BOOK_DETAILS = 'SET_BOOK_DETAILS';
|
"""
Created on May 4, 2018
@author: Alejandro Molina
@author: Antonio Vergari
"""
import numpy as np
from spn.algorithms.Inference import EPSILON, add_node_likelihood, add_node_mpe_likelihood, leaf_marginalized_likelihood
from spn.structure.leaves.piecewise.PiecewiseLinear import PiecewiseLinear
import logging
logger = logging.getLogger(__name__)
LOG_ZERO = -300
def piecewise_likelihood(node, data=None, dtype=np.float64):
probs, marg_ids, observations = leaf_marginalized_likelihood(node, data, dtype)
probs[~marg_ids] = piecewise_complete_cases_likelihood(node, observations, dtype=dtype)
x = piecewise_complete_cases_likelihood(node, observations, dtype=dtype)
return probs
def _compute_probability_for_range(node, interval):
lower = interval[0]
higher = interval[1]
x_range = np.array(node.x_range)
y_range = np.array(node.y_range)
lower_prob = np.interp(lower, xp=x_range, fp=y_range)
higher_prob = np.interp(higher, xp=x_range, fp=y_range)
indicies = np.where((lower <= x_range) & (x_range <= higher))
x_tmp = [lower] + list(x_range[indicies]) + [higher]
y_tmp = [lower_prob] + list(y_range[indicies]) + [higher_prob]
return np.trapz(y_tmp, x_tmp)
def piecewise_complete_cases_likelihood(node, obs, dtype=np.float64):
probs = np.ones((obs.shape[0]), dtype=dtype) # + EPSILON
ivalues = np.interp(x=obs, xp=node.x_range, fp=node.y_range)
probs[:] = ivalues
# ividx = ivalues > 0
# probs[ividx, 0] = ivalues[ividx]
return probs
def add_piecewise_inference_support():
add_node_likelihood(PiecewiseLinear, piecewise_likelihood)
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:46:40 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/Frameworks/SceneKit.framework/SceneKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <SceneKit/SceneKit-Structs.h>
#import <libobjc.A.dylib/NSSecureCoding.h>
@interface SCNTimingFunction : NSObject <NSSecureCoding> {
C3DTimingFunctionRef _timingFunction;
}
+(id)functionWithTimingMode:(long long)arg1 ;
+(id)functionWithCAMediaTimingFunction:(id)arg1 ;
+(BOOL)supportsSecureCoding;
-(id)initWithTimingFunctionRef:(C3DTimingFunctionRef)arg1 ;
-(C3DTimingFunctionRef)c3dTimingFunction;
-(void)dealloc;
-(void)encodeWithCoder:(id)arg1 ;
-(id)initWithCoder:(id)arg1 ;
@end
|
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x^y).count('1')
|
DesktopResponsive={"1009":{
"pageLayer":{"w":785,"h":450,"bgColor":"#ffffff"}
,
"button24890":{"x":17,"y":14,"w":53.000000,"h":50.000000,"stylemods":[{"sel":"div.button24890Text","decl":" { position:fixed; left:11px; top:4px; width:30px; height:41px;}"},{"sel":"span.button24890Text","decl":" { display:table-cell; position:relative; width:30px; height:41px; vertical-align:middle; text-align:center; line-height:16px; font-size:16px; font-family:\"Lucida Sans Unicode\"; color:#ffffff;}"}],"bOffBottom":0 ,"td": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"tdO": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"tdD": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADcAAAA0CAYAAAAuT6DoAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAiSURBVGhD7cExAQAAAMKg9U9tDQ8gAAAAAAAAAAAAAIAbNSzkAAFzvEswAAAAAElFTkSuQmCC" ,"tdDi": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"fd": "" ,"fdO": "" ,"fdD": "" ,"fdDi": "" ,"p": "M 0.000000 24.500000 L 0.500000 19.562500 L 2.062500 15.000000 L 4.437500 10.812500 L 7.625000 7.187500 L 11.500000 4.187500 L 15.875000 1.937500 L 20.750000 0.500000 L 26.000000 0.000000 L 31.250000 0.500000 L 36.125000 1.937500 L 40.562500 4.187500 L 44.375000 7.187500 L 47.562500 10.812500 L 49.937500 15.000000 L 51.500000 19.562500 L 52.000000 24.500000 L 51.500000 29.437500 L 49.937500 34.062500 L 47.562500 38.187500 L 44.375000 41.812500 L 40.562500 44.812500 L 36.125000 47.062500 L 31.250000 48.500000 L 26.000000 49.000000 L 20.750000 48.500000 L 15.875000 47.062500 L 11.500000 44.812500 L 7.625000 41.812500 L 4.437500 38.187500 L 2.062500 34.062500 L 0.500000 29.437500 L 0.000000 24.500000 z"}
,
"button24884":{"x":19,"y":83,"w":53.000000,"h":50.000000,"stylemods":[{"sel":"div.button24884Text","decl":" { position:fixed; left:11px; top:4px; width:30px; height:41px;}"},{"sel":"span.button24884Text","decl":" { display:table-cell; position:relative; width:30px; height:41px; vertical-align:middle; text-align:center; line-height:16px; font-size:16px; font-family:\"Lucida Sans Unicode\"; color:#ffffff;}"}],"bOffBottom":0 ,"td": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"tdO": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"tdD": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADcAAAA0CAYAAAAuT6DoAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAiSURBVGhD7cExAQAAAMKg9U9tDQ8gAAAAAAAAAAAAAIAbNSzkAAFzvEswAAAAAElFTkSuQmCC" ,"tdDi": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAyCAYAAAD845PIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhSURBVGhD7cExAQAAAMKg9U9tCU8gAAAAAAAAAAAAAC5qKZoAAU1/azgAAAAASUVORK5CYII=" ,"fd": "" ,"fdO": "" ,"fdD": "" ,"fdDi": "" ,"p": "M 0.000000 24.500000 L 0.500000 19.562500 L 2.062500 15.000000 L 4.437500 10.812500 L 7.625000 7.187500 L 11.500000 4.187500 L 15.875000 1.937500 L 20.750000 0.500000 L 26.000000 0.000000 L 31.250000 0.500000 L 36.125000 1.937500 L 40.562500 4.187500 L 44.375000 7.187500 L 47.562500 10.812500 L 49.937500 15.000000 L 51.500000 19.562500 L 52.000000 24.500000 L 51.500000 29.437500 L 49.937500 34.062500 L 47.562500 38.187500 L 44.375000 41.812500 L 40.562500 44.812500 L 36.125000 47.062500 L 31.250000 48.500000 L 26.000000 49.000000 L 20.750000 48.500000 L 15.875000 47.062500 L 11.500000 44.812500 L 7.625000 41.812500 L 4.437500 38.187500 L 2.062500 34.062500 L 0.500000 29.437500 L 0.000000 24.500000 z"}
,
"image29536":{"x":0,"y":0,"w":785,"h":450,"bOffBottom":0,"i":"images/mufrodat_manjil_1.png"}
,
"RCDResetQuestion":function(){
try{if(window.dragMgr)window.dragMgr.clearDropZones();}catch(e){if(e&&e.message)console.log(e.message);}
}
,
"RCDResultResize":function(){}
,"preload":['images/mufrodat_manjil_1.png']
}}
|
import os
from datetime import datetime
import sys
try:
from hashlib import sha1
except ImportError:
sys.exit('ImportError: No module named hashlib\n'
'If you are on python2.4 this library is not part of python. '
'Please install it. Example: easy_install hashlib')
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Unicode, Integer, DateTime
from sqlalchemy.orm import relation, synonym
from sqlalchemy import *;
from comcenter.model import DeclarativeBase2, metadata2, DBSession2
#from sqlalchemy.sql.expression import *;
import logging;
import sys;
log = logging.getLogger(__name__);
#__all__ = ['User', 'Group', 'Permission']
class VisitTransection(object):
def __init__(self):
pass;
@classmethod
def queryVisitInYear(cls,year=None):
sql = text("""select
vn_stat.ym ,
count(vn_stat.vn) as count_vn
from
vn_stat
where vn_stat.ym like :year
group by vn_stat.ym """, bindparams=[ bindparam('year', str(year+'%')) ]);
result = DBSession2.execute(sql );
return result ;
@classmethod
def queryPatientInYear(cls,year=None):
"""select
pt.ym,
count(pt.hn) as count_hn
from (
select
vn_stat.ym,
vn_stat.hn
from vn_stat
where vn_stat.ym like :year
group by
vn_stat.hn
) as pt
group by pt.ym """
sql = text("""select
vn_stat.ym,
count( distinct vn_stat.hn ) as count_hn
from vn_stat
where vn_stat.ym like :year
group by vn_stat.ym""", bindparams=[ bindparam('year', str(year+'%')) ]);
result = DBSession2.execute(sql );
return result ;
@classmethod
def queryPatientSexInYear(cls,year=None):
sql = text(""" select
pt.ym,
sum(pt.men) as men ,
sum(pt.women) as women
from (
select
vn_stat.ym,
case when vn_stat.sex = 1 then 1 else 0 end as men,
case when vn_stat.sex = 2 then 1 else 0 end as women
from vn_stat
where vn_stat.ym like :year
group by vn_stat.ym,vn_stat.hn
) pt
group by pt.ym """, bindparams=[ bindparam('year', str(year+'%')) ]);
result = DBSession2.execute(sql );
return result ;
|
#!/usr/bin/env python3
# Authors:
# Patrick Lehmann
# Unai Martinez-Corral
#
# Copyright 2021 Unai Martinez-Corral <unai.martinezcorral@ehu.eus>
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from typing import List
from setuptools import (
setup as setuptools_setup,
find_namespace_packages as setuptools_find_namespace_packages
)
packagePath = Path(__file__).resolve().parent / 'pyHDLC'
requirementsFile = packagePath / "requirements.txt"
# Read requirements file and add them to package dependency list
def get_requirements(file: Path) -> List[str]:
requirements = []
with file.open("r") as fh:
for line in fh.read().splitlines():
if line.startswith("#") or line == "":
continue
elif line.startswith("-r"):
# Remove the first word/argument (-r)
filename = " ".join(line.split(" ")[1:])
requirements += get_requirements(file.parent / filename)
elif line.startswith("https"):
# Convert 'URL#NAME' to 'NAME @ URL'
splitItems = line.split("#")
requirements.append("{} @ {}".format(splitItems[1], splitItems[0]))
else:
requirements.append(line)
return requirements
setuptools_setup(
name=packagePath.name,
version="0.0.0",
license="Apache-2.0",
author="Unai Martinez-Corral and contributors",
author_email="unai.martinezcorral@ehu.eus",
description="Helper tool for HDL Containers.",
url="https://github.com/hdl/containers",
packages=setuptools_find_namespace_packages(exclude=[]),
classifiers=[],
python_requires='>=3.6',
install_requires=list(set(get_requirements(requirementsFile))),
entry_points={
"console_scripts": [
"pyHDLC = pyHDLC.cli:main",
]
},
)
|
import { getSheetIndex } from '../methods/get';
import editor from '../global/editor';
import { isRealNull, isEditMode } from '../global/validate';
import tooltip from '../global/tooltip';
import { rowlenByRange } from '../global/getRowlen';
import { selectHightlightShow } from './select';
import { luckysheetMoveEndCell } from './sheetMove';
import server from './server';
import locale from '../locale/locale';
import Store from '../store';
import menuButton from './menuButton';
import conditionformat from './conditionformat';
import alternateformat from './alternateformat';
import {checkProtectionAuthorityNormal} from './protection';
import {
rgbTohex,
showrightclickmenu,
} from '../utils/util';
import cleargridelement from '../global/cleargridelement';
import {
jfrefreshgrid,
jfrefreshgrid_rhcw,
} from '../global/refresh';
import { orderbydata, orderbydata1D } from '../global/sort';
import json from '../global/json';
import { update, genarate } from '../global/format';
//筛选配置状态
function labelFilterOptionState($top, optionstate, rowhidden, caljs, notSave, str, edr, cindex, stc, edc) {
if (optionstate) {
$top.addClass("luckysheet-filter-options-active").data("rowhidden", JSON.stringify(rowhidden)).data("caljs", JSON.stringify(caljs)).html('<i class="fa fa-filter luckysheet-mousedown-cancel" aria-hidden="true"></i>');
if (caljs != null) {
$top.data("byconditionvalue", caljs["value"]).data("byconditiontype", caljs["type"]).data("byconditiontext", caljs["text"]);
if (caljs["value1"] != null) {
$top.data("byconditionvalue1", caljs["value1"]);
}
if (caljs["value2"] != null) {
$top.data("byconditionvalue2", caljs["value2"]);
}
}
}
else {
$top.removeClass("luckysheet-filter-options-active").data("rowhidden", "").data("caljs", "").html('<i class="fa fa-caret-down luckysheet-mousedown-cancel" aria-hidden="true"></i>');
$top.data("byconditionvalue", "null").data("byconditiontype", "0").data("byconditiontext", "无").data("byconditionvalue1", "").data("byconditionvalue2", "");
}
if(!!notSave){
let file = Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)];
if(file.filter == null){
file.filter = {};
}
if (optionstate) {
let param = {
"caljs": caljs,
"rowhidden": rowhidden,
"optionstate": optionstate,
"str": str,
"edr": edr,
"cindex": cindex,
"stc": stc,
"edc": edc
};
file.filter[cindex - stc] = param;
}
else {
delete file.filter[cindex - stc];
}
server.saveParam("all", Store.currentSheetIndex, file.filter, { "k": "filter" });
}
}
//筛选排序
function orderbydatafiler(str, stc, edr, edc, index, asc) {
let d = editor.deepCopyFlowData(Store.flowdata);
str = str + 1;
let hasMc = false; //排序选区是否有合并单元格
let data = [];
for(let r = str; r <= edr; r++){
let data_row = [];
for(let c = stc; c <= edc; c++){
if(d[r][c] != null && d[r][c].mc != null){
hasMc = true;
break;
}
data_row.push(d[r][c]);
}
data.push(data_row);
}
if(hasMc){
const locale_filter = locale().filter;
if(isEditMode()){
alert(locale_filter.mergeError);
}
else{
tooltip.info(locale_filter.mergeError, "");
}
return;
}
data = orderbydata(data, index - stc, asc);
for(let r = str; r <= edr; r++){
for(let c = stc; c <= edc; c++){
d[r][c] = data[r - str][c - stc];
}
}
let allParam = {};
if(Store.config["rowlen"] != null){
let cfg = $.extend(true, {}, Store.config);
cfg = rowlenByRange(d, str, edr, cfg);
allParam = {
"cfg": cfg,
"RowlChange": true
}
}
jfrefreshgrid(d, [{ "row": [str, edr], "column": [stc, edc] }], allParam);
}
//创建筛选按钮
function createFilter() {
if(!checkProtectionAuthorityNormal(Store.currentSheetIndex, "filter")){
return;
}
if(Store.luckysheet_select_save.length > 1){
$("#luckysheet-rightclick-menu").hide();
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
$("#" + Store.container).attr("tabindex", 0).focus();
const locale_splitText = locale().splitText;
if(isEditMode()){
alert(locale_splitText.tipNoMulti);
}
else{
tooltip.info(locale_splitText.tipNoMulti, "");
}
return;
}
if(Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].isPivotTable){
return;
}
$('#luckysheet-filter-selected-sheet' + Store.currentSheetIndex + ', #luckysheet-filter-options-sheet' + Store.currentSheetIndex).remove();
let last = Store.luckysheet_select_save[0];
if (last["row"][0] == last["row"][1] && last["column"][0] == last["column"][1]) {
let st_c, ed_c, curR = last["row"][1];
for (let c = 0; c < Store.flowdata[curR].length; c++) {
let cell = Store.flowdata[curR][c];
if (cell != null && !isRealNull(cell.v)) {
if (st_c == null) {
st_c = c;
}
}
else if (st_c != null) {
ed_c = c - 1;
break;
}
}
if (ed_c == null) {
ed_c = Store.flowdata[curR].length - 1;
}
Store.luckysheet_select_save = [{ "row": [curR, curR], "column": [st_c, ed_c] }];
selectHightlightShow();
Store.luckysheet_shiftpositon = $.extend(true, {}, last);
luckysheetMoveEndCell("down", "range");
}
else if (last["row"][1] - last["row"][0] < 2) {
Store.luckysheet_shiftpositon = $.extend(true, {}, last);
luckysheetMoveEndCell("down", "range");
}
Store.luckysheet_filter_save = $.extend(true, {}, Store.luckysheet_select_save[0]);
createFilterOptions(Store.luckysheet_filter_save);
server.saveParam("all", Store.currentSheetIndex, Store.luckysheet_filter_save, { "k": "filter_select" });
if (Store.filterchage) {
Store.jfredo.push({
"type": "filtershow",
"data": [],
"curdata": [],
"sheetIndex": Store.currentSheetIndex,
"filter_save": Store.luckysheet_filter_save
});
}
}
//创建筛选配置
function createFilterOptions(luckysheet_filter_save, filterObj) {
$("#luckysheet-filter-selected-sheet" + Store.currentSheetIndex).remove();
$("#luckysheet-filter-options-sheet" + Store.currentSheetIndex).remove();
if(luckysheet_filter_save == null || JSON.stringify(luckysheet_filter_save) == "{}"){
return;
}
let r1 = luckysheet_filter_save.row[0],
r2 = luckysheet_filter_save.row[1];
let c1 = luckysheet_filter_save.column[0],
c2 = luckysheet_filter_save.column[1];
let row = Store.visibledatarow[r2],
row_pre = r1 - 1 == -1 ? 0 : Store.visibledatarow[r1 - 1];
let col = Store.visibledatacolumn[c2],
col_pre = c1 - 1 == -1 ? 0 : Store.visibledatacolumn[c1 - 1];
let newSelectedHTML = '<div id="luckysheet-filter-selected-sheet'+ Store.currentSheetIndex +'" class="luckysheet-cell-selected luckysheet-filter-selected" style="left:'+ col_pre +'px;width:'+ (col - col_pre - 1) +'px;top:'+ row_pre +'px;height:'+ (row - row_pre - 1) +'px;display:block;border-color:#897BFF;z-index:20;background:none;"></div>';
$("#luckysheet-cell-main").append(newSelectedHTML);
let optionHTML = "";
for (let c = c1; c <= c2; c++) {
if(filterObj == null || filterObj[c - c1] == null){
optionHTML += '<div data-rowhidden="" data-str="'+ r1 +'" data-edr="'+ r2 +'" data-cindex="'+ c +'" data-stc="'+ c1 +'" data-edc="'+ c2 +'" class="luckysheet-filter-options" style="left:'+ (Store.visibledatacolumn[c] - 20) +'px;top:'+ row_pre +'px;display:block;"><i class="fa fa-caret-down" aria-hidden="true"></i></div>';
}
else{
let caljs_data;
if(filterObj[c - c1].caljs != null){
let caljs_value1_data;
if (filterObj[c - c1].caljs["value1"] != null) {
caljs_value1_data = 'data-byconditionvalue1="'+ filterObj[c - c1].caljs["value1"] +'" ';
}
else{
caljs_value1_data = '';
}
let caljs_value2_data;
if (filterObj[c - c1].caljs["value2"] != null) {
caljs_value2_data = 'data-byconditionvalue2="'+ filterObj[c - c1].caljs["value2"] +'" ';
}
else{
caljs_value2_data = '';
}
caljs_data = 'data-caljs="'+ JSON.stringify(filterObj[c - c1].caljs) +'" ' +
'data-byconditionvalue="'+ filterObj[c - c1].caljs["value"] +'" ' +
'data-byconditiontype="'+ filterObj[c - c1].caljs["type"] +'" ' +
'data-byconditiontext="'+ filterObj[c - c1].caljs["text"] +'" ' +
caljs_value1_data + caljs_value2_data;
}
else{
caljs_data = '';
}
optionHTML += '<div data-rowhidden="'+ JSON.stringify(filterObj[c - c1].rowhidden).replace(/\"/g, "'") +'" '+ caljs_data +' data-str="'+ r1 +'" data-edr="'+ r2 +'" data-cindex="'+ c +'" data-stc="'+ c1 +'" data-edc="'+ c2 +'" class="luckysheet-filter-options luckysheet-filter-options-active" style="left:'+ (Store.visibledatacolumn[c] - 20) +'px;top:'+ row_pre +'px;display:block;"><i class="fa fa-filter luckysheet-mousedown-cancel" aria-hidden="true"></i></div>';
}
}
$("#luckysheet-cell-main").append('<div id="luckysheet-filter-options-sheet'+ Store.currentSheetIndex +'" class="luckysheet-filter-options-c">' + optionHTML + '</div>');
$("#luckysheet-rightclick-menu").hide();
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
if ($("#luckysheet-cell-main").scrollTop() > luckysheet_filter_save["top_move"]) {
$("#luckysheet-scrollbar-y").scrollTop(luckysheet_filter_save["top_move"]);
}
let file = Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)];
file.filter_select = luckysheet_filter_save;
}
function initialFilterHandler(){
//filter event handler
let hidefilersubmenu = null;
const _locale = locale();
const locale_filter = _locale.filter;
const locale_button= _locale.button;
$("#luckysheetfilter").click(createFilter);
//右键菜单 菜单项hover
let submenuhide = null, rightclickmenu = null;
$(".luckysheet-cols-menu .luckysheet-cols-submenu").hover(
function () {
let $t = $(this), attrid = $t.attr("id"), $attr = $("#" + attrid + "_sub"), $con = $t.parent();
let winW = $(window).width(), winH = $(window).height();
let menuW = $con.width(), attrH = $attr.height() + 25, attrW = $attr.width() + 5;
let offset = $t.offset();
let top = offset.top, left = offset.left + menuW;
if (left + attrW > winW) {
left = offset.left - attrW;
}
if (top + attrH > winH) {
top = winH - attrH;
}
$attr.css({ "top": top, "left": left }).show();
rightclickmenu = $t;
},
function () {
let $t = $(this), attrid = $t.attr("id"), $attr = $("#" + attrid + "_sub");
submenuhide = setTimeout(function () { $attr.hide(); }, 200);
}
);
$(".luckysheet-rightgclick-menu-sub").hover(
function () {
rightclickmenu.addClass("luckysheet-cols-menuitem-hover");
clearTimeout(submenuhide);
},
function () {
rightclickmenu.removeClass("luckysheet-cols-menuitem-hover");
$(this).hide();
}
);
$("#luckysheet-filter-menu").mouseover(function () {
clearTimeout(hidefilersubmenu);
hidefilersubmenu = setTimeout(function () {
$("#luckysheet-filter-submenu").hide();
}, 500);
});
$("#luckysheet-filter-submenu").mouseover(function () {
clearTimeout(hidefilersubmenu);
}).find(".luckysheet-cols-menuitem").click(function (e) {
$("#luckysheet-filter-selected span").html($(this).find(".luckysheet-cols-menuitem-content").text()).data("value", $(this).data("value"));
$("#luckysheet-filter-menu .luckysheet-filter-selected-input").hide();
let $type = $(this).data("type");
let $value = $(this).attr("data-value");
if ($type == "2") {
$("#luckysheet-filter-selected span").data("type", "2");
$("#luckysheet-filter-menu .luckysheet-filter-selected-input2").show();
$("#luckysheet-filter-menu .luckysheet-filter-selected-input input").prop("type", "number");
}
else if ($type == "0") {
$("#luckysheet-filter-selected span").data("type", "0");
}
else {
$("#luckysheet-filter-selected span").data("type", "1");
$("#luckysheet-filter-menu .luckysheet-filter-selected-input").eq(0).show();
//若是日期 改变input type类型为date
if($value == "dateequal" || $value == "datelessthan" || $value == "datemorethan"){
$("#luckysheet-filter-menu .luckysheet-filter-selected-input input").prop("type", "date");
}
else if($value == "morethan" || $value == "moreequalthan" || $value == "lessthan" || $value == "lessequalthan" || $value == "equal" || $value == "noequal"){
$("#luckysheet-filter-menu .luckysheet-filter-selected-input input").prop("type", "number");
}
else{
$("#luckysheet-filter-menu .luckysheet-filter-selected-input input").prop("type", "text");
}
}
$("#luckysheet-filter-byvalue").next().slideUp();
$("#luckysheet-filter-submenu").hide();
});
$("#luckysheet-filter-bycondition, #luckysheet-filter-byvalue").click(function () {
let $t = $(this);
$t.next().slideToggle(200);
setTimeout(function () {
if ($t.attr("id") == "luckysheet-filter-bycondition" && $("#luckysheet-filter-bycondition").next().is(":visible")) {
if ($("#luckysheet-filter-selected span").text() != locale_filter.filiterInputNone) {
$("#luckysheet-filter-byvalue").next().slideUp(200);
}
}
if ($t.is($("#luckysheet-filter-bycondition"))) {
if ($("#luckysheet-filter-bycondition").next().is(":hidden") && $("#luckysheet-filter-byvalue").next().is(":hidden")) {
$("#luckysheet-filter-byvalue").next().slideDown(200);
}
}
}, 300);
});
$("#luckysheet-filter-selected").click(function () {
let $t = $(this), toffset = $t.offset(), $menu = $("#luckysheet-filter-submenu");
$menu.hide();
let winH = $(window).height(), winW = $(window).width();
let menuW = $menu.width(), menuH = $menu.height();
let top = toffset.top, left = toffset.left, mheight = winH - toffset.top - 20;
if (toffset.left + menuW > winW) {
left = toffset.left - menuW;
}
if (toffset.top > winH / 2) {
top = winH - toffset.top;
if (top < 0) {
top = 0;
}
mheight = toffset.top - 20;
}
$menu.css({ "top": top, "left": left, "height": mheight }).show();
clearTimeout(hidefilersubmenu);
});
//筛选按钮点击事件
$("#luckysheet-cell-main").on("click", ".luckysheet-filter-options", function (e) {
if(!checkProtectionAuthorityNormal(Store.currentSheetIndex, "filter")){
return;
}
let $t = $(e.currentTarget),
toffset = $t.offset(),
$menu = $("#luckysheet-filter-menu"),
winH = $(window).height(),
winW = $(window).width();
let st_r = $t.data("str"),
ed_r = $t.data("edr"),
cindex = $t.data("cindex"),
st_c = $t.data("stc"),
ed_c = $t.data("edc"),
rowhidden = $t.data("rowhidden") == "" ? {} : JSON.parse($t.data("rowhidden").replace(/\'/g, '"'));
$("body .luckysheet-cols-menu").hide();
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
$("#luckysheet-filter-byvalue-input").val("");
$("#luckysheet-filter-bycondition").next().hide();
$("#luckysheet-filter-byvalue").next().show();
$menu.data("str", st_r);
$menu.data("edr", ed_r);
$menu.data("cindex", cindex);
$menu.data("stc", st_c);
$menu.data("edc", ed_c);
$("#luckysheet-filter-menu .luckysheet-filter-selected-input").hide().find("input").val();
$("#luckysheet-filter-selected span").data("type", "0").data("type", null).text(locale_filter.filiterInputNone);
let byconditiontype = $t.data("byconditiontype");
$("#luckysheet-filter-selected span").data("value", $t.data("byconditionvalue")).data("type", byconditiontype).text($t.data("byconditiontext"));
if (byconditiontype == "2") {
let $input = $("#luckysheet-filter-menu .luckysheet-filter-selected-input2").show().find("input");
$input.eq(0).val($t.data("byconditionvalue1"));
$input.eq(1).val($t.data("byconditionvalue2"));
}
else if (byconditiontype == "1") {
$("#luckysheet-filter-menu .luckysheet-filter-selected-input").eq(0).show().find("input").val($t.data("byconditionvalue1"));
}
$("#luckysheet-filter-orderby-asc").off("click").on("click", function () {
orderbydatafiler(st_r, st_c, ed_r, ed_c, cindex, true);
});
$("#luckysheet-filter-orderby-desc").off("click").on("click", function () {
orderbydatafiler(st_r, st_c, ed_r, ed_c, cindex, false);
});
$("#luckysheet-filter-byvalue-select").empty().html('<div style="width:100%;text-align:center;position:relative;top:45%;font-size:14px;"><div class="luckysheetLoaderGif"></div><span>'+locale_filter.filiterMoreDataTip+'</span></div>');
let rowhiddenother = {}; //其它筛选列的隐藏行
$("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").not(this).each(function () {
let $t = $(this), rh = $t.data("rowhidden");
if (rh == "") {
return true;
}
rh = JSON.parse(rh.replace(/\'/g, '"'));
for (let r in rh) {
rowhiddenother[r] = 0;
}
});
let data = Store.flowdata;
setTimeout(function () {
//日期值
let dvmap = {};
let dvmap_uncheck = {};
//除日期以外的值
let vmap = {};
let vmap_uncheck = {};
for (let r = st_r + 1; r <= ed_r; r++) {
if(r in rowhiddenother){
continue;
}
if(Store.flowdata[r] == null){
continue;
}
let cell = Store.flowdata[r][cindex];
if(cell != null && !isRealNull(cell.v) && cell.ct != null && cell.ct.t == "d" ){ //单元格是日期
let v = update("YYYY-MM-DD", cell.v);
let y = v.split("-")[0];
let m = v.split("-")[1];
let d = v.split("-")[2];
if(!(y in dvmap)){
dvmap[y] = {};
}
if(!(m in dvmap[y])){
dvmap[y][m] = {};
}
if(!(d in dvmap[y][m])){
dvmap[y][m][d] = 0;
}
dvmap[y][m][d]++;
if(r in rowhidden){
dvmap_uncheck[y] = 0;
dvmap_uncheck[m] = 0;
dvmap_uncheck[d] = 0;
}
}
else{
let v, m;
if(cell == null || isRealNull(cell.v)){
v = null;
m = null;
}
else{
v = cell.v;
m = cell.m;
}
if(!(v in vmap)){
vmap[v] = {};
}
if(!(m in vmap[v])){
vmap[v][m] = 0;
}
vmap[v][m]++;
if(r in rowhidden){
vmap_uncheck[v + "#$$$#" + m] = 0;
}
}
}
//遍历数据加到页面
let item = [];
if(JSON.stringify(dvmap).length > 2){
for(let y in dvmap){
let ysum = 0;
let monthHtml = '';
for(let m in dvmap[y]){
let msum = 0;
let dayHtml = '';
for(let d in dvmap[y][m]){
let dayL = dvmap[y][m][d];
msum += dayL;
//月 小于 10
let mT;
if(Number(m) < 10){
mT = "0" + Number(m);
}
else{
mT = m;
}
//日 小于 10
let dT;
if(Number(d) < 10){
dT = "0" + Number(d);
}
else{
dT = d;
}
//日是否选中状态
if((y in dvmap_uncheck) && (m in dvmap_uncheck) && (d in dvmap_uncheck)){
dayHtml += '<div class="day luckysheet-mousedown-cancel cf" data-check="false" title="'+ y +'-'+ mT +'-'+ dT +'">' +
'<input class="luckysheet-mousedown-cancel" type="checkbox"/>' +
'<label class="luckysheet-mousedown-cancel">' + d + '</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + dayL + ' )</span>' +
'</div>';
}
else{
dayHtml += '<div class="day luckysheet-mousedown-cancel cf" data-check="true" title="'+ y +'-'+ mT +'-'+ dT +'">' +
'<input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/>' +
'<label class="luckysheet-mousedown-cancel">' + d + '</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + dayL + ' )</span>' +
'</div>';
}
}
ysum += msum;
//月 小于 10
let mT2;
if(Number(m) < 10){
mT2 = "0" + Number(m);
}
else{
mT2 = m;
}
//月是否选中状态
if((y in dvmap_uncheck) && (m in dvmap_uncheck)){
monthHtml += '<div class="monthBox luckysheet-mousedown-cancel">' +
'<div class="month luckysheet-mousedown-cancel cf" data-check="false" title="'+ y +'-'+ mT2 +'">' +
'<i class="fa fa-caret-right luckysheet-mousedown-cancel" aria-hidden="true"></i>' +
'<input class="luckysheet-mousedown-cancel" type="checkbox"/>' +
'<label class="luckysheet-mousedown-cancel">' + m + ''+ locale_filter.filiterMonthText +'</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + msum + ' )</span>' +
'</div>' +
'<div class="dayList luckysheet-mousedown-cancel">' + dayHtml + '</div>' +
'</div>';
}
else{
monthHtml += '<div class="monthBox luckysheet-mousedown-cancel">' +
'<div class="month luckysheet-mousedown-cancel cf" data-check="true" title="'+ y +'-'+ mT2 +'">' +
'<i class="fa fa-caret-right luckysheet-mousedown-cancel" aria-hidden="true"></i>' +
'<input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/>' +
'<label class="luckysheet-mousedown-cancel">' + m + ''+ locale_filter.filiterMonthText +'</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + msum + ' )</span>' +
'</div>' +
'<div class="dayList luckysheet-mousedown-cancel">' + dayHtml + '</div>' +
'</div>';
}
}
//年是否选中状态
let yearHtml;
if(y in dvmap_uncheck){
yearHtml = '<div class="yearBox luckysheet-mousedown-cancel">' +
'<div class="year luckysheet-mousedown-cancel cf" data-check="false" title="'+ y +'">' +
'<i class="fa fa-caret-right luckysheet-mousedown-cancel" aria-hidden="true"></i>' +
'<input class="luckysheet-mousedown-cancel" type="checkbox"/>' +
'<label class="luckysheet-mousedown-cancel">' + y + ''+ locale_filter.filiterYearText +'</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + ysum + ' )</span>' +
'</div>' +
'<div class="monthList luckysheet-mousedown-cancel">' + monthHtml + '</div>' +
'</div>';
}
else{
yearHtml = '<div class="yearBox luckysheet-mousedown-cancel">' +
'<div class="year luckysheet-mousedown-cancel cf" data-check="true" title="'+ y +'">' +
'<i class="fa fa-caret-right luckysheet-mousedown-cancel" aria-hidden="true"></i>' +
'<input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/>' +
'<label class="luckysheet-mousedown-cancel">' + y + ''+ locale_filter.filiterYearText +'</label>' +
'<span class="count luckysheet-mousedown-cancel">( ' + ysum + ' )</span>' +
'</div>' +
'<div class="monthList luckysheet-mousedown-cancel">' + monthHtml + '</div>' +
'</div>';
}
item.unshift(yearHtml);
}
}
if(JSON.stringify(vmap).length > 2){
let vmapKeys = Object.keys(vmap);
vmapKeys = orderbydata1D(vmapKeys, true);
for(let i = 0; i < vmapKeys.length; i++){
let v = vmapKeys[i];
for(let x in vmap[v]){
let text;
if((v + "#$$$#" + x) == "null#$$$#null"){
text = locale_filter.valueBlank;
}
else{
text = x;
}
//是否选中状态
let dataHtml;
if((v + "#$$$#" + x) in vmap_uncheck){
dataHtml = '<div class="textBox luckysheet-mousedown-cancel cf" data-check="false" data-filter="'+ (v + "#$$$#" + x) +'" title="'+ text +'">' +
'<input class="luckysheet-mousedown-cancel" type="checkbox"/>' +
'<label class="luckysheet-mousedown-cancel">' + text + '</label>' +
'<span class="luckysheet-mousedown-cancel count">( ' + vmap[v][x] + ' )</span>' +
'</div>';
}
else{
dataHtml = '<div class="textBox luckysheet-mousedown-cancel cf" data-check="true" data-filter="'+ (v + "#$$$#" + x) +'" title="'+ text +'">' +
'<input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/>' +
'<label class="luckysheet-mousedown-cancel">' + text + '</label>' +
'<span class="luckysheet-mousedown-cancel count">( ' + vmap[v][x] + ' )</span>' +
'</div>';
}
item.push(dataHtml);
}
}
}
$("#luckysheet-filter-byvalue-select").html("<div class='ListBox luckysheet-mousedown-cancel' style='min-height: 100px; max-height: " + (winH - toffset.top - 350) + "px; overflow-y: auto; overflow-x: hidden;'><table cellspacing='0' style='width:100%;' class='luckysheet-mousedown-cancel'>" + item.join("") + "</table></div>");
}, 1);
showrightclickmenu($menu, toffset.left, toffset.top + 20);
e.stopPropagation();
return false;
});
//按颜色筛选
$("#luckysheet-filter-orderby-color").hover(
function(){
//遍历筛选列颜色
let $menu = $("#luckysheet-filter-menu");
let st_r = $menu.data("str"),
ed_r = $menu.data("edr"),
cindex = $menu.data("cindex"),
st_c = $menu.data("stc"),
ed_c = $menu.data("edc");
let bgMap = {}; //单元格颜色
let fcMap = {}; //字体颜色
let af_compute = alternateformat.getComputeMap();
let cf_compute = conditionformat.getComputeMap();
for (let r = st_r + 1; r <= ed_r; r++) {
let cell = Store.flowdata[r][cindex];
//单元格颜色
let bg = menuButton.checkstatus(Store.flowdata, r, cindex , "bg");
if(bg == null){
bg = "#ffffff";
}
let checksAF = alternateformat.checksAF(r, cindex, af_compute);
if(checksAF != null){//若单元格有交替颜色
bg = checksAF[1];
}
let checksCF = conditionformat.checksCF(r, cindex, cf_compute);
if(checksCF != null && checksCF["cellColor"] != null){//若单元格有条件格式
bg = checksCF["cellColor"];
}
if(bg.indexOf("rgb") > -1){
bg = rgbTohex(bg);
}
if(bg.length == 4){
bg = bg.substr(0, 1) + bg.substr(1, 1).repeat(2) + bg.substr(2, 1).repeat(2) + bg.substr(3, 1).repeat(2);
}
//字体颜色
let fc = menuButton.checkstatus(Store.flowdata, r, cindex , "fc");
if(checksAF != null){//若单元格有交替颜色
fc = checksAF[0];
}
if(checksCF != null && checksCF["textColor"] != null){//若单元格有条件格式
fc = checksCF["textColor"];
}
if(fc.indexOf("rgb") > -1){
fc = rgbTohex(fc);
}
if(fc.length == 4){
fc = fc.substr(0, 1) + fc.substr(1, 1).repeat(2) + fc.substr(2, 1).repeat(2) + fc.substr(3, 1).repeat(2);
}
if(Store.config != null && Store.config["rowhidden"] != null && r in Store.config["rowhidden"]){
bgMap[bg] = 1;
if(cell != null && !isRealNull(cell.v)){
fcMap[fc] = 1;
}
}
else{
bgMap[bg] = 0;
if(cell != null && !isRealNull(cell.v)){
fcMap[fc] = 0;
}
}
}
//
let filterBgColorHtml = '';
if(JSON.stringify(bgMap).length > 2 && Object.keys(bgMap).length > 1){
let bgColorItemHtml = '';
for(let b in bgMap){
if(bgMap[b] == 0){
bgColorItemHtml += '<div class="item luckysheet-mousedown-cancel"><label class="luckysheet-mousedown-cancel" style="background-color: ' + b + '" title="' + b + '"></label><input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/></div>';
}
else{
bgColorItemHtml += '<div class="item luckysheet-mousedown-cancel"><label class="luckysheet-mousedown-cancel" style="background-color: ' + b + '" title="' + b + '"></label><input class="luckysheet-mousedown-cancel" type="checkbox"/></div>';
}
}
filterBgColorHtml = '<div id="filterBgColor" class="box luckysheet-mousedown-cancel"><div class="title luckysheet-mousedown-cancel">'+locale_filter.filiterByColorTip+'</div><div style="max-height:128px;overflow:auto;" class="luckysheet-mousedown-cancel">' + bgColorItemHtml + '</div></div>';
}
let filterFcColorHtml = '';
if(JSON.stringify(fcMap).length > 2 && Object.keys(fcMap).length > 1){
let fcColorItemHtml = '';
for(let f in fcMap){
if(fcMap[f] == 0){
fcColorItemHtml += '<div class="item luckysheet-mousedown-cancel"><label class="luckysheet-mousedown-cancel" style="background-color: ' + f + '" title="' + f + '"></label><input class="luckysheet-mousedown-cancel" type="checkbox" checked="checked"/></div>';
}
else{
fcColorItemHtml += '<div class="item luckysheet-mousedown-cancel"><label class="luckysheet-mousedown-cancel" style="background-color: ' + f + '" title="' + f + '"></label><input class="luckysheet-mousedown-cancel" type="checkbox"/></div>';
}
}
filterFcColorHtml = '<div id="filterFcColor" class="box luckysheet-mousedown-cancel"><div class="title luckysheet-mousedown-cancel">'+locale_filter.filiterByTextColorTip+'</div><div style="max-height:128px;overflow:auto;" class="luckysheet-mousedown-cancel">' + fcColorItemHtml + '</div></div>';
}
//
let content;
if(filterBgColorHtml == '' && filterFcColorHtml == ''){
content = '<div class="luckysheet-mousedown-cancel" style="padding: 10px 30px;text-align: center;">'+locale_filter.filterContainerOneColorTip+'</div>';
}
else{
content = filterBgColorHtml + filterFcColorHtml + '<div class="luckysheet-mousedown-cancel"><button id="luckysheet-filter-orderby-color-confirm" class="btn btn-primary luckysheet-mousedown-cancel" style="margin: 5px 20px;width: 70px;">'+locale_button.confirm+'</button></div>';
}
//颜色筛选子菜单
$("#luckysheet-filter-orderby-color-submenu").remove();
$("body").append('<div id="luckysheet-filter-orderby-color-submenu" class="luckysheet-cols-menu luckysheet-mousedown-cancel">'+content+'</div>');
let $t = $("#luckysheet-filter-orderby-color-submenu").end();
let $con = $(this).parent();
let winW = $(window).width(), winH = $(window).height();
let menuW = $con.width(),
myh = $t.height() + 25,
myw = $t.width() + 5;
let offset = $(this).offset();
let top = offset.top, left = offset.left + menuW;
if (left + myw > winW) {
left = offset.left - myw;
}
if (top + myh > winH) {
top = winH - myh;
}
$("#luckysheet-filter-orderby-color-submenu").css({ "top": top, "left": left }).show();
},
function(){
submenuhide = setTimeout(function () { $("#luckysheet-filter-orderby-color-submenu").hide(); }, 200);
}
);
$(document).on("mouseover mouseleave", "#luckysheet-filter-orderby-color-submenu", function(e){
if (e.type === "mouseover") {
clearTimeout(submenuhide);
}
else {
$(this).hide();
}
});
$(document).on("click", "#luckysheet-filter-orderby-color-submenu .item label", function(){
$(this).siblings("input[type='checkbox']").click();
});
$(document).off("click.orderbyColorConfirm").on("click.orderbyColorConfirm", "#luckysheet-filter-orderby-color-submenu #luckysheet-filter-orderby-color-confirm", function(){
let bg_colorMap = {};
let fc_colorMap = {};
$("#luckysheet-filter-orderby-color-submenu .item").each(function(i, e){
if($(e).find("input[type='checkbox']").is(":checked")){
let color = $(this).find("label").attr("title");
let $id = $(this).closest(".box").attr("id");
if($id == "filterBgColor"){
bg_colorMap[color] = 0;
}
else if($id == "filterFcColor"){
fc_colorMap[color] = 0;
}
}
});
let bg_filter;
if($("#luckysheet-filter-orderby-color-submenu #filterBgColor").length > 0){
bg_filter = true;
}
else{
bg_filter = false;
}
let fc_filter;
if($("#luckysheet-filter-orderby-color-submenu #filterFcColor").length > 0){
fc_filter = true;
}
else{
fc_filter = false;
}
let $menu = $("#luckysheet-filter-menu");
let st_r = $menu.data("str"),
ed_r = $menu.data("edr"),
cindex = $menu.data("cindex"),
st_c = $menu.data("stc"),
ed_c = $menu.data("edc");
let rowhiddenother = {}; //其它筛选列的隐藏行
$("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").not($("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").eq(cindex - st_c).get(0)).each(function () {
let $t = $(this), rh = $t.data("rowhidden");
if (rh == "") {
return true;
}
rh = JSON.parse(rh);
for (let r in rh) {
rowhiddenother[r] = 0;
}
});
let filterdata = {};
let rowhidden = {};
let caljs = {};
let af_compute = alternateformat.getComputeMap();
let cf_compute = conditionformat.getComputeMap();
for (let r = st_r + 1; r <= ed_r; r++) {
if(r in rowhiddenother){
continue;
}
if(Store.flowdata[r] == null){
continue;
}
let cell = Store.flowdata[r][cindex];
//单元格颜色
let bg = menuButton.checkstatus(Store.flowdata, r, cindex , "bg");
let checksAF = alternateformat.checksAF(r, cindex, af_compute);
if(checksAF != null){//若单元格有交替颜色
bg = checksAF[1];
}
let checksCF = conditionformat.checksCF(r, cindex, cf_compute);
if(checksCF != null && checksCF["cellColor"] != null){//若单元格有条件格式
bg = checksCF["cellColor"];
}
// bg maybe null
bg = bg == null ? '#ffffff' : bg;
if(bg.indexOf("rgb") > -1){
bg = rgbTohex(bg);
}
if(bg.length == 4){
bg = bg.substr(0, 1) + bg.substr(1, 1).repeat(2) + bg.substr(2, 1).repeat(2) + bg.substr(3, 1).repeat(2);
}
//文本颜色
let fc = menuButton.checkstatus(Store.flowdata, r, cindex , "fc");
if(checksAF != null){//若单元格有交替颜色
fc = checksAF[0];
}
if(checksCF != null && checksCF["textColor"] != null){//若单元格有条件格式
fc = checksCF["textColor"];
}
if(fc.indexOf("rgb") > -1){
fc = rgbTohex(fc);
}
if(fc.length == 4){
fc = fc.substr(0, 1) + fc.substr(1, 1).repeat(2) + fc.substr(2, 1).repeat(2) + fc.substr(3, 1).repeat(2);
}
if(bg_filter && fc_filter){
if(!(bg in bg_colorMap) && (!(fc in fc_colorMap) || cell == null || isRealNull(cell.v))){
rowhidden[r] = 0;
}
}
else if(bg_filter){
if(!(bg in bg_colorMap)){
rowhidden[r] = 0;
}
}
else if(fc_filter){
if(!(fc in fc_colorMap) || cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
}
}
let $top = $("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").eq(cindex - st_c);
let optionstate = Object.keys(rowhidden).length > 0;
let rowhiddenall = $.extend(true, rowhiddenother, rowhidden),
rowhidenPre = json.parseJsonParm($top.data("rowhidden"));
labelFilterOptionState($top, optionstate, rowhidden, caljs, true, st_r, ed_r, cindex, st_c, ed_c);
let cfg = $.extend(true, {}, Store.config);
cfg["rowhidden"] = rowhiddenall;
//保存撤销
if(Store.clearjfundo){
let redo = {};
redo["type"] = "datachangeAll_filter";
redo["sheetIndex"] = Store.currentSheetIndex;
redo["config"] = $.extend(true, {}, Store.config);
redo["curconfig"] = cfg;
redo["optionstate"] = optionstate;
redo["optionsindex"] = cindex - st_c;
redo["rowhidden"] = $.extend(true, {}, rowhidden);
redo["rowhidenPre"] = $.extend(true, {}, rowhidenPre);
if (caljs != null) {
redo["caljs"] = caljs;
}
Store.jfundo = [];
Store.jfredo.push(redo);
}
//config
Store.config = cfg;
Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].config = Store.config;
server.saveParam("cg", Store.currentSheetIndex, cfg["rowhidden"], { "k": "rowhidden" });
//行高、列宽 刷新
jfrefreshgrid_rhcw(Store.flowdata.length, Store.flowdata[0].length);
$("#luckysheet-filter-menu, #luckysheet-filter-submenu, #luckysheet-filter-orderby-color-submenu").hide();
cleargridelement();
});
//点击复选框
$(document).off("click.filterCheckbox1").on("click.filterCheckbox1", "#luckysheet-filter-byvalue-select .textBox",function(){
if($(this).attr("data-check") == "true"){
$(this).attr("data-check", "false");
$(this).find("input[type='checkbox']").removeAttr("checked");
}
else{
$(this).attr("data-check", "true");
$(this).find("input[type='checkbox']").prop("checked", true);
}
})
$(document).off("click.filterCheckbox2").on("click.filterCheckbox2", "#luckysheet-filter-byvalue-select .year",function(){
if($(this).attr("data-check") == "true"){
$(this).attr("data-check", "false");
$(this).parents(".yearBox").find(".month").attr("data-check", "false");
$(this).parents(".yearBox").find(".day").attr("data-check", "false");
$(this).parents(".yearBox").find("input[type='checkbox']").removeAttr("checked");
}
else{
$(this).attr("data-check", "true");
$(this).parents(".yearBox").find(".month").attr("data-check", "true");
$(this).parents(".yearBox").find(".day").attr("data-check", "true");
$(this).parents(".yearBox").find("input[type='checkbox']").prop("checked", true);
}
})
$(document).off("click.filterCheckbox3").on("click.filterCheckbox3", "#luckysheet-filter-byvalue-select .month",function(){
//月份 对应的 天
if($(this).attr("data-check") == "true"){
$(this).attr("data-check", "false");
$(this).parents(".monthBox").find(".day").attr("data-check", "false");
$(this).parents(".monthBox").find("input[type='checkbox']").removeAttr("checked");
}
else{
$(this).attr("data-check", "true");
$(this).parents(".monthBox").find(".day").attr("data-check", "true");
$(this).parents(".monthBox").find("input[type='checkbox']").prop("checked", true);
}
//月份 对应的 年份
let yearDayAllCheck = true;
let $yearDay = $(this).parents(".yearBox").find(".day");
$yearDay.each(function(i,e){
if($(e).attr("data-check") == "true"){
}
else{
yearDayAllCheck = false;
}
});
if(yearDayAllCheck){
$(this).parents(".yearBox").find(".year").attr("data-check", "true");
$(this).parents(".yearBox").find(".year input[type='checkbox']").prop("checked", true);
}
else{
$(this).parents(".yearBox").find(".year").attr("data-check", "false");
$(this).parents(".yearBox").find(".year input[type='checkbox']").removeAttr("checked");
}
})
$(document).off("click.filterCheckbox4").on("click.filterCheckbox4", "#luckysheet-filter-byvalue-select .day",function(){
if($(this).attr("data-check") == "true"){
$(this).attr("data-check", "false");
$(this).find("input[type='checkbox']").removeAttr("checked");
}
else{
$(this).attr("data-check", "true");
$(this).find("input[type='checkbox']").prop("checked", true);
}
//天 对应的 月份
let monthDayAllCheck = true;
let $monthDay = $(this).parents(".monthBox").find(".day");
$monthDay.each(function(i,e){
if($(e).attr("data-check") == "true"){
}
else{
monthDayAllCheck = false;
}
});
if(monthDayAllCheck){
$(this).parents(".monthBox").find(".month").attr("data-check", "true");
$(this).parents(".monthBox").find(".month input[type='checkbox']").prop("checked", true);
}
else{
$(this).parents(".monthBox").find(".month").attr("data-check", "false");
$(this).parents(".monthBox").find(".month input[type='checkbox']").removeAttr("checked");
}
//天 对应的 年份
let yearDayAllCheck = true;
let $yearDay = $(this).parents(".yearBox").find(".day");
$yearDay.each(function(i,e){
if($(e).attr("data-check") == "true"){
}
else{
yearDayAllCheck = false;
}
});
if(yearDayAllCheck){
$(this).parents(".yearBox").find(".year").attr("data-check", "true");
$(this).parents(".yearBox").find(".year input[type='checkbox']").prop("checked", true);
}
else{
$(this).parents(".yearBox").find(".year").attr("data-check", "false");
$(this).parents(".yearBox").find(".year input[type='checkbox']").removeAttr("checked");
}
})
//日期 三级下拉显示
$(document).off("click.filterYearDropdown").on("click.filterYearDropdown", "#luckysheet-filter-byvalue-select .yearBox .fa-caret-right",function(event){
let $p = $(this).parents(".luckysheet-mousedown-cancel");
if($p.hasClass("year")){
$(this).parents(".yearBox").find(".monthList").slideToggle();
}
if($p.hasClass("month")){
$(this).parents(".monthBox").find(".dayList").slideToggle();
}
event.stopPropagation();
});
//全选
$("#luckysheet-filter-byvalue-btn-all").click(function () {
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").prop("checked", true);
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").parents(".luckysheet-mousedown-cancel").attr("data-check", "true");
});
//清除
$("#luckysheet-filter-byvalue-btn-clear").click(function () {
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").removeAttr("checked");
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").parents(".luckysheet-mousedown-cancel").attr("data-check", "false");
});
//反选
$("#luckysheet-filter-byvalue-btn-contra").click(function () {
let $input = $("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']");
$input.each(function(i, e){
if($(e).is(":checked")){
$(e).removeAttr("checked");
$(e).parents(".luckysheet-mousedown-cancel").attr("data-check", "false");
}
else{
$(e).prop("checked", true);
$(e).parents(".luckysheet-mousedown-cancel").attr("data-check", "true");
}
});
//天 对应的 月份
let $month = $("#luckysheet-filter-byvalue-select .ListBox .monthBox");
$month.each(function(index, event){
let monthDayAllCheck = true;
let $monthDay = $(event).find(".day input[type='checkbox']");
$monthDay.each(function(i,e){
if($(e).is(":checked")){
}
else{
monthDayAllCheck = false;
}
});
if(monthDayAllCheck){
$(event).find(".month input[type='checkbox']").prop("checked", true);
$(event).attr("data-check", "true");
}
else{
$(event).find(".month input[type='checkbox']").removeAttr("checked");
$(event).attr("data-check", "false");
}
});
//天 对应的 年份
let $year = $("#luckysheet-filter-byvalue-select .ListBox .yearBox");
$year.each(function(index, event){
let yearDayAllCheck = true;
let $yearDay = $(event).find(".day input[type='checkbox']");
$yearDay.each(function(i,e){
if($(e).is(":checked")){
}
else{
yearDayAllCheck = false;
}
});
if(yearDayAllCheck){
$(event).find(".year input[type='checkbox']").prop("checked", true);
$(event).attr("data-check", "true");
}
else{
$(event).find(".year input[type='checkbox']").removeAttr("checked");
$(event).attr("data-check", "false");
}
});
});
//清除筛选
$("#luckysheet-filter-initial").click(function () {
if(!checkProtectionAuthorityNormal(Store.currentSheetIndex, "filter")){
return;
}
$("#luckysheet-filter-menu .luckysheet-filter-selected-input").hide().find("input").val();
$("#luckysheet-filter-selected span").data("type", "0").data("type", null).text(locale_filter.conditionNone);
let redo = {};
redo["type"] = "datachangeAll_filter_clear";
redo["sheetIndex"] = Store.currentSheetIndex;
redo["config"] = $.extend(true, {}, Store.config);
Store.config["rowhidden"] = {};
redo["curconfig"] = $.extend(true, {}, Store.config);
redo["filter_save"] = $.extend(true, {}, Store.luckysheet_filter_save);
let optiongroups = [];
$("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").each(function () {
let $t = $(this);
let optionstate = $t.hasClass("luckysheet-filter-options-active");
let rowhidden = json.parseJsonParm($t.data("rowhidden"));
let caljs = json.parseJsonParm($t.data("caljs"));
optiongroups.push({
"optionstate":optionstate,
"rowhidden": rowhidden,
"caljs":caljs,
"str": $t.data("str"),
"edr": $t.data("edr"),
"cindex": $t.data("cindex"),
"stc": $t.data("stc"),
"edc": $t.data("edc")
});
});
redo["optiongroups"] = optiongroups;
Store.jfundo = [];
Store.jfredo.push(redo);
$('#luckysheet-filter-selected-sheet' + Store.currentSheetIndex + ', #luckysheet-filter-options-sheet' + Store.currentSheetIndex).remove();
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
//清除筛选发送给后台
Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].filter = null;
Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].filter_select = null;
server.saveParam("fsc", Store.currentSheetIndex, null);
//config
Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].config = Store.config;
server.saveParam("cg", Store.currentSheetIndex, {}, { "k": "rowhidden" });
//行高、列宽 刷新
jfrefreshgrid_rhcw(Store.flowdata.length, Store.flowdata[0].length);
});
//按照值进行筛选
$("#luckysheet-filter-byvalue-input").on('input propertychange', function () {
let v = $(this).val().toString();
$("#luckysheet-filter-byvalue-select .ListBox .luckysheet-mousedown-cancel").show();
if(v != ""){
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").each(function(i, e){
if($(e).closest(".day").length > 0){
let day = $(e).siblings("label").text().toString();
let month = $(e).closest(".monthBox").find(".month label").text().toString();
let year = $(e).closest(".yearBox").find(".year label").text().toString();
let itemV = year + "-" + month + "-" + day;
if(itemV.indexOf(v) == -1){
$(e).closest(".day").hide();
//天 对应的 月份
let $monthDay = $(e).closest(".dayList").find(".day:visible");
if($monthDay.length == 0){
$(e).closest(".monthBox").find(".month").hide();
}
//天 对应的 年份
let $yearDay = $(e).closest(".monthList").find(".day:visible");
if($yearDay.length == 0){
$(e).closest(".yearBox").find(".year").hide();
}
}
}
if($(e).closest(".textBox").length > 0){
let itemV = $(e).siblings("label").text().toString();
if(itemV.indexOf(v) == -1){
$(e).parents(".textBox").hide();
}
}
});
}
});
//筛选取消
$("#luckysheet-filter-cancel").click(function () {
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
});
//筛选 确认
$("#luckysheet-filter-confirm").click(function () {
let $menu = $("#luckysheet-filter-menu");
let st_r = $menu.data("str"),
ed_r = $menu.data("edr"),
cindex = $menu.data("cindex"),
st_c = $menu.data("stc"),
ed_c = $menu.data("edc");
let rowhiddenother = {}; //其它筛选列的隐藏行
$("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").not($("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").eq(cindex - st_c).get(0)).each(function () {
let $t = $(this), rh = $t.data("rowhidden");
if (rh == "") {
return true;
}
rh = JSON.parse(rh.replace(/\'/g, '"'));
for (let r in rh) {
rowhiddenother[r] = 0;
}
});
let filterdata = {};
let rowhidden = {};
let caljs = {};
if ($("#luckysheet-filter-bycondition").next().is(":visible") && $("#luckysheet-filter-byvalue").next().is(":hidden") && $("#luckysheet-filter-selected span").data("value") != "null") {
let $t = $("#luckysheet-filter-selected span");
let type = $t.data("type"), value = $t.data("value");
caljs["value"] = value;
caljs["text"] = $t.text();
if (type == "0") {
caljs["type"] = "0";
}
else if (type == "2") {
let $input = $("#luckysheet-filter-menu .luckysheet-filter-selected-input2 input");
caljs["type"] = "2";
caljs["value1"] = $input.eq(0).val();
caljs["value2"] = $input.eq(1).val();
}
else {
caljs["type"] = "1";
caljs["value1"] = $("#luckysheet-filter-menu .luckysheet-filter-selected-input").eq(0).find("input").val();
}
for (let r = st_r + 1; r <= ed_r; r++) {
if(r in rowhiddenother){
continue;
}
if(Store.flowdata[r] == null){
continue;
}
let cell = Store.flowdata[r][cindex];
if (value == "cellnull") { //单元格为空
if(cell != null && !isRealNull(cell.v)){
rowhidden[r] = 0;
}
}
else if (value == "cellnonull") { //单元格有数据
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
}
else if (value == "textinclude") { //文本包含
let value1 = caljs["value1"];
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else{
if(cell.m.indexOf(value1) == -1){
rowhidden[r] = 0;
}
}
}
else if (value == "textnotinclude") { //文本不包含
let value1 = caljs["value1"];
if(cell == null || isRealNull(cell.v)){
}
else{
if(cell.m.indexOf(value1) > -1){
rowhidden[r] = 0;
}
}
}
else if (value == "textstart") { //文本开头为
let value1 = caljs["value1"], valuelen = value1.length;
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else{
if(cell.m.substr(0, valuelen) != value1){
rowhidden[r] = 0;
}
}
}
else if (value == "textend") { //文本结尾为
let value1 = caljs["value1"], valuelen = value1.length;
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else{
if(valuelen > cell.m.length || cell.m.substr(cell.m.length - valuelen, valuelen) != value1){
rowhidden[r] = 0;
}
}
}
else if (value == "textequal") { //文本等于
let value1 = caljs["value1"];
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else{
if(cell.m != value1){
rowhidden[r] = 0;
}
}
}
else if (value == "dateequal") { //日期等于
let value1 = genarate(caljs["value1"])[2];
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "d"){
if(parseInt(cell.v) != value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "datelessthan") { //日期早于
let value1 = genarate(caljs["value1"])[2];
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "d"){
if(parseInt(cell.v) >= value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "datemorethan") { //日期晚于
let value1 = genarate(caljs["value1"])[2];
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "d"){
if(parseInt(cell.v) <= value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "morethan") { //大于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v <= value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "moreequalthan") { //大于等于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v < value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "lessthan") { //小于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v >= value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "lessequalthan") { //小于等于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v > value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "equal") { //等于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v != value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "noequal") { //不等于
let value1 = parseFloat(caljs["value1"]);
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v == value1){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "include") { //介于
let value1 = parseFloat(caljs["value1"]), value2 = parseFloat(caljs["value2"]);
let min, max;
if(value1 < value2){
min = value1;
max = value2;
}
else{
max = value1;
min = value2;
}
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v < min || cell.v > max){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
else if (value == "noinclude") { //不在其中
let value1 = parseFloat(caljs["value1"]), value2 = parseFloat(caljs["value2"]);
let min, max;
if(value1 < value2){
min = value1;
max = value2;
}
else{
max = value1;
min = value2;
}
if(cell == null || isRealNull(cell.v)){
rowhidden[r] = 0;
}
else if(cell.ct != null && cell.ct.t == "n"){
if(cell.v >= min && cell.v <= max){
rowhidden[r] = 0;
}
}
else{
rowhidden[r] = 0;
}
}
}
}
else {
$("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']").each(function(i, e){
if($(e).is(":visible") && $(e).is(":checked")){
return true;
}
if($(e).closest(".day").length > 0){
let day = $(e).siblings("label").text();
if(Number(day) < 10){
day = "0" + Number(day);
}
let month = $(e).closest(".monthBox").find(".month label").text().replace(locale_filter.filiterMonthText, "");
if(Number(month) < 10){
month = "0" + Number(month);
}
let year = $(e).closest(".yearBox").find(".year label").text().replace(locale_filter.filiterYearText, "");
let itemV = locale_filter.filterDateFormatTip +"#$$$#" + year + "-" + month + "-" + day;
filterdata[itemV] = "1";
}
if($(e).closest(".textBox").length > 0){
let itemV = $(e).closest(".textBox").data("filter");
filterdata[itemV] = "1";
}
});
for (let r = st_r + 1; r <= ed_r; r++) {
if(r in rowhiddenother){
continue;
}
if(Store.flowdata[r] == null){
continue;
}
let cell = Store.flowdata[r][cindex];
let value;
if(cell == null || isRealNull(cell.v)){
value = "null#$$$#null";
}
else if(cell.ct != null && cell.ct.t == "d"){
let fmt = update("YYYY-MM-DD", cell.v);
value = locale_filter.filterDateFormatTip +"#$$$#" + fmt;
}
else{
value = cell.v + "#$$$#" + cell.m;
}
if(value in filterdata){
rowhidden[r] = 0;
}
}
}
let $top = $("#luckysheet-filter-options-sheet" + Store.currentSheetIndex + " .luckysheet-filter-options").eq(cindex - st_c);
let optionstate = $("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']:visible:checked").length < $("#luckysheet-filter-byvalue-select .ListBox input[type='checkbox']:visible").length || $("#luckysheet-filter-byvalue-input").val().length > 0 || ($("#luckysheet-filter-bycondition").next().is(":visible") && $("#luckysheet-filter-byvalue").next().is(":hidden") && $("#luckysheet-filter-selected span").data("value") != "null");
let rowhiddenall = $.extend(true, rowhiddenother, rowhidden),
rowhidenPre = json.parseJsonParm($top.data("rowhidden"));
labelFilterOptionState($top, optionstate, rowhidden, caljs, true, st_r, ed_r, cindex, st_c, ed_c);
let cfg = $.extend(true, {}, Store.config);
cfg["rowhidden"] = rowhiddenall;
//保存撤销
if(Store.clearjfundo){
let redo = {};
redo["type"] = "datachangeAll_filter";
redo["sheetIndex"] = Store.currentSheetIndex;
redo["config"] = $.extend(true, {}, Store.config);
redo["curconfig"] = cfg;
redo["optionstate"] = optionstate;
redo["optionsindex"] = cindex - st_c;
redo["rowhidden"] = $.extend(true, {}, rowhidden);
redo["rowhidenPre"] = $.extend(true, {}, rowhidenPre);
if (caljs != null) {
redo["caljs"] = caljs;
}
Store.jfundo = [];
Store.jfredo.push(redo);
}
//config
Store.config = cfg;
Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].config = Store.config;
server.saveParam("cg", Store.currentSheetIndex, cfg["rowhidden"], { "k": "rowhidden" });
//行高、列宽 刷新
jfrefreshgrid_rhcw(Store.flowdata.length, Store.flowdata[0].length);
$("#luckysheet-filter-menu, #luckysheet-filter-submenu").hide();
cleargridelement();
});
}
export {
labelFilterOptionState,
orderbydatafiler,
createFilter,
createFilterOptions,
initialFilterHandler
}
|
from ipaddr import IPv4Network
from pyramid.view import view_config
from geoportailv3.models import LuxLayerInternalWMS, LuxPredefinedWms
from c2cgeoportal.models import DBSession, RestrictionArea, Role, Layer
from pyramid.response import Response
from pyramid.httpexceptions import HTTPBadGateway, HTTPBadRequest
from pyramid.httpexceptions import HTTPNotFound, HTTPUnauthorized
from urlparse import urlparse
import logging
import urllib
import urllib2
import socket
log = logging.getLogger(__name__)
class Wms(object):
def __init__(self, request):
self.request = request
def _check_token(self, token):
config = self.request.registry.settings
if config["authtkt_secret"] == token:
return True
return False
def _check_ip(self, client_ip):
client_ip = IPv4Network(client_ip).ip
config = self.request.registry.settings
if "authorized_ips" in config:
authorized_ips = config["authorized_ips"].split(",")
for authorized_ip in authorized_ips:
a_ip = IPv4Network(authorized_ip.strip())
if (client_ip == a_ip.network) or (
(client_ip >= a_ip.network) and
(client_ip < a_ip.broadcast)):
return True
return False
def _check_ip_for_httpsproxy(self, url):
parsedurl = urlparse(url)
hostname = parsedurl.netloc.split(":")
remote_ip = IPv4Network(socket.gethostbyname(hostname[0])).ip
config = self.request.registry.settings
if "https_proxy" in config:
if "unauthorized_ips" in config["https_proxy"]:
unauthorized_ips =\
config["https_proxy"]['unauthorized_ips'].split(",")
for unauthorized_ip in unauthorized_ips:
a_ip = IPv4Network(unauthorized_ip.strip())
if (remote_ip == a_ip.network) or (
(remote_ip >= a_ip.network) and
(remote_ip < a_ip.broadcast)):
return False
return True
@view_config(route_name='wms')
def internal_proxy_wms(self):
layers = self.request.params.get('LAYERS', '')
layers = layers.split(',')
if len(layers) == 0:
return HTTPBadRequest()
# TODO: Multiple layers could be requested with a single request
# Today the first layer wins.
layer = layers[0]
internal_wms = DBSession.query(LuxLayerInternalWMS).filter(
LuxLayerInternalWMS.layer == layer).first()
if internal_wms is None:
return HTTPNotFound()
# If the layer is not public check if it comes from an authorized url
# or from a connected user or uses the right token
if not internal_wms.public and self.request.user is None:
remote_addr = str(self.request.environ.get(
'HTTP_X_FORWARDED_FOR', self.request.environ['REMOTE_ADDR']))
if not self._check_token(self.request.params.get('GP_TOKEN')) and \
not self._check_ip(remote_addr.split(",")[0]):
return HTTPUnauthorized()
# If the layer is not public and we are connected check the rights
if not internal_wms.public and self.request.user is not None:
# Check if the layer has a resctriction area
restriction = DBSession.query(RestrictionArea).filter(
RestrictionArea.roles.any(
Role.id == self.request.user.role.id)).filter(
RestrictionArea.layers.any(
Layer.id == internal_wms.id
)
).first()
# If not restriction is set then return unauthorized
if restriction is None or not restriction.readwrite:
return HTTPUnauthorized()
remote_host = internal_wms.url
param_wms = ""
for param in self.request.params:
if param.lower() == "styles" and \
remote_host.lower().find("styles") > -1:
continue
if param.lower() != 'layers':
param_wms = param_wms + param + "=" + \
urllib2.quote(
self.request.params.get(param, '').encode('utf-8')
) + "&"
else:
param_wms = param_wms + param + "=" + \
urllib2.quote(internal_wms.layers.encode('utf-8')) + "&"
# TODO : Specific action when user is logged in ?
# Forward authorization to the remote host
# check sso
if self.request.user and self.request.user.ogc_role is not None and\
self.request.user.ogc_role != -1:
param_wms += "roleOGC=%s&" % str(self.request.user.ogc_role)
url = ""
t = "transparent=true"
if remote_host.lower().find(t) > -1 and param_wms.lower().find(t) > -1:
remote_host = remote_host.replace(t, "")
if remote_host.find("?") == -1:
remote_host = remote_host + "?"
separator = ""
if remote_host[:-1] != "?" and remote_host[:-1] != "&":
separator = "&"
url = remote_host + separator + param_wms[:-1]
timeout = 15
try:
f = urllib2.urlopen(url, None, timeout)
data = f.read()
except:
try:
# Retry to get the result
f = urllib2.urlopen(url, None, timeout)
data = f.read()
except Exception as e:
log.exception(e)
log.error(url)
return HTTPBadGateway()
headers = {"Content-Type": f.info()['Content-Type']}
return Response(data, headers=headers)
@view_config(route_name='predefined_wms', renderer='json')
def predefined_wms(self):
predefined_wms = DBSession.query(LuxPredefinedWms).all()
return [{'url': wms.url,
'label': wms.label} for wms in predefined_wms]
@view_config(route_name='https_proxy')
def proxy(self):
url = self.request.params.get("url", "")
if not url.lower().startswith("http://"):
log.error("This service can only request HTTP protocol")
return HTTPBadGateway()
if not self._check_ip_for_httpsproxy(url):
log.error("Try to access an unathorized network")
log.error(url)
return HTTPUnauthorized()
params_dict = {}
for key in self.request.params.keys():
if not (key == "url"):
params_dict[key] = self.request.params.get(key)
params = urllib.urlencode(params_dict)
separator = "?"
if "?" in url:
separator = "&"
url = url + separator + params
timeout = 15
try:
f = urllib2.urlopen(url, None, timeout)
data = f.read()
except:
try:
# Retry to get the result
f = urllib2.urlopen(url, None, timeout)
data = f.read()
except Exception as e:
log.exception(e)
log.error(url)
return HTTPBadGateway()
headers = {"Content-Type": f.info()['Content-Type']}
return Response(data, headers=headers)
|
from __future__ import division, absolute_import, print_function
import sys
import warnings
import functools
import operator
import numpy as np
from numpy.core.multiarray_tests import array_indexing
from itertools import product
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal, assert_raises,
assert_array_equal, assert_warns
)
try:
cdll = np.ctypeslib.load_library('multiarray', np.core.multiarray.__file__)
_HAS_CTYPE = True
except ImportError:
_HAS_CTYPE = False
class TestIndexing(TestCase):
def test_index_no_floats(self):
a = np.array([[[5]]])
assert_raises(IndexError, lambda: a[0.0])
assert_raises(IndexError, lambda: a[0, 0.0])
assert_raises(IndexError, lambda: a[0.0, 0])
assert_raises(IndexError, lambda: a[0.0,:])
assert_raises(IndexError, lambda: a[:, 0.0])
assert_raises(IndexError, lambda: a[:, 0.0,:])
assert_raises(IndexError, lambda: a[0.0,:,:])
assert_raises(IndexError, lambda: a[0, 0, 0.0])
assert_raises(IndexError, lambda: a[0.0, 0, 0])
assert_raises(IndexError, lambda: a[0, 0.0, 0])
assert_raises(IndexError, lambda: a[-1.4])
assert_raises(IndexError, lambda: a[0, -1.4])
assert_raises(IndexError, lambda: a[-1.4, 0])
assert_raises(IndexError, lambda: a[-1.4,:])
assert_raises(IndexError, lambda: a[:, -1.4])
assert_raises(IndexError, lambda: a[:, -1.4,:])
assert_raises(IndexError, lambda: a[-1.4,:,:])
assert_raises(IndexError, lambda: a[0, 0, -1.4])
assert_raises(IndexError, lambda: a[-1.4, 0, 0])
assert_raises(IndexError, lambda: a[0, -1.4, 0])
assert_raises(IndexError, lambda: a[0.0:, 0.0])
assert_raises(IndexError, lambda: a[0.0:, 0.0,:])
def test_slicing_no_floats(self):
a = np.array([[5]])
# start as float.
assert_raises(IndexError, lambda: a[0.0:])
assert_raises(IndexError, lambda: a[0:, 0.0:2])
assert_raises(IndexError, lambda: a[0.0::2, :0])
assert_raises(IndexError, lambda: a[0.0:1:2,:])
assert_raises(IndexError, lambda: a[:, 0.0:])
# stop as float.
assert_raises(IndexError, lambda: a[:0.0])
assert_raises(IndexError, lambda: a[:0, 1:2.0])
assert_raises(IndexError, lambda: a[:0.0:2, :0])
assert_raises(IndexError, lambda: a[:0.0,:])
assert_raises(IndexError, lambda: a[:, 0:4.0:2])
# step as float.
assert_raises(IndexError, lambda: a[::1.0])
assert_raises(IndexError, lambda: a[0:, :2:2.0])
assert_raises(IndexError, lambda: a[1::4.0, :0])
assert_raises(IndexError, lambda: a[::5.0,:])
assert_raises(IndexError, lambda: a[:, 0:4:2.0])
# mixed.
assert_raises(IndexError, lambda: a[1.0:2:2.0])
assert_raises(IndexError, lambda: a[1.0::2.0])
assert_raises(IndexError, lambda: a[0:, :2.0:2.0])
assert_raises(IndexError, lambda: a[1.0:1:4.0, :0])
assert_raises(IndexError, lambda: a[1.0:5.0:5.0,:])
assert_raises(IndexError, lambda: a[:, 0.4:4.0:2.0])
# should still get the DeprecationWarning if step = 0.
assert_raises(IndexError, lambda: a[::0.0])
def test_index_no_array_to_index(self):
# No non-scalar arrays.
a = np.array([[[1]]])
assert_raises(IndexError, lambda: a[a:a:a])
def test_none_index(self):
# `None` index adds newaxis
a = np.array([1, 2, 3])
assert_equal(a[None], a[np.newaxis])
assert_equal(a[None].ndim, a.ndim + 1)
def test_empty_tuple_index(self):
# Empty tuple index creates a view
a = np.array([1, 2, 3])
assert_equal(a[()], a)
assert_(a[()].base is a)
a = np.array(0)
assert_(isinstance(a[()], np.int_))
def test_same_kind_index_casting(self):
# Indexes should be cast with same-kind and not safe, even if that
# is somewhat unsafe. So test various different code paths.
index = np.arange(5)
u_index = index.astype(np.uintp)
arr = np.arange(10)
assert_array_equal(arr[index], arr[u_index])
arr[u_index] = np.arange(5)
assert_array_equal(arr, np.arange(10))
arr = np.arange(10).reshape(5, 2)
assert_array_equal(arr[index], arr[u_index])
arr[u_index] = np.arange(5)[:,None]
assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1))
arr = np.arange(25).reshape(5, 5)
assert_array_equal(arr[u_index, u_index], arr[index, index])
def test_empty_fancy_index(self):
# Empty list index creates an empty array
# with the same dtype (but with weird shape)
a = np.array([1, 2, 3])
assert_equal(a[[]], [])
assert_equal(a[[]].dtype, a.dtype)
b = np.array([], dtype=np.intp)
assert_equal(a[[]], [])
assert_equal(a[[]].dtype, a.dtype)
b = np.array([])
assert_raises(IndexError, a.__getitem__, b)
def test_ellipsis_index(self):
# Ellipsis index does not create a view
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
assert_equal(a[...], a)
# `a[...]` was `a` in numpy <1.9.
assert_(a[...].base is a)
# Slicing with ellipsis can skip an
# arbitrary number of dimensions
assert_equal(a[0, ...], a[0])
assert_equal(a[0, ...], a[0,:])
assert_equal(a[..., 0], a[:, 0])
# Slicing with ellipsis always results
# in an array, not a scalar
assert_equal(a[0, ..., 1], np.array(2))
# Assignment with `(Ellipsis,)` on 0-d arrays
b = np.array(1)
b[(Ellipsis,)] = 2
assert_equal(b, 2)
def test_single_int_index(self):
# Single integer index selects one row
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
assert_equal(a[0], [1, 2, 3])
assert_equal(a[-1], [7, 8, 9])
# Index out of bounds produces IndexError
assert_raises(IndexError, a.__getitem__, 1 << 30)
# Index overflow produces IndexError
assert_raises(IndexError, a.__getitem__, 1 << 64)
def test_single_bool_index(self):
# Single boolean index
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Python boolean converts to integer
# These are being deprecated (and test in test_deprecations)
#assert_equal(a[True], a[1])
#assert_equal(a[False], a[0])
# Same with NumPy boolean scalar
# Before DEPRECATE, this is an error (as always, but telling about
# future change):
assert_raises(IndexError, a.__getitem__, np.array(True))
assert_raises(IndexError, a.__getitem__, np.array(False))
# After DEPRECATE, this behaviour can be enabled:
#assert_equal(a[np.array(True)], a[None])
#assert_equal(a[np.array(False), a[None][0:0]])
def test_boolean_indexing_onedim(self):
# Indexing a 2-dimensional array with
# boolean array of length one
a = np.array([[ 0., 0., 0.]])
b = np.array([ True], dtype=bool)
assert_equal(a[b], a)
# boolean assignment
a[b] = 1.
assert_equal(a, [[1., 1., 1.]])
def test_boolean_assignment_value_mismatch(self):
# A boolean assignment should fail when the shape of the values
# cannot be broadcast to the subscription. (see also gh-3458)
a = np.arange(4)
def f(a, v):
a[a > -1] = v
assert_raises(ValueError, f, a, [])
assert_raises(ValueError, f, a, [1, 2, 3])
assert_raises(ValueError, f, a[:1], [1, 2, 3])
def test_boolean_indexing_twodim(self):
# Indexing a 2-dimensional array with
# 2-dimensional boolean array
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
b = np.array([[ True, False, True],
[False, True, False],
[ True, False, True]])
assert_equal(a[b], [1, 3, 5, 7, 9])
assert_equal(a[b[1]], [[4, 5, 6]])
assert_equal(a[b[0]], a[b[2]])
# boolean assignment
a[b] = 0
assert_equal(a, [[0, 2, 0],
[4, 0, 6],
[0, 8, 0]])
def test_reverse_strides_and_subspace_bufferinit(self):
# This tests that the strides are not reversed for simple and
# subspace fancy indexing.
a = np.ones(5)
b = np.zeros(5, dtype=np.intp)[::-1]
c = np.arange(5)[::-1]
a[b] = c
# If the strides are not reversed, the 0 in the arange comes last.
assert_equal(a[0], 0)
# This also tests that the subspace buffer is initialized:
a = np.ones((5, 2))
c = np.arange(10).reshape(5, 2)[::-1]
a[b, :] = c
assert_equal(a[0], [0, 1])
def test_reversed_strides_result_allocation(self):
# Test a bug when calculating the output strides for a result array
# when the subspace size was 1 (and test other cases as well)
a = np.arange(10)[:, None]
i = np.arange(10)[::-1]
assert_array_equal(a[i], a[i.copy('C')])
a = np.arange(20).reshape(-1, 2)
def test_uncontiguous_subspace_assignment(self):
# During development there was a bug activating a skip logic
# based on ndim instead of size.
a = np.full((3, 4, 2), -1)
b = np.full((3, 4, 2), -1)
a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T
b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy()
assert_equal(a, b)
def test_too_many_fancy_indices_special_case(self):
# Just documents behaviour, this is a small limitation.
a = np.ones((1,) * 32) # 32 is NPY_MAXDIMS
assert_raises(IndexError, a.__getitem__, (np.array([0]),) * 32)
def test_scalar_array_bool(self):
# Numpy bools can be used as boolean index (python ones as of yet not)
a = np.array(1)
assert_equal(a[np.bool_(True)], a[np.array(True)])
assert_equal(a[np.bool_(False)], a[np.array(False)])
# After deprecating bools as integers:
#a = np.array([0,1,2])
#assert_equal(a[True, :], a[None, :])
#assert_equal(a[:, True], a[:, None])
#
#assert_(not np.may_share_memory(a, a[True, :]))
def test_everything_returns_views(self):
# Before `...` would return a itself.
a = np.arange(5)
assert_(a is not a[()])
assert_(a is not a[...])
assert_(a is not a[:])
def test_broaderrors_indexing(self):
a = np.zeros((5, 5))
assert_raises(IndexError, a.__getitem__, ([0, 1], [0, 1, 2]))
assert_raises(IndexError, a.__setitem__, ([0, 1], [0, 1, 2]), 0)
def test_trivial_fancy_out_of_bounds(self):
a = np.zeros(5)
ind = np.ones(20, dtype=np.intp)
ind[-1] = 10
assert_raises(IndexError, a.__getitem__, ind)
assert_raises(IndexError, a.__setitem__, ind, 0)
ind = np.ones(20, dtype=np.intp)
ind[0] = 11
assert_raises(IndexError, a.__getitem__, ind)
assert_raises(IndexError, a.__setitem__, ind, 0)
def test_nonbaseclass_values(self):
class SubClass(np.ndarray):
def __array_finalize__(self, old):
# Have array finalize do funny things
self.fill(99)
a = np.zeros((5, 5))
s = a.copy().view(type=SubClass)
s.fill(1)
a[[0, 1, 2, 3, 4], :] = s
assert_((a == 1).all())
# Subspace is last, so transposing might want to finalize
a[:, [0, 1, 2, 3, 4]] = s
assert_((a == 1).all())
a.fill(0)
a[...] = s
assert_((a == 1).all())
def test_subclass_writeable(self):
d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)],
dtype=[('target', 'S20'), ('V_mag', '>f4')])
ind = np.array([False, True, True], dtype=bool)
assert_(d[ind].flags.writeable)
ind = np.array([0, 1])
assert_(d[ind].flags.writeable)
assert_(d[...].flags.writeable)
assert_(d[0].flags.writeable)
def test_memory_order(self):
# This is not necessary to preserve. Memory layouts for
# more complex indices are not as simple.
a = np.arange(10)
b = np.arange(10).reshape(5,2).T
assert_(a[b].flags.f_contiguous)
# Takes a different implementation branch:
a = a.reshape(-1, 1)
assert_(a[b, 0].flags.f_contiguous)
def test_scalar_return_type(self):
# Full scalar indices should return scalars and object
# arrays should not call PyArray_Return on their items
class Zero(object):
# The most basic valid indexing
def __index__(self):
return 0
z = Zero()
class ArrayLike(object):
# Simple array, should behave like the array
def __array__(self):
return np.array(0)
a = np.zeros(())
assert_(isinstance(a[()], np.float_))
a = np.zeros(1)
assert_(isinstance(a[z], np.float_))
a = np.zeros((1, 1))
assert_(isinstance(a[z, np.array(0)], np.float_))
assert_(isinstance(a[z, ArrayLike()], np.float_))
# And object arrays do not call it too often:
b = np.array(0)
a = np.array(0, dtype=object)
a[()] = b
assert_(isinstance(a[()], np.ndarray))
a = np.array([b, None])
assert_(isinstance(a[z], np.ndarray))
a = np.array([[b, None]])
assert_(isinstance(a[z, np.array(0)], np.ndarray))
assert_(isinstance(a[z, ArrayLike()], np.ndarray))
def test_small_regressions(self):
# Reference count of intp for index checks
a = np.array([0])
refcount = sys.getrefcount(np.dtype(np.intp))
# item setting always checks indices in separate function:
a[np.array([0], dtype=np.intp)] = 1
a[np.array([0], dtype=np.uint8)] = 1
assert_raises(IndexError, a.__setitem__,
np.array([1], dtype=np.intp), 1)
assert_raises(IndexError, a.__setitem__,
np.array([1], dtype=np.uint8), 1)
assert_equal(sys.getrefcount(np.dtype(np.intp)), refcount)
def test_unaligned(self):
v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]
d = v.view(np.dtype("S8"))
# unaligned source
x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]
x = x.view(np.dtype("S8"))
x[...] = np.array("b" * 8, dtype="S")
b = np.arange(d.size)
#trivial
assert_equal(d[b], d)
d[b] = x
# nontrivial
# unaligned index array
b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]
b = b.view(np.intp)[:d.size]
b[...] = np.arange(d.size)
assert_equal(d[b.astype(np.int16)], d)
d[b.astype(np.int16)] = x
# boolean
d[b % 2 == 0]
d[b % 2 == 0] = x[::2]
def test_tuple_subclass(self):
arr = np.ones((5, 5))
# A tuple subclass should also be an nd-index
class TupleSubclass(tuple):
pass
index = ([1], [1])
index = TupleSubclass(index)
assert_(arr[index].shape == (1,))
# Unlike the non nd-index:
assert_(arr[index,].shape != (1,))
def test_broken_sequence_not_nd_index(self):
# See gh-5063:
# If we have an object which claims to be a sequence, but fails
# on item getting, this should not be converted to an nd-index (tuple)
# If this object happens to be a valid index otherwise, it should work
# This object here is very dubious and probably bad though:
class SequenceLike(object):
def __index__(self):
return 0
def __len__(self):
return 1
def __getitem__(self, item):
raise IndexError('Not possible')
arr = np.arange(10)
assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
# also test that field indexing does not segfault
# for a similar reason, by indexing a structured array
arr = np.zeros((1,), dtype=[('f1', 'i8'), ('f2', 'i8')])
assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
def test_indexing_array_weird_strides(self):
# See also gh-6221
# the shapes used here come from the issue and create the correct
# size for the iterator buffering size.
x = np.ones(10)
x2 = np.ones((10, 2))
ind = np.arange(10)[:, None, None, None]
ind = np.broadcast_to(ind, (10, 55, 4, 4))
# single advanced index case
assert_array_equal(x[ind], x[ind.copy()])
# higher dimensional advanced index
zind = np.zeros(4, dtype=np.intp)
assert_array_equal(x2[ind, zind], x2[ind.copy(), zind])
class TestFieldIndexing(TestCase):
def test_scalar_return_type(self):
# Field access on an array should return an array, even if it
# is 0-d.
a = np.zeros((), [('a','f8')])
assert_(isinstance(a['a'], np.ndarray))
assert_(isinstance(a[['a']], np.ndarray))
class TestBroadcastedAssignments(TestCase):
def assign(self, a, ind, val):
a[ind] = val
return a
def test_prepending_ones(self):
a = np.zeros((3, 2))
a[...] = np.ones((1, 3, 2))
# Fancy with subspace with and without transpose
a[[0, 1, 2], :] = np.ones((1, 3, 2))
a[:, [0, 1]] = np.ones((1, 3, 2))
# Fancy without subspace (with broadcasting)
a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2))
def test_prepend_not_one(self):
assign = self.assign
s_ = np.s_
a = np.zeros(5)
# Too large and not only ones.
assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1)))
with warnings.catch_warnings():
# Will be a ValueError as well.
warnings.simplefilter("error", DeprecationWarning)
assert_raises(DeprecationWarning, assign, a, s_[[1, 2, 3],],
np.ones((2, 1)))
assert_raises(DeprecationWarning, assign, a, s_[[[1], [2]],],
np.ones((2,2,1)))
def test_simple_broadcasting_errors(self):
assign = self.assign
s_ = np.s_
a = np.zeros((5, 1))
assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 2)))
assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 0)))
assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 2)))
assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 0)))
assert_raises(ValueError, assign, a, s_[[0], :], np.zeros((2, 1)))
def test_index_is_larger(self):
# Simple case of fancy index broadcasting of the index.
a = np.zeros((5, 5))
a[[[0], [1], [2]], [0, 1, 2]] = [2, 3, 4]
assert_((a[:3, :3] == [2, 3, 4]).all())
def test_broadcast_subspace(self):
a = np.zeros((100, 100))
v = np.arange(100)[:,None]
b = np.arange(100)[::-1]
a[b] = v
assert_((a[::-1] == v).all())
class TestSubclasses(TestCase):
def test_basic(self):
class SubClass(np.ndarray):
pass
s = np.arange(5).view(SubClass)
assert_(isinstance(s[:3], SubClass))
assert_(s[:3].base is s)
assert_(isinstance(s[[0, 1, 2]], SubClass))
assert_(isinstance(s[s > 0], SubClass))
def test_matrix_fancy(self):
# The matrix class messes with the shape. While this is always
# weird (getitem is not used, it does not have setitem nor knows
# about fancy indexing), this tests gh-3110
m = np.matrix([[1, 2], [3, 4]])
assert_(isinstance(m[[0,1,0], :], np.matrix))
# gh-3110. Note the transpose currently because matrices do *not*
# support dimension fixing for fancy indexing correctly.
x = np.asmatrix(np.arange(50).reshape(5,10))
assert_equal(x[:2, np.array(-1)], x[:2, -1].T)
def test_finalize_gets_full_info(self):
# Array finalize should be called on the filled array.
class SubClass(np.ndarray):
def __array_finalize__(self, old):
self.finalize_status = np.array(self)
self.old = old
s = np.arange(10).view(SubClass)
new_s = s[:3]
assert_array_equal(new_s.finalize_status, new_s)
assert_array_equal(new_s.old, s)
new_s = s[[0,1,2,3]]
assert_array_equal(new_s.finalize_status, new_s)
assert_array_equal(new_s.old, s)
new_s = s[s > 0]
assert_array_equal(new_s.finalize_status, new_s)
assert_array_equal(new_s.old, s)
class TestFancingIndexingCast(TestCase):
def test_boolean_index_cast_assign(self):
# Setup the boolean index and float arrays.
shape = (8, 63)
bool_index = np.zeros(shape).astype(bool)
bool_index[0, 1] = True
zero_array = np.zeros(shape)
# Assigning float is fine.
zero_array[bool_index] = np.array([1])
assert_equal(zero_array[0, 1], 1)
# Fancy indexing works, although we get a cast warning.
assert_warns(np.ComplexWarning,
zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
assert_equal(zero_array[0, 1], 2) # No complex part
# Cast complex to float, throwing away the imaginary portion.
assert_warns(np.ComplexWarning,
zero_array.__setitem__, bool_index, np.array([1j]))
assert_equal(zero_array[0, 1], 0)
class TestFancyIndexingEquivalence(TestCase):
def test_object_assign(self):
# Check that the field and object special case using copyto is active.
# The right hand side cannot be converted to an array here.
a = np.arange(5, dtype=object)
b = a.copy()
a[:3] = [1, (1,2), 3]
b[[0, 1, 2]] = [1, (1,2), 3]
assert_array_equal(a, b)
# test same for subspace fancy indexing
b = np.arange(5, dtype=object)[None, :]
b[[0], :3] = [[1, (1,2), 3]]
assert_array_equal(a, b[0])
# Check that swapping of axes works.
# There was a bug that made the later assignment throw a ValueError
# do to an incorrectly transposed temporary right hand side (gh-5714)
b = b.T
b[:3, [0]] = [[1], [(1,2)], [3]]
assert_array_equal(a, b[:, 0])
# Another test for the memory order of the subspace
arr = np.ones((3, 4, 5), dtype=object)
# Equivalent slicing assignment for comparison
cmp_arr = arr.copy()
cmp_arr[:1, ...] = [[[1], [2], [3], [4]]]
arr[[0], ...] = [[[1], [2], [3], [4]]]
assert_array_equal(arr, cmp_arr)
arr = arr.copy('F')
arr[[0], ...] = [[[1], [2], [3], [4]]]
assert_array_equal(arr, cmp_arr)
def test_cast_equivalence(self):
# Yes, normal slicing uses unsafe casting.
a = np.arange(5)
b = a.copy()
a[:3] = np.array(['2', '-3', '-1'])
b[[0, 2, 1]] = np.array(['2', '-1', '-3'])
assert_array_equal(a, b)
# test the same for subspace fancy indexing
b = np.arange(5)[None, :]
b[[0], :3] = np.array([['2', '-3', '-1']])
assert_array_equal(a, b[0])
class TestMultiIndexingAutomated(TestCase):
"""
These test use code to mimic the C-Code indexing for selection.
NOTE: * This still lacks tests for complex item setting.
* If you change behavior of indexing, you might want to modify
these tests to try more combinations.
* Behavior was written to match numpy version 1.8. (though a
first version matched 1.7.)
* Only tuple indices are supported by the mimicking code.
(and tested as of writing this)
* Error types should match most of the time as long as there
is only one error. For multiple errors, what gets raised
will usually not be the same one. They are *not* tested.
"""
def setUp(self):
self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
self.b = np.empty((3, 0, 5, 6))
self.complex_indices = ['skip', Ellipsis,
0,
# Boolean indices, up to 3-d for some special cases of eating up
# dimensions, also need to test all False
np.array(False),
np.array([True, False, False]),
np.array([[True, False], [False, True]]),
np.array([[[False, False], [False, False]]]),
# Some slices:
slice(-5, 5, 2),
slice(1, 1, 100),
slice(4, -1, -2),
slice(None, None, -3),
# Some Fancy indexes:
np.empty((0, 1, 1), dtype=np.intp), # empty and can be broadcast
np.array([0, 1, -2]),
np.array([[2], [0], [1]]),
np.array([[0, -1], [0, 1]], dtype=np.dtype('intp').newbyteorder()),
np.array([2, -1], dtype=np.int8),
np.zeros([1]*31, dtype=int), # trigger too large array.
np.array([0., 1.])] # invalid datatype
# Some simpler indices that still cover a bit more
self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]),
'skip']
# Very simple ones to fill the rest:
self.fill_indices = [slice(None, None), 0]
def _get_multi_index(self, arr, indices):
"""Mimic multi dimensional indexing.
Parameters
----------
arr : ndarray
Array to be indexed.
indices : tuple of index objects
Returns
-------
out : ndarray
An array equivalent to the indexing operation (but always a copy).
`arr[indices]` should be identical.
no_copy : bool
Whether the indexing operation requires a copy. If this is `True`,
`np.may_share_memory(arr, arr[indicies])` should be `True` (with
some exceptions for scalars and possibly 0-d arrays).
Notes
-----
While the function may mostly match the errors of normal indexing this
is generally not the case.
"""
in_indices = list(indices)
indices = []
# if False, this is a fancy or boolean index
no_copy = True
# number of fancy/scalar indexes that are not consecutive
num_fancy = 0
# number of dimensions indexed by a "fancy" index
fancy_dim = 0
# NOTE: This is a funny twist (and probably OK to change).
# The boolean array has illegal indexes, but this is
# allowed if the broadcast fancy-indices are 0-sized.
# This variable is to catch that case.
error_unless_broadcast_to_empty = False
# We need to handle Ellipsis and make arrays from indices, also
# check if this is fancy indexing (set no_copy).
ndim = 0
ellipsis_pos = None # define here mostly to replace all but first.
for i, indx in enumerate(in_indices):
if indx is None:
continue
if isinstance(indx, np.ndarray) and indx.dtype == bool:
no_copy = False
if indx.ndim == 0:
raise IndexError
# boolean indices can have higher dimensions
ndim += indx.ndim
fancy_dim += indx.ndim
continue
if indx is Ellipsis:
if ellipsis_pos is None:
ellipsis_pos = i
continue # do not increment ndim counter
raise IndexError
if isinstance(indx, slice):
ndim += 1
continue
if not isinstance(indx, np.ndarray):
# This could be open for changes in numpy.
# numpy should maybe raise an error if casting to intp
# is not safe. It rejects np.array([1., 2.]) but not
# [1., 2.] as index (same for ie. np.take).
# (Note the importance of empty lists if changing this here)
indx = np.array(indx, dtype=np.intp)
in_indices[i] = indx
elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i':
raise IndexError('arrays used as indices must be of '
'integer (or boolean) type')
if indx.ndim != 0:
no_copy = False
ndim += 1
fancy_dim += 1
if arr.ndim - ndim < 0:
# we can't take more dimensions then we have, not even for 0-d
# arrays. since a[()] makes sense, but not a[(),]. We will
# raise an error later on, unless a broadcasting error occurs
# first.
raise IndexError
if ndim == 0 and None not in in_indices:
# Well we have no indexes or one Ellipsis. This is legal.
return arr.copy(), no_copy
if ellipsis_pos is not None:
in_indices[ellipsis_pos:ellipsis_pos+1] = ([slice(None, None)] *
(arr.ndim - ndim))
for ax, indx in enumerate(in_indices):
if isinstance(indx, slice):
# convert to an index array
indx = np.arange(*indx.indices(arr.shape[ax]))
indices.append(['s', indx])
continue
elif indx is None:
# this is like taking a slice with one element from a new axis:
indices.append(['n', np.array([0], dtype=np.intp)])
arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:]))
continue
if isinstance(indx, np.ndarray) and indx.dtype == bool:
if indx.shape != arr.shape[ax:ax+indx.ndim]:
raise IndexError
try:
flat_indx = np.ravel_multi_index(np.nonzero(indx),
arr.shape[ax:ax+indx.ndim], mode='raise')
except:
error_unless_broadcast_to_empty = True
# fill with 0s instead, and raise error later
flat_indx = np.array([0]*indx.sum(), dtype=np.intp)
# concatenate axis into a single one:
if indx.ndim != 0:
arr = arr.reshape((arr.shape[:ax]
+ (np.prod(arr.shape[ax:ax+indx.ndim]),)
+ arr.shape[ax+indx.ndim:]))
indx = flat_indx
else:
# This could be changed, a 0-d boolean index can
# make sense (even outside the 0-d indexed array case)
# Note that originally this is could be interpreted as
# integer in the full integer special case.
raise IndexError
else:
# If the index is a singleton, the bounds check is done
# before the broadcasting. This used to be different in <1.9
if indx.ndim == 0:
if indx >= arr.shape[ax] or indx < -arr.shape[ax]:
raise IndexError
if indx.ndim == 0:
# The index is a scalar. This used to be two fold, but if
# fancy indexing was active, the check was done later,
# possibly after broadcasting it away (1.7. or earlier).
# Now it is always done.
if indx >= arr.shape[ax] or indx < - arr.shape[ax]:
raise IndexError
if (len(indices) > 0 and
indices[-1][0] == 'f' and
ax != ellipsis_pos):
# NOTE: There could still have been a 0-sized Ellipsis
# between them. Checked that with ellipsis_pos.
indices[-1].append(indx)
else:
# We have a fancy index that is not after an existing one.
# NOTE: A 0-d array triggers this as well, while one may
# expect it to not trigger it, since a scalar would not be
# considered fancy indexing.
num_fancy += 1
indices.append(['f', indx])
if num_fancy > 1 and not no_copy:
# We have to flush the fancy indexes left
new_indices = indices[:]
axes = list(range(arr.ndim))
fancy_axes = []
new_indices.insert(0, ['f'])
ni = 0
ai = 0
for indx in indices:
ni += 1
if indx[0] == 'f':
new_indices[0].extend(indx[1:])
del new_indices[ni]
ni -= 1
for ax in range(ai, ai + len(indx[1:])):
fancy_axes.append(ax)
axes.remove(ax)
ai += len(indx) - 1 # axis we are at
indices = new_indices
# and now we need to transpose arr:
arr = arr.transpose(*(fancy_axes + axes))
# We only have one 'f' index now and arr is transposed accordingly.
# Now handle newaxis by reshaping...
ax = 0
for indx in indices:
if indx[0] == 'f':
if len(indx) == 1:
continue
# First of all, reshape arr to combine fancy axes into one:
orig_shape = arr.shape
orig_slice = orig_shape[ax:ax + len(indx[1:])]
arr = arr.reshape((arr.shape[:ax]
+ (np.prod(orig_slice).astype(int),)
+ arr.shape[ax + len(indx[1:]):]))
# Check if broadcasting works
res = np.broadcast(*indx[1:])
# unfortunately the indices might be out of bounds. So check
# that first, and use mode='wrap' then. However only if
# there are any indices...
if res.size != 0:
if error_unless_broadcast_to_empty:
raise IndexError
for _indx, _size in zip(indx[1:], orig_slice):
if _indx.size == 0:
continue
if np.any(_indx >= _size) or np.any(_indx < -_size):
raise IndexError
if len(indx[1:]) == len(orig_slice):
if np.product(orig_slice) == 0:
# Work around for a crash or IndexError with 'wrap'
# in some 0-sized cases.
try:
mi = np.ravel_multi_index(indx[1:], orig_slice,
mode='raise')
except:
# This happens with 0-sized orig_slice (sometimes?)
# here it is a ValueError, but indexing gives a:
raise IndexError('invalid index into 0-sized')
else:
mi = np.ravel_multi_index(indx[1:], orig_slice,
mode='wrap')
else:
# Maybe never happens...
raise ValueError
arr = arr.take(mi.ravel(), axis=ax)
arr = arr.reshape((arr.shape[:ax]
+ mi.shape
+ arr.shape[ax+1:]))
ax += mi.ndim
continue
# If we are here, we have a 1D array for take:
arr = arr.take(indx[1], axis=ax)
ax += 1
return arr, no_copy
def _check_multi_index(self, arr, index):
"""Check a multi index item getting and simple setting.
Parameters
----------
arr : ndarray
Array to be indexed, must be a reshaped arange.
index : tuple of indexing objects
Index being tested.
"""
# Test item getting
try:
mimic_get, no_copy = self._get_multi_index(arr, index)
except Exception:
prev_refcount = sys.getrefcount(arr)
assert_raises(Exception, arr.__getitem__, index)
assert_raises(Exception, arr.__setitem__, index, 0)
assert_equal(prev_refcount, sys.getrefcount(arr))
return
self._compare_index_result(arr, index, mimic_get, no_copy)
def _check_single_index(self, arr, index):
"""Check a single index item getting and simple setting.
Parameters
----------
arr : ndarray
Array to be indexed, must be an arange.
index : indexing object
Index being tested. Must be a single index and not a tuple
of indexing objects (see also `_check_multi_index`).
"""
try:
mimic_get, no_copy = self._get_multi_index(arr, (index,))
except Exception:
prev_refcount = sys.getrefcount(arr)
assert_raises(Exception, arr.__getitem__, index)
assert_raises(Exception, arr.__setitem__, index, 0)
assert_equal(prev_refcount, sys.getrefcount(arr))
return
self._compare_index_result(arr, index, mimic_get, no_copy)
def _compare_index_result(self, arr, index, mimic_get, no_copy):
"""Compare mimicked result to indexing result.
"""
arr = arr.copy()
indexed_arr = arr[index]
assert_array_equal(indexed_arr, mimic_get)
# Check if we got a view, unless its a 0-sized or 0-d array.
# (then its not a view, and that does not matter)
if indexed_arr.size != 0 and indexed_arr.ndim != 0:
assert_(np.may_share_memory(indexed_arr, arr) == no_copy)
# Check reference count of the original array
if no_copy:
# refcount increases by one:
assert_equal(sys.getrefcount(arr), 3)
else:
assert_equal(sys.getrefcount(arr), 2)
# Test non-broadcast setitem:
b = arr.copy()
b[index] = mimic_get + 1000
if b.size == 0:
return # nothing to compare here...
if no_copy and indexed_arr.ndim != 0:
# change indexed_arr in-place to manipulate original:
indexed_arr += 1000
assert_array_equal(arr, b)
return
# Use the fact that the array is originally an arange:
arr.flat[indexed_arr.ravel()] += 1000
assert_array_equal(arr, b)
def test_boolean(self):
a = np.array(5)
assert_equal(a[np.array(True)], 5)
a[np.array(True)] = 1
assert_equal(a, 1)
# NOTE: This is different from normal broadcasting, as
# arr[boolean_array] works like in a multi index. Which means
# it is aligned to the left. This is probably correct for
# consistency with arr[boolean_array,] also no broadcasting
# is done at all
self._check_multi_index(
self.a, (np.zeros_like(self.a, dtype=bool),))
self._check_multi_index(
self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],))
self._check_multi_index(
self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))
def test_multidim(self):
# Automatically test combinations with complex indexes on 2nd (or 1st)
# spot and the simple ones in one other spot.
with warnings.catch_warnings():
# This is so that np.array(True) is not accepted in a full integer
# index, when running the file separately.
warnings.filterwarnings('error', '', DeprecationWarning)
warnings.filterwarnings('error', '', np.VisibleDeprecationWarning)
def isskip(idx):
return isinstance(idx, str) and idx == "skip"
for simple_pos in [0, 2, 3]:
tocheck = [self.fill_indices, self.complex_indices,
self.fill_indices, self.fill_indices]
tocheck[simple_pos] = self.simple_indices
for index in product(*tocheck):
index = tuple(i for i in index if not isskip(i))
self._check_multi_index(self.a, index)
self._check_multi_index(self.b, index)
# Check very simple item getting:
self._check_multi_index(self.a, (0, 0, 0, 0))
self._check_multi_index(self.b, (0, 0, 0, 0))
# Also check (simple cases of) too many indices:
assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0))
assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0)
assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0))
assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0)
def test_1d(self):
a = np.arange(10)
with warnings.catch_warnings():
warnings.filterwarnings('error', '', np.VisibleDeprecationWarning)
for index in self.complex_indices:
self._check_single_index(a, index)
class TestFloatNonIntegerArgument(TestCase):
"""
These test that ``TypeError`` is raised when you try to use
non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.
"""
def test_valid_indexing(self):
# These should raise no errors.
a = np.array([[[5]]])
a[np.array([0])]
a[[0, 0]]
a[:, [0, 0]]
a[:, 0,:]
a[:,:,:]
def test_valid_slicing(self):
# These should raise no errors.
a = np.array([[[5]]])
a[::]
a[0:]
a[:2]
a[0:2]
a[::2]
a[1::2]
a[:2:2]
a[1:2:2]
def test_non_integer_argument_errors(self):
a = np.array([[5]])
assert_raises(TypeError, np.reshape, a, (1., 1., -1))
assert_raises(TypeError, np.reshape, a, (np.array(1.), -1))
assert_raises(TypeError, np.take, a, [0], 1.)
assert_raises(TypeError, np.take, a, [0], np.float64(1.))
def test_non_integer_sequence_multiplication(self):
# Numpy scalar sequence multiply should not work with non-integers
def mult(a, b):
return a * b
assert_raises(TypeError, mult, [1], np.float_(3))
# following should be OK
mult([1], np.int_(3))
def test_reduce_axis_float_index(self):
d = np.zeros((3,3,3))
assert_raises(TypeError, np.min, d, 0.5)
assert_raises(TypeError, np.min, d, (0.5, 1))
assert_raises(TypeError, np.min, d, (1, 2.2))
assert_raises(TypeError, np.min, d, (.2, 1.2))
class TestBooleanArgumentErrors(TestCase):
"""Using a boolean as integer argument/indexing is an error.
"""
def test_bool_as_int_argument(self):
a = np.array([[[1]]])
assert_raises(TypeError, np.reshape, a, (True, -1))
assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))
# Note that operator.index(np.array(True)) does not work, a boolean
# array is thus also deprecated, but not with the same message:
assert_raises(TypeError, operator.index, np.array(True))
assert_raises(TypeError, np.take, args=(a, [0], False))
assert_raises(IndexError, lambda: a[False:True:True])
assert_raises(IndexError, lambda: a[False, 0])
assert_raises(IndexError, lambda: a[False, 0, 0])
class TestArrayToIndexDeprecation(TestCase):
"""Creating an an index from array not 0-D is an error.
"""
def test_array_to_index_error(self):
# so no exception is expected. The raising is effectively tested above.
a = np.array([[[1]]])
assert_raises(TypeError, operator.index, np.array([1]))
assert_raises(TypeError, np.reshape, a, (a, -1))
assert_raises(TypeError, np.take, a, [0], a)
class TestNonIntegerArrayLike(TestCase):
"""Tests that array_likes only valid if can safely cast to integer.
For instance, lists give IndexError when they cannot be safely cast to
an integer.
"""
def test_basic(self):
a = np.arange(10)
assert_raises(IndexError, a.__getitem__, [0.5, 1.5])
assert_raises(IndexError, a.__getitem__, (['1', '2'],))
# The following is valid
a.__getitem__([])
class TestMultipleEllipsisError(TestCase):
"""An index can only have a single ellipsis.
"""
def test_basic(self):
a = np.arange(10)
assert_raises(IndexError, lambda: a[..., ...])
assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 2,))
assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))
class TestCApiAccess(TestCase):
def test_getitem(self):
subscript = functools.partial(array_indexing, 0)
# 0-d arrays don't work:
assert_raises(IndexError, subscript, np.ones(()), 0)
# Out of bound values:
assert_raises(IndexError, subscript, np.ones(10), 11)
assert_raises(IndexError, subscript, np.ones(10), -11)
assert_raises(IndexError, subscript, np.ones((10, 10)), 11)
assert_raises(IndexError, subscript, np.ones((10, 10)), -11)
a = np.arange(10)
assert_array_equal(a[4], subscript(a, 4))
a = a.reshape(5, 2)
assert_array_equal(a[-4], subscript(a, -4))
def test_setitem(self):
assign = functools.partial(array_indexing, 1)
# Deletion is impossible:
assert_raises(ValueError, assign, np.ones(10), 0)
# 0-d arrays don't work:
assert_raises(IndexError, assign, np.ones(()), 0, 0)
# Out of bound values:
assert_raises(IndexError, assign, np.ones(10), 11, 0)
assert_raises(IndexError, assign, np.ones(10), -11, 0)
assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0)
assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0)
a = np.arange(10)
assign(a, 4, 10)
assert_(a[4] == 10)
a = a.reshape(5, 2)
assign(a, 4, 10)
assert_array_equal(a[-1], [10, 10])
if __name__ == "__main__":
run_module_suite()
|
import ui from '../util/ui';
import exportUtils from '../util/export';
import sketchUtils from '../util/sketch';
import exportComponents from './export-components';
export default function(context, opts, cb) {
ui.createSettingsDialog(context, opts, exportComponents, (data) => {
// Defaults
data.propertyNamingConvention = data.propertyNamingConvention || 'Numeric';
data.cssUnit = (data.cssUnit === 'No unit' ? 0 : data.cssUnit);
// First store the properties we should exclude
let excludeProps = [];
if (data['excludeProps']['Color']) {
excludeProps.push('color');
}
if (data['excludeProps']['Line height']) {
excludeProps.push('lineHeight');
}
// Get the text styles from the Sketch document
let textStyles = sketchUtils.getTextStyles(context);
textStyles = exportUtils.sortTextStyles(textStyles);
textStyles = exportUtils.excludeTextStyleProperties(textStyles, excludeProps);
if (data['merge']) {
textStyles = exportUtils.removeDoubleTextStyles(textStyles);
}
cb(textStyles, data);
});
};
|
//
// VENPopupView.h
// TibetanAssistant
//
// Created by YVEN on 2018/11/30.
// Copyright © 2018年 Hefei Haiba Network Technology Co., Ltd. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface VENPopupView : UIView
@property (nonatomic, strong) UIView *view;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *button;
@end
NS_ASSUME_NONNULL_END
|
/**
* 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.
*/
'use strict';
var assert = require('assert');
var extend = require('extend');
var proxyquire = require('proxyquire').noPreserveCache();
var util = require('@google-cloud/common').util;
function FakeOperation() {
this.calledWith_ = arguments;
}
function FakeServiceObject() {
this.calledWith_ = arguments;
}
var parseHttpRespBodyOverride = null;
var promisified = false;
var fakeUtil = extend({}, util, {
parseHttpRespBody: function() {
if (parseHttpRespBodyOverride) {
return parseHttpRespBodyOverride.apply(null, arguments);
}
return util.parseHttpRespBody.apply(this, arguments);
},
promisifyAll: function(Class) {
if (Class.name === 'Operation') {
promisified = true;
}
},
});
describe('Operation', function() {
var Operation;
var operation;
var SCOPE = {
Promise: Promise,
};
var OPERATION_NAME = 'operation-name';
before(function() {
Operation = proxyquire('../src/operation.js', {
'@google-cloud/common': {
Operation: FakeOperation,
ServiceObject: FakeServiceObject,
util: fakeUtil,
},
});
});
beforeEach(function() {
parseHttpRespBodyOverride = null;
operation = new Operation(SCOPE, OPERATION_NAME);
});
describe('instantiation', function() {
it('should localize the name', function() {
assert.strictEqual(operation.name, OPERATION_NAME);
});
it('should inherit from Operation', function() {
assert(operation instanceof FakeOperation);
var calledWith = operation.calledWith_[0];
assert.strictEqual(calledWith.parent, SCOPE);
assert.strictEqual(calledWith.baseUrl, '/operations');
assert.strictEqual(calledWith.id, OPERATION_NAME);
assert.deepEqual(calledWith.methods, {
delete: true,
exists: true,
get: true,
});
});
it('should promisify all the things', function() {
assert(promisified);
});
it('should give the right baseUrl for a global Operation', function() {
var operation = new Operation(
{
constructor: {
name: 'Compute',
},
},
OPERATION_NAME
);
var calledWith = operation.calledWith_[0];
assert.strictEqual(calledWith.baseUrl, '/global/operations');
});
});
describe('getMetadata', function() {
it('should call ServiceObject.delete', function(done) {
FakeServiceObject.prototype.getMetadata = function() {
assert.strictEqual(this, operation);
done();
};
operation.getMetadata();
});
describe('error', function() {
var error = new Error('Error.');
var apiResponse = {a: 'b', c: 'd'};
beforeEach(function() {
FakeServiceObject.prototype.getMetadata = function(callback) {
callback(error, apiResponse);
};
});
it('should ignore false errors', function(done) {
var apiResponse = {
name: operation.name,
error: {
errors: [],
},
};
FakeServiceObject.prototype.getMetadata = function(callback) {
callback(apiResponse.error, apiResponse);
};
operation.getMetadata(function(err, metadata, apiResponse_) {
assert.ifError(err);
assert.strictEqual(metadata, apiResponse);
assert.strictEqual(apiResponse_, apiResponse);
done();
});
});
it('should execute callback with error and API response', function(done) {
operation.getMetadata(function(err, metadata, apiResponse_) {
assert.strictEqual(err, error);
assert.strictEqual(metadata, null);
assert.strictEqual(apiResponse_, apiResponse);
done();
});
});
it('should not require a callback', function() {
assert.doesNotThrow(function() {
operation.getMetadata();
});
});
});
describe('success', function() {
var apiResponse = {a: 'b', c: 'd'};
beforeEach(function() {
FakeServiceObject.prototype.getMetadata = function(callback) {
callback(null, apiResponse);
};
});
it('should update the metadata to the API response', function(done) {
operation.getMetadata(function(err) {
assert.ifError(err);
assert.strictEqual(operation.metadata, apiResponse);
done();
});
});
it('should exec callback with metadata and API response', function(done) {
operation.getMetadata(function(err, metadata, apiResponse_) {
assert.ifError(err);
assert.strictEqual(metadata, apiResponse);
assert.strictEqual(apiResponse_, apiResponse);
done();
});
});
it('should not require a callback', function() {
assert.doesNotThrow(function() {
operation.getMetadata();
});
});
});
});
describe('poll_', function() {
beforeEach(function() {
operation.emit = util.noop;
});
it('should call getMetadata', function(done) {
operation.getMetadata = function() {
done();
};
operation.poll_(assert.ifError);
});
describe('API error', function() {
var error = new Error('Error.');
beforeEach(function() {
operation.getMetadata = function(callback) {
callback(error);
};
});
it('should emit the error', function(done) {
operation.poll_(function(err) {
assert.strictEqual(err, error);
done();
});
});
});
describe('operation failure', function() {
var error = new Error('Error.');
var apiResponse = {error: error};
beforeEach(function() {
operation.getMetadata = function(callback) {
callback(null, apiResponse, apiResponse);
};
});
it('should parse and return the response body', function(done) {
var parsedHttpRespBody = {err: {}};
parseHttpRespBodyOverride = function(body) {
assert.strictEqual(body, apiResponse);
return parsedHttpRespBody;
};
operation.poll_(function(err) {
assert.strictEqual(err, parsedHttpRespBody.err);
done();
});
});
});
describe('operation running', function() {
var apiResponse = {status: 'RUNNING'};
beforeEach(function() {
operation.getMetadata = function(callback) {
callback(null, apiResponse, apiResponse);
};
});
it('should update status', function(done) {
delete operation.status;
operation.poll_(function(err) {
assert.ifError(err);
assert.strictEqual(operation.status, apiResponse.status);
done();
});
});
it('should emit the running event', function(done) {
operation.emit = function(eventName, metadata) {
assert.strictEqual(eventName, 'running');
assert.strictEqual(metadata, apiResponse);
done();
};
operation.poll_(assert.ifError);
});
it('should not emit running if already running', function(done) {
operation.emit = function(eventName) {
assert.strictEqual(eventName, 'running');
operation.emit = done; // will fail test if called
operation.poll_(done);
};
operation.poll_(assert.ifError);
});
});
describe('operation complete', function() {
var apiResponse = {status: 'DONE'};
beforeEach(function() {
operation.getMetadata = function(callback) {
callback(null, apiResponse, apiResponse);
};
});
it('should update status', function(done) {
operation.status = 'PENDING';
operation.poll_(function(err) {
assert.ifError(err);
assert.strictEqual(operation.status, apiResponse.status);
done();
});
});
it('should execute callback with metadata', function(done) {
operation.poll_(function(err, metadata) {
assert.ifError(err);
assert.strictEqual(metadata, apiResponse);
done();
});
});
});
});
});
|
from common.scripts.cleaning import clean_date
def test_clean_date():
# YYYY
raw_input_1 = "2015"
output_1 = clean_date(raw_input_1)
assert output_1 == "2015-01-01"
# YYYY-MM
raw_input_2 = "2015-02"
output_2 = clean_date(raw_input_2)
assert output_2 == "2015-02-01"
# YYYYMM
raw_input_3 = "201502"
output_3 = clean_date(raw_input_3)
assert output_3 == "2015-02-01"
# YYYY-MM-DD
raw_input_4 = "2015-02-07"
output_4 = clean_date(raw_input_4)
assert output_4 == "2015-02-07"
# YYYYMMDD
raw_input_5 = "20150207"
output_5 = clean_date(raw_input_5)
assert output_5 == "2015-02-07"
# YYYY-MM-DD H:M:S
raw_input_6 = "2015-02-07 13:28:17"
output_6 = clean_date(raw_input_6)
assert output_6 == "2015-02-07"
# YYYY-MM-DDTH:M:S
raw_input_7 = "2015-02-07T13:28:17"
output_7 = clean_date(raw_input_7)
assert output_7 == "2015-02-07"
# YYYY-MM-DDTH:M:S+zzzz
raw_input_8 = "2015-02-07T13:28:17+0500"
output_8 = clean_date(raw_input_8)
assert output_8 == "2015-02-07"
# YYYY-MM-DDTH:M:S-zz:zz
raw_input_9 = "2015-02-07T13:28:17-0500"
output_9 = clean_date(raw_input_9)
assert output_9 == "2015-02-07"
# RFC 1123
raw_input_10 = "Wed, 13 Mar 2075 00:00:00 GMT"
output_10 = clean_date(raw_input_10)
assert output_10 == "2075-03-13"
# YYYYMMDDHHMM
raw_input_11 = "201502071740"
output_11 = clean_date(raw_input_11)
assert output_11 == "2015-02-07"
# YYYY-MM-DDTH:M:S+zz:zz
raw_input_12 = "2015-02-07T13:28:17+05:00"
output_12 = clean_date(raw_input_12)
assert output_12 == "2015-02-07"
|
# -*- coding: utf-8 -*-
'''
Manage information about regular files, directories,
and special files on the minion, set/read user,
group, mode, and data
'''
# TODO: We should add the capability to do u+r type operations here
# some time in the future
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import datetime
import errno
import fnmatch
import io
import itertools
import logging
import operator
import os
import re
import shutil
import stat
import string
import sys
import tempfile
import time
import glob
import hashlib
import mmap
from collections import Iterable, Mapping, namedtuple
from functools import reduce # pylint: disable=redefined-builtin
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import range, zip
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module,redefined-builtin
try:
import grp
import pwd
except ImportError:
pass
# Import salt libs
import salt.utils.args
import salt.utils.atomicfile
import salt.utils.data
import salt.utils.filebuffer
import salt.utils.files
import salt.utils.find
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.itertools
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.url
import salt.utils.user
import salt.utils.data
import salt.utils.versions
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message
from salt.utils.files import HASHES, HASHES_REVMAP
log = logging.getLogger(__name__)
__func_alias__ = {
'makedirs_': 'makedirs'
}
AttrChanges = namedtuple('AttrChanges', 'added,removed')
def __virtual__():
'''
Only work on POSIX-like systems
'''
# win_file takes care of windows
if salt.utils.platform.is_windows():
return (
False,
'The file execution module cannot be loaded: only available on '
'non-Windows systems - use win_file instead.'
)
return True
def __clean_tmp(sfn):
'''
Clean out a template temp file
'''
if sfn.startswith(os.path.join(tempfile.gettempdir(),
salt.utils.files.TEMPFILE_PREFIX)):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
six.itervalues(__opts__['file_roots']))
in_roots = any(sfn.startswith(root) for root in all_roots)
# Only clean up files that exist
if os.path.exists(sfn) and not in_roots:
os.remove(sfn)
def _error(ret, err_msg):
'''
Common function for setting error information for return dicts
'''
ret['result'] = False
ret['comment'] = err_msg
return ret
def _binary_replace(old, new):
'''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should only be run AFTER it has been determined that the
files differ.
'''
old_isbin = not __utils__['files.is_text'](old)
new_isbin = not __utils__['files.is_text'](new)
if any((old_isbin, new_isbin)):
if all((old_isbin, new_isbin)):
return 'Replace binary file'
elif old_isbin:
return 'Replace binary file with text file'
elif new_isbin:
return 'Replace text file with binary file'
return ''
def _get_bkroot():
'''
Get the location of the backup dir in the minion cache
'''
# Get the cachedir from the minion config
return os.path.join(__salt__['config.get']('cachedir'), 'file_backup')
def _splitlines_preserving_trailing_newline(str):
'''
Returns a list of the lines in the string, breaking at line boundaries and
preserving a trailing newline (if present).
Essentially, this works like ``str.striplines(False)`` but preserves an
empty line at the end. This is equivalent to the following code:
.. code-block:: python
lines = str.splitlines()
if str.endswith('\n') or str.endswith('\r'):
lines.append('')
'''
lines = str.splitlines()
if str.endswith('\n') or str.endswith('\r'):
lines.append('')
return lines
def _chattr_version():
'''
Return the version of chattr installed
'''
# There's no really *good* way to get the version of chattr installed.
# It's part of the e2fsprogs package - we could try to parse the version
# from the package manager, but there's no guarantee that it was
# installed that way.
#
# The most reliable approach is to just check tune2fs, since that should
# be installed with chattr, at least if it was installed in a conventional
# manner.
#
# See https://unix.stackexchange.com/a/520399/5788 for discussion.
tune2fs = salt.utils.path.which('tune2fs')
if not tune2fs or salt.utils.platform.is_aix():
return None
cmd = [tune2fs]
result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False)
match = re.search(
r'tune2fs (?P<version>[0-9\.]+)',
salt.utils.stringutils.to_str(result),
)
if match is None:
version = None
else:
version = match.group('version')
return version
def _chattr_has_extended_attrs():
'''
Return ``True`` if chattr supports extended attributes, that is,
the version is >1.41.22. Otherwise, ``False``
'''
ver = _chattr_version()
if ver is None:
return False
needed_version = salt.utils.versions.LooseVersion('1.41.12')
chattr_version = salt.utils.versions.LooseVersion(ver)
return chattr_version > needed_version
def gid_to_group(gid):
'''
Convert the group id to the group name on this system
gid
gid to convert to a group name
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group 0
'''
try:
gid = int(gid)
except ValueError:
# This is not an integer, maybe it's already the group name?
gid = group_to_gid(gid)
if gid == '':
# Don't even bother to feed it to grp
return ''
try:
return grp.getgrgid(gid).gr_name
except (KeyError, NameError):
# If group is not present, fall back to the gid.
return gid
def group_to_gid(group):
'''
Convert the group to the gid on this system
group
group to convert to its gid
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid root
'''
if group is None:
return ''
try:
if isinstance(group, int):
return group
return grp.getgrnam(group).gr_gid
except KeyError:
return ''
def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1)
def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
path
file or directory of which to get the group
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_group /etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False)
def uid_to_user(uid):
'''
Convert a uid to a user name
uid
uid to convert to a username
CLI Example:
.. code-block:: bash
salt '*' file.uid_to_user 0
'''
try:
return pwd.getpwuid(uid).pw_name
except (KeyError, NameError):
# If user is not present, fall back to the uid.
return uid
def user_to_uid(user):
'''
Convert user name to a uid
user
user name to convert to its uid
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid root
'''
if user is None:
user = salt.utils.user.get_user()
try:
if isinstance(user, int):
return user
return pwd.getpwnam(user).pw_uid
except KeyError:
return ''
def get_uid(path, follow_symlinks=True):
'''
Return the id of the user that owns a given file
path
file or directory of which to get the uid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_uid /etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1)
def get_user(path, follow_symlinks=True):
'''
Return the user that owns a given file
path
file or directory of which to get the user
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_user /etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False)
def get_mode(path, follow_symlinks=True):
'''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchanged:: 2014.1.0
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '')
def set_mode(path, mode):
'''
Set the mode of a file
path
file or directory of which to set the mode
mode
mode to set the path to
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passwd 0644
'''
path = os.path.expanduser(path)
mode = six.text_type(mode).lstrip('0Oo')
if not mode:
mode = '0'
if not os.path.exists(path):
raise CommandExecutionError('{0}: File not found'.format(path))
try:
os.chmod(path, int(mode, 8))
except Exception: # pylint: disable=broad-except
return 'Invalid Mode ' + mode
return get_mode(path)
def lchown(path, user, group):
'''
Chown a file, pass the file the desired user and group without following
symlinks.
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/passwd root root
'''
path = os.path.expanduser(path)
uid = user_to_uid(user)
gid = group_to_gid(group)
err = ''
if uid == '':
if user:
err += 'User does not exist\n'
else:
uid = -1
if gid == '':
if group:
err += 'Group does not exist\n'
else:
gid = -1
return os.lchown(path, uid, gid)
def chown(path, user, group):
'''
Chown a file, pass the file the desired user and group
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/passwd root root
'''
path = os.path.expanduser(path)
uid = user_to_uid(user)
gid = group_to_gid(group)
err = ''
if uid == '':
if user:
err += 'User does not exist\n'
else:
uid = -1
if gid == '':
if group:
err += 'Group does not exist\n'
else:
gid = -1
if not os.path.exists(path):
try:
# Broken symlinks will return false, but still need to be chowned
return os.lchown(path, uid, gid)
except OSError:
pass
err += 'File not found'
if err:
return err
return os.chown(path, uid, gid)
def chgrp(path, group):
'''
Change the group of a file
path
path to the file or directory
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chgrp /etc/passwd root
'''
path = os.path.expanduser(path)
user = get_user(path)
return chown(path, user, group)
def _cmp_attrs(path, attrs):
'''
.. versionadded:: 2018.3.0
Compare attributes of a given file to given attributes.
Returns a pair (list) where first item are attributes to
add and second item are to be removed.
Please take into account when using this function that some minions will
not have lsattr installed.
path
path to file to compare attributes with.
attrs
string of attributes to compare against a given file
'''
# lsattr for AIX is not the same thing as lsattr for linux.
if salt.utils.platform.is_aix():
return None
try:
lattrs = lsattr(path).get(path, '')
except AttributeError:
# lsattr not installed
return None
new = set(attrs)
old = set(lattrs)
return AttrChanges(
added=''.join(new-old) or None,
removed=''.join(old-new) or None,
)
def lsattr(path):
'''
.. versionadded:: 2018.3.0
.. versionchanged:: 2018.3.1
If ``lsattr`` is not installed on the system, ``None`` is returned.
.. versionchanged:: 2018.3.4
If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX``
is not the same thing as the linux version.
Obtain the modifiable attributes of the given file. If path
is to a directory, an empty list is returned.
path
path to file to obtain attributes of. File/directory must exist.
CLI Example:
.. code-block:: bash
salt '*' file.lsattr foo1.txt
'''
if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix():
return None
if not os.path.exists(path):
raise SaltInvocationError("File or directory does not exist: " + path)
cmd = ['lsattr', path]
result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False)
results = {}
for line in result.splitlines():
if not line.startswith('lsattr: '):
attrs, file = line.split(None, 1)
if _chattr_has_extended_attrs():
pattern = r"[aAcCdDeijPsStTu]"
else:
pattern = r"[acdijstuADST]"
results[file] = re.findall(pattern, attrs)
return results
def chattr(*files, **kwargs):
'''
.. versionadded:: 2018.3.0
Change the attributes of files. This function accepts one or more files and
the following options:
operator
Can be wither ``add`` or ``remove``. Determines whether attributes
should be added or removed from files
attributes
One or more of the following characters: ``aAcCdDeijPsStTu``,
representing attributes to add to/remove from files
version
a version number to assign to the file(s)
flags
One or more of the following characters: ``RVf``, representing
flags to assign to chattr (recurse, verbose, suppress most errors)
CLI Example:
.. code-block:: bash
salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai
salt '*' file.chattr foo3.txt operator=remove attributes=i version=2
'''
operator = kwargs.pop('operator', None)
attributes = kwargs.pop('attributes', None)
flags = kwargs.pop('flags', None)
version = kwargs.pop('version', None)
if (operator is None) or (operator not in ('add', 'remove')):
raise SaltInvocationError(
"Need an operator: 'add' or 'remove' to modify attributes.")
if attributes is None:
raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]")
cmd = ['chattr']
if operator == "add":
attrs = '+{0}'.format(attributes)
elif operator == "remove":
attrs = '-{0}'.format(attributes)
cmd.append(attrs)
if flags is not None:
cmd.append('-{0}'.format(flags))
if version is not None:
cmd.extend(['-v', version])
cmd.extend(files)
result = __salt__['cmd.run'](cmd, python_shell=False)
if bool(result):
return False
return True
def get_sum(path, form='sha256'):
'''
Return the checksum for the given file. The following checksum algorithms
are supported:
* md5
* sha1
* sha224
* sha256 **(default)**
* sha384
* sha512
path
path to the file or directory
form
desired sum format
CLI Example:
.. code-block:: bash
salt '*' file.get_sum /etc/passwd sha512
'''
path = os.path.expanduser(path)
if not os.path.isfile(path):
return 'File not found'
return salt.utils.hashutils.get_hash(path, form, 4096)
def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really be trusted since it is vulnerable to
collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'``
path
path to the file or directory
form
desired sum format
chunk_size
amount to sum at once
CLI Example:
.. code-block:: bash
salt '*' file.get_hash /etc/shadow
'''
return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size)
def get_source_sum(file_name='',
source='',
source_hash=None,
source_hash_name=None,
saltenv='base'):
'''
.. versionadded:: 2016.11.0
Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to
obtain the hash and hash type from the parameters specified below.
file_name
Optional file name being managed, for matching with
:py:func:`file.extract_hash <salt.modules.file.extract_hash>`.
source
Source file, as used in :py:mod:`file <salt.states.file>` and other
states. If ``source_hash`` refers to a file containing hashes, then
this filename will be used to match a filename in that file. If the
``source_hash`` is a hash expression, then this argument will be
ignored.
source_hash
Hash file/expression, as used in :py:mod:`file <salt.states.file>` and
other states. If this value refers to a remote URL or absolute path to
a local file, it will be cached and :py:func:`file.extract_hash
<salt.modules.file.extract_hash>` will be used to obtain a hash from
it.
source_hash_name
Specific file name to look for when ``source_hash`` refers to a remote
file, used to disambiguate ambiguous matches.
saltenv : base
Salt fileserver environment from which to retrieve the source_hash. This
value will only be used when ``source_hash`` refers to a file on the
Salt fileserver (i.e. one beginning with ``salt://``).
CLI Example:
.. code-block:: bash
salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6
salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5
salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz
'''
def _invalid_source_hash_format():
'''
DRY helper for reporting invalid source_hash input
'''
raise CommandExecutionError(
'Source hash {0} format is invalid. The supported formats are: '
'1) a hash, 2) an expression in the format <hash_type>=<hash>, or '
'3) either a path to a local file containing hashes, or a URI of '
'a remote hash file. Supported protocols for remote hash files '
'are: {1}. The hash may also not be of a valid length, the '
'following are supported hash types and lengths: {2}.'.format(
source_hash,
', '.join(salt.utils.files.VALID_PROTOS),
', '.join(
['{0} ({1})'.format(HASHES_REVMAP[x], x)
for x in sorted(HASHES_REVMAP)]
),
)
)
hash_fn = None
if os.path.isabs(source_hash):
hash_fn = source_hash
else:
try:
proto = _urlparse(source_hash).scheme
if proto in salt.utils.files.VALID_PROTOS:
hash_fn = __salt__['cp.cache_file'](source_hash, saltenv)
if not hash_fn:
raise CommandExecutionError(
'Source hash file {0} not found'.format(source_hash)
)
else:
if proto != '':
# Some unsupported protocol (e.g. foo://) is being used.
# We'll get into this else block if a hash expression
# (like md5=<md5 checksum here>), but in those cases, the
# protocol will be an empty string, in which case we avoid
# this error condition.
_invalid_source_hash_format()
except (AttributeError, TypeError):
_invalid_source_hash_format()
if hash_fn is not None:
ret = extract_hash(hash_fn, '', file_name, source, source_hash_name)
if ret is None:
_invalid_source_hash_format()
ret['hsum'] = ret['hsum'].lower()
return ret
else:
# The source_hash is a hash expression
ret = {}
try:
ret['hash_type'], ret['hsum'] = \
[x.strip() for x in source_hash.split('=', 1)]
except AttributeError:
_invalid_source_hash_format()
except ValueError:
# No hash type, try to figure out by hash length
if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash):
_invalid_source_hash_format()
ret['hsum'] = source_hash
source_hash_len = len(source_hash)
if source_hash_len in HASHES_REVMAP:
ret['hash_type'] = HASHES_REVMAP[source_hash_len]
else:
_invalid_source_hash_format()
if ret['hash_type'] not in HASHES:
raise CommandExecutionError(
'Invalid hash type \'{0}\'. Supported hash types are: {1}. '
'Either remove the hash type and simply use \'{2}\' as the '
'source_hash, or change the hash type to a supported type.'
.format(ret['hash_type'], ', '.join(HASHES), ret['hsum'])
)
else:
hsum_len = len(ret['hsum'])
if hsum_len not in HASHES_REVMAP:
_invalid_source_hash_format()
elif hsum_len != HASHES[ret['hash_type']]:
raise CommandExecutionError(
'Invalid length ({0}) for hash type \'{1}\'. Either '
'remove the hash type and simply use \'{2}\' as the '
'source_hash, or change the hash type to \'{3}\''.format(
hsum_len,
ret['hash_type'],
ret['hsum'],
HASHES_REVMAP[hsum_len],
)
)
ret['hsum'] = ret['hsum'].lower()
return ret
def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versionchanged:: 2016.11.4
For this and newer versions the hash can be specified without an
accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``),
but for earlier releases it is necessary to also specify the hash type
in the format ``<hash_type>=<hash_value>`` (e.g.
``md5=e138491e9d5b97023cea823fe17bac22``).
CLI Example:
.. code-block:: bash
salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22
salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22
'''
path = os.path.expanduser(path)
if not isinstance(file_hash, six.string_types):
raise SaltInvocationError('hash must be a string')
for sep in (':', '='):
if sep in file_hash:
hash_type, hash_value = file_hash.split(sep, 1)
break
else:
hash_value = file_hash
hash_len = len(file_hash)
hash_type = HASHES_REVMAP.get(hash_len)
if hash_type is None:
raise SaltInvocationError(
'Hash {0} (length: {1}) could not be matched to a supported '
'hash type. The supported hash types and lengths are: '
'{2}'.format(
file_hash,
hash_len,
', '.join(
['{0} ({1})'.format(HASHES_REVMAP[x], x)
for x in sorted(HASHES_REVMAP)]
),
)
)
return get_hash(path, hash_type) == hash_value
def find(path, *args, **kwargs):
'''
Approximate the Unix ``find(1)`` command and return a list of paths that
meet the specified criteria.
The options include match criteria:
.. code-block:: text
name = path-glob # case sensitive
iname = path-glob # case insensitive
regex = path-regex # case sensitive
iregex = path-regex # case insensitive
type = file-types # match any listed type
user = users # match any listed user
group = groups # match any listed group
size = [+-]number[size-unit] # default unit = byte
mtime = interval # modified since date
grep = regex # search file contents
and/or actions:
.. code-block:: text
delete [= file-types] # default type = 'f'
exec = command [arg ...] # where {} is replaced by pathname
print [= print-opts]
and/or depth criteria:
.. code-block:: text
maxdepth = maximum depth to transverse in path
mindepth = minimum depth to transverse before checking files or directories
The default action is ``print=path``
``path-glob``:
.. code-block:: text
* = match zero or more chars
? = match any char
[abc] = match a, b, or c
[!abc] or [^abc] = match anything except a, b, and c
[x-y] = match chars x through y
[!x-y] or [^x-y] = match anything except chars x through y
{a,b,c} = match a or b or c
``path-regex``: a Python Regex (regular expression) pattern to match pathnames
``file-types``: a string of one or more of the following:
.. code-block:: text
a: all file types
b: block device
c: character device
d: directory
p: FIFO (named pipe)
f: plain file
l: symlink
s: socket
``users``: a space and/or comma separated list of user names and/or uids
``groups``: a space and/or comma separated list of group names and/or gids
``size-unit``:
.. code-block:: text
b: bytes
k: kilobytes
m: megabytes
g: gigabytes
t: terabytes
interval:
.. code-block:: text
[<num>w] [<num>d] [<num>h] [<num>m] [<num>s]
where:
w: week
d: day
h: hour
m: minute
s: second
print-opts: a comma and/or space separated list of one or more of the
following:
.. code-block:: text
group: group name
md5: MD5 digest of file contents
mode: file permissions (as integer)
mtime: last modification time (as time_t)
name: file basename
path: file absolute path
size: file size in bytes
type: file type
user: user name
CLI Examples:
.. code-block:: bash
salt '*' file.find / type=f name=\\*.bak size=+10m
salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime
salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete
'''
if 'delete' in args:
kwargs['delete'] = 'f'
elif 'print' in args:
kwargs['print'] = 'path'
try:
finder = salt.utils.find.Finder(kwargs)
except ValueError as ex:
return 'error: {0}'.format(ex)
ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i]
ret.sort()
return ret
def _sed_esc(string, escape_all=False):
'''
Escape single quotes and forward slashes
'''
special_chars = "^.[$()|*+?{"
string = string.replace("'", "'\"'\"'").replace("/", "\\/")
if escape_all is True:
for char in special_chars:
string = string.replace(char, "\\" + char)
return string
def sed(path,
before,
after,
limit='',
backup='.bak',
options='-r -e',
flags='g',
escape_all=False,
negate_match=False):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Make a simple edit to a file
Equivalent to:
.. code-block:: bash
sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>"
path
The full path to the file to be edited
before
A pattern to find in order to replace with ``after``
after
Text that will replace ``before``
limit : ``''``
An initial pattern to search for before searching for ``before``
backup : ``.bak``
The file will be backed up before edit with this file extension;
**WARNING:** each time ``sed``/``comment``/``uncomment`` is called will
overwrite this backup
options : ``-r -e``
Options to pass to sed
flags : ``g``
Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern
matching
negate_match : False
Negate the search command (``!``)
.. versionadded:: 0.17.0
Forward slashes and single quotes will be escaped automatically in the
``before`` and ``after`` patterns.
CLI Example:
.. code-block:: bash
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
'''
# Largely inspired by Fabric's contrib.files.sed()
# XXX:dc: Do we really want to always force escaping?
#
path = os.path.expanduser(path)
if not os.path.exists(path):
return False
# Mandate that before and after are strings
before = six.text_type(before)
after = six.text_type(after)
before = _sed_esc(before, escape_all)
after = _sed_esc(after, escape_all)
limit = _sed_esc(limit, escape_all)
if sys.platform == 'darwin':
options = options.replace('-r', '-E')
cmd = ['sed']
cmd.append('-i{0}'.format(backup) if backup else '-i')
cmd.extend(salt.utils.args.shlex_split(options))
cmd.append(
r'{limit}{negate_match}s/{before}/{after}/{flags}'.format(
limit='/{0}/ '.format(limit) if limit else '',
negate_match='!' if negate_match else '',
before=before,
after=after,
flags=flags
)
)
cmd.append(path)
return __salt__['cmd.run_all'](cmd, python_shell=False)
def sed_contains(path,
text,
limit='',
flags='g'):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag will be added to any flags you pass in.
CLI Example:
.. code-block:: bash
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
'''
# Largely inspired by Fabric's contrib.files.contains()
path = os.path.expanduser(path)
if not os.path.exists(path):
return False
before = _sed_esc(six.text_type(text), False)
limit = _sed_esc(six.text_type(limit), False)
options = '-n -r -e'
if sys.platform == 'darwin':
options = options.replace('-r', '-E')
cmd = ['sed']
cmd.extend(salt.utils.args.shlex_split(options))
cmd.append(
r'{limit}s/{before}/$/{flags}'.format(
limit='/{0}/ '.format(limit) if limit else '',
before=before,
flags='p{0}'.format(flags)
)
)
cmd.append(path)
result = __salt__['cmd.run'](cmd, python_shell=False)
return bool(result)
def psed(path,
before,
after,
limit='',
backup='.bak',
flags='gMS',
escape_all=False,
multi=False):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Make a simple edit to a file (pure Python version)
Equivalent to:
.. code-block:: bash
sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>"
path
The full path to the file to be edited
before
A pattern to find in order to replace with ``after``
after
Text that will replace ``before``
limit : ``''``
An initial pattern to search for before searching for ``before``
backup : ``.bak``
The file will be backed up before edit with this file extension;
**WARNING:** each time ``sed``/``comment``/``uncomment`` is called will
overwrite this backup
flags : ``gMS``
Flags to modify the search. Valid values are:
- ``g``: Replace all occurrences of the pattern, not just the first.
- ``I``: Ignore case.
- ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S``
dependent on the locale.
- ``M``: Treat multiple lines as a single line.
- ``S``: Make `.` match all characters, including newlines.
- ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``,
``\\s`` and ``\\S`` dependent on Unicode.
- ``X``: Verbose (whitespace is ignored).
multi: ``False``
If True, treat the entire file as a single line
Forward slashes and single quotes will be escaped automatically in the
``before`` and ``after`` patterns.
CLI Example:
.. code-block:: bash
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
'''
# Largely inspired by Fabric's contrib.files.sed()
# XXX:dc: Do we really want to always force escaping?
#
# Mandate that before and after are strings
path = os.path.expanduser(path)
multi = bool(multi)
before = six.text_type(before)
after = six.text_type(after)
before = _sed_esc(before, escape_all)
# The pattern to replace with does not need to be escaped!!!
#after = _sed_esc(after, escape_all)
limit = _sed_esc(limit, escape_all)
shutil.copy2(path, '{0}{1}'.format(path, backup))
with salt.utils.files.fopen(path, 'w') as ofile:
with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile:
if multi is True:
for line in ifile.readline():
ofile.write(
salt.utils.stringutils.to_str(
_psed(
salt.utils.stringutils.to_unicode(line),
before,
after,
limit,
flags
)
)
)
else:
ofile.write(
salt.utils.stringutils.to_str(
_psed(
salt.utils.stringutils.to_unicode(ifile.read()),
before,
after,
limit,
flags
)
)
)
RE_FLAG_TABLE = {'I': re.I,
'L': re.L,
'M': re.M,
'S': re.S,
'U': re.U,
'X': re.X}
def _psed(text,
before,
after,
limit,
flags):
'''
Does the actual work for file.psed, so that single lines can be passed in
'''
atext = text
if limit:
limit = re.compile(limit)
comps = text.split(limit)
atext = ''.join(comps[1:])
count = 1
if 'g' in flags:
count = 0
flags = flags.replace('g', '')
aflags = 0
for flag in flags:
aflags |= RE_FLAG_TABLE[flag]
before = re.compile(before, flags=aflags)
text = re.sub(before, after, atext, count=count)
return text
def uncomment(path,
regex,
char='#',
backup='.bak'):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Uncomment specified commented lines in a file
path
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be uncommented.
This regex should not include the comment character. A leading ``^``
character will be stripped for convenience (for easily switching
between comment() and uncomment()).
char : ``#``
The character to remove in order to uncomment a line
backup : ``.bak``
The file will be backed up before edit with this file extension;
**WARNING:** each time ``sed``/``comment``/``uncomment`` is called will
overwrite this backup
CLI Example:
.. code-block:: bash
salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
'''
return comment_line(path=path,
regex=regex,
char=char,
cmnt=False,
backup=backup)
def comment(path,
regex,
char='#',
backup='.bak'):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Comment out specified lines in a file
path
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be commented;
this pattern will be wrapped in parenthesis and will move any
preceding/trailing ``^`` or ``$`` characters outside the parenthesis
(e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``)
char : ``#``
The character to be inserted at the beginning of a line in order to
comment it out
backup : ``.bak``
The file will be backed up before edit with this file extension
.. warning::
This backup will be overwritten each time ``sed`` / ``comment`` /
``uncomment`` is called. Meaning the backup will only be useful
after the first invocation.
CLI Example:
.. code-block:: bash
salt '*' file.comment /etc/modules pcspkr
'''
return comment_line(path=path,
regex=regex,
char=char,
cmnt=True,
backup=backup)
def comment_line(path,
regex,
char='#',
cmnt=True,
backup='.bak'):
r'''
Comment or Uncomment a line in a text file.
:param path: string
The full path to the text file.
:param regex: string
A regex expression that begins with ``^`` that will find the line you wish
to comment. Can be as simple as ``^color =``
:param char: string
The character used to comment a line in the type of file you're referencing.
Default is ``#``
:param cmnt: boolean
True to comment the line. False to uncomment the line. Default is True.
:param backup: string
The file extension to give the backup file. Default is ``.bak``
Set to False/None to not keep a backup.
:return: boolean
Returns True if successful, False if not
CLI Example:
The following example will comment out the ``pcspkr`` line in the
``/etc/modules`` file using the default ``#`` character and create a backup
file named ``modules.bak``
.. code-block:: bash
salt '*' file.comment_line '/etc/modules' '^pcspkr'
CLI Example:
The following example will uncomment the ``log_level`` setting in ``minion``
config file if it is set to either ``warning``, ``info``, or ``debug`` using
the ``#`` character and create a backup file named ``minion.bk``
.. code-block:: bash
salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk'
'''
# Get the regex for comment or uncomment
if cmnt:
regex = '{0}({1}){2}'.format(
'^' if regex.startswith('^') else '',
regex.lstrip('^').rstrip('$'),
'$' if regex.endswith('$') else '')
else:
regex = r'^{0}\s*({1}){2}'.format(
char,
regex.lstrip('^').rstrip('$'),
'$' if regex.endswith('$') else '')
# Load the real path to the file
path = os.path.realpath(os.path.expanduser(path))
# Make sure the file exists
if not os.path.isfile(path):
raise SaltInvocationError('File not found: {0}'.format(path))
# Make sure it is a text file
if not __utils__['files.is_text'](path):
raise SaltInvocationError(
'Cannot perform string replacements on a binary file: {0}'.format(path))
# First check the whole file, determine whether to make the replacement
# Searching first avoids modifying the time stamp if there are no changes
found = False
# Dictionaries for comparing changes
orig_file = []
new_file = []
# Buffer size for fopen
bufsize = os.path.getsize(path)
try:
# Use a read-only handle to open the file
with salt.utils.files.fopen(path,
mode='rb',
buffering=bufsize) as r_file:
# Loop through each line of the file and look for a match
for line in r_file:
# Is it in this line
line = salt.utils.stringutils.to_unicode(line)
if re.match(regex, line):
# Load lines into dictionaries, set found to True
orig_file.append(line)
if cmnt:
new_file.append('{0}{1}'.format(char, line))
else:
new_file.append(line.lstrip(char))
found = True
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to open file '{0}'. "
"Exception: {1}".format(path, exc)
)
# We've searched the whole file. If we didn't find anything, return False
if not found:
return False
if not salt.utils.platform.is_windows():
pre_user = get_user(path)
pre_group = get_group(path)
pre_mode = salt.utils.files.normalize_mode(get_mode(path))
# Create a copy to read from and to use as a backup later
try:
temp_file = _mkstemp_copy(path=path, preserve_inode=False)
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
try:
# Open the file in write mode
mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w'
with salt.utils.files.fopen(path,
mode=mode,
buffering=bufsize) as w_file:
try:
# Open the temp file in read mode
with salt.utils.files.fopen(temp_file,
mode='rb',
buffering=bufsize) as r_file:
# Loop through each line of the file and look for a match
for line in r_file:
line = salt.utils.stringutils.to_unicode(line)
try:
# Is it in this line
if re.match(regex, line):
# Write the new line
if cmnt:
wline = '{0}{1}'.format(char, line)
else:
wline = line.lstrip(char)
else:
# Write the existing line (no change)
wline = line
wline = salt.utils.stringutils.to_bytes(wline) \
if six.PY2 and salt.utils.platform.is_windows() \
else salt.utils.stringutils.to_str(wline)
w_file.write(wline)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to write file '{0}'. Contents may "
"be truncated. Temporary file contains copy "
"at '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
if backup:
# Move the backup file to the original directory
backup_name = '{0}{1}'.format(path, backup)
try:
shutil.move(temp_file, backup_name)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to move the temp file '{0}' to the "
"backup file '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
else:
os.remove(temp_file)
if not salt.utils.platform.is_windows():
check_perms(path, None, pre_user, pre_group, pre_mode)
# Return a diff using the two dictionaries
return __utils__['stringutils.get_diff'](orig_file, new_file)
def _get_flags(flags):
'''
Return an integer appropriate for use as a flag for the re module from a
list of human-readable strings
.. code-block:: python
>>> _get_flags(['MULTILINE', 'IGNORECASE'])
10
>>> _get_flags('MULTILINE')
8
>>> _get_flags(2)
2
'''
if isinstance(flags, six.string_types):
flags = [flags]
if isinstance(flags, Iterable) and not isinstance(flags, Mapping):
_flags_acc = []
for flag in flags:
_flag = getattr(re, six.text_type(flag).upper())
if not isinstance(_flag, six.integer_types):
raise SaltInvocationError(
'Invalid re flag given: {0}'.format(flag)
)
_flags_acc.append(_flag)
return reduce(operator.__or__, _flags_acc)
elif isinstance(flags, six.integer_types):
return flags
else:
raise SaltInvocationError(
'Invalid re flags: "{0}", must be given either as a single flag '
'string, a list of strings, or as an integer'.format(flags)
)
def _add_flags(flags, new_flags):
'''
Combine ``flags`` and ``new_flags``
'''
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return flags | new_flags
def _mkstemp_copy(path,
preserve_inode=True):
'''
Create a temp file and move/copy the contents of ``path`` to the temp file.
Return the path to the temp file.
path
The full path to the file whose contents will be moved/copied to a temp file.
Whether it's moved or copied depends on the value of ``preserve_inode``.
preserve_inode
Preserve the inode of the file, so that any hard links continue to share the
inode with the original filename. This works by *copying* the file, reading
from the copy, and writing to the file at the original inode. If ``False``, the
file will be *moved* rather than copied, and a new file will be written to a
new inode, but using the original filename. Hard links will then share an inode
with the backup, instead (if using ``backup`` to create a backup copy).
Default is ``True``.
'''
temp_file = None
# Create the temp file
try:
temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to create temp file. "
"Exception: {0}".format(exc)
)
# use `copy` to preserve the inode of the
# original file, and thus preserve hardlinks
# to the inode. otherwise, use `move` to
# preserve prior behavior, which results in
# writing the file to a new inode.
if preserve_inode:
try:
shutil.copy2(path, temp_file)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to copy file '{0}' to the "
"temp file '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
else:
try:
shutil.move(path, temp_file)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to move file '{0}' to the "
"temp file '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
return temp_file
def _starts_till(src, probe, strip_comments=True):
'''
Returns True if src and probe at least matches at the beginning till some point.
'''
def _strip_comments(txt):
'''
Strip possible comments.
Usually comments are one or two symbols at the beginning of the line, separated with space
'''
buff = txt.split(" ", 1)
return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt
def _to_words(txt):
'''
Split by words
'''
return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt
no_match = -1
equal = 0
if not src or not probe:
return no_match
src = src.rstrip('\n\r')
probe = probe.rstrip('\n\r')
if src == probe:
return equal
src = _to_words(strip_comments and _strip_comments(src) or src)
probe = _to_words(strip_comments and _strip_comments(probe) or probe)
a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src)
b_buff = ' '.join(b_buff)
for idx in range(len(a_buff)):
prb = ' '.join(a_buff[:-(idx + 1)])
if prb and b_buff.startswith(prb):
return idx
return no_match
def _regex_to_static(src, regex):
'''
Expand regular expression to static match.
'''
if not src or not regex:
return None
try:
compiled = re.compile(regex, re.DOTALL)
src = [line for line in src if compiled.search(line) or line.count(regex)]
except Exception as ex: # pylint: disable=broad-except
raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex))
return src and src or []
def _assert_occurrence(probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = len(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
else:
msg = None
if msg:
raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target))
return occ
def _set_line_indent(src, line, indent):
'''
Indent the line with the source line.
'''
if not indent:
return line
idt = []
for c in src:
if c not in ['\t', ' ']:
break
idt.append(c)
return ''.join(idt) + line.lstrip()
def _get_eol(line):
match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line)
return match and match.group() or ''
def _set_line_eol(src, line):
'''
Add line ending
'''
line_ending = _get_eol(src) or os.linesep
return line.rstrip() + line_ending
def _insert_line_before(idx, body, content, indent):
if not idx or (idx and _starts_till(body[idx - 1], content) < 0):
cnd = _set_line_indent(body[idx], content, indent)
body.insert(idx, cnd)
return body
def _insert_line_after(idx, body, content, indent):
# No duplicates or append, if "after" is the last line
next_line = idx + 1 < len(body) and body[idx + 1] or None
if next_line is None or _starts_till(next_line, content) < 0:
cnd = _set_line_indent(body[idx], content, indent)
body.insert(idx + 1, cnd)
return body
def line(path, content=None, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True):
'''
.. versionadded:: 2015.8.0
Edit a line in the configuration file. The ``path`` and ``content``
arguments are required, as well as passing in one of the ``mode``
options.
path
Filesystem path to the file to be edited.
content
Content of the line. Allowed to be empty if mode=delete.
match
Match the target line for an action by
a fragment of a string or regular expression.
If neither ``before`` nor ``after`` are provided, and ``match``
is also ``None``, match becomes the ``content`` value.
mode
Defines how to edit a line. One of the following options is
required:
- ensure
If line does not exist, it will be added. This is based on the
``content`` argument.
- replace
If line already exists, it will be replaced.
- delete
Delete the line, once found.
- insert
Insert a line.
.. note::
If ``mode=insert`` is used, at least one of the following
options must also be defined: ``location``, ``before``, or
``after``. If ``location`` is used, it takes precedence
over the other two options.
location
Defines where to place content in the line. Note this option is only
used when ``mode=insert`` is specified. If a location is passed in, it
takes precedence over both the ``before`` and ``after`` kwargs. Valid
locations are:
- start
Place the content at the beginning of the file.
- end
Place the content at the end of the file.
before
Regular expression or an exact case-sensitive fragment of the string.
This option is only used when either the ``ensure`` or ``insert`` mode
is defined.
after
Regular expression or an exact case-sensitive fragment of the string.
This option is only used when either the ``ensure`` or ``insert`` mode
is defined.
show_changes
Output a unified diff of the old file and the new file.
If ``False`` return a boolean if any changes were made.
Default is ``True``
.. note::
Using this option will store two copies of the file in-memory
(the original version and the edited version) in order to generate the diff.
backup
Create a backup of the original file with the extension:
"Year-Month-Day-Hour-Minutes-Seconds".
quiet
Do not raise any exceptions. E.g. ignore the fact that the file that is
tried to be edited does not exist and nothing really happened.
indent
Keep indentation with the previous line. This option is not considered when
the ``delete`` mode is specified.
CLI Example:
.. code-block:: bash
salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure'
.. note::
If an equal sign (``=``) appears in an argument to a Salt command, it is
interpreted as a keyword argument in the format of ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace"
'''
path = os.path.realpath(os.path.expanduser(path))
if not os.path.isfile(path):
if not quiet:
raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path))
return False # No changes had happened
mode = mode and mode.lower() or mode
if mode not in ['insert', 'ensure', 'delete', 'replace']:
if mode is None:
raise CommandExecutionError('Mode was not defined. How to process the file?')
else:
raise CommandExecutionError('Unknown mode: "{0}"'.format(mode))
# We've set the content to be empty in the function params but we want to make sure
# it gets passed when needed. Feature #37092
empty_content_modes = ['delete']
if mode not in empty_content_modes and content is None:
raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes)))
del empty_content_modes
# Before/after has privilege. If nothing defined, match is used by content.
if before is None and after is None and not match:
match = content
with salt.utils.files.fopen(path, mode='r') as fp_:
body = salt.utils.data.decode_list(fp_.readlines())
body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest()
# Add empty line at the end if last line ends with eol.
# Allows simpler code
if body and _get_eol(body[-1]):
body.append('')
after = _regex_to_static(body, after)
before = _regex_to_static(body, before)
match = _regex_to_static(body, match)
if os.stat(path).st_size == 0 and mode in ('delete', 'replace'):
log.warning('Cannot find text to {0}. File \'{1}\' is empty.'.format(mode, path))
body = []
elif mode == 'delete' and match:
body = [line for line in body if line != match[0]]
elif mode == 'replace' and match:
idx = body.index(match[0])
file_line = body.pop(idx)
body.insert(idx, _set_line_indent(file_line, content, indent))
elif mode == 'insert':
if not location and not before and not after:
raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.')
if not location:
if before and after:
_assert_occurrence(before, 'before')
_assert_occurrence(after, 'after')
out = []
in_range = False
for line in body:
if line == after[0]:
in_range = True
elif line == before[0] and in_range:
cnd = _set_line_indent(line, content, indent)
out.append(cnd)
out.append(line)
body = out
if before and not after:
_assert_occurrence(before, 'before')
idx = body.index(before[0])
body = _insert_line_before(idx, body, content, indent)
elif after and not before:
_assert_occurrence(after, 'after')
idx = body.index(after[0])
body = _insert_line_after(idx, body, content, indent)
else:
if location == 'start':
if body:
body.insert(0, _set_line_eol(body[0], content))
else:
body.append(content + os.linesep)
elif location == 'end':
body.append(_set_line_indent(body[-1], content, indent) if body else content)
elif mode == 'ensure':
if before and after:
_assert_occurrence(before, 'before')
_assert_occurrence(after, 'after')
is_there = bool([l for l in body if l.count(content)])
if not is_there:
idx = body.index(after[0])
if idx < (len(body) - 1) and body[idx + 1] == before[0]:
cnd = _set_line_indent(body[idx], content, indent)
body.insert(idx + 1, cnd)
else:
raise CommandExecutionError('Found more than one line between '
'boundaries "before" and "after".')
elif before and not after:
_assert_occurrence(before, 'before')
idx = body.index(before[0])
body = _insert_line_before(idx, body, content, indent)
elif not before and after:
_assert_occurrence(after, 'after')
idx = body.index(after[0])
body = _insert_line_after(idx, body, content, indent)
else:
raise CommandExecutionError("Wrong conditions? "
"Unable to ensure line without knowing "
"where to put it before and/or after.")
if body:
for idx, line in enumerate(body):
if not _get_eol(line) and idx+1 < len(body):
prev = idx and idx-1 or 1
body[idx] = _set_line_eol(body[prev], line)
# We do not need empty line at the end anymore
if '' == body[-1]:
body.pop()
changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest()
if backup and changed and __opts__['test'] is False:
try:
temp_file = _mkstemp_copy(path=path, preserve_inode=True)
shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())))
except (OSError, IOError) as exc:
raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc))
changes_diff = None
if changed:
if show_changes:
with salt.utils.files.fopen(path, 'r') as fp_:
path_content = salt.utils.data.decode_list(fp_.read().splitlines(True))
changes_diff = __utils__['stringutils.get_diff'](path_content, body)
if __opts__['test'] is False:
fh_ = None
try:
# Make sure we match the file mode from salt.utils.files.fopen
if six.PY2 and salt.utils.platform.is_windows():
mode = 'wb'
body = salt.utils.data.encode_list(body)
else:
mode = 'w'
body = salt.utils.data.decode_list(body, to_str=True)
fh_ = salt.utils.atomicfile.atomic_open(path, mode)
fh_.writelines(body)
finally:
if fh_:
fh_.close()
return show_changes and changes_diff or changed
def replace(path,
pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
backup='.bak',
dry_run=False,
search_only=False,
show_changes=True,
ignore_if_missing=False,
preserve_inode=True,
backslash_literal=False,
):
'''
.. versionadded:: 0.17.0
Replace occurrences of a pattern in a file. If ``show_changes`` is
``True``, then a diff of what changed will be returned, otherwise a
``True`` will be returned when changes are made, and ``False`` when
no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
path
Filesystem path to the file to be edited. If a symlink is specified, it
will be resolved to its target.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text
count : 0
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int)
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str)
How much of the file to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found : False
.. versionadded:: 2014.7.0
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found : False
.. versionadded:: 2014.7.0
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
.. versionadded:: 2014.7.0
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
backup : .bak
The file extension to use for a backup of the file before editing. Set
to ``False`` to skip making a backup.
dry_run : False
If set to ``True``, no changes will be made to the file, the function
will just return the changes that would have been made (or a
``True``/``False`` value if ``show_changes`` is set to ``False``).
search_only : False
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes : True
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
.. note::
Using this option will store two copies of the file in memory (the
original version and the edited version) in order to generate the
diff. This may not normally be a concern, but could impact
performance if used with large files.
ignore_if_missing : False
.. versionadded:: 2015.8.0
If set to ``True``, this function will simply return ``False``
if the file doesn't exist. Otherwise, an error will be thrown.
preserve_inode : True
.. versionadded:: 2015.8.0
Preserve the inode of the file, so that any hard links continue to
share the inode with the original filename. This works by *copying* the
file, reading from the copy, and writing to the file at the original
inode. If ``False``, the file will be *moved* rather than copied, and a
new file will be written to a new inode, but using the original
filename. Hard links will then share an inode with the backup, instead
(if using ``backup`` to create a backup copy).
backslash_literal : False
.. versionadded:: 2016.11.7
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' file.replace /path/to/file pattern='=' repl=':'
salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:'
CLI Examples:
.. code-block:: bash
salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info'
salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]'
'''
symlink = False
if is_link(path):
symlink = True
target_path = os.readlink(path)
given_path = os.path.expanduser(path)
path = os.path.realpath(os.path.expanduser(path))
if not os.path.exists(path):
if ignore_if_missing:
return False
else:
raise SaltInvocationError('File not found: {0}'.format(path))
if not __utils__['files.is_text'](path):
raise SaltInvocationError(
'Cannot perform string replacements on a binary file: {0}'
.format(path)
)
if search_only and (append_if_not_found or prepend_if_not_found):
raise SaltInvocationError(
'search_only cannot be used with append/prepend_if_not_found'
)
if append_if_not_found and prepend_if_not_found:
raise SaltInvocationError(
'Only one of append and prepend_if_not_found is permitted'
)
flags_num = _get_flags(flags)
cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num)
filesize = os.path.getsize(path)
if bufsize == 'file':
bufsize = filesize
# Search the file; track if any changes have been made for the return val
has_changes = False
orig_file = [] # used for show_changes and change detection
new_file = [] # used for show_changes and change detection
if not salt.utils.platform.is_windows():
pre_user = get_user(path)
pre_group = get_group(path)
pre_mode = salt.utils.files.normalize_mode(get_mode(path))
# Avoid TypeErrors by forcing repl to be bytearray related to mmap
# Replacement text may contains integer: 123 for example
repl = salt.utils.stringutils.to_bytes(six.text_type(repl))
if not_found_content:
not_found_content = salt.utils.stringutils.to_bytes(not_found_content)
found = False
temp_file = None
content = salt.utils.stringutils.to_unicode(not_found_content) \
if not_found_content and (prepend_if_not_found or append_if_not_found) \
else salt.utils.stringutils.to_unicode(repl)
try:
# First check the whole file, determine whether to make the replacement
# Searching first avoids modifying the time stamp if there are no changes
r_data = None
# Use a read-only handle to open the file
with salt.utils.files.fopen(path,
mode='rb',
buffering=bufsize) as r_file:
try:
# mmap throws a ValueError if the file is empty.
r_data = mmap.mmap(r_file.fileno(),
0,
access=mmap.ACCESS_READ)
except (ValueError, mmap.error):
# size of file in /proc is 0, but contains data
r_data = salt.utils.stringutils.to_bytes("".join(r_file))
if search_only:
# Just search; bail as early as a match is found
if re.search(cpattern, r_data):
return True # `with` block handles file closure
else:
return False
else:
result, nrepl = re.subn(cpattern,
repl.replace('\\', '\\\\') if backslash_literal else repl,
r_data,
count)
# found anything? (even if no change)
if nrepl > 0:
found = True
# Identity check the potential change
has_changes = True if pattern != repl else has_changes
if prepend_if_not_found or append_if_not_found:
# Search for content, to avoid pre/appending the
# content if it was pre/appended in a previous run.
if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))),
r_data,
flags=flags_num):
# Content was found, so set found.
found = True
orig_file = r_data.read(filesize).splitlines(True) \
if isinstance(r_data, mmap.mmap) \
else r_data.splitlines(True)
new_file = result.splitlines(True)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to open file '{0}'. "
"Exception: {1}".format(path, exc)
)
finally:
if r_data and isinstance(r_data, mmap.mmap):
r_data.close()
if has_changes and not dry_run:
# Write the replacement text in this block.
try:
# Create a copy to read from and to use as a backup later
temp_file = _mkstemp_copy(path=path,
preserve_inode=preserve_inode)
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
r_data = None
try:
# Open the file in write mode
with salt.utils.files.fopen(path,
mode='w',
buffering=bufsize) as w_file:
try:
# Open the temp file in read mode
with salt.utils.files.fopen(temp_file,
mode='r',
buffering=bufsize) as r_file:
r_data = mmap.mmap(r_file.fileno(),
0,
access=mmap.ACCESS_READ)
result, nrepl = re.subn(cpattern,
repl.replace('\\', '\\\\') if backslash_literal else repl,
r_data,
count)
try:
w_file.write(salt.utils.stringutils.to_str(result))
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to write file '{0}'. Contents may "
"be truncated. Temporary file contains copy "
"at '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
finally:
if r_data and isinstance(r_data, mmap.mmap):
r_data.close()
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
if not found and (append_if_not_found or prepend_if_not_found):
if not_found_content is None:
not_found_content = repl
if prepend_if_not_found:
new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep))
else:
# append_if_not_found
# Make sure we have a newline at the end of the file
if 0 != len(new_file):
if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)):
new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep)
new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep))
has_changes = True
if not dry_run:
try:
# Create a copy to read from and for later use as a backup
temp_file = _mkstemp_copy(path=path,
preserve_inode=preserve_inode)
except (OSError, IOError) as exc:
raise CommandExecutionError("Exception: {0}".format(exc))
# write new content in the file while avoiding partial reads
try:
fh_ = salt.utils.atomicfile.atomic_open(path, 'wb')
for line in new_file:
fh_.write(salt.utils.stringutils.to_bytes(line))
finally:
fh_.close()
if backup and has_changes and not dry_run:
# keep the backup only if it was requested
# and only if there were any changes
backup_name = '{0}{1}'.format(path, backup)
try:
shutil.move(temp_file, backup_name)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to move the temp file '{0}' to the "
"backup file '{1}'. "
"Exception: {2}".format(path, temp_file, exc)
)
if symlink:
symlink_backup = '{0}{1}'.format(given_path, backup)
target_backup = '{0}{1}'.format(target_path, backup)
# Always clobber any existing symlink backup
# to match the behaviour of the 'backup' option
try:
os.symlink(target_backup, symlink_backup)
except OSError:
os.remove(symlink_backup)
os.symlink(target_backup, symlink_backup)
except Exception: # pylint: disable=broad-except
raise CommandExecutionError(
"Unable create backup symlink '{0}'. "
"Target was '{1}'. "
"Exception: {2}".format(symlink_backup, target_backup,
exc)
)
elif temp_file:
try:
os.remove(temp_file)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to delete temp file '{0}'. "
"Exception: {1}".format(temp_file, exc)
)
if not dry_run and not salt.utils.platform.is_windows():
check_perms(path, None, pre_user, pre_group, pre_mode)
differences = __utils__['stringutils.get_diff'](orig_file, new_file)
if show_changes:
return differences
# We may have found a regex line match but don't need to change the line
# (for situations where the pattern also matches the repl). Revert the
# has_changes flag to False if the final result is unchanged.
if not differences:
has_changes = False
return has_changes
def blockreplace(path,
marker_start='#-- start managed zone --',
marker_end='#-- end managed zone --',
content='',
append_if_not_found=False,
prepend_if_not_found=False,
backup='.bak',
dry_run=False,
show_changes=True,
append_newline=False):
'''
.. versionadded:: 2014.1.0
Replace content of a text block in a file, delimited by line markers
A block of content delimited by comments can help you manage several lines
entries without worrying about old entries removal.
.. note::
This function will store two copies of the file in-memory (the original
version and the edited version) in order to detect changes and only
edit the targeted file if necessary.
path
Filesystem path to the file to be edited
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered, so
whitespace or extra content before or after the marker is included in
final output
marker_end
The line content identifying the end of the content block. As of
versions 2017.7.5 and 2018.3.1, everything up to the text matching the
marker will be replaced, so it's important to ensure that your marker
includes the beginning of the text you wish to replace.
content
The content to be used between the two lines identified by marker_start
and marker_stop.
append_if_not_found : False
If markers are not found and set to ``True`` then, the markers and
content will be appended to the file.
prepend_if_not_found : False
If markers are not found and set to ``True`` then, the markers and
content will be prepended to the file.
backup
The file extension to use for a backup of the file if any edit is made.
Set to ``False`` to skip making a backup.
dry_run : False
If ``True``, do not make any edits to the file and simply return the
changes that *would* be made.
show_changes : True
Controls how changes are presented. If ``True``, this function will
return a unified diff of the changes made. If False, then it will
return a boolean (``True`` if any changes were made, otherwise
``False``).
append_newline : False
Controls whether or not a newline is appended to the content block. If
the value of this argument is ``True`` then a newline will be added to
the content block. If it is ``False``, then a newline will *not* be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
.. versionadded:: 2016.3.4
.. versionchanged:: 2017.7.5,2018.3.1
New behavior added when value is ``None``.
.. versionchanged:: 2019.2.0
The default value of this argument will change to ``None`` to match
the behavior of the :py:func:`file.blockreplace state
<salt.states.file.blockreplace>`
CLI Example:
.. code-block:: bash
salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\
'#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True
'''
if append_if_not_found and prepend_if_not_found:
raise SaltInvocationError(
'Only one of append and prepend_if_not_found is permitted'
)
path = os.path.expanduser(path)
if not os.path.exists(path):
raise SaltInvocationError('File not found: {0}'.format(path))
try:
file_encoding = __utils__['files.get_encoding'](path)
except CommandExecutionError:
file_encoding = None
if __utils__['files.is_binary'](path):
if not file_encoding:
raise SaltInvocationError(
'Cannot perform string replacements on a binary file: {0}'
.format(path)
)
if append_newline is None and not content.endswith((os.linesep, '\n')):
append_newline = True
# Split the content into a list of lines, removing newline characters. To
# ensure that we handle both Windows and POSIX newlines, first split on
# Windows newlines, and then split on POSIX newlines.
split_content = []
for win_line in content.split('\r\n'):
for content_line in win_line.split('\n'):
split_content.append(content_line)
line_count = len(split_content)
has_changes = False
orig_file = []
new_file = []
in_block = False
block_found = False
linesep = None
def _add_content(linesep, lines=None, include_marker_start=True,
end_line=None):
if lines is None:
lines = []
include_marker_start = True
if end_line is None:
end_line = marker_end
end_line = end_line.rstrip('\r\n') + linesep
if include_marker_start:
lines.append(marker_start + linesep)
if split_content:
for index, content_line in enumerate(split_content, 1):
if index != line_count:
lines.append(content_line + linesep)
else:
# We're on the last line of the content block
if append_newline:
lines.append(content_line + linesep)
lines.append(end_line)
else:
lines.append(content_line + end_line)
else:
lines.append(end_line)
return lines
# We do not use in-place editing to avoid file attrs modifications when
# no changes are required and to avoid any file access on a partially
# written file.
try:
fi_file = io.open(path, mode='r', encoding=file_encoding, newline='')
for line in fi_file:
write_line_to_new_file = True
if linesep is None:
# Auto-detect line separator
if line.endswith('\r\n'):
linesep = '\r\n'
elif line.endswith('\n'):
linesep = '\n'
else:
# No newline(s) in file, fall back to system's linesep
linesep = os.linesep
if marker_start in line:
# We've entered the content block
in_block = True
else:
if in_block:
# We're not going to write the lines from the old file to
# the new file until we have exited the block.
write_line_to_new_file = False
marker_end_pos = line.find(marker_end)
if marker_end_pos != -1:
# End of block detected
in_block = False
# We've found and exited the block
block_found = True
_add_content(linesep, lines=new_file,
include_marker_start=False,
end_line=line[marker_end_pos:])
# Save the line from the original file
orig_file.append(line)
if write_line_to_new_file:
new_file.append(line)
except (IOError, OSError) as exc:
raise CommandExecutionError(
'Failed to read from {0}: {1}'.format(path, exc)
)
finally:
if linesep is None:
# If the file was empty, we will not have set linesep yet. Assume
# the system's line separator. This is needed for when we
# prepend/append later on.
linesep = os.linesep
try:
fi_file.close()
except Exception: # pylint: disable=broad-except
pass
if in_block:
# unterminated block => bad, always fail
raise CommandExecutionError(
'Unterminated marked block. End of file reached before marker_end.'
)
if not block_found:
if prepend_if_not_found:
# add the markers and content at the beginning of file
prepended_content = _add_content(linesep)
prepended_content.extend(new_file)
new_file = prepended_content
block_found = True
elif append_if_not_found:
# Make sure we have a newline at the end of the file
if 0 != len(new_file):
if not new_file[-1].endswith(linesep):
new_file[-1] += linesep
# add the markers and content at the end of file
_add_content(linesep, lines=new_file)
block_found = True
else:
raise CommandExecutionError(
'Cannot edit marked block. Markers were not found in file.'
)
if block_found:
diff = __utils__['stringutils.get_diff'](orig_file, new_file)
has_changes = diff is not ''
if has_changes and not dry_run:
# changes detected
# backup file attrs
perms = {}
perms['user'] = get_user(path)
perms['group'] = get_group(path)
perms['mode'] = salt.utils.files.normalize_mode(get_mode(path))
# backup old content
if backup is not False:
backup_path = '{0}{1}'.format(path, backup)
shutil.copy2(path, backup_path)
# copy2 does not preserve ownership
if salt.utils.platform.is_windows():
# This function resides in win_file.py and will be available
# on Windows. The local function will be overridden
# pylint: disable=E1120,E1123
check_perms(path=backup_path,
ret=None,
owner=perms['user'])
# pylint: enable=E1120,E1123
else:
check_perms(name=backup_path,
ret=None,
user=perms['user'],
group=perms['group'],
mode=perms['mode'])
# write new content in the file while avoiding partial reads
try:
fh_ = salt.utils.atomicfile.atomic_open(path, 'wb')
for line in new_file:
fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding))
finally:
fh_.close()
# this may have overwritten file attrs
if salt.utils.platform.is_windows():
# This function resides in win_file.py and will be available
# on Windows. The local function will be overridden
# pylint: disable=E1120,E1123
check_perms(path=path,
ret=None,
owner=perms['user'])
# pylint: enable=E1120,E1123
else:
check_perms(path,
ret=None,
user=perms['user'],
group=perms['group'],
mode=perms['mode'])
if show_changes:
return diff
return has_changes
def search(path,
pattern,
flags=8,
bufsize=1,
ignore_if_missing=False,
multiline=False
):
'''
.. versionadded:: 0.17.0
Search for occurrences of a pattern in a file
Except for multiline, params are identical to
:py:func:`~salt.modules.file.replace`.
multiline
If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to
'file'.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' file.search /etc/crontab 'mymaintenance.sh'
'''
if multiline:
flags = _add_flags(flags, 'MULTILINE')
bufsize = 'file'
# This function wraps file.replace on purpose in order to enforce
# consistent usage, compatible regex's, expected behavior, *and* bugs. :)
# Any enhancements or fixes to one should affect the other.
return replace(path,
pattern,
'',
flags=flags,
bufsize=bufsize,
dry_run=True,
search_only=True,
show_changes=False,
ignore_if_missing=ignore_if_missing)
def patch(originalfile, patchfile, options='', dry_run=False):
'''
.. versionadded:: 0.10.4
Apply a patch to a file or directory.
Equivalent to:
.. code-block:: bash
patch <options> -i <patchfile> <originalfile>
Or, when a directory is patched:
.. code-block:: bash
patch <options> -i <patchfile> -d <originalfile> -p0
originalfile
The full path to the file or directory to be patched
patchfile
A patch file to apply to ``originalfile``
options
Options to pass to patch.
CLI Example:
.. code-block:: bash
salt '*' file.patch /opt/file.txt /tmp/file.txt.patch
'''
patchpath = salt.utils.path.which('patch')
if not patchpath:
raise CommandExecutionError(
'patch executable not found. Is the distribution\'s patch '
'package installed?'
)
cmd = [patchpath]
cmd.extend(salt.utils.args.shlex_split(options))
if dry_run:
if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'):
cmd.append('-C')
else:
cmd.append('--dry-run')
# this argument prevents interactive prompts when the patch fails to apply.
# the exit code will still be greater than 0 if that is the case.
if '-N' not in cmd and '--forward' not in cmd:
cmd.append('--forward')
has_rejectfile_option = False
for option in cmd:
if option == '-r' or option.startswith('-r ') \
or option.startswith('--reject-file'):
has_rejectfile_option = True
break
# by default, patch will write rejected patch files to <filename>.rej.
# this option prevents that.
if not has_rejectfile_option:
cmd.append('--reject-file=-')
cmd.extend(['-i', patchfile])
if os.path.isdir(originalfile):
cmd.extend(['-d', originalfile])
has_strip_option = False
for option in cmd:
if option.startswith('-p') or option.startswith('--strip='):
has_strip_option = True
break
if not has_strip_option:
cmd.append('--strip=0')
else:
cmd.append(originalfile)
return __salt__['cmd.run_all'](cmd, python_shell=False)
def contains(path, text):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the file at ``path`` contains ``text``
CLI Example:
.. code-block:: bash
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
'''
path = os.path.expanduser(path)
if not os.path.exists(path):
return False
stripped_text = six.text_type(text).strip()
try:
with salt.utils.filebuffer.BufferedReader(path) as breader:
for chunk in breader:
if stripped_text in chunk:
return True
return False
except (IOError, OSError):
return False
def contains_regex(path, regex, lchar=''):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches on any line in the text
of a given file.
If the lchar argument (leading char) is specified, it
will strip `lchar` from the left side of each line before trying to match
CLI Example:
.. code-block:: bash
salt '*' file.contains_regex /etc/crontab
'''
path = os.path.expanduser(path)
if not os.path.exists(path):
return False
try:
with salt.utils.files.fopen(path, 'r') as target:
for line in target:
line = salt.utils.stringutils.to_unicode(line)
if lchar:
line = line.lstrip(lchar)
if re.search(regex, line):
return True
return False
except (IOError, OSError):
return False
def contains_glob(path, glob_expr):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the given glob matches a string in the named file
CLI Example:
.. code-block:: bash
salt '*' file.contains_glob /etc/foobar '*cheese*'
'''
path = os.path.expanduser(path)
if not os.path.exists(path):
return False
try:
with salt.utils.filebuffer.BufferedReader(path) as breader:
for chunk in breader:
if fnmatch.fnmatch(chunk, glob_expr):
return True
return False
except (IOError, OSError):
return False
def append(path, *args, **kwargs):
'''
.. versionadded:: 0.9.5
Append text to the end of a file
path
path to file
`*args`
strings to append to file
CLI Example:
.. code-block:: bash
salt '*' file.append /etc/motd \\
"With all thine offerings thou shalt offer salt." \\
"Salt is what makes things taste bad when it isn't in them."
.. admonition:: Attention
If you need to pass a string to append and that string contains
an equal sign, you **must** include the argument name, args.
For example:
.. code-block:: bash
salt '*' file.append /etc/motd args='cheese=spam'
salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']"
'''
path = os.path.expanduser(path)
# Largely inspired by Fabric's contrib.files.append()
if 'args' in kwargs:
if isinstance(kwargs['args'], list):
args = kwargs['args']
else:
args = [kwargs['args']]
# Make sure we have a newline at the end of the file. Do this in binary
# mode so SEEK_END with nonzero offset will work.
with salt.utils.files.fopen(path, 'rb+') as ofile:
linesep = salt.utils.stringutils.to_bytes(os.linesep)
try:
ofile.seek(-len(linesep), os.SEEK_END)
except IOError as exc:
if exc.errno in (errno.EINVAL, errno.ESPIPE):
# Empty file, simply append lines at the beginning of the file
pass
else:
raise
else:
if ofile.read(len(linesep)) != linesep:
ofile.seek(0, os.SEEK_END)
ofile.write(linesep)
# Append lines in text mode
with salt.utils.files.fopen(path, 'a') as ofile:
for new_line in args:
ofile.write(
salt.utils.stringutils.to_str(
'{0}{1}'.format(new_line, os.linesep)
)
)
return 'Wrote {0} lines to "{1}"'.format(len(args), path)
def prepend(path, *args, **kwargs):
'''
.. versionadded:: 2014.7.0
Prepend text to the beginning of a file
path
path to file
`*args`
strings to prepend to the file
CLI Example:
.. code-block:: bash
salt '*' file.prepend /etc/motd \\
"With all thine offerings thou shalt offer salt." \\
"Salt is what makes things taste bad when it isn't in them."
.. admonition:: Attention
If you need to pass a string to append and that string contains
an equal sign, you **must** include the argument name, args.
For example:
.. code-block:: bash
salt '*' file.prepend /etc/motd args='cheese=spam'
salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']"
'''
path = os.path.expanduser(path)
if 'args' in kwargs:
if isinstance(kwargs['args'], list):
args = kwargs['args']
else:
args = [kwargs['args']]
try:
with salt.utils.files.fopen(path) as fhr:
contents = [salt.utils.stringutils.to_unicode(line)
for line in fhr.readlines()]
except IOError:
contents = []
preface = []
for line in args:
preface.append('{0}\n'.format(line))
with salt.utils.files.fopen(path, 'w') as ofile:
contents = preface + contents
ofile.write(salt.utils.stringutils.to_str(''.join(contents)))
return 'Prepended {0} lines to "{1}"'.format(len(args), path)
def write(path, *args, **kwargs):
'''
.. versionadded:: 2014.7.0
Write text to a file, overwriting any existing contents.
path
path to file
`*args`
strings to write to the file
CLI Example:
.. code-block:: bash
salt '*' file.write /etc/motd \\
"With all thine offerings thou shalt offer salt."
.. admonition:: Attention
If you need to pass a string to append and that string contains
an equal sign, you **must** include the argument name, args.
For example:
.. code-block:: bash
salt '*' file.write /etc/motd args='cheese=spam'
salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']"
'''
path = os.path.expanduser(path)
if 'args' in kwargs:
if isinstance(kwargs['args'], list):
args = kwargs['args']
else:
args = [kwargs['args']]
contents = []
for line in args:
contents.append('{0}\n'.format(line))
with salt.utils.files.fopen(path, "w") as ofile:
ofile.write(salt.utils.stringutils.to_str(''.join(contents)))
return 'Wrote {0} lines to "{1}"'.format(len(contents), path)
def touch(name, atime=None, mtime=None):
'''
.. versionadded:: 0.9.5
Just like the ``touch`` command, create a file if it doesn't exist or
simply update the atime and mtime if it already does.
atime:
Access time in Unix epoch time
mtime:
Last modification in Unix epoch time
CLI Example:
.. code-block:: bash
salt '*' file.touch /var/log/emptyfile
'''
name = os.path.expanduser(name)
if atime and atime.isdigit():
atime = int(atime)
if mtime and mtime.isdigit():
mtime = int(mtime)
try:
if not os.path.exists(name):
with salt.utils.files.fopen(name, 'a'):
pass
if not atime and not mtime:
times = None
elif not mtime and atime:
times = (atime, time.time())
elif not atime and mtime:
times = (time.time(), mtime)
else:
times = (atime, mtime)
os.utime(name, times)
except TypeError:
raise SaltInvocationError('atime and mtime must be integers')
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
return os.path.exists(name)
def seek_read(path, size, offset):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and read it
path
path to file
seek
amount to read at once
offset
offset to start into the file
CLI Example:
.. code-block:: bash
salt '*' file.seek_read /path/to/file 4096 0
'''
path = os.path.expanduser(path)
seek_fh = os.open(path, os.O_RDONLY)
try:
os.lseek(seek_fh, int(offset), 0)
data = os.read(seek_fh, int(size))
finally:
os.close(seek_fh)
return data
def seek_write(path, data, offset):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and write to it
path
path to file
data
data to write to file
offset
position in file to start writing
CLI Example:
.. code-block:: bash
salt '*' file.seek_write /path/to/file 'some data' 4096
'''
path = os.path.expanduser(path)
seek_fh = os.open(path, os.O_WRONLY)
try:
os.lseek(seek_fh, int(offset), 0)
ret = os.write(seek_fh, data)
os.fsync(seek_fh)
finally:
os.close(seek_fh)
return ret
def truncate(path, length):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and delete everything after that point
path
path to file
length
offset into file to truncate
CLI Example:
.. code-block:: bash
salt '*' file.truncate /path/to/file 512
'''
path = os.path.expanduser(path)
with salt.utils.files.fopen(path, 'rb+') as seek_fh:
seek_fh.truncate(int(length))
def link(src, path):
'''
.. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link
'''
src = os.path.expanduser(src)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
try:
os.link(src, path)
return True
except (OSError, IOError) as E:
raise CommandExecutionError('Could not create \'{0}\': {1}'.format(path, E))
return False
def is_hardlink(path):
'''
Check if the path is a hard link by verifying that the number of links
is larger than 1
CLI Example:
.. code-block:: bash
salt '*' file.is_hardlink /path/to/link
'''
# Simply use lstat and count the st_nlink field to determine if this path
# is hardlinked to something.
res = lstat(os.path.expanduser(path))
return res and res['st_nlink'] > 1
def is_link(path):
'''
Check if the path is a symbolic link
CLI Example:
.. code-block:: bash
salt '*' file.is_link /path/to/link
'''
# This function exists because os.path.islink does not support Windows,
# therefore a custom function will need to be called. This function
# therefore helps API consistency by providing a single function to call for
# both operating systems.
return os.path.islink(os.path.expanduser(path))
def symlink(src, path):
'''
Create a symbolic link (symlink, soft link) to a file
CLI Example:
.. code-block:: bash
salt '*' file.symlink /path/to/file /path/to/link
'''
path = os.path.expanduser(path)
try:
if os.path.normpath(os.readlink(path)) == os.path.normpath(src):
log.debug('link already in correct state: %s -> %s', path, src)
return True
except OSError:
pass
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute.')
try:
os.symlink(src, path)
return True
except (OSError, IOError):
raise CommandExecutionError('Could not create \'{0}\''.format(path))
return False
def rename(src, dst):
'''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
try:
os.rename(src, dst)
return True
except OSError:
raise CommandExecutionError(
'Could not rename \'{0}\' to \'{1}\''.format(src, dst)
)
return False
def copy(src, dst, recurse=False, remove_existing=False):
'''
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on unix)
remove_existing will remove all files in the target directory,
and then copy files from the source.
.. note::
The copy function accepts paths that are local to the Salt minion.
This function does not support salt://, http://, or the other
additional file paths that are supported by :mod:`states.file.managed
<salt.states.file.managed>` and :mod:`states.file.recurse
<salt.states.file.recurse>`.
CLI Example:
.. code-block:: bash
salt '*' file.copy /path/to/src /path/to/dst
salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True
salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
if not os.path.exists(src):
raise CommandExecutionError('No such file or directory \'{0}\''.format(src))
if not salt.utils.platform.is_windows():
pre_user = get_user(src)
pre_group = get_group(src)
pre_mode = salt.utils.files.normalize_mode(get_mode(src))
try:
if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src):
if not recurse:
raise SaltInvocationError(
"Cannot copy overwriting a directory without recurse flag set to true!")
if remove_existing:
if os.path.exists(dst):
shutil.rmtree(dst)
shutil.copytree(src, dst)
else:
salt.utils.files.recursive_copy(src, dst)
else:
shutil.copyfile(src, dst)
except OSError:
raise CommandExecutionError(
'Could not copy \'{0}\' to \'{1}\''.format(src, dst)
)
if not salt.utils.platform.is_windows():
check_perms(dst, None, pre_user, pre_group, pre_mode)
return True
def lstat(path):
'''
.. versionadded:: 2014.1.0
Returns the lstat attributes for the given file or dir. Does not support
symbolic links.
CLI Example:
.. code-block:: bash
salt '*' file.lstat /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Path to file must be absolute.')
try:
lst = os.lstat(path)
return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime',
'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid'))
except Exception: # pylint: disable=broad-except
return {}
def access(path, mode):
'''
.. versionadded:: 2014.1.0
Test whether the Salt process has the specified access to the file. One of
the following modes must be specified:
.. code-block::text
f: Test the existence of the path
r: Test the readability of the path
w: Test the writability of the path
x: Test whether the path can be executed
CLI Example:
.. code-block:: bash
salt '*' file.access /path/to/file f
salt '*' file.access /path/to/file x
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Path to link must be absolute.')
modes = {'f': os.F_OK,
'r': os.R_OK,
'w': os.W_OK,
'x': os.X_OK}
if mode in modes:
return os.access(path, modes[mode])
elif mode in six.itervalues(modes):
return os.access(path, mode)
else:
raise SaltInvocationError('Invalid mode specified.')
def read(path, binary=False):
'''
.. versionadded:: 2017.7.0
Return the content of the file.
CLI Example:
.. code-block:: bash
salt '*' file.read /path/to/file
'''
access_mode = 'r'
if binary is True:
access_mode += 'b'
with salt.utils.files.fopen(path, access_mode) as file_obj:
return salt.utils.stringutils.to_unicode(file_obj.read())
def readlink(path, canonicalize=False):
'''
.. versionadded:: 2014.1.0
Return the path that a symlink points to
If canonicalize is set to True, then it return the final target
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Path to link must be absolute.')
if not os.path.islink(path):
raise SaltInvocationError('A valid link was not specified.')
if canonicalize:
return os.path.realpath(path)
else:
return os.readlink(path)
def readdir(path):
'''
.. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Dir path must be absolute.')
if not os.path.isdir(path):
raise SaltInvocationError('A valid directory was not specified.')
dirents = ['.', '..']
dirents.extend(os.listdir(path))
return dirents
def statvfs(path):
'''
.. versionadded:: 2014.1.0
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
.. code-block:: bash
salt '*' file.statvfs /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute.')
try:
stv = os.statvfs(path)
return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',
'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',
'f_frsize', 'f_namemax'))
except (OSError, IOError):
raise CommandExecutionError('Could not statvfs \'{0}\''.format(path))
return False
def stats(path, hash_type=None, follow_symlinks=True):
'''
Return a dict containing the stats for a given file
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd
'''
path = os.path.expanduser(path)
ret = {}
if not os.path.exists(path):
try:
# Broken symlinks will return False for os.path.exists(), but still
# have a uid and gid
pstat = os.lstat(path)
except OSError:
# Not a broken symlink, just a nonexistent path
# NOTE: The file.directory state checks the content of the error
# message in this exception. Any changes made to the message for this
# exception will reflect the file.directory state as well, and will
# likely require changes there.
raise CommandExecutionError('Path not found: {0}'.format(path))
else:
if follow_symlinks:
pstat = os.stat(path)
else:
pstat = os.lstat(path)
ret['inode'] = pstat.st_ino
ret['uid'] = pstat.st_uid
ret['gid'] = pstat.st_gid
ret['group'] = gid_to_group(pstat.st_gid)
ret['user'] = uid_to_user(pstat.st_uid)
ret['atime'] = pstat.st_atime
ret['mtime'] = pstat.st_mtime
ret['ctime'] = pstat.st_ctime
ret['size'] = pstat.st_size
ret['mode'] = salt.utils.files.normalize_mode(oct(stat.S_IMODE(pstat.st_mode)))
if hash_type:
ret['sum'] = get_hash(path, hash_type)
ret['type'] = 'file'
if stat.S_ISDIR(pstat.st_mode):
ret['type'] = 'dir'
if stat.S_ISCHR(pstat.st_mode):
ret['type'] = 'char'
if stat.S_ISBLK(pstat.st_mode):
ret['type'] = 'block'
if stat.S_ISREG(pstat.st_mode):
ret['type'] = 'file'
if stat.S_ISLNK(pstat.st_mode):
ret['type'] = 'link'
if stat.S_ISFIFO(pstat.st_mode):
ret['type'] = 'pipe'
if stat.S_ISSOCK(pstat.st_mode):
ret['type'] = 'socket'
ret['target'] = os.path.realpath(path)
return ret
def rmdir(path):
'''
.. versionadded:: 2014.1.0
Remove the specified directory. Fails if a directory is not empty.
CLI Example:
.. code-block:: bash
salt '*' file.rmdir /tmp/foo/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute.')
if not os.path.isdir(path):
raise SaltInvocationError('A valid directory was not specified.')
try:
os.rmdir(path)
return True
except OSError as exc:
return exc.strerror
def remove(path):
'''
Remove the named file. If a directory is supplied, it will be recursively
deleted.
CLI Example:
.. code-block:: bash
salt '*' file.remove /tmp/foo
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
try:
if os.path.isfile(path) or os.path.islink(path):
os.remove(path)
return True
elif os.path.isdir(path):
shutil.rmtree(path)
return True
except (OSError, IOError) as exc:
raise CommandExecutionError(
'Could not remove \'{0}\': {1}'.format(path, exc)
)
return False
def directory_exists(path):
'''
Tests to see if path is a valid directory. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.directory_exists /etc
'''
return os.path.isdir(os.path.expanduser(path))
def file_exists(path):
'''
Tests to see if path is a valid file. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.file_exists /etc/passwd
'''
return os.path.isfile(os.path.expanduser(path))
def path_exists_glob(path):
'''
Tests to see if path after expansion is a valid path (file or directory).
Expansion allows usage of ? * and character ranges []. Tilde expansion
is not supported. Returns True/False.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' file.path_exists_glob /etc/pam*/pass*
'''
return True if glob.glob(os.path.expanduser(path)) else False
def restorecon(path, recursive=False):
'''
Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', path]
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def get_selinux_context(path):
'''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0)
except AttributeError:
ret = (
'No selinux context information is available for {0}'.format(path)
)
return ret
def set_selinux_context(path,
user=None,
role=None,
type=None, # pylint: disable=W0622
range=None): # pylint: disable=W0622
'''
Set a specific SELinux label on a given path
CLI Example:
.. code-block:: bash
salt '*' file.set_selinux_context path <user> <role> <type> <range>
salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0
'''
if not any((user, role, type, range)):
return False
cmd = ['chcon']
if user:
cmd.extend(['-u', user])
if role:
cmd.extend(['-r', role])
if type:
cmd.extend(['-t', type])
if range:
cmd.extend(['-l', range])
cmd.append(path)
ret = not __salt__['cmd.retcode'](cmd, python_shell=False)
if ret:
return get_selinux_context(path)
else:
return ret
def source_list(source, source_hash, saltenv):
'''
Check the source list and return the source to use
CLI Example:
.. code-block:: bash
salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
'''
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
if contextkey in __context__:
return __context__[contextkey]
# get the master file list
if isinstance(source, list):
mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)]
mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)]
for single in source:
if isinstance(single, dict):
single = next(iter(single))
path, senv = salt.utils.url.parse(single)
if senv:
mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)]
mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)]
ret = None
for single in source:
if isinstance(single, dict):
# check the proto, if it is http or ftp then download the file
# to check, if it is salt then check the master list
# if it is a local file, check if the file exists
if len(single) != 1:
continue
single_src = next(iter(single))
single_hash = single[single_src] if single[single_src] else source_hash
urlparsed_single_src = _urlparse(single_src)
# Fix this for Windows
if salt.utils.platform.is_windows():
# urlparse doesn't handle a local Windows path without the
# protocol indicator (file://). The scheme will be the
# drive letter instead of the protocol. So, we'll add the
# protocol and re-parse
if urlparsed_single_src.scheme.lower() in string.ascii_lowercase:
urlparsed_single_src = _urlparse('file://' + single_src)
proto = urlparsed_single_src.scheme
if proto == 'salt':
path, senv = salt.utils.url.parse(single_src)
if not senv:
senv = saltenv
if (path, saltenv) in mfiles or (path, saltenv) in mdirs:
ret = (single_src, single_hash)
break
elif proto.startswith('http') or proto == 'ftp':
ret = (single_src, single_hash)
break
elif proto == 'file' and (
os.path.exists(urlparsed_single_src.netloc) or
os.path.exists(urlparsed_single_src.path) or
os.path.exists(os.path.join(
urlparsed_single_src.netloc,
urlparsed_single_src.path))):
ret = (single_src, single_hash)
break
elif single_src.startswith(os.sep) and os.path.exists(single_src):
ret = (single_src, single_hash)
break
elif isinstance(single, six.string_types):
path, senv = salt.utils.url.parse(single)
if not senv:
senv = saltenv
if (path, senv) in mfiles or (path, senv) in mdirs:
ret = (single, source_hash)
break
urlparsed_src = _urlparse(single)
if salt.utils.platform.is_windows():
# urlparse doesn't handle a local Windows path without the
# protocol indicator (file://). The scheme will be the
# drive letter instead of the protocol. So, we'll add the
# protocol and re-parse
if urlparsed_src.scheme.lower() in string.ascii_lowercase:
urlparsed_src = _urlparse('file://' + single)
proto = urlparsed_src.scheme
if proto == 'file' and (
os.path.exists(urlparsed_src.netloc) or
os.path.exists(urlparsed_src.path) or
os.path.exists(os.path.join(
urlparsed_src.netloc,
urlparsed_src.path))):
ret = (single, source_hash)
break
elif proto.startswith('http') or proto == 'ftp':
ret = (single, source_hash)
break
elif single.startswith(os.sep) and os.path.exists(single):
ret = (single, source_hash)
break
if ret is None:
# None of the list items matched
raise CommandExecutionError(
'none of the specified sources were found'
)
else:
ret = (source, source_hash)
__context__[contextkey] = ret
return ret
def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
'''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
CLI Example:
.. code-block:: bash
salt '*' file.apply_template_on_contents \\
contents='This is a {{ template }} string.' \\
template=jinja \\
"context={}" "defaults={'template': 'cool'}" \\
saltenv=base
'''
if template in salt.utils.templates.TEMPLATE_REGISTRY:
context_dict = defaults if defaults else {}
if context:
context_dict.update(context)
# Apply templating
contents = salt.utils.templates.TEMPLATE_REGISTRY[template](
contents,
from_str=True,
to_str=True,
context=context_dict,
saltenv=saltenv,
grains=__opts__['grains'],
pillar=__pillar__,
salt=__salt__,
opts=__opts__)['data']
if six.PY2:
contents = contents.encode('utf-8')
elif six.PY3 and isinstance(contents, bytes):
# bytes -> str
contents = contents.decode('utf-8')
else:
ret = {}
ret['result'] = False
ret['comment'] = ('Specified template format {0} is not supported'
).format(template)
return ret
return contents
def get_managed(
name,
template,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
saltenv,
context,
defaults,
skip_verify=False,
**kwargs):
'''
Return the managed file data for file.managed
name
location where the file lives on the server
template
template format
source
managed source file
source_hash
hash of the source file
source_hash_name
When ``source_hash`` refers to a remote file, this specifies the
filename to look for in that file.
.. versionadded:: 2016.3.5
user
Owner of file
group
Group owner of file
mode
Permissions of file
attrs
Attributes of file
.. versionadded:: 2018.3.0
context
Variables to add to the template context
defaults
Default values of for context_dict
skip_verify
If ``True``, hash verification of remote file sources (``http://``,
``https://``, ``ftp://``) will be skipped, and the ``source_hash``
argument will be ignored.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None
'''
# Copy the file to the minion and templatize it
sfn = ''
source_sum = {}
def _get_local_file_source_sum(path):
'''
DRY helper for getting the source_sum value from a locally cached
path.
'''
return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'}
# If we have a source defined, let's figure out what the hash is
if source:
urlparsed_source = _urlparse(source)
if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS:
parsed_scheme = urlparsed_source.scheme
else:
parsed_scheme = ''
parsed_path = os.path.join(
urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep)
unix_local_source = parsed_scheme in ('file', '')
if parsed_scheme == '':
parsed_path = sfn = source
if not os.path.exists(sfn):
msg = 'Local file source {0} does not exist'.format(sfn)
return '', {}, msg
elif parsed_scheme == 'file':
sfn = parsed_path
if not os.path.exists(sfn):
msg = 'Local file source {0} does not exist'.format(sfn)
return '', {}, msg
if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase:
parsed_path = ':'.join([parsed_scheme, parsed_path])
parsed_scheme = 'file'
if parsed_scheme == 'salt':
source_sum = __salt__['cp.hash_file'](source, saltenv)
if not source_sum:
return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv)
elif not source_hash and unix_local_source:
source_sum = _get_local_file_source_sum(parsed_path)
elif not source_hash and source.startswith(os.sep):
# This should happen on Windows
source_sum = _get_local_file_source_sum(source)
else:
if not skip_verify:
if source_hash:
try:
source_sum = get_source_sum(name,
source,
source_hash,
source_hash_name,
saltenv)
except CommandExecutionError as exc:
return '', {}, exc.strerror
else:
msg = (
'Unable to verify upstream hash of source file {0}, '
'please set source_hash or set skip_verify to True'
.format(salt.utils.url.redact_http_basic_auth(source))
)
return '', {}, msg
if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS):
# Check if we have the template or remote file cached
cache_refetch = False
cached_dest = __salt__['cp.is_cached'](source, saltenv)
if cached_dest and (source_hash or skip_verify):
htype = source_sum.get('hash_type', 'sha256')
cached_sum = get_hash(cached_dest, form=htype)
if skip_verify:
# prev: if skip_verify or cached_sum == source_sum['hsum']:
# but `cached_sum == source_sum['hsum']` is elliptical as prev if
sfn = cached_dest
source_sum = {'hsum': cached_sum, 'hash_type': htype}
elif cached_sum != source_sum.get('hsum', __opts__['hash_type']):
cache_refetch = True
else:
sfn = cached_dest
# If we didn't have the template or remote file, or the file has been
# updated and the cache has to be refreshed, download the file.
if not sfn or cache_refetch:
try:
sfn = __salt__['cp.cache_file'](
source,
saltenv,
source_hash=source_sum.get('hsum'))
except Exception as exc: # pylint: disable=broad-except
# A 404 or other error code may raise an exception, catch it
# and return a comment that will fail the calling state.
_source = salt.utils.url.redact_http_basic_auth(source)
return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc)
# If cache failed, sfn will be False, so do a truth check on sfn first
# as invoking os.path.exists() on a bool raises a TypeError.
if not sfn or not os.path.exists(sfn):
_source = salt.utils.url.redact_http_basic_auth(source)
return sfn, {}, 'Source file \'{0}\' not found'.format(_source)
if sfn == name:
raise SaltInvocationError(
'Source file cannot be the same as destination'
)
if template:
if template in salt.utils.templates.TEMPLATE_REGISTRY:
context_dict = defaults if defaults else {}
if context:
context_dict.update(context)
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
sfn,
name=name,
source=source,
user=user,
group=group,
mode=mode,
attrs=attrs,
saltenv=saltenv,
context=context_dict,
salt=__salt__,
pillar=__pillar__,
grains=__opts__['grains'],
opts=__opts__,
**kwargs)
else:
return sfn, {}, ('Specified template format {0} is not supported'
).format(template)
if data['result']:
sfn = data['data']
hsum = get_hash(sfn, form='sha256')
source_sum = {'hash_type': 'sha256',
'hsum': hsum}
else:
__clean_tmp(sfn)
return sfn, {}, data['data']
return sfn, source_sum, ''
def extract_hash(hash_fn,
hash_type='sha256',
file_name='',
source='',
source_hash_name=None):
'''
.. versionchanged:: 2016.3.5
Prior to this version, only the ``file_name`` argument was considered
for filename matches in the hash file. This would be problematic for
cases in which the user was relying on a remote checksum file that they
do not control, and they wished to use a different name for that file
on the minion from the filename on the remote server (and in the
checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the
remote file was at ``https://mydomain.tld/different_name.tar.gz``. The
:py:func:`file.managed <salt.states.file.managed>` state now also
passes this function the source URI as well as the ``source_hash_name``
(if specified). In cases where ``source_hash_name`` is specified, it
takes precedence over both the ``file_name`` and ``source``. When it is
not specified, ``file_name`` takes precedence over ``source``. This
allows for better capability for matching hashes.
.. versionchanged:: 2016.11.0
File name and source URI matches are no longer disregarded when
``source_hash_name`` is specified. They will be used as fallback
matches if there is no match to the ``source_hash_name`` value.
This routine is called from the :mod:`file.managed
<salt.states.file.managed>` state to pull a hash from a remote file.
Regular expressions are used line by line on the ``source_hash`` file, to
find a potential candidate of the indicated hash type. This avoids many
problems of arbitrary file layout rules. It specifically permits pulling
hash codes from debian ``*.dsc`` files.
If no exact match of a hash and filename are found, then the first hash
found (if any) will be returned. If no hashes at all are found, then
``None`` will be returned.
For example:
.. code-block:: yaml
openerp_7.0-latest-1.tar.gz:
file.managed:
- name: /tmp/openerp_7.0-20121227-075624-1_all.deb
- source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz
- source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc
CLI Example:
.. code-block:: bash
salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo
'''
hash_len = HASHES.get(hash_type)
if hash_len is None:
if hash_type:
log.warning(
'file.extract_hash: Unsupported hash_type \'%s\', falling '
'back to matching any supported hash_type', hash_type
)
hash_type = ''
hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP))
else:
hash_len_expr = six.text_type(hash_len)
filename_separators = string.whitespace + r'\/'
if source_hash_name:
if not isinstance(source_hash_name, six.string_types):
source_hash_name = six.text_type(source_hash_name)
source_hash_name_idx = (len(source_hash_name) + 1) * -1
log.debug(
'file.extract_hash: Extracting %s hash for file matching '
'source_hash_name \'%s\'',
'any supported' if not hash_type else hash_type,
source_hash_name
)
if file_name:
if not isinstance(file_name, six.string_types):
file_name = six.text_type(file_name)
file_name_basename = os.path.basename(file_name)
file_name_idx = (len(file_name_basename) + 1) * -1
if source:
if not isinstance(source, six.string_types):
source = six.text_type(source)
urlparsed_source = _urlparse(source)
source_basename = os.path.basename(
urlparsed_source.path or urlparsed_source.netloc
)
source_idx = (len(source_basename) + 1) * -1
basename_searches = [x for x in (file_name, source) if x]
if basename_searches:
log.debug(
'file.extract_hash: %s %s hash for file matching%s: %s',
'If no source_hash_name match found, will extract'
if source_hash_name
else 'Extracting',
'any supported' if not hash_type else hash_type,
'' if len(basename_searches) == 1 else ' either of the following',
', '.join(basename_searches)
)
partial = None
found = {}
with salt.utils.files.fopen(hash_fn, 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line.strip())
hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])'
hash_match = re.search(hash_re, line)
matched = None
if hash_match:
matched_hsum = hash_match.group(1)
if matched_hsum is not None:
matched_type = HASHES_REVMAP.get(len(matched_hsum))
if matched_type is None:
# There was a match, but it's not of the correct length
# to match one of the supported hash types.
matched = None
else:
matched = {'hsum': matched_hsum,
'hash_type': matched_type}
if matched is None:
log.debug(
'file.extract_hash: In line \'%s\', no %shash found',
line,
'' if not hash_type else hash_type + ' '
)
continue
if partial is None:
partial = matched
def _add_to_matches(found, line, match_type, value, matched):
log.debug(
'file.extract_hash: Line \'%s\' matches %s \'%s\'',
line, match_type, value
)
found.setdefault(match_type, []).append(matched)
hash_matched = False
if source_hash_name:
if line.endswith(source_hash_name):
# Checking the character before where the basename
# should start for either whitespace or a path
# separator. We can't just rsplit on spaces/whitespace,
# because the filename may contain spaces.
try:
if line[source_hash_name_idx] in string.whitespace:
_add_to_matches(found, line, 'source_hash_name',
source_hash_name, matched)
hash_matched = True
except IndexError:
pass
elif re.match(re.escape(source_hash_name) + r'\s+',
line):
_add_to_matches(found, line, 'source_hash_name',
source_hash_name, matched)
hash_matched = True
if file_name:
if line.endswith(file_name_basename):
# Checking the character before where the basename
# should start for either whitespace or a path
# separator. We can't just rsplit on spaces/whitespace,
# because the filename may contain spaces.
try:
if line[file_name_idx] in filename_separators:
_add_to_matches(found, line, 'file_name',
file_name, matched)
hash_matched = True
except IndexError:
pass
elif re.match(re.escape(file_name) + r'\s+', line):
_add_to_matches(found, line, 'file_name',
file_name, matched)
hash_matched = True
if source:
if line.endswith(source_basename):
# Same as above, we can't just do an rsplit here.
try:
if line[source_idx] in filename_separators:
_add_to_matches(found, line, 'source',
source, matched)
hash_matched = True
except IndexError:
pass
elif re.match(re.escape(source) + r'\s+', line):
_add_to_matches(found, line, 'source', source, matched)
hash_matched = True
if not hash_matched:
log.debug(
'file.extract_hash: Line \'%s\' contains %s hash '
'\'%s\', but line did not meet the search criteria',
line, matched['hash_type'], matched['hsum']
)
for found_type, found_str in (('source_hash_name', source_hash_name),
('file_name', file_name),
('source', source)):
if found_type in found:
if len(found[found_type]) > 1:
log.debug(
'file.extract_hash: Multiple %s matches for %s: %s',
found_type,
found_str,
', '.join(
['{0} ({1})'.format(x['hsum'], x['hash_type'])
for x in found[found_type]]
)
)
ret = found[found_type][0]
log.debug(
'file.extract_hash: Returning %s hash \'%s\' as a match of %s',
ret['hash_type'], ret['hsum'], found_str
)
return ret
if partial:
log.debug(
'file.extract_hash: Returning the partially identified %s hash '
'\'%s\'', partial['hash_type'], partial['hsum']
)
return partial
log.debug('file.extract_hash: No matches, returning None')
return None
def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False):
'''
Check the permissions on files, modify attributes and chown if needed. File
attributes are only verified if lsattr(1) is installed.
CLI Example:
.. code-block:: bash
salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai
.. versionchanged:: 2014.1.3
``follow_symlinks`` option added
'''
name = os.path.expanduser(name)
if not ret:
ret = {'name': name,
'changes': {},
'comment': [],
'result': True}
orig_comment = ''
else:
orig_comment = ret['comment']
ret['comment'] = []
# Check permissions
perms = {}
cur = stats(name, follow_symlinks=follow_symlinks)
perms['luser'] = cur['user']
perms['lgroup'] = cur['group']
perms['lmode'] = salt.utils.files.normalize_mode(cur['mode'])
is_dir = os.path.isdir(name)
is_link = os.path.islink(name)
# user/group changes if needed, then check if it worked
if user:
if isinstance(user, int):
user = uid_to_user(user)
if (salt.utils.platform.is_windows() and
user_to_uid(user) != user_to_uid(perms['luser'])
) or (
not salt.utils.platform.is_windows() and user != perms['luser']
):
perms['cuser'] = user
if group:
if isinstance(group, int):
group = gid_to_group(group)
if (salt.utils.platform.is_windows() and
group_to_gid(group) != group_to_gid(perms['lgroup'])
) or (
not salt.utils.platform.is_windows() and group != perms['lgroup']
):
perms['cgroup'] = group
if 'cuser' in perms or 'cgroup' in perms:
if not __opts__['test']:
if os.path.islink(name) and not follow_symlinks:
chown_func = lchown
else:
chown_func = chown
if user is None:
user = perms['luser']
if group is None:
group = perms['lgroup']
try:
chown_func(name, user, group)
# Python os.chown() does reset the suid and sgid,
# that's why setting the right mode again is needed here.
set_mode(name, mode)
except OSError:
ret['result'] = False
if user:
if isinstance(user, int):
user = uid_to_user(user)
if (salt.utils.platform.is_windows() and
user_to_uid(user) != user_to_uid(
get_user(name, follow_symlinks=follow_symlinks)) and
user != ''
) or (
not salt.utils.platform.is_windows() and
user != get_user(name, follow_symlinks=follow_symlinks) and
user != ''
):
if __opts__['test'] is True:
ret['changes']['user'] = user
else:
ret['result'] = False
ret['comment'].append('Failed to change user to {0}'
.format(user))
elif 'cuser' in perms and user != '':
ret['changes']['user'] = user
if group:
if isinstance(group, int):
group = gid_to_group(group)
if (salt.utils.platform.is_windows() and
group_to_gid(group) != group_to_gid(
get_group(name, follow_symlinks=follow_symlinks)) and
user != '') or (
not salt.utils.platform.is_windows() and
group != get_group(name, follow_symlinks=follow_symlinks) and
user != ''
):
if __opts__['test'] is True:
ret['changes']['group'] = group
else:
ret['result'] = False
ret['comment'].append('Failed to change group to {0}'
.format(group))
elif 'cgroup' in perms and user != '':
ret['changes']['group'] = group
# Mode changes if needed
if mode is not None:
# File is a symlink, ignore the mode setting
# if follow_symlinks is False
if os.path.islink(name) and not follow_symlinks:
pass
else:
mode = salt.utils.files.normalize_mode(mode)
if mode != perms['lmode']:
if __opts__['test'] is True:
ret['changes']['mode'] = mode
else:
set_mode(name, mode)
if mode != salt.utils.files.normalize_mode(get_mode(name)):
ret['result'] = False
ret['comment'].append(
'Failed to change mode to {0}'.format(mode)
)
else:
ret['changes']['mode'] = mode
# Modify attributes of file if needed
if attrs is not None and not is_dir:
# File is a symlink, ignore the mode setting
# if follow_symlinks is False
if os.path.islink(name) and not follow_symlinks:
pass
else:
diff_attrs = _cmp_attrs(name, attrs)
if diff_attrs and any(attr for attr in diff_attrs):
changes = {
'old': ''.join(lsattr(name)[name]),
'new': None,
}
if __opts__['test'] is True:
changes['new'] = attrs
else:
if diff_attrs.added:
chattr(
name,
operator="add",
attributes=diff_attrs.added,
)
if diff_attrs.removed:
chattr(
name,
operator="remove",
attributes=diff_attrs.removed,
)
cmp_attrs = _cmp_attrs(name, attrs)
if any(attr for attr in cmp_attrs):
ret['result'] = False
ret['comment'].append(
'Failed to change attributes to {0}'.format(attrs)
)
changes['new'] = ''.join(lsattr(name)[name])
else:
changes['new'] = attrs
if changes['old'] != changes['new']:
ret['changes']['attrs'] = changes
# Only combine the comment list into a string
# after all comments are added above
if isinstance(orig_comment, six.string_types):
if orig_comment:
ret['comment'].insert(0, orig_comment)
ret['comment'] = '; '.join(ret['comment'])
# Set result to None at the very end of the function,
# after all changes have been recorded above
if __opts__['test'] is True and ret['changes']:
ret['result'] = None
return ret, perms
def check_managed(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
**kwargs):
'''
Check to see what changes need to be made for a file
CLI Example:
.. code-block:: bash
salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
'''
# If the source is a list then find which file exists
source, source_hash = source_list(source, # pylint: disable=W0633
source_hash,
saltenv)
sfn = ''
source_sum = None
if contents is None:
# Gather the source file from the server
sfn, source_sum, comments = get_managed(
name,
template,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
saltenv,
context,
defaults,
skip_verify,
**kwargs)
if comments:
__clean_tmp(sfn)
return False, comments
changes = check_file_meta(name, sfn, source, source_sum, user,
group, mode, attrs, saltenv, contents)
# Ignore permission for files written temporary directories
# Files in any path will still be set correctly using get_managed()
if name.startswith(tempfile.gettempdir()):
for key in ['user', 'group', 'mode']:
changes.pop(key, None)
__clean_tmp(sfn)
if changes:
log.info(changes)
comments = ['The following values are set to be changed:\n']
comments.extend('{0}: {1}\n'.format(key, val)
for key, val in six.iteritems(changes))
return None, ''.join(comments)
return True, 'The file {0} is in the correct state'.format(name)
def check_managed_changes(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
keep_mode=False,
**kwargs):
'''
Return a dictionary of what changes need to be made for a file
CLI Example:
.. code-block:: bash
salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
'''
# If the source is a list then find which file exists
source, source_hash = source_list(source, # pylint: disable=W0633
source_hash,
saltenv)
sfn = ''
source_sum = None
if contents is None:
# Gather the source file from the server
sfn, source_sum, comments = get_managed(
name,
template,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
saltenv,
context,
defaults,
skip_verify,
**kwargs)
# Ensure that user-provided hash string is lowercase
if source_sum and ('hsum' in source_sum):
source_sum['hsum'] = source_sum['hsum'].lower()
if comments:
__clean_tmp(sfn)
return False, comments
if sfn and source and keep_mode:
if _urlparse(source).scheme in ('salt', 'file') \
or source.startswith('/'):
try:
mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True)
except Exception as exc: # pylint: disable=broad-except
log.warning('Unable to stat %s: %s', sfn, exc)
changes = check_file_meta(name, sfn, source, source_sum, user,
group, mode, attrs, saltenv, contents)
__clean_tmp(sfn)
return changes
def check_file_meta(
name,
sfn,
source,
source_sum,
user,
group,
mode,
attrs,
saltenv,
contents=None):
'''
Check for the changes in the file metadata.
CLI Example:
.. code-block:: bash
salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base
.. note::
Supported hash types include sha512, sha384, sha256, sha224, sha1, and
md5.
name
Path to file destination
sfn
Template-processed source file contents
source
URL to file source
source_sum
File checksum information as a dictionary
.. code-block:: yaml
{hash_type: md5, hsum: <md5sum>}
user
Destination file user owner
group
Destination file group owner
mode
Destination file permissions mode
attrs
Destination file attributes
.. versionadded:: 2018.3.0
saltenv
Salt environment used to resolve source files
contents
File contents
'''
changes = {}
if not source_sum:
source_sum = dict()
try:
lstats = stats(name, hash_type=source_sum.get('hash_type', None),
follow_symlinks=False)
except CommandExecutionError:
lstats = {}
if not lstats:
changes['newfile'] = name
return changes
if 'hsum' in source_sum:
if source_sum['hsum'] != lstats['sum']:
if not sfn and source:
sfn = __salt__['cp.cache_file'](
source,
saltenv,
source_hash=source_sum['hsum'])
if sfn:
try:
changes['diff'] = get_diff(
name, sfn, template=True, show_filenames=False)
except CommandExecutionError as exc:
changes['diff'] = exc.strerror
else:
changes['sum'] = 'Checksum differs'
if contents is not None:
# Write a tempfile with the static contents
tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX,
text=True)
if salt.utils.platform.is_windows():
contents = os.linesep.join(
_splitlines_preserving_trailing_newline(contents))
with salt.utils.files.fopen(tmp, 'w') as tmp_:
tmp_.write(salt.utils.stringutils.to_str(contents))
# Compare the static contents with the named file
try:
differences = get_diff(name, tmp, show_filenames=False)
except CommandExecutionError as exc:
log.error('Failed to diff files: {0}'.format(exc))
differences = exc.strerror
__clean_tmp(tmp)
if differences:
if __salt__['config.option']('obfuscate_templates'):
changes['diff'] = '<Obfuscated Template>'
else:
changes['diff'] = differences
if not salt.utils.platform.is_windows():
# Check owner
if (user is not None
and user != lstats['user']
and user != lstats['uid']):
changes['user'] = user
# Check group
if (group is not None
and group != lstats['group']
and group != lstats['gid']):
changes['group'] = group
# Normalize the file mode
smode = salt.utils.files.normalize_mode(lstats['mode'])
mode = salt.utils.files.normalize_mode(mode)
if mode is not None and mode != smode:
changes['mode'] = mode
if attrs:
diff_attrs = _cmp_attrs(name, attrs)
if diff_attrs is not None:
if attrs is not None \
and (diff_attrs[0] is not None
or diff_attrs[1] is not None):
changes['attrs'] = attrs
return changes
def get_diff(file1,
file2,
saltenv='base',
show_filenames=True,
show_changes=True,
template=False,
source_hash_file1=None,
source_hash_file2=None):
'''
Return unified diff of two files
file1
The first file to feed into the diff utility
.. versionchanged:: 2018.3.0
Can now be either a local or remote file. In earlier releases,
thuis had to be a file local to the minion.
file2
The second file to feed into the diff utility
.. versionchanged:: 2018.3.0
Can now be either a local or remote file. In earlier releases, this
had to be a file on the salt fileserver (i.e.
``salt://somefile.txt``)
show_filenames : True
Set to ``False`` to hide the filenames in the top two lines of the
diff.
show_changes : True
If set to ``False``, and there are differences, then instead of a diff
a simple message stating that show_changes is set to ``False`` will be
returned.
template : False
Set to ``True`` if two templates are being compared. This is not useful
except for within states, with the ``obfuscate_templates`` option set
to ``True``.
.. versionadded:: 2018.3.0
source_hash_file1
If ``file1`` is an http(s)/ftp URL and the file exists in the minion's
file cache, this option can be passed to keep the minion from
re-downloading the archive if the cached copy matches the specified
hash.
.. versionadded:: 2018.3.0
source_hash_file2
If ``file2`` is an http(s)/ftp URL and the file exists in the minion's
file cache, this option can be passed to keep the minion from
re-downloading the archive if the cached copy matches the specified
hash.
.. versionadded:: 2018.3.0
CLI Examples:
.. code-block:: bash
salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc
salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt
'''
files = (file1, file2)
source_hashes = (source_hash_file1, source_hash_file2)
paths = []
errors = []
for filename, source_hash in zip(files, source_hashes):
try:
# Local file paths will just return the same path back when passed
# to cp.cache_file.
cached_path = __salt__['cp.cache_file'](filename,
saltenv,
source_hash=source_hash)
if cached_path is False:
errors.append(
'File {0} not found'.format(
salt.utils.stringutils.to_unicode(filename)
)
)
continue
paths.append(cached_path)
except MinionError as exc:
errors.append(salt.utils.stringutils.to_unicode(exc.__str__()))
continue
if errors:
raise CommandExecutionError(
'Failed to cache one or more files',
info=errors
)
args = []
for filename in paths:
try:
with salt.utils.files.fopen(filename, 'rb') as fp_:
args.append(fp_.readlines())
except (IOError, OSError) as exc:
raise CommandExecutionError(
'Failed to read {0}: {1}'.format(
salt.utils.stringutils.to_unicode(filename),
exc.strerror
)
)
if args[0] != args[1]:
if template and __salt__['config.option']('obfuscate_templates'):
ret = '<Obfuscated Template>'
elif not show_changes:
ret = '<show_changes=False>'
else:
bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter
if bdiff:
ret = bdiff
else:
if show_filenames:
args.extend(paths)
ret = __utils__['stringutils.get_diff'](*args)
return ret
return ''
def manage_file(name,
sfn,
ret,
source,
source_sum,
user,
group,
mode,
attrs,
saltenv,
backup,
makedirs=False,
template=None, # pylint: disable=W0613
show_changes=True,
contents=None,
dir_mode=None,
follow_symlinks=True,
skip_verify=False,
keep_mode=False,
encoding=None,
encoding_errors='strict',
**kwargs):
'''
Checks the destination against what was retrieved with get_managed and
makes the appropriate modifications (if necessary).
name
location to place the file
sfn
location of cached file on the minion
This is the path to the file stored on the minion. This file is placed
on the minion using cp.cache_file. If the hash sum of that file
matches the source_sum, we do not transfer the file to the minion
again.
This file is then grabbed and if it has template set, it renders the
file to be placed into the correct place on the system using
salt.files.utils.copyfile()
ret
The initial state return data structure. Pass in ``None`` to use the
default structure.
source
file reference on the master
source_sum
sum hash for source
user
user owner
group
group owner
backup
backup_mode
attrs
attributes to be set on file: '' means remove all of them
.. versionadded:: 2018.3.0
makedirs
make directories if they do not exist
template
format of templating
show_changes
Include diff in state return
contents:
contents to be placed in the file
dir_mode
mode for directories created with makedirs
skip_verify : False
If ``True``, hash verification of remote file sources (``http://``,
``https://``, ``ftp://``) will be skipped, and the ``source_hash``
argument will be ignored.
.. versionadded:: 2016.3.0
keep_mode : False
If ``True``, and the ``source`` is a file from the Salt fileserver (or
a local file on the minion), the mode of the destination file will be
set to the mode of the source file.
.. note:: keep_mode does not work with salt-ssh.
As a consequence of how the files are transferred to the minion, and
the inability to connect back to the master with salt-ssh, salt is
unable to stat the file as it exists on the fileserver and thus
cannot mirror the mode on the salt-ssh minion
encoding
If specified, then the specified encoding will be used. Otherwise, the
file will be encoded using the system locale (usually UTF-8). See
https://docs.python.org/3/library/codecs.html#standard-encodings for
the list of available encodings.
.. versionadded:: 2017.7.0
encoding_errors : 'strict'
Default is ```'strict'```.
See https://docs.python.org/2/library/codecs.html#codec-base-classes
for the error handling schemes.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base ''
.. versionchanged:: 2014.7.0
``follow_symlinks`` option added
'''
name = os.path.expanduser(name)
if not ret:
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
# Ensure that user-provided hash string is lowercase
if source_sum and ('hsum' in source_sum):
source_sum['hsum'] = source_sum['hsum'].lower()
if source:
if not sfn:
# File is not present, cache it
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
return _error(
ret, 'Source file \'{0}\' not found'.format(source))
htype = source_sum.get('hash_type', __opts__['hash_type'])
# Recalculate source sum now that file has been cached
source_sum = {
'hash_type': htype,
'hsum': get_hash(sfn, form=htype)
}
if keep_mode:
if _urlparse(source).scheme in ('salt', 'file', ''):
try:
mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True)
except Exception as exc: # pylint: disable=broad-except
log.warning('Unable to stat %s: %s', sfn, exc)
# Check changes if the target file exists
if os.path.isfile(name) or os.path.islink(name):
if os.path.islink(name) and follow_symlinks:
real_name = os.path.realpath(name)
else:
real_name = name
# Only test the checksums on files with managed contents
if source and not (not follow_symlinks and os.path.islink(real_name)):
name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type']))
else:
name_sum = None
# Check if file needs to be replaced
if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum):
if not sfn:
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
return _error(
ret, 'Source file \'{0}\' not found'.format(source))
# If the downloaded file came from a non salt server or local
# source, and we are not skipping checksum verification, then
# verify that it matches the specified checksum.
if not skip_verify \
and _urlparse(source).scheme != 'salt':
dl_sum = get_hash(sfn, source_sum['hash_type'])
if dl_sum != source_sum['hsum']:
ret['comment'] = (
'Specified {0} checksum for {1} ({2}) does not match '
'actual checksum ({3}). If the \'source_hash\' value '
'refers to a remote file with multiple possible '
'matches, then it may be necessary to set '
'\'source_hash_name\'.'.format(
source_sum['hash_type'],
source,
source_sum['hsum'],
dl_sum
)
)
ret['result'] = False
return ret
# Print a diff equivalent to diff -u old new
if __salt__['config.option']('obfuscate_templates'):
ret['changes']['diff'] = '<Obfuscated Template>'
elif not show_changes:
ret['changes']['diff'] = '<show_changes=False>'
else:
try:
ret['changes']['diff'] = get_diff(
real_name, sfn, show_filenames=False)
except CommandExecutionError as exc:
ret['changes']['diff'] = exc.strerror
# Pre requisites are met, and the file needs to be replaced, do it
try:
salt.utils.files.copyfile(sfn,
real_name,
__salt__['config.backup_mode'](backup),
__opts__['cachedir'])
except IOError as io_error:
__clean_tmp(sfn)
return _error(
ret, 'Failed to commit change: {0}'.format(io_error))
if contents is not None:
# Write the static contents to a temporary file
tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX,
text=True)
with salt.utils.files.fopen(tmp, 'wb') as tmp_:
if encoding:
if salt.utils.platform.is_windows():
contents = os.linesep.join(
_splitlines_preserving_trailing_newline(contents))
log.debug('File will be encoded with %s', encoding)
tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors))
else:
tmp_.write(salt.utils.stringutils.to_bytes(contents))
try:
differences = get_diff(
real_name, tmp, show_filenames=False,
show_changes=show_changes, template=True)
except CommandExecutionError as exc:
ret.setdefault('warnings', []).append(
'Failed to detect changes to file: {0}'.format(exc.strerror)
)
differences = ''
if differences:
ret['changes']['diff'] = differences
# Pre requisites are met, the file needs to be replaced, do it
try:
salt.utils.files.copyfile(tmp,
real_name,
__salt__['config.backup_mode'](backup),
__opts__['cachedir'])
except IOError as io_error:
__clean_tmp(tmp)
return _error(
ret, 'Failed to commit change: {0}'.format(io_error))
__clean_tmp(tmp)
# Check for changing symlink to regular file here
if os.path.islink(name) and not follow_symlinks:
if not sfn:
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
return _error(
ret, 'Source file \'{0}\' not found'.format(source))
# If the downloaded file came from a non salt server source verify
# that it matches the intended sum value
if not skip_verify and _urlparse(source).scheme != 'salt':
dl_sum = get_hash(sfn, source_sum['hash_type'])
if dl_sum != source_sum['hsum']:
ret['comment'] = (
'Specified {0} checksum for {1} ({2}) does not match '
'actual checksum ({3})'.format(
source_sum['hash_type'],
name,
source_sum['hsum'],
dl_sum
)
)
ret['result'] = False
return ret
try:
salt.utils.files.copyfile(sfn,
name,
__salt__['config.backup_mode'](backup),
__opts__['cachedir'])
except IOError as io_error:
__clean_tmp(sfn)
return _error(
ret, 'Failed to commit change: {0}'.format(io_error))
ret['changes']['diff'] = \
'Replace symbolic link with regular file'
if salt.utils.platform.is_windows():
# This function resides in win_file.py and will be available
# on Windows. The local function will be overridden
# pylint: disable=E1120,E1121,E1123
ret = check_perms(
path=name,
ret=ret,
owner=kwargs.get('win_owner'),
grant_perms=kwargs.get('win_perms'),
deny_perms=kwargs.get('win_deny_perms'),
inheritance=kwargs.get('win_inheritance', True),
reset=kwargs.get('win_perms_reset', False))
# pylint: enable=E1120,E1121,E1123
else:
ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks)
if ret['changes']:
ret['comment'] = 'File {0} updated'.format(
salt.utils.data.decode(name)
)
elif not ret['changes'] and ret['result']:
ret['comment'] = 'File {0} is in the correct state'.format(
salt.utils.data.decode(name)
)
if sfn:
__clean_tmp(sfn)
return ret
else: # target file does not exist
contain_dir = os.path.dirname(name)
def _set_mode_and_make_dirs(name, dir_mode, mode, user, group):
# check for existence of windows drive letter
if salt.utils.platform.is_windows():
drive, _ = os.path.splitdrive(name)
if drive and not os.path.exists(drive):
__clean_tmp(sfn)
return _error(ret,
'{0} drive not present'.format(drive))
if dir_mode is None and mode is not None:
# Add execute bit to each nonzero digit in the mode, if
# dir_mode was not specified. Otherwise, any
# directories created with makedirs_() below can't be
# listed via a shell.
mode_list = [x for x in six.text_type(mode)][-3:]
for idx in range(len(mode_list)):
if mode_list[idx] != '0':
mode_list[idx] = six.text_type(int(mode_list[idx]) | 1)
dir_mode = ''.join(mode_list)
if salt.utils.platform.is_windows():
# This function resides in win_file.py and will be available
# on Windows. The local function will be overridden
# pylint: disable=E1120,E1121,E1123
makedirs_(
path=name,
owner=kwargs.get('win_owner'),
grant_perms=kwargs.get('win_perms'),
deny_perms=kwargs.get('win_deny_perms'),
inheritance=kwargs.get('win_inheritance', True),
reset=kwargs.get('win_perms_reset', False))
# pylint: enable=E1120,E1121,E1123
else:
makedirs_(name, user=user, group=group, mode=dir_mode)
if source:
# Apply the new file
if not sfn:
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
return _error(
ret, 'Source file \'{0}\' not found'.format(source))
# If the downloaded file came from a non salt server source verify
# that it matches the intended sum value
if not skip_verify \
and _urlparse(source).scheme != 'salt':
dl_sum = get_hash(sfn, source_sum['hash_type'])
if dl_sum != source_sum['hsum']:
ret['comment'] = (
'Specified {0} checksum for {1} ({2}) does not match '
'actual checksum ({3})'.format(
source_sum['hash_type'],
name,
source_sum['hsum'],
dl_sum
)
)
ret['result'] = False
return ret
# It is a new file, set the diff accordingly
ret['changes']['diff'] = 'New file'
if not os.path.isdir(contain_dir):
if makedirs:
_set_mode_and_make_dirs(name, dir_mode, mode, user, group)
else:
__clean_tmp(sfn)
# No changes actually made
ret['changes'].pop('diff', None)
return _error(ret, 'Parent directory not present')
else: # source != True
if not os.path.isdir(contain_dir):
if makedirs:
_set_mode_and_make_dirs(name, dir_mode, mode, user, group)
else:
__clean_tmp(sfn)
# No changes actually made
ret['changes'].pop('diff', None)
return _error(ret, 'Parent directory not present')
# Create the file, user rw-only if mode will be set to prevent
# a small security race problem before the permissions are set
with salt.utils.files.set_umask(0o077 if mode else None):
# Create a new file when test is False and source is None
if contents is None:
if not __opts__['test']:
if touch(name):
ret['changes']['new'] = 'file {0} created'.format(name)
ret['comment'] = 'Empty file'
else:
return _error(
ret, 'Empty file {0} not created'.format(name)
)
else:
if not __opts__['test']:
if touch(name):
ret['changes']['diff'] = 'New file'
else:
return _error(
ret, 'File {0} not created'.format(name)
)
if contents is not None:
# Write the static contents to a temporary file
tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX,
text=True)
with salt.utils.files.fopen(tmp, 'wb') as tmp_:
if encoding:
if salt.utils.platform.is_windows():
contents = os.linesep.join(
_splitlines_preserving_trailing_newline(contents))
log.debug('File will be encoded with %s', encoding)
tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors))
else:
tmp_.write(salt.utils.stringutils.to_bytes(contents))
# Copy into place
salt.utils.files.copyfile(tmp,
name,
__salt__['config.backup_mode'](backup),
__opts__['cachedir'])
__clean_tmp(tmp)
# Now copy the file contents if there is a source file
elif sfn:
salt.utils.files.copyfile(sfn,
name,
__salt__['config.backup_mode'](backup),
__opts__['cachedir'])
__clean_tmp(sfn)
# This is a new file, if no mode specified, use the umask to figure
# out what mode to use for the new file.
if mode is None and not salt.utils.platform.is_windows():
# Get current umask
mask = salt.utils.files.get_umask()
# Calculate the mode value that results from the umask
mode = oct((0o777 ^ mask) & 0o666)
if salt.utils.platform.is_windows():
# This function resides in win_file.py and will be available
# on Windows. The local function will be overridden
# pylint: disable=E1120,E1121,E1123
ret = check_perms(
path=name,
ret=ret,
owner=kwargs.get('win_owner'),
grant_perms=kwargs.get('win_perms'),
deny_perms=kwargs.get('win_deny_perms'),
inheritance=kwargs.get('win_inheritance', True),
reset=kwargs.get('win_perms_reset', False))
# pylint: enable=E1120,E1121,E1123
else:
ret, _ = check_perms(name, ret, user, group, mode, attrs)
if not ret['comment']:
ret['comment'] = 'File ' + name + ' updated'
if __opts__['test']:
ret['comment'] = 'File ' + name + ' not updated'
elif not ret['changes'] and ret['result']:
ret['comment'] = 'File ' + name + ' is in the correct state'
if sfn:
__clean_tmp(sfn)
return ret
def mkdir(dir_path,
user=None,
group=None,
mode=None):
'''
Ensure that a directory is available.
CLI Example:
.. code-block:: bash
salt '*' file.mkdir /opt/jetty/context
'''
dir_path = os.path.expanduser(dir_path)
directory = os.path.normpath(dir_path)
if not os.path.isdir(directory):
# If a caller such as managed() is invoked with makedirs=True, make
# sure that any created dirs are created with the same user and group
# to follow the principal of least surprise method.
makedirs_perms(directory, user, group, mode)
return True
def makedirs_(path,
user=None,
group=None,
mode=None):
'''
Ensure that the directory containing this path is available.
.. note::
The path must end with a trailing slash otherwise the directory/directories
will be created up to the parent directory. For example if path is
``/opt/code``, then it would be treated as ``/opt/`` but if the path
ends with a trailing slash like ``/opt/code/``, then it would be
treated as ``/opt/code/``.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs /opt/code/
'''
path = os.path.expanduser(path)
if mode:
mode = salt.utils.files.normalize_mode(mode)
# walk up the directory structure until we find the first existing
# directory
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
# There's nothing for us to do
msg = 'Directory \'{0}\' already exists'.format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = 'The path \'{0}\' already exists and is not a directory'.format(
dirname
)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if current_dirname == dirname:
raise SaltInvocationError(
'Recursive creation for path \'{0}\' would result in an '
'infinite loop. Please use an absolute path.'.format(dirname)
)
# create parent directories from the topmost to the most deeply nested one
directories_to_create.reverse()
for directory_to_create in directories_to_create:
# all directories have the user, group and mode set!!
log.debug('Creating directory: %s', directory_to_create)
mkdir(directory_to_create, user=user, group=group, mode=mode)
def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
'''
Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code
'''
name = os.path.expanduser(name)
path = os.path
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
if head and tail and not path.exists(head):
try:
makedirs_perms(head, user, group, mode)
except OSError as exc:
# be happy if someone already created the path
if exc.errno != errno.EEXIST:
raise
if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists
return
os.mkdir(name)
check_perms(name,
None,
user,
group,
int('{0}'.format(mode)) if mode else None)
def get_devmm(name):
'''
Get major/minor info from a device
CLI Example:
.. code-block:: bash
salt '*' file.get_devmm /dev/chr
'''
name = os.path.expanduser(name)
if is_chrdev(name) or is_blkdev(name):
stat_structure = os.stat(name)
return (
os.major(stat_structure.st_rdev),
os.minor(stat_structure.st_rdev))
else:
return (0, 0)
def is_chrdev(name):
'''
Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno == errno.ENOENT:
# If the character device does not exist in the first place
return False
else:
raise
return stat.S_ISCHR(stat_structure.st_mode)
def mknod_chrdev(name,
major,
minor,
user=None,
group=None,
mode='0660'):
'''
.. versionadded:: 0.17.0
Create a character device.
CLI Example:
.. code-block:: bash
salt '*' file.mknod_chrdev /dev/chr 180 31
'''
name = os.path.expanduser(name)
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
log.debug('Creating character device name:{0} major:{1} minor:{2} mode:{3}'
.format(name, major, minor, mode))
try:
if __opts__['test']:
ret['changes'] = {'new': 'Character device {0} created.'.format(name)}
ret['result'] = None
else:
if os.mknod(name,
int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR,
os.makedev(major, minor)) is None:
ret['changes'] = {'new': 'Character device {0} created.'.format(name)}
ret['result'] = True
except OSError as exc:
# be happy it is already there....however, if you are trying to change the
# major/minor, you will need to unlink it first as os.mknod will not overwrite
if exc.errno != errno.EEXIST:
raise
else:
ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name)
# quick pass at verifying the permissions of the newly created character device
check_perms(name,
None,
user,
group,
int('{0}'.format(mode)) if mode else None)
return ret
def is_blkdev(name):
'''
Check if a file exists and is a block device.
CLI Example:
.. code-block:: bash
salt '*' file.is_blkdev /dev/blk
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno == errno.ENOENT:
# If the block device does not exist in the first place
return False
else:
raise
return stat.S_ISBLK(stat_structure.st_mode)
def mknod_blkdev(name,
major,
minor,
user=None,
group=None,
mode='0660'):
'''
.. versionadded:: 0.17.0
Create a block device.
CLI Example:
.. code-block:: bash
salt '*' file.mknod_blkdev /dev/blk 8 999
'''
name = os.path.expanduser(name)
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
log.debug('Creating block device name:{0} major:{1} minor:{2} mode:{3}'
.format(name, major, minor, mode))
try:
if __opts__['test']:
ret['changes'] = {'new': 'Block device {0} created.'.format(name)}
ret['result'] = None
else:
if os.mknod(name,
int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK,
os.makedev(major, minor)) is None:
ret['changes'] = {'new': 'Block device {0} created.'.format(name)}
ret['result'] = True
except OSError as exc:
# be happy it is already there....however, if you are trying to change the
# major/minor, you will need to unlink it first as os.mknod will not overwrite
if exc.errno != errno.EEXIST:
raise
else:
ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name)
# quick pass at verifying the permissions of the newly created block device
check_perms(name,
None,
user,
group,
int('{0}'.format(mode)) if mode else None)
return ret
def is_fifo(name):
'''
Check if a file exists and is a FIFO.
CLI Example:
.. code-block:: bash
salt '*' file.is_fifo /dev/fifo
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno == errno.ENOENT:
# If the fifo does not exist in the first place
return False
else:
raise
return stat.S_ISFIFO(stat_structure.st_mode)
def mknod_fifo(name,
user=None,
group=None,
mode='0660'):
'''
.. versionadded:: 0.17.0
Create a FIFO pipe.
CLI Example:
.. code-block:: bash
salt '*' file.mknod_fifo /dev/fifo
'''
name = os.path.expanduser(name)
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
log.debug('Creating FIFO name: {0}'.format(name))
try:
if __opts__['test']:
ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)}
ret['result'] = None
else:
if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None:
ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)}
ret['result'] = True
except OSError as exc:
# be happy it is already there
if exc.errno != errno.EEXIST:
raise
else:
ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name)
# quick pass at verifying the permissions of the newly created fifo
check_perms(name,
None,
user,
group,
int('{0}'.format(mode)) if mode else None)
return ret
def mknod(name,
ntype,
major=0,
minor=0,
user=None,
group=None,
mode='0600'):
'''
.. versionadded:: 0.17.0
Create a block device, character device, or fifo pipe.
Identical to the gnu mknod.
CLI Examples:
.. code-block:: bash
salt '*' file.mknod /dev/chr c 180 31
salt '*' file.mknod /dev/blk b 8 999
salt '*' file.nknod /dev/fifo p
'''
ret = False
makedirs_(name, user, group)
if ntype == 'c':
ret = mknod_chrdev(name, major, minor, user, group, mode)
elif ntype == 'b':
ret = mknod_blkdev(name, major, minor, user, group, mode)
elif ntype == 'p':
ret = mknod_fifo(name, user, group, mode)
else:
raise SaltInvocationError(
'Node type unavailable: \'{0}\'. Available node types are '
'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype)
)
return ret
def list_backups(path, limit=None):
'''
.. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The path on the minion to check for backups
limit
Limit the number of results to the most recent N backups
CLI Example:
.. code-block:: bash
salt '*' file.list_backups /foo/bar/baz.txt
'''
path = os.path.expanduser(path)
try:
limit = int(limit)
except TypeError:
pass
except ValueError:
log.error('file.list_backups: \'limit\' value must be numeric')
limit = None
bkroot = _get_bkroot()
parent_dir, basename = os.path.split(path)
if salt.utils.platform.is_windows():
# ':' is an illegal filesystem path character on Windows
src_dir = parent_dir.replace(':', '_')
else:
src_dir = parent_dir[1:]
# Figure out full path of location of backup file in minion cache
bkdir = os.path.join(bkroot, src_dir)
if not os.path.isdir(bkdir):
return {}
files = {}
for fname in [x for x in os.listdir(bkdir)
if os.path.isfile(os.path.join(bkdir, x))]:
if salt.utils.platform.is_windows():
# ':' is an illegal filesystem path character on Windows
strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename)
else:
strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename)
try:
timestamp = datetime.datetime.strptime(fname, strpfmt)
except ValueError:
# File didn't match the strp format string, so it's not a backup
# for this file. Move on to the next one.
continue
if salt.utils.platform.is_windows():
str_format = '%a %b %d %Y %H-%M-%S.%f'
else:
str_format = '%a %b %d %Y %H:%M:%S.%f'
files.setdefault(timestamp, {})['Backup Time'] = \
timestamp.strftime(str_format)
location = os.path.join(bkdir, fname)
files[timestamp]['Size'] = os.stat(location).st_size
files[timestamp]['Location'] = location
return dict(list(zip(
list(range(len(files))),
[files[x] for x in sorted(files, reverse=True)[:limit]]
)))
list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup')
def list_backups_dir(path, limit=None):
'''
Lists the previous versions of a directory backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The directory on the minion to check for backups
limit
Limit the number of results to the most recent N backups
CLI Example:
.. code-block:: bash
salt '*' file.list_backups_dir /foo/bar/baz/
'''
path = os.path.expanduser(path)
try:
limit = int(limit)
except TypeError:
pass
except ValueError:
log.error('file.list_backups_dir: \'limit\' value must be numeric')
limit = None
bkroot = _get_bkroot()
parent_dir, basename = os.path.split(path)
# Figure out full path of location of backup folder in minion cache
bkdir = os.path.join(bkroot, parent_dir[1:])
if not os.path.isdir(bkdir):
return {}
files = {}
f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])])
ff = os.listdir(bkdir)
for i, n in six.iteritems(f):
ssfile = {}
for x in sorted(ff):
basename = x.split('_')[0]
if i == basename:
strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename)
try:
timestamp = datetime.datetime.strptime(x, strpfmt)
except ValueError:
# Folder didn't match the strp format string, so it's not a backup
# for this folder. Move on to the next one.
continue
ssfile.setdefault(timestamp, {})['Backup Time'] = \
timestamp.strftime('%a %b %d %Y %H:%M:%S.%f')
location = os.path.join(bkdir, x)
ssfile[timestamp]['Size'] = os.stat(location).st_size
ssfile[timestamp]['Location'] = location
sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]])))
sefiles = {i: sfiles}
files.update(sefiles)
return files
def restore_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Restore a previous version of a file that was backed up using Salt's
:ref:`file state backup <file-state-backups>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup you wish to restore, as found using
:mod:`file.list_backups <salt.modules.file.list_backups>`
CLI Example:
.. code-block:: bash
salt '*' file.restore_backup /foo/bar/baz.txt 0
'''
path = os.path.expanduser(path)
# Note: This only supports minion backups, so this function will need to be
# modified if/when master backups are implemented.
ret = {'result': False,
'comment': 'Invalid backup_id \'{0}\''.format(backup_id)}
try:
if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))):
backup = list_backups(path)[int(backup_id)]
else:
return ret
except ValueError:
return ret
except KeyError:
ret['comment'] = 'backup_id \'{0}\' does not exist for ' \
'{1}'.format(backup_id, path)
return ret
salt.utils.files.backup_minion(path, _get_bkroot())
try:
shutil.copyfile(backup['Location'], path)
except IOError as exc:
ret['comment'] = \
'Unable to restore {0} to {1}: ' \
'{2}'.format(backup['Location'], path, exc)
return ret
else:
ret['result'] = True
ret['comment'] = 'Successfully restored {0} to ' \
'{1}'.format(backup['Location'], path)
# Try to set proper ownership
if not salt.utils.platform.is_windows():
try:
fstat = os.stat(path)
except (OSError, IOError):
ret['comment'] += ', but was unable to set ownership'
else:
os.chown(path, fstat.st_uid, fstat.st_gid)
return ret
def delete_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Delete a previous version of a file that was backed up using Salt's
:ref:`file state backup <file-state-backups>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup you wish to delete, as found using
:mod:`file.list_backups <salt.modules.file.list_backups>`
CLI Example:
.. code-block:: bash
salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0
'''
path = os.path.expanduser(path)
ret = {'result': False,
'comment': 'Invalid backup_id \'{0}\''.format(backup_id)}
try:
if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))):
backup = list_backups(path)[int(backup_id)]
else:
return ret
except ValueError:
return ret
except KeyError:
ret['comment'] = 'backup_id \'{0}\' does not exist for ' \
'{1}'.format(backup_id, path)
return ret
try:
os.remove(backup['Location'])
except IOError as exc:
ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'],
exc)
else:
ret['result'] = True
ret['comment'] = 'Successfully removed {0}'.format(backup['Location'])
return ret
remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup')
def grep(path,
pattern,
*opts):
'''
Grep for a string in the specified file
.. note::
This function's return value is slated for refinement in future
versions of Salt
path
Path to the file to be searched
.. note::
Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing
is being used then the path should be quoted to keep the shell from
attempting to expand the glob expression.
pattern
Pattern to match. For example: ``test``, or ``a[0-5]``
opts
Additional command-line flags to pass to the grep command. For example:
``-v``, or ``-i -B2``
.. note::
The options should come after a double-dash (as shown in the
examples below) to keep Salt's own argument parser from
interpreting them.
CLI Example:
.. code-block:: bash
salt '*' file.grep /etc/passwd nobody
salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i
salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2
salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l
'''
path = os.path.expanduser(path)
# Backup the path in case the glob returns nothing
_path = path
path = glob.glob(path)
# If the list is empty no files exist
# so we revert back to the original path
# so the result is an error.
if not path:
path = _path
split_opts = []
for opt in opts:
try:
split = salt.utils.args.shlex_split(opt)
except AttributeError:
split = salt.utils.args.shlex_split(six.text_type(opt))
if len(split) > 1:
raise SaltInvocationError(
'Passing multiple command line arguments in a single string '
'is not supported, please pass the following arguments '
'separately: {0}'.format(opt)
)
split_opts.extend(split)
if isinstance(path, list):
cmd = ['grep'] + split_opts + [pattern] + path
else:
cmd = ['grep'] + split_opts + [pattern, path]
try:
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
return ret
def open_files(by_pid=False):
'''
Return a list of all physical open files on the system.
CLI Examples:
.. code-block:: bash
salt '*' file.open_files
salt '*' file.open_files by_pid=True
'''
# First we collect valid PIDs
pids = {}
procfs = os.listdir('/proc/')
for pfile in procfs:
try:
pids[int(pfile)] = []
except ValueError:
# Not a valid PID, move on
pass
# Then we look at the open files for each PID
files = {}
for pid in pids:
ppath = '/proc/{0}'.format(pid)
try:
tids = os.listdir('{0}/task'.format(ppath))
except OSError:
continue
# Collect the names of all of the file descriptors
fd_ = []
#try:
# fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid)))
#except Exception: # pylint: disable=broad-except
# pass
for fpath in os.listdir('{0}/fd'.format(ppath)):
fd_.append('{0}/fd/{1}'.format(ppath, fpath))
for tid in tids:
try:
fd_.append(
os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid))
)
except OSError:
continue
for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)):
fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath))
fd_ = sorted(set(fd_))
# Loop through file descriptors and return useful data for each file
for fdpath in fd_:
# Sometimes PIDs and TIDs disappear before we can query them
try:
name = os.path.realpath(fdpath)
# Running stat on the file cuts out all of the sockets and
# deleted files from the list
os.stat(name)
except OSError:
continue
if name not in files:
files[name] = [pid]
else:
# We still want to know which PIDs are using each file
files[name].append(pid)
files[name] = sorted(set(files[name]))
pids[pid].append(name)
pids[pid] = sorted(set(pids[pid]))
if by_pid:
return pids
return files
def pardir():
'''
Return the relative parent directory path symbol for underlying OS
.. versionadded:: 2014.7.0
This can be useful when constructing Salt Formulas.
.. code-block:: jinja
{% set pardir = salt['file.pardir']() %}
{% set final_path = salt['file.join']('subdir', pardir, 'confdir') %}
CLI Example:
.. code-block:: bash
salt '*' file.pardir
'''
return os.path.pardir
def normpath(path):
'''
Returns Normalize path, eliminating double slashes, etc.
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: jinja
{%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %}
CLI Example:
.. code-block:: bash
salt '*' file.normpath 'a/b/c/..'
'''
return os.path.normpath(path)
def basename(path):
'''
Returns the final component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: jinja
{%- set filename = salt['file.basename'](source_file) %}
CLI Example:
.. code-block:: bash
salt '*' file.basename 'test/test.config'
'''
return os.path.basename(path)
def dirname(path):
'''
Returns the directory component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: jinja
{%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %}
CLI Example:
.. code-block:: bash
salt '*' file.dirname 'test/path/filename.config'
'''
return os.path.dirname(path)
def join(*args):
'''
Return a normalized file system path for the underlying OS
.. versionadded:: 2014.7.0
This can be useful at the CLI but is frequently useful when scripting
combining path variables:
.. code-block:: jinja
{% set www_root = '/var' %}
{% set app_dir = 'myapp' %}
myapp_config:
file:
- managed
- name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }}
CLI Example:
.. code-block:: bash
salt '*' file.join '/' 'usr' 'local' 'bin'
'''
return os.path.join(*args)
def move(src, dst):
'''
Move a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.move /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('Source path must be absolute.')
if not os.path.isabs(dst):
raise SaltInvocationError('Destination path must be absolute.')
ret = {
'result': True,
'comment': "'{0}' moved to '{1}'".format(src, dst),
}
try:
shutil.move(src, dst)
except (OSError, IOError) as exc:
raise CommandExecutionError(
"Unable to move '{0}' to '{1}': {2}".format(src, dst, exc)
)
return ret
def diskusage(path):
'''
Recursively calculate disk usage of path and return it
in bytes
CLI Example:
.. code-block:: bash
salt '*' file.diskusage /path/to/check
'''
total_size = 0
seen = set()
if os.path.isfile(path):
stat_structure = os.stat(path)
ret = stat_structure.st_size
return ret
for dirpath, dirnames, filenames in salt.utils.path.os_walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
try:
stat_structure = os.stat(fp)
except OSError:
continue
if stat_structure.st_ino in seen:
continue
seen.add(stat_structure.st_ino)
total_size += stat_structure.st_size
ret = total_size
return ret
|
/* Copyright 2003-2018, University Corporation for Atmospheric
* Research. See COPYRIGHT file for copying and redistribution
* conditions. */
/**
* @file
* @internal The netCDF-4 file functions.
*
* This file is part of netcdf-4, a netCDF-like interface for HDF5, or
* a HDF5 backend for netCDF, depending on your point of view.
*
* @author Ed Hartnett
*/
#include "config.h"
#include "hdf5internal.h"
#include "ncrc.h"
extern int NC4_extract_file_image(NC_FILE_INFO_T* h5); /* In nc4memcb.c */
static void dumpopenobjects(NC_FILE_INFO_T* h5);
/** @internal When we have open objects at file close, should
we log them or print to stdout. Default is to log. */
#define LOGOPEN 1
/** @internal Number of reserved attributes. These attributes are
* hidden from the netcdf user, but exist in the HDF5 file to help
* netcdf read the file. */
#define NRESERVED 11 /*|NC_reservedatt|*/
/** @internal List of reserved attributes. This list must be in sorted
* order for binary search. */
static const NC_reservedatt NC_reserved[NRESERVED] = {
{NC_ATT_CLASS, READONLYFLAG|DIMSCALEFLAG}, /*CLASS*/
{NC_ATT_DIMENSION_LIST, READONLYFLAG|DIMSCALEFLAG}, /*DIMENSION_LIST*/
{NC_ATT_NAME, READONLYFLAG|DIMSCALEFLAG}, /*NAME*/
{NC_ATT_REFERENCE_LIST, READONLYFLAG|DIMSCALEFLAG}, /*REFERENCE_LIST*/
{NC_ATT_FORMAT, READONLYFLAG}, /*_Format*/
{ISNETCDF4ATT, READONLYFLAG|NAMEONLYFLAG}, /*_IsNetcdf4*/
{NCPROPS, READONLYFLAG|NAMEONLYFLAG|MATERIALIZEDFLAG},/*_NCProperties*/
{NC_ATT_COORDINATES, READONLYFLAG|DIMSCALEFLAG|MATERIALIZEDFLAG},/*_Netcdf4Coordinates*/
{NC_DIMID_ATT_NAME, READONLYFLAG|DIMSCALEFLAG|MATERIALIZEDFLAG},/*_Netcdf4Dimid*/
{SUPERBLOCKATT, READONLYFLAG|NAMEONLYFLAG},/*_SuperblockVersion*/
{NC3_STRICT_ATT_NAME, READONLYFLAG|MATERIALIZEDFLAG}, /*_nc3_strict*/
};
/* Forward */
static int NC4_enddef(int ncid);
static void dumpopenobjects(NC_FILE_INFO_T* h5);
/**
* @internal Define a binary searcher for reserved attributes
* @param name for which to search
* @return pointer to the matchig NC_reservedatt structure.
* @return NULL if not found.
* @author Dennis Heimbigner
*/
const NC_reservedatt*
NC_findreserved(const char* name)
{
int n = NRESERVED;
int L = 0;
int R = (n - 1);
for(;;) {
if(L > R) break;
int m = (L + R) / 2;
const NC_reservedatt* p = &NC_reserved[m];
int cmp = strcmp(p->name,name);
if(cmp == 0) return p;
if(cmp < 0)
L = (m + 1);
else /*cmp > 0*/
R = (m - 1);
}
return NULL;
}
/**
* @internal Recursively determine if there is a mismatch between
* order of coordinate creation and associated dimensions in this
* group or any subgroups, to find out if we have to handle that
* situation. Also check if there are any multidimensional coordinate
* variables defined, which require the same treatment to fix a
* potential bug when such variables occur in subgroups.
*
* @param grp Pointer to group info struct.
* @param bad_coord_orderp Pointer that gets 1 if there is a bad
* coordinate order.
*
* @returns NC_NOERR No error.
* @returns NC_EHDFERR HDF5 returned an error.
* @author Ed Hartnett
*/
static int
detect_preserve_dimids(NC_GRP_INFO_T *grp, nc_bool_t *bad_coord_orderp)
{
NC_VAR_INFO_T *var;
NC_GRP_INFO_T *child_grp;
int last_dimid = -1;
int retval;
int i;
/* Iterate over variables in this group */
for (i=0; i < ncindexsize(grp->vars); i++)
{
var = (NC_VAR_INFO_T*)ncindexith(grp->vars,i);
if (var == NULL) continue;
/* Only matters for dimension scale variables, with non-scalar dimensionality */
if (var->dimscale && var->ndims)
{
/* If the user writes coord vars in a different order then he
* defined their dimensions, then, when the file is reopened, the
* order of the dimids will change to match the order of the coord
* vars. Detect if this is about to happen. */
if (var->dimids[0] < last_dimid)
{
LOG((5, "%s: %s is out of order coord var", __func__, var->hdr.name));
*bad_coord_orderp = NC_TRUE;
return NC_NOERR;
}
last_dimid = var->dimids[0];
/* If there are multidimensional coordinate variables defined, then
* it's also necessary to preserve dimension IDs when the file is
* reopened ... */
if (var->ndims > 1)
{
LOG((5, "%s: %s is multidimensional coord var", __func__, var->hdr.name));
*bad_coord_orderp = NC_TRUE;
return NC_NOERR;
}
/* Did the user define a dimension, end define mode, reenter define
* mode, and then define a coordinate variable for that dimension?
* If so, dimensions will be out of order. */
if (var->is_new_var || var->became_coord_var)
{
LOG((5, "%s: coord var defined after enddef/redef", __func__));
*bad_coord_orderp = NC_TRUE;
return NC_NOERR;
}
}
}
/* If there are any child groups, check them also for this condition. */
for (i = 0; i < ncindexsize(grp->children); i++)
{
if (!(child_grp = (NC_GRP_INFO_T *)ncindexith(grp->children, i)))
continue;
if ((retval = detect_preserve_dimids(child_grp, bad_coord_orderp)))
return retval;
}
return NC_NOERR;
}
/**
* @internal This function will write all changed metadata and flush
* HDF5 file to disk.
*
* @param h5 Pointer to HDF5 file info struct.
*
* @return ::NC_NOERR No error.
* @return ::NC_EINDEFINE Classic model file in define mode.
* @return ::NC_EHDFERR HDF5 error.
* @author Ed Hartnett
*/
static int
sync_netcdf4_file(NC_FILE_INFO_T *h5)
{
NC_HDF5_FILE_INFO_T *hdf5_info;
int retval;
assert(h5 && h5->format_file_info);
LOG((3, "%s", __func__));
/* If we're in define mode, that's an error, for strict nc3 rules,
* otherwise, end define mode. */
if (h5->flags & NC_INDEF)
{
if (h5->cmode & NC_CLASSIC_MODEL)
return NC_EINDEFINE;
/* Turn define mode off. */
h5->flags ^= NC_INDEF;
/* Redef mode needs to be tracked separately for nc_abort. */
h5->redef = NC_FALSE;
}
#ifdef LOGGING
/* This will print out the names, types, lens, etc of the vars and
atts in the file, if the logging level is 2 or greater. */
log_metadata_nc(h5);
#endif
/* Write any metadata that has changed. */
if (!h5->no_write)
{
nc_bool_t bad_coord_order = NC_FALSE;
/* Write any user-defined types. */
if ((retval = nc4_rec_write_groups_types(h5->root_grp)))
return retval;
/* Check to see if the coordinate order is messed up. If
* detected, propagate to all groups to consistently store
* dimids. */
if ((retval = detect_preserve_dimids(h5->root_grp, &bad_coord_order)))
return retval;
/* Write all the metadata. */
if ((retval = nc4_rec_write_metadata(h5->root_grp, bad_coord_order)))
return retval;
/* Write out provenance*/
if((retval = NC4_write_provenance(h5)))
return retval;
}
/* Tell HDF5 to flush all changes to the file. */
hdf5_info = (NC_HDF5_FILE_INFO_T *)h5->format_file_info;
if (H5Fflush(hdf5_info->hdfid, H5F_SCOPE_GLOBAL) < 0)
return NC_EHDFERR;
return NC_NOERR;
}
/**
* @internal This function will free all allocated metadata memory,
* and close the HDF5 file. The group that is passed in must be the
* root group of the file. If inmemory is used, then save
* the final memory in mem.memio.
*
* @param h5 Pointer to HDF5 file info struct.
* @param abort True if this is an abort.
* @param memio the place to return a core image if not NULL
*
* @return ::NC_NOERR No error.
* @return ::NC_EHDFERR HDF5 could not close the file.
* @return ::NC_EINDEFINE Classic model file is in define mode.
* @author Ed Hartnett, Dennis Heimbigner
*/
int
nc4_close_netcdf4_file(NC_FILE_INFO_T *h5, int abort, NC_memio *memio)
{
NC_HDF5_FILE_INFO_T *hdf5_info;
int retval;
assert(h5 && h5->root_grp && h5->format_file_info);
LOG((3, "%s: h5->path %s abort %d", __func__, h5->controller->path, abort));
/* Get HDF5 specific info. */
hdf5_info = (NC_HDF5_FILE_INFO_T *)h5->format_file_info;
#ifdef USE_PARALLEL4
/* Free the MPI Comm & Info objects, if we opened the file in
* parallel. */
if (h5->parallel)
{
if (h5->comm != MPI_COMM_NULL)
MPI_Comm_free(&h5->comm);
if (h5->info != MPI_INFO_NULL)
MPI_Info_free(&h5->info);
}
#endif
/* Free the fileinfo struct, which holds info from the fileinfo
* hidden attribute. */
NC4_clear_provenance(&h5->provenance);
/* Close hdf file. It may not be open, since this function is also
* called by NC_create() when a file opening is aborted. */
if (hdf5_info->hdfid > 0 && H5Fclose(hdf5_info->hdfid) < 0)
{
dumpopenobjects(h5);
return NC_EHDFERR;
}
/* If inmemory is used and user wants the final memory block,
then capture and return the final memory block else free it */
if (h5->mem.inmemory)
{
/* Pull out the final memory */
(void)NC4_extract_file_image(h5);
if (!abort && memio != NULL)
{
*memio = h5->mem.memio; /* capture it */
h5->mem.memio.memory = NULL; /* avoid duplicate free */
}
/* If needed, reclaim extraneous memory */
if (h5->mem.memio.memory != NULL)
{
/* If the original block of memory is not resizeable, then
it belongs to the caller and we should not free it. */
if(!h5->mem.locked)
free(h5->mem.memio.memory);
}
h5->mem.memio.memory = NULL;
h5->mem.memio.size = 0;
NC4_image_finalize(h5->mem.udata);
}
/* Free the HDF5-specific info. */
if (h5->format_file_info)
free(h5->format_file_info);
/* Free the NC_FILE_INFO_T struct. */
if ((retval = nc4_nc4f_list_del(h5)))
return retval;
return NC_NOERR;
}
/**
* @internal This function will recurse through an open HDF5 file and
* release resources. All open HDF5 objects in the file will be
* closed.
*
* @param h5 Pointer to HDF5 file info struct.
* @param abort True if this is an abort.
* @param memio the place to return a core image if not NULL
*
* @return ::NC_NOERR No error.
* @return ::NC_EHDFERR HDF5 could not close the file.
* @author Ed Hartnett
*/
int
nc4_close_hdf5_file(NC_FILE_INFO_T *h5, int abort, NC_memio *memio)
{
int retval;
assert(h5 && h5->root_grp && h5->format_file_info);
LOG((3, "%s: h5->path %s abort %d", __func__, h5->controller->path, abort));
/* According to the docs, always end define mode on close. */
if (h5->flags & NC_INDEF)
h5->flags ^= NC_INDEF;
/* Sync the file, unless we're aborting, or this is a read-only
* file. */
if (!h5->no_write && !abort)
if ((retval = sync_netcdf4_file(h5)))
return retval;
/* Close all open HDF5 objects within the file. */
if ((retval = nc4_rec_grp_HDF5_del(h5->root_grp)))
return retval;
/* Release all intarnal lists and metadata associated with this
* file. All HDF5 objects have already been released. */
if ((retval = nc4_close_netcdf4_file(h5, abort, memio)))
return retval;
return NC_NOERR;
}
/**
* @internal Output a list of still-open objects in the HDF5
* file. This is only called if the file fails to close cleanly.
*
* @param h5 Pointer to file info.
*
* @author Dennis Heimbigner
*/
static void
dumpopenobjects(NC_FILE_INFO_T* h5)
{
NC_HDF5_FILE_INFO_T *hdf5_info;
int nobjs;
assert(h5 && h5->format_file_info);
hdf5_info = (NC_HDF5_FILE_INFO_T *)h5->format_file_info;
if(hdf5_info->hdfid <= 0)
return; /* File was never opened */
nobjs = H5Fget_obj_count(hdf5_info->hdfid, H5F_OBJ_ALL);
/* Apparently we can get an error even when nobjs == 0 */
if(nobjs < 0) {
return;
} else if(nobjs > 0) {
char msg[1024];
int logit = 0;
/* If the close doesn't work, probably there are still some HDF5
* objects open, which means there's a bug in the library. So
* print out some info on to help the poor programmer figure it
* out. */
snprintf(msg,sizeof(msg),"There are %d HDF5 objects open!", nobjs);
#ifdef LOGGING
#ifdef LOGOPEN
LOG((0, msg));
logit = 1;
#endif
#else
fprintf(stdout,"%s\n",msg);
logit = 0;
#endif
reportopenobjects(logit,hdf5_info->hdfid);
fflush(stderr);
}
return;
}
/**
* @internal Unfortunately HDF only allows specification of fill value
* only when a dataset is created. Whereas in netcdf, you first create
* the variable and then (optionally) specify the fill value. To
* accomplish this in HDF5 I have to delete the dataset, and recreate
* it, with the fill value specified.
*
* @param ncid File and group ID.
* @param fillmode File mode.
* @param old_modep Pointer that gets old mode. Ignored if NULL.
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4_set_fill(int ncid, int fillmode, int *old_modep)
{
NC_FILE_INFO_T *nc4_info;
int retval;
LOG((2, "%s: ncid 0x%x fillmode %d", __func__, ncid, fillmode));
/* Get pointer to file info. */
if ((retval = nc4_find_grp_h5(ncid, NULL, &nc4_info)))
return retval;
assert(nc4_info);
/* Trying to set fill on a read-only file? You sicken me! */
if (nc4_info->no_write)
return NC_EPERM;
/* Did you pass me some weird fillmode? */
if (fillmode != NC_FILL && fillmode != NC_NOFILL)
return NC_EINVAL;
/* If the user wants to know, tell him what the old mode was. */
if (old_modep)
*old_modep = nc4_info->fill_mode;
nc4_info->fill_mode = fillmode;
return NC_NOERR;
}
/**
* @internal Put the file back in redef mode. This is done
* automatically for netcdf-4 files, if the user forgets.
*
* @param ncid File and group ID.
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4_redef(int ncid)
{
NC_FILE_INFO_T *nc4_info;
int retval;
LOG((1, "%s: ncid 0x%x", __func__, ncid));
/* Find this file's metadata. */
if ((retval = nc4_find_grp_h5(ncid, NULL, &nc4_info)))
return retval;
assert(nc4_info);
/* If we're already in define mode, return an error. */
if (nc4_info->flags & NC_INDEF)
return NC_EINDEFINE;
/* If the file is read-only, return an error. */
if (nc4_info->no_write)
return NC_EPERM;
/* Set define mode. */
nc4_info->flags |= NC_INDEF;
/* For nc_abort, we need to remember if we're in define mode as a
redef. */
nc4_info->redef = NC_TRUE;
return NC_NOERR;
}
/**
* @internal For netcdf-4 files, this just calls nc_enddef, ignoring
* the extra parameters.
*
* @param ncid File and group ID.
* @param h_minfree Ignored for netCDF-4 files.
* @param v_align Ignored for netCDF-4 files.
* @param v_minfree Ignored for netCDF-4 files.
* @param r_align Ignored for netCDF-4 files.
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4__enddef(int ncid, size_t h_minfree, size_t v_align,
size_t v_minfree, size_t r_align)
{
return NC4_enddef(ncid);
}
/**
* @internal Take the file out of define mode. This is called
* automatically for netcdf-4 files, if the user forgets.
*
* @param ncid File and group ID.
*
* @return ::NC_NOERR No error.
* @return ::NC_EBADID Bad ncid.
* @return ::NC_EBADGRPID Bad group ID.
* @author Ed Hartnett
*/
static int
NC4_enddef(int ncid)
{
NC_FILE_INFO_T *nc4_info;
NC_GRP_INFO_T *grp;
NC_VAR_INFO_T *var;
int i;
int retval;
LOG((1, "%s: ncid 0x%x", __func__, ncid));
/* Find pointer to group and nc4_info. */
if ((retval = nc4_find_grp_h5(ncid, &grp, &nc4_info)))
return retval;
/* When exiting define mode, mark all variable written. */
for (i = 0; i < ncindexsize(grp->vars); i++)
{
var = (NC_VAR_INFO_T *)ncindexith(grp->vars, i);
assert(var);
var->written_to = NC_TRUE;
}
return nc4_enddef_netcdf4_file(nc4_info);
}
/**
* @internal Flushes all buffers associated with the file, after
* writing all changed metadata. This may only be called in data mode.
*
* @param ncid File and group ID.
*
* @return ::NC_NOERR No error.
* @return ::NC_EBADID Bad ncid.
* @return ::NC_EINDEFINE Classic model file is in define mode.
* @author Ed Hartnett
*/
int
NC4_sync(int ncid)
{
NC_FILE_INFO_T *nc4_info;
int retval;
LOG((2, "%s: ncid 0x%x", __func__, ncid));
if ((retval = nc4_find_grp_h5(ncid, NULL, &nc4_info)))
return retval;
assert(nc4_info);
/* If we're in define mode, we can't sync. */
if (nc4_info->flags & NC_INDEF)
{
if (nc4_info->cmode & NC_CLASSIC_MODEL)
return NC_EINDEFINE;
if ((retval = NC4_enddef(ncid)))
return retval;
}
return sync_netcdf4_file(nc4_info);
}
/**
* @internal From the netcdf-3 docs: The function nc_abort just closes
* the netCDF dataset, if not in define mode. If the dataset is being
* created and is still in define mode, the dataset is deleted. If
* define mode was entered by a call to nc_redef, the netCDF dataset
* is restored to its state before definition mode was entered and the
* dataset is closed.
*
* @param ncid File and group ID.
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4_abort(int ncid)
{
NC *nc;
NC_FILE_INFO_T *nc4_info;
int delete_file = 0;
char path[NC_MAX_NAME + 1];
int retval;
LOG((2, "%s: ncid 0x%x", __func__, ncid));
/* Find metadata for this file. */
if ((retval = nc4_find_nc_grp_h5(ncid, &nc, NULL, &nc4_info)))
return retval;
assert(nc4_info);
/* If we're in define mode, but not redefing the file, delete it. */
if (nc4_info->flags & NC_INDEF && !nc4_info->redef)
{
delete_file++;
strncpy(path, nc->path, NC_MAX_NAME);
}
/* Free any resources the netcdf-4 library has for this file's
* metadata. */
if ((retval = nc4_close_hdf5_file(nc4_info, 1, NULL)))
return retval;
/* Delete the file, if we should. */
if (delete_file)
if (remove(path) < 0)
return NC_ECANTREMOVE;
return NC_NOERR;
}
/**
* @internal Close the netcdf file, writing any changes first.
*
* @param ncid File and group ID.
* @param params any extra parameters in/out of close
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4_close(int ncid, void* params)
{
NC_GRP_INFO_T *grp;
NC_FILE_INFO_T *h5;
int retval;
int inmemory;
NC_memio* memio = NULL;
LOG((1, "%s: ncid 0x%x", __func__, ncid));
/* Find our metadata for this file. */
if ((retval = nc4_find_grp_h5(ncid, &grp, &h5)))
return retval;
assert(h5 && grp);
/* This must be the root group. */
if (grp->parent)
return NC_EBADGRPID;
inmemory = ((h5->cmode & NC_INMEMORY) == NC_INMEMORY);
if(inmemory && params != NULL) {
memio = (NC_memio*)params;
}
/* Call the nc4 close. */
if ((retval = nc4_close_hdf5_file(grp->nc4_info, 0, memio)))
return retval;
return NC_NOERR;
}
/**
* @internal Learn number of dimensions, variables, global attributes,
* and the ID of the first unlimited dimension (if any).
*
* @note It's possible for any of these pointers to be NULL, in which
* case don't try to figure out that value.
*
* @param ncid File and group ID.
* @param ndimsp Pointer that gets number of dimensions.
* @param nvarsp Pointer that gets number of variables.
* @param nattsp Pointer that gets number of global attributes.
* @param unlimdimidp Pointer that gets first unlimited dimension ID,
* or -1 if there are no unlimied dimensions.
*
* @return ::NC_NOERR No error.
* @author Ed Hartnett
*/
int
NC4_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimidp)
{
NC *nc;
NC_FILE_INFO_T *h5;
NC_GRP_INFO_T *grp;
int retval;
int i;
LOG((2, "%s: ncid 0x%x", __func__, ncid));
/* Find file metadata. */
if ((retval = nc4_find_nc_grp_h5(ncid, &nc, &grp, &h5)))
return retval;
assert(h5 && grp && nc);
/* Count the number of dims, vars, and global atts; need to iterate
* because of possible nulls. */
if (ndimsp)
{
*ndimsp = ncindexcount(grp->dim);
}
if (nvarsp)
{
*nvarsp = ncindexcount(grp->vars);
}
if (nattsp)
{
/* Do we need to read the atts? */
if (!grp->atts_read)
if ((retval = nc4_read_atts(grp, NULL)))
return retval;
*nattsp = ncindexcount(grp->att);
}
if (unlimdimidp)
{
/* Default, no unlimited dimension */
*unlimdimidp = -1;
/* If there's more than one unlimited dim, which was not possible
with netcdf-3, then only the last unlimited one will be reported
back in xtendimp. */
/* Note that this code is inconsistent with nc_inq_unlimid() */
for(i=0;i<ncindexsize(grp->dim);i++) {
NC_DIM_INFO_T* d = (NC_DIM_INFO_T*)ncindexith(grp->dim,i);
if(d == NULL) continue;
if(d->unlimited) {
*unlimdimidp = d->hdr.id;
break;
}
}
}
return NC_NOERR;
}
/**
* @internal This function will do the enddef stuff for a netcdf-4 file.
*
* @param h5 Pointer to HDF5 file info struct.
*
* @return ::NC_NOERR No error.
* @return ::NC_ENOTINDEFINE Not in define mode.
* @author Ed Hartnett
*/
int
nc4_enddef_netcdf4_file(NC_FILE_INFO_T *h5)
{
assert(h5);
LOG((3, "%s", __func__));
/* If we're not in define mode, return an error. */
if (!(h5->flags & NC_INDEF))
return NC_ENOTINDEFINE;
/* Turn define mode off. */
h5->flags ^= NC_INDEF;
/* Redef mode needs to be tracked separately for nc_abort. */
h5->redef = NC_FALSE;
return sync_netcdf4_file(h5);
}
|
'use strict';
const XError = require('./XError');
class XErrorNotFound extends XError {
constructor(message) {
super();
this.status = 404;
this.type = 'NOT_FOUND';
this.message = message || 'Not found';
}
}
module.exports = XErrorNotFound;
|
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
},
],
},
};
|
/**
* Auto-generated action file for "AWS Support" API.
*
* Generated at: 2019-07-08T11:13:29.241Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / amazonaws-com-support-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'CreateCase'
* Endpoint Path: '/#CreateCase'
* Method: 'post'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"Action",
"Version",
"X-Amz-Content-Sha256",
"X-Amz-Date",
"X-Amz-Algorithm",
"X-Amz-Credential",
"X-Amz-Security-Token",
"X-Amz-Signature",
"X-Amz-SignedHeaders"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"Action": "Action",
"Version": "Version",
"X_Amz_Content_Sha256": "X-Amz-Content-Sha256",
"X_Amz_Date": "X-Amz-Date",
"X_Amz_Algorithm": "X-Amz-Algorithm",
"X_Amz_Credential": "X-Amz-Credential",
"X_Amz_Security_Token": "X-Amz-Security-Token",
"X_Amz_Signature": "X-Amz-Signature",
"X_Amz_SignedHeaders": "X-Amz-SignedHeaders",
"attachmentSetId": "attachmentSetId",
"categoryCode": "categoryCode",
"ccEmailAddresses": "ccEmailAddresses",
"communicationBody": "communicationBody",
"issueType": "issueType",
"language": "language",
"serviceCode": "serviceCode",
"severityCode": "severityCode",
"subject": "subject",
"requestBody": "requestBody"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = 'application/json';
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
securities['hmac'] = cfg['auth_hmac'];
let callParams = {
spec: spec,
operationId: 'CreateCase',
pathName: '/#CreateCase',
method: 'post',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
/* $Id: gvmm.h $ */
/** @file
* GVMM - The Global VM Manager.
*/
/*
* Copyright (C) 2007-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___VBox_vmm_gvmm_h
#define ___VBox_vmm_gvmm_h
#include <VBox/types.h>
#include <VBox/sup.h>
#include <iprt/cpuset.h> /* RTCPUSET_MAX_CPUS */
RT_C_DECLS_BEGIN
/** @defgroup grp_gvmm GVMM - The Global VM Manager.
* @ingroup grp_vmm
* @{
*/
/** @def IN_GVMM_R0
* Used to indicate whether we're inside the same link module as the ring 0
* part of the Global VM Manager or not.
*/
#ifdef DOXYGEN_RUNNING
# define IN_GVMM_R0
#endif
/** @def GVMMR0DECL
* Ring 0 VM export or import declaration.
* @param type The return type of the function declaration.
*/
#ifdef IN_GVMM_R0
# define GVMMR0DECL(type) DECLEXPORT(type) VBOXCALL
#else
# define GVMMR0DECL(type) DECLIMPORT(type) VBOXCALL
#endif
/** @def NIL_GVM_HANDLE
* The nil GVM VM handle value (VM::hSelf).
*/
#define NIL_GVM_HANDLE 0
/**
* The scheduler statistics
*/
typedef struct GVMMSTATSSCHED
{
/** The number of calls to GVMMR0SchedHalt. */
uint64_t cHaltCalls;
/** The number of times we did go to sleep in GVMMR0SchedHalt. */
uint64_t cHaltBlocking;
/** The number of times we timed out in GVMMR0SchedHalt. */
uint64_t cHaltTimeouts;
/** The number of times we didn't go to sleep in GVMMR0SchedHalt. */
uint64_t cHaltNotBlocking;
/** The number of wake ups done during GVMMR0SchedHalt. */
uint64_t cHaltWakeUps;
/** The number of calls to GVMMR0WakeUp. */
uint64_t cWakeUpCalls;
/** The number of times the EMT thread wasn't actually halted when GVMMR0WakeUp
* was called. */
uint64_t cWakeUpNotHalted;
/** The number of wake ups done during GVMMR0WakeUp (not counting the explicit
* one). */
uint64_t cWakeUpWakeUps;
/** The number of calls to GVMMR0Poke. */
uint64_t cPokeCalls;
/** The number of times the EMT thread wasn't actually busy when
* GVMMR0Poke was called. */
uint64_t cPokeNotBusy;
/** The number of calls to GVMMR0SchedPoll. */
uint64_t cPollCalls;
/** The number of times the EMT has halted in a GVMMR0SchedPoll call. */
uint64_t cPollHalts;
/** The number of wake ups done during GVMMR0SchedPoll. */
uint64_t cPollWakeUps;
uint64_t u64Alignment; /**< padding */
} GVMMSTATSSCHED;
/** Pointer to the GVMM scheduler statistics. */
typedef GVMMSTATSSCHED *PGVMMSTATSSCHED;
/**
* Per host cpu statistics.
*/
typedef struct GVMMSTATSHOSTCPU
{
/** The CPU ID. */
RTCPUID idCpu;
/** The CPU's set index. */
uint32_t idxCpuSet;
/** The desired PPT frequency. */
uint32_t uDesiredHz;
/** The current PPT timer frequency. */
uint32_t uTimerHz;
/** The number of times the PPT was changed. */
uint32_t cChanges;
/** The number of times the PPT was started. */
uint32_t cStarts;
} GVMMSTATSHOSTCPU;
/** Pointer to the GVMM per host CPU statistics. */
typedef GVMMSTATSHOSTCPU *PGVMMSTATSHOSTCPU;
/**
* The GVMM statistics.
*/
typedef struct GVMMSTATS
{
/** The VM statistics if a VM was specified. */
GVMMSTATSSCHED SchedVM;
/** The sum statistics of all VMs accessible to the caller. */
GVMMSTATSSCHED SchedSum;
/** The number of VMs accessible to the caller. */
uint32_t cVMs;
/** The number of emulation threads in those VMs. */
uint32_t cEMTs;
/** Padding. */
uint32_t u32Padding;
/** The number of valid entries in aHostCpus. */
uint32_t cHostCpus;
/** Per host CPU statistics. */
GVMMSTATSHOSTCPU aHostCpus[RTCPUSET_MAX_CPUS];
} GVMMSTATS;
/** Pointer to the GVMM statistics. */
typedef GVMMSTATS *PGVMMSTATS;
/** Const pointer to the GVMM statistics. */
typedef const GVMMSTATS *PCGVMMSTATS;
GVMMR0DECL(int) GVMMR0Init(void);
GVMMR0DECL(void) GVMMR0Term(void);
GVMMR0DECL(int) GVMMR0SetConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t u64Value);
GVMMR0DECL(int) GVMMR0QueryConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t *pu64Value);
GVMMR0DECL(int) GVMMR0CreateVM(PSUPDRVSESSION pSession, uint32_t cCpus, PVM *ppVM);
GVMMR0DECL(int) GVMMR0InitVM(PGVM pGVM);
GVMMR0DECL(void) GVMMR0DoneInitVM(PGVM pGVM);
GVMMR0DECL(bool) GVMMR0DoingTermVM(PGVM pGVM);
GVMMR0DECL(int) GVMMR0DestroyVM(PGVM pGVM, PVM pVM);
GVMMR0DECL(int) GVMMR0RegisterVCpu(PGVM pGVM, PVM pVM, VMCPUID idCpu);
GVMMR0DECL(int) GVMMR0DeregisterVCpu(PGVM pGVM, PVM pVM, VMCPUID idCpu);
GVMMR0DECL(PGVM) GVMMR0ByHandle(uint32_t hGVM);
GVMMR0DECL(int) GVMMR0ValidateGVMandVM(PGVM pGVM, PVM pVM);
GVMMR0DECL(int) GVMMR0ValidateGVMandVMandEMT(PGVM pGVM, PVM pVM, VMCPUID idCpu);
GVMMR0DECL(PVM) GVMMR0GetVMByEMT(RTNATIVETHREAD hEMT);
GVMMR0DECL(int) GVMMR0SchedHalt(PGVM pGVM, PVM pVM, VMCPUID idCpu, uint64_t u64ExpireGipTime);
GVMMR0DECL(int) GVMMR0SchedWakeUp(PGVM pGVM, PVM pVM, VMCPUID idCpu);
GVMMR0DECL(int) GVMMR0SchedWakeUpEx(PGVM pGVM, PVM pVM, VMCPUID idCpu, bool fTakeUsedLock);
GVMMR0DECL(int) GVMMR0SchedWakeUpNoGVMNoLock(PVM pVM, VMCPUID idCpu);
GVMMR0DECL(int) GVMMR0SchedPoke(PGVM pGVM, PVM pVM, VMCPUID idCpu);
GVMMR0DECL(int) GVMMR0SchedPokeEx(PGVM pGVM, PVM pVM, VMCPUID idCpu, bool fTakeUsedLock);
GVMMR0DECL(int) GVMMR0SchedPokeNoGVMNoLock(PVM pVM, VMCPUID idCpu);
GVMMR0DECL(int) GVMMR0SchedWakeUpAndPokeCpus(PGVM pGVM, PVM pVM, PCVMCPUSET pSleepSet, PCVMCPUSET pPokeSet);
GVMMR0DECL(int) GVMMR0SchedPoll(PGVM pGVM, PVM pVM, VMCPUID idCpu, bool fYield);
GVMMR0DECL(void) GVMMR0SchedUpdatePeriodicPreemptionTimer(PVM pVM, RTCPUID idHostCpu, uint32_t uHz);
GVMMR0DECL(int) GVMMR0QueryStatistics(PGVMMSTATS pStats, PSUPDRVSESSION pSession, PGVM pGVM, PVM pVM);
GVMMR0DECL(int) GVMMR0ResetStatistics(PCGVMMSTATS pStats, PSUPDRVSESSION pSession, PGVM pGVM, PVM pVM);
/**
* Request packet for calling GVMMR0CreateVM.
*/
typedef struct GVMMCREATEVMREQ
{
/** The request header. */
SUPVMMR0REQHDR Hdr;
/** The support driver session. (IN) */
PSUPDRVSESSION pSession;
/** Number of virtual CPUs for the new VM. (IN) */
uint32_t cCpus;
/** Pointer to the ring-3 mapping of the shared VM structure on return. (OUT) */
PVMR3 pVMR3;
/** Pointer to the ring-0 mapping of the shared VM structure on return. (OUT) */
PVMR0 pVMR0;
} GVMMCREATEVMREQ;
/** Pointer to a GVMMR0CreateVM request packet. */
typedef GVMMCREATEVMREQ *PGVMMCREATEVMREQ;
GVMMR0DECL(int) GVMMR0CreateVMReq(PGVMMCREATEVMREQ pReq, PSUPDRVSESSION pSession);
/**
* Request buffer for GVMMR0SchedWakeUpAndPokeCpusReq / VMMR0_DO_GVMM_SCHED_WAKE_UP_AND_POKE_CPUS.
* @see GVMMR0SchedWakeUpAndPokeCpus.
*/
typedef struct GVMMSCHEDWAKEUPANDPOKECPUSREQ /* nice and unreadable... */
{
/** The header. */
SUPVMMR0REQHDR Hdr;
/** The sleeper set. */
VMCPUSET SleepSet;
/** The set of virtual CPUs to poke. */
VMCPUSET PokeSet;
} GVMMSCHEDWAKEUPANDPOKECPUSREQ;
/** Pointer to a GVMMR0QueryStatisticsReq / VMMR0_DO_GVMM_QUERY_STATISTICS request buffer. */
typedef GVMMSCHEDWAKEUPANDPOKECPUSREQ *PGVMMSCHEDWAKEUPANDPOKECPUSREQ;
GVMMR0DECL(int) GVMMR0SchedWakeUpAndPokeCpusReq(PGVM pGVM, PVM pVM, PGVMMSCHEDWAKEUPANDPOKECPUSREQ pReq);
/**
* Request buffer for GVMMR0QueryStatisticsReq / VMMR0_DO_GVMM_QUERY_STATISTICS.
* @see GVMMR0QueryStatistics.
*/
typedef struct GVMMQUERYSTATISTICSSREQ
{
/** The header. */
SUPVMMR0REQHDR Hdr;
/** The support driver session. */
PSUPDRVSESSION pSession;
/** The statistics. */
GVMMSTATS Stats;
} GVMMQUERYSTATISTICSSREQ;
/** Pointer to a GVMMR0QueryStatisticsReq / VMMR0_DO_GVMM_QUERY_STATISTICS request buffer. */
typedef GVMMQUERYSTATISTICSSREQ *PGVMMQUERYSTATISTICSSREQ;
GVMMR0DECL(int) GVMMR0QueryStatisticsReq(PGVM pGVM, PVM pVM, PGVMMQUERYSTATISTICSSREQ pReq, PSUPDRVSESSION pSession);
/**
* Request buffer for GVMMR0ResetStatisticsReq / VMMR0_DO_GVMM_RESET_STATISTICS.
* @see GVMMR0ResetStatistics.
*/
typedef struct GVMMRESETSTATISTICSSREQ
{
/** The header. */
SUPVMMR0REQHDR Hdr;
/** The support driver session. */
PSUPDRVSESSION pSession;
/** The statistics to reset.
* Any non-zero entry will be reset (if permitted). */
GVMMSTATS Stats;
} GVMMRESETSTATISTICSSREQ;
/** Pointer to a GVMMR0ResetStatisticsReq / VMMR0_DO_GVMM_RESET_STATISTICS request buffer. */
typedef GVMMRESETSTATISTICSSREQ *PGVMMRESETSTATISTICSSREQ;
GVMMR0DECL(int) GVMMR0ResetStatisticsReq(PGVM pGVM, PVM pVM, PGVMMRESETSTATISTICSSREQ pReq, PSUPDRVSESSION pSession);
/** @} */
RT_C_DECLS_END
#endif
|
/** @file
PostCode status code implementation.
Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Library/UefiDriverEntryPoint.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Guid/EventGroup.h>
#include <Library/HobLib.h>
#include <Library/PcdLib.h>
#include <Library/DebugLib.h>
#include <Library/ReportStatusCodeLib.h>
#include <Protocol/ReportStatusCodeHandler.h>
#include <Library/PostCodeMapLib.h>
#include <Library/PostCodeLib.h>
EFI_RSC_HANDLER_PROTOCOL *mPostCodeRscHandlerProtocol = NULL;
EFI_EVENT mPostCodeExitBootServicesEvent = NULL;
BOOLEAN mPostCodeRegisted = FALSE;
/**
Convert status code value and write data to post code.
@param CodeType Indicates the type of status code being reported.
@param Value Describes the current status of a hardware or
software entity. This includes information about the class and
subclass that is used to classify the entity as well as an operation.
For progress codes, the operation is the current activity.
For error codes, it is the exception.For debug codes,it is not defined at this time.
@param Instance The enumeration of a hardware or software entity within
the system. A system may contain multiple entities that match a class/subclass
pairing. The instance differentiates between them. An instance of 0 indicates
that instance information is unavailable, not meaningful, or not relevant.
Valid instance numbers start with 1.
@param CallerId This optional parameter may be used to identify the caller.
This parameter allows the status code driver to apply different rules to
different callers.
@param Data This optional parameter may be used to pass additional data.
@retval EFI_SUCCESS Status code reported to post code successfully.
**/
EFI_STATUS
EFIAPI
PostCodeStatusCodeReportWorker (
IN EFI_STATUS_CODE_TYPE CodeType,
IN EFI_STATUS_CODE_VALUE Value,
IN UINT32 Instance,
IN EFI_GUID *CallerId,
IN EFI_STATUS_CODE_DATA *Data OPTIONAL
)
{
UINT32 PostCodeValue;
PostCodeValue = GetPostCodeFromStatusCode (CodeType, Value);
if (PostCodeValue != 0) {
DEBUG ((EFI_D_INFO, "POSTCODE=<%02x>\n", PostCodeValue));
PostCode (PostCodeValue);
}
return EFI_SUCCESS;
}
/**
Unregister status code callback functions only available at boot time from
report status code router when exiting boot services.
@param Event Event whose notification function is being invoked.
@param Context Pointer to the notification function's context, which is
always zero in current implementation.
**/
VOID
EFIAPI
UnregisterPostCodeBootTimeHandlers (
IN EFI_EVENT Event,
IN VOID *Context
)
{
if (mPostCodeRegisted) {
mPostCodeRscHandlerProtocol->Unregister (PostCodeStatusCodeReportWorker);
}
}
/**
Register status code callback function only when Report Status Code protocol
is installed.
@param Event Event whose notification function is being invoked.
@param Context Pointer to the notification function's context, which is
always zero in current implementation.
**/
VOID
EFIAPI
RegisterPostCodeBootTimeHandlers (
IN EFI_EVENT Event,
IN VOID *Context
)
{
EFI_STATUS Status;
Status = gBS->LocateProtocol (
&gEfiRscHandlerProtocolGuid,
NULL,
(VOID **) &mPostCodeRscHandlerProtocol
);
ASSERT_EFI_ERROR (Status);
mPostCodeRscHandlerProtocol->Register (PostCodeStatusCodeReportWorker, TPL_HIGH_LEVEL);
ASSERT_EFI_ERROR (Status);
mPostCodeRegisted = TRUE;
Status = gBS->CreateEventEx (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
UnregisterPostCodeBootTimeHandlers,
NULL,
&gEfiEventExitBootServicesGuid,
&mPostCodeExitBootServicesEvent
);
ASSERT_EFI_ERROR (Status);
}
/**
Constructor function of RuntimeDxePostCodeStatusCodeHandlerLib.
This function allocates memory for extended status code data, caches
the report status code service, and registers events.
@param ImageHandle The firmware allocated handle for the EFI image.
@param SystemTable A pointer to the EFI System Table.
@retval EFI_SUCCESS The constructor always returns EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
RuntimeDxePostCodeStatusCodeHandlerLibConstructor (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
EFI_EVENT RegisterStatusCodeHandlerEvent;
VOID *Registration;
if (!PcdGetBool (PcdStatusCodeUsePostCode)) {
return EFI_SUCCESS;
}
Status = gBS->LocateProtocol (
&gEfiRscHandlerProtocolGuid,
NULL,
(VOID **) &mPostCodeRscHandlerProtocol
);
if (!EFI_ERROR (Status)) {
RegisterPostCodeBootTimeHandlers (NULL, NULL);
} else {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
RegisterPostCodeBootTimeHandlers,
NULL,
&RegisterStatusCodeHandlerEvent
);
ASSERT_EFI_ERROR (Status);
//
// Register for protocol notifications on this event
//
Status = gBS->RegisterProtocolNotify (
&gEfiRscHandlerProtocolGuid,
RegisterStatusCodeHandlerEvent,
&Registration
);
ASSERT_EFI_ERROR (Status);
}
return EFI_SUCCESS;
}
|
# Copyright 2017 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.
# ==============================================================================
"""Utility functions for creating TFRecord data sets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def int64_list_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def bytes_list_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
def float_list_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def read_examples_list(path):
"""Read list of training or validation examples.
The file is assumed to contain a single example per line where the first
token in the line is an identifier that allows us to find the image and
annotation xml for that example.
For example, the line:
xyz 3
would allow us to find files xyz.jpg and xyz.xml (the 3 would be ignored).
Args:
path: absolute path to examples list file.
Returns:
list of example identifiers (strings).
"""
with tf.gfile.GFile(path) as fid:
lines = fid.readlines()
return [line.strip().split(' ')[0] for line in lines]
def recursive_parse_xml_to_dict(xml):
"""Recursively parses XML contents to python dict.
We assume that `object` tags are the only ones that can appear
multiple times at the same level of a tree.
Args:
xml: xml tree obtained by parsing XML file contents using lxml.etree
Returns:
Python dictionary holding XML contents.
"""
if not xml:
return {xml.tag: xml.text}
result = {}
for child in xml:
child_result = recursive_parse_xml_to_dict(child)
if child.tag != 'object':
result[child.tag] = child_result[child.tag]
else:
if child.tag not in result:
result[child.tag] = []
result[child.tag].append(child_result[child.tag])
return {xml.tag: result}
|
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
var hxPreset = {
"version" : 6,
"data" : {
"meta" : {
"name" : "Ashwagandha",
"application" : "Helix",
"build_sha" : "61d1df5",
"modifieddate" : 1496188265,
"appversion" : 35651584
},
"device" : 2162689,
"tone" : {
"snapshot7" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 8",
"@tempo" : 109.8231
},
"snapshot4" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 5",
"@tempo" : 109.8231
},
"dsp1" : {
"join" : {
"@model" : "HD2_AppDSPFlowJoin",
"B Pan" : 0.5,
"B Level" : 0,
"A Level" : 0,
"A Pan" : 0.5,
"@position" : 8,
"Level" : 0,
"@enabled" : true,
"B Polarity" : false
},
"block3" : {
"@model" : "HD2_DelayElephantMan",
"@position" : 5,
"Feedback" : 0.71,
"SyncSelect1" : 6,
"TempoSync1" : true,
"Scale" : 1,
"@enabled" : true,
"@path" : 1,
"@trails" : true,
"@type" : 7,
"Headroom" : 0,
"Mix" : 1,
"Noise" : 0.1,
"Time" : 0.375,
"Level" : 0,
"@stereo" : true,
"Mode" : false,
"Spread" : 0.41,
"Depth" : 0.28
},
"block2" : {
"Time2" : 0,
"@model" : "HD2_PitchDualPitch",
"Cents1" : -15,
"@position" : 4,
"Interval2" : 12,
"PanVoice2" : 0.875,
"Time1" : 0,
"@enabled" : true,
"@path" : 1,
"@type" : 0,
"Mix" : 0.5,
"LevelVoice1" : 1,
"LevelVoice2" : 1,
"Interval1" : -12,
"Level" : -0.6999998,
"@stereo" : false,
"PanDry" : 0.5,
"Cents2" : 15,
"PanVoice1" : 0.125
},
"inputB" : {
"@input" : 0,
"@model" : "HD2_AppDSPFlow2Input",
"noiseGate" : false,
"decay" : 0.5,
"threshold" : -48
},
"block1" : {
"@model" : "HD2_ReverbPlate",
"@position" : 5,
"LowCut" : 90,
"@enabled" : true,
"@path" : 0,
"@trails" : false,
"@type" : 7,
"Mix" : 0.39,
"Level" : 0,
"Decay" : 0.74,
"HighCut" : 4570,
"Predelay" : 0.01499999
},
"outputB" : {
"@model" : "HD2_AppDSPFlowOutput",
"@output" : 0,
"pan" : 0.5,
"gain" : 0
},
"inputA" : {
"@input" : 0,
"@model" : "HD2_AppDSPFlow1Input",
"noiseGate" : false,
"decay" : 0.5,
"threshold" : -48
},
"split" : {
"BalanceA" : 0.5,
"@model" : "HD2_AppDSPFlowSplitY",
"@enabled" : true,
"bypass" : false,
"@position" : 4,
"BalanceB" : 0.5
},
"block0" : {
"@model" : "HD2_DelayReverseDelay",
"@position" : 4,
"Feedback" : 0.5,
"LowCut" : 19.9,
"Speed" : 0.01999998,
"SyncSelect1" : 6,
"@enabled" : true,
"TempoSync1" : true,
"@path" : 0,
"@trails" : false,
"@type" : 7,
"Mix" : 0.3099999,
"ModulationMode" : 0,
"Time" : 1,
"Level" : 0,
"@stereo" : true,
"Spread" : 1,
"HighCut" : 20100,
"Depth" : 0.5
},
"block5" : {
"@model" : "HD2_TremoloOpticalTrem",
"@position" : 7,
"SyncSelect1" : 1,
"TempoSync1" : true,
"Intensity" : 0.6700001,
"Speed" : 0.6600001,
"@enabled" : true,
"@path" : 1,
"@type" : 0,
"Level" : -7.4,
"@stereo" : true,
"Spread" : 1
},
"outputA" : {
"@model" : "HD2_AppDSPFlowOutput",
"@output" : 1,
"pan" : 0.5,
"gain" : 0
},
"block4" : {
"@model" : "HD2_ReverbCave",
"@position" : 6,
"LowCut" : 59,
"@enabled" : true,
"@path" : 1,
"@trails" : false,
"@type" : 7,
"Mix" : 0.8199999,
"Level" : 0,
"Decay" : 0.9300001,
"HighCut" : 9400,
"Predelay" : 0.04999995
}
},
"snapshot1" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 2",
"@tempo" : 109.8231
},
"snapshot5" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 6",
"@tempo" : 109.8231
},
"dsp0" : {
"block0" : {
"@model" : "HD2_DistScream808",
"@path" : 0,
"@stereo" : false,
"@type" : 0,
"Gain" : 0.4,
"@position" : 2,
"Level" : 0.76,
"Tone" : 0.34,
"@enabled" : false
},
"block1" : {
"Bias" : 0.5,
"@model" : "HD2_AmpMatchstickCh1",
"Master" : 1,
"@position" : 3,
"Cut" : 0,
"Treble" : 0.5,
"ChVol" : 0.9300001,
"@enabled" : true,
"Ripple" : 0.5,
"@path" : 0,
"@type" : 1,
"Bass" : 0.55,
"BiasX" : 0.5,
"Hum" : 0.5,
"Ch1Drive" : 0.14,
"@bypassvolume" : 1,
"Presence" : 0.1900001,
"Sag" : 0.5
},
"block2" : {
"@model" : "HD2_ImpulseResponse1024",
"LowCut" : 100,
"@path" : 0,
"@type" : 5,
"Index" : 108,
"@position" : 4,
"Level" : -18,
"Mix" : 1,
"@enabled" : false,
"HighCut" : 20100
},
"block3" : {
"@model" : "HD2_Cab4X12CaliV30",
"Level" : 0,
"LowCut" : 19.9,
"@path" : 0,
"@mic" : 4,
"@type" : 2,
"@position" : 5,
"Distance" : 2,
"EarlyReflections" : 0,
"@enabled" : true,
"HighCut" : 20100
},
"inputA" : {
"@input" : 1,
"@model" : "HD2_AppDSPFlow1Input",
"noiseGate" : false,
"decay" : 0.5,
"threshold" : -48
},
"inputB" : {
"@input" : 0,
"@model" : "HD2_AppDSPFlow2Input",
"noiseGate" : false,
"decay" : 0.5,
"threshold" : -48
},
"join" : {
"@model" : "HD2_AppDSPFlowJoin",
"B Pan" : 0.5,
"B Level" : 0,
"A Level" : 0,
"A Pan" : 0.5,
"@position" : 8,
"Level" : 0,
"@enabled" : true,
"B Polarity" : false
},
"split" : {
"BalanceA" : 0.5,
"@model" : "HD2_AppDSPFlowSplitY",
"@enabled" : true,
"bypass" : false,
"@position" : 0,
"BalanceB" : 0.5
},
"outputB" : {
"@model" : "HD2_AppDSPFlowOutput",
"@output" : 0,
"pan" : 0.5,
"gain" : 0
},
"outputA" : {
"@model" : "HD2_AppDSPFlowOutput",
"@output" : 2,
"pan" : 0.5,
"gain" : 0
}
},
"snapshot2" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 3",
"@tempo" : 109.8231
},
"global" : {
"@variax_volumeknob" : -0.1,
"@pedalstate" : 2,
"@variax_customtuning" : false,
"@variax_str1tuning" : 0,
"@variax_str2tuning" : 0,
"@variax_str4tuning" : 0,
"@variax_str6tuning" : 0,
"@variax_model" : 0,
"@model" : "@global_params",
"@topology0" : "A",
"@cursor_dsp" : 0,
"@cursor_path" : 0,
"@guitarinputZ" : 0,
"@tempo" : 48.23151,
"@topology1" : "SABJ",
"@cursor_position" : 2,
"@variax_lockctrls" : 0,
"@variax_magmode" : true,
"@variax_str3tuning" : 0,
"@variax_str5tuning" : 0,
"@variax_toneknob" : -0.1,
"@current_snapshot" : 0,
"@cursor_group" : "block0"
},
"snapshot6" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 7",
"@tempo" : 109.8231
},
"footswitch" : {
"dsp1" : {
"block0" : {
"@fs_label" : "Reverse Delay",
"@fs_enabled" : true,
"@fs_index" : 10,
"@fs_ledcolor" : 458496,
"@fs_momentary" : false
},
"block4" : {
"@fs_momentary" : false,
"@fs_customcolor" : 8,
"@fs_index" : 5,
"@fs_enabled" : true,
"@fs_ledcolor" : 16723200,
"@fs_customlabel" : "Ambience",
"@fs_label" : "Cave"
},
"block1" : {
"@fs_label" : "Plate",
"@fs_enabled" : true,
"@fs_index" : 11,
"@fs_ledcolor" : 16723200,
"@fs_momentary" : false
},
"block5" : {
"@fs_momentary" : false,
"@fs_customcolor" : 8,
"@fs_index" : 5,
"@fs_enabled" : true,
"@fs_ledcolor" : 13055,
"@fs_customlabel" : "Ambience",
"@fs_label" : "Optical Trem"
},
"block2" : {
"@fs_momentary" : false,
"@fs_customcolor" : 8,
"@fs_index" : 5,
"@fs_enabled" : true,
"@fs_ledcolor" : 3277055,
"@fs_customlabel" : "Ambience",
"@fs_label" : "Dual Pitch"
},
"block3" : {
"@fs_momentary" : false,
"@fs_customcolor" : 8,
"@fs_index" : 5,
"@fs_enabled" : true,
"@fs_ledcolor" : 458496,
"@fs_customlabel" : "Ambience",
"@fs_label" : "Elephant Man"
}
},
"dsp0" : {
"block1" : {
"@fs_label" : "Matchstick Ch1",
"@fs_enabled" : true,
"@fs_index" : 13,
"@fs_ledcolor" : 16711683,
"@fs_momentary" : false
},
"block0" : {
"@fs_label" : "Scream 808",
"@fs_enabled" : false,
"@fs_index" : 2,
"@fs_ledcolor" : 525824,
"@fs_momentary" : false
}
}
},
"snapshot3" : {
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 4",
"@tempo" : 109.8231
},
"snapshot0" : {
"blocks" : {
"dsp1" : {
"block0" : true,
"block4" : true,
"block1" : true,
"block5" : true,
"block2" : true,
"block3" : true
},
"dsp0" : {
"block0" : false,
"block1" : true,
"block2" : false,
"block3" : true
}
},
"@pedalstate" : 2,
"@ledcolor" : 0,
"@name" : "SNAPSHOT 1",
"@tempo" : 109.8231
}
},
"device_version" : 35717152
},
"schema" : "L6Preset"
};
var hxModels = {
// TODO: Add all models and type mappings
/* Distortion */
"HD2_DistKinkyBoost": {
"type": "dist",
"name": "Kinky Boost"
},
"HD2_DistDerangedMaster": {
"type": "dist",
"name": "Deranged Master"
},
"HD2_DistMinotaur": {
"type": "dist",
"name": "Minotaur"
},
"HD2_DistTeemah": {
"type": "dist",
"name": "Teemah!"
},
"HD2_DistCompulsiveDrive": {
"type": "dist",
"name": "Compulsive Drive"
},
"HD2_DistValveDriver": {
"type": "dist",
"name": "Valve Driver"
},
"HD2_DistTopSecretOD": {
"type": "dist",
"name": "Top Secret OD"
},
"HD2_DistScream808": {
"type": "dist",
"name": "Scream 808"
},
"HD2_DistHedgehogD9": {
"type": "dist",
"name": "Hedgehog D9"
},
"HD2_DistStuporOD": {
"type": "dist",
"name": "Stupor OD"
},
"HD2_DistDeezOneVintage": {
"type": "dist",
"name": "Deez One Vintage"
},
"HD2_DistDeezOneMod": {
"type": "dist",
"name": "Deez One Mod"
},
"HD2_DistVerminDist": {
"type": "dist",
"name": "Vermin Dist"
},
"HD2_DistKWB": {
"type": "dist",
"name": "KWB"
},
"HD2_DistArbitratorFuzz": {
"type": "dist",
"name": "Arbitrator Fuzz"
},
"HD2_DistTriangleFuzz": {
"type": "dist",
"name": "Triangle Fuzz"
},
"HD2_DistIndustrialFuzz": {
"type": "dist",
"name": "Industrial Fuzz"
},
"HD2_DistTycoctaviaFuzz": {
"type": "dist",
"name": "Tycoctavia Fuzz"
},
"HD2_DistWringerFuzz": {
"type": "dist",
"name": "Wringer Fuzz"
},
"HD2_DistThrifterFuzz": {
"type": "dist",
"name": "ThrifterFuzz"
},
"HD2_DistMegaphone": {
"type": "dist",
"name": "Megaphone"
},
"HD2_DistBitcrusher": {
"type": "dist",
"name": "Bitcrusher"
},
"HD2_DistObsidian7000": {
"type": "dist",
"name": "Obsidian 7000"
},
"HD2_DistClawthornDrive": {
"type": "dist",
"name": "Clawthorn Drive"
},
"HD2_DM4TubeDrive": {
"type": "dist",
"name": "Tube Drive"
},
"HD2_DM4Screamer": {
"type": "dist",
"name": "Screamer"
},
"HD2_DM4Overdrive": {
"type": "dist",
"name": "Overdrive"
},
"HD2_DM4ClassicDistortion": {
"type": "dist",
"name": "Classic Dist"
},
"HD2_DM4HeavyDistortion": {
"type": "dist",
"name": "Heavy Dist"
},
"HD2_DM4ColorDrive": {
"type": "dist",
"name": "Colordrive"
},
"HD2_DM4BuzzSaw": {
"type": "dist",
"name": "Buzz Saw"
},
"HD2_DM4FacialFuzz": {
"type": "dist",
"name": "Facial Fuzz"
},
"HD2_DM4JumboFuzz": {
"type": "dist",
"name": "Jumbo Fuzz"
},
"HD2_DM4FuzzPi": {
"type": "dist",
"name": "Fuzz Pi"
},
"HD2_DM4JetFuzz": {
"type": "dist",
"name": "Jet Fuzz"
},
"HD2_DM4Line6Drive": {
"type": "dist",
"name": "L6 Drive"
},
"HD2_DM4Line6Distortion": {
"type": "dist",
"name": "L6 Distortion"
},
"HD2_DM4SubOctFuzz": {
"type": "dist",
"name": "Sub Oct Fuzz"
},
"HD2_DM4OctaveFuzz": {
"type": "dist",
"name": "Octave Fuzz"
},
/* EQ */
"HD2_EQSimple3Band": {
"type": "eq",
"name": "Simple EQ"
},
"HD2_EQLowCutHighCut": {
"type": "eq",
"name": "Low and High Cut"
},
"HD2_EQParametric": {
"type": "eq",
"name": "Parametric"
},
"HD2_EQGraphic10Band": {
"type": "eq",
"name": "10 Band Graphic"
},
"HD2_CaliQ": {
"type": "eq",
"name": "Cali Q Graphic"
},
/* Amps */
"HD2_AmpWhoWatt100": {
"type":"amp",
"name":"WhoWatt 100"
},
"HD2_AmpSoupPro": {
"type":"amp",
"name":"Soup Pro"
},
"HD2_AmpStoneAge185": {
"type":"amp",
"name":"Stone Age 185"
},
"HD2_AmpVoltageQueen": {
"type":"amp",
"name":"Voltage Queen"
},
"HD2_AmpTweedBluesNrm": {
"type":"amp",
"name":"Tweed Blues Nrm"
},
"HD2_AmpTweedBluesBrt": {
"type":"amp",
"name":"Tweed Blues Brt"
},
"HD2_AmpUSSmallTweed": {
"type":"amp",
"name":"US Small Tweed"
},
"HD2_AmpUSDeluxeNrm": {
"type":"amp",
"name":"US Deluxe Nrm"
},
"HD2_AmpUSDeluxeVib": {
"type":"amp",
"name":"US Deluxe Vib"
},
"HD2_AmpUSDoubleNrm": {
"type":"amp",
"name":"US Double Nrm"
},
"HD2_AmpUSDoubleVib": {
"type":"amp",
"name":"US Double Vib"
},
"HD2_AmpMailOrderTwin": {
"type":"amp",
"name":"Mail Order Twin"
},
"HD2_AmpDividedDuo": {
"type":"amp",
"name":"Divided Duo"
},
"HD2_AmpInterstateZed": {
"type":"amp",
"name":"Interstate Zed"
},
"HD2_AmpDerailedIngrid": {
"type":"amp",
"name":"Derailed Ingrid"
},
"HD2_AmpJazzRivet120": {
"type":"amp",
"name":"Jazz Rivet 120"
},
"HD2_AmpEssexA15": {
"type":"amp",
"name":"Essex A15"
},
"HD2_AmpEssexA30": {
"type":"amp",
"name":"Essex A30"
},
"HD2_AmpA30FawnNrm": {
"type":"amp",
"name":"A30 Fawn Nrm"
},
"HD2_AmpA30FawnBrt": {
"type":"amp",
"name":"A30 Fawn Brt"
},
"HD2_AmpMatchstickCh1": {
"type":"amp",
"name":"Matchstick Ch1"
},
"HD2_AmpMatchstickCh2": {
"type":"amp",
"name":"Matchstick Ch2"
},
"HD2_AmpMatchstickJump": {
"type":"amp",
"name":"Matchstick Jump"
},
"HD2_AmpMandarin80": {
"type":"amp",
"name":"Mandarin 80"
},
"HD2_AmpBritJ45Nrm": {
"type":"amp",
"name":"Brit J45 Nrm"
},
"HD2_AmpBritJ45Brt": {
"type":"amp",
"name":"Brit J45 Brt"
},
"HD2_AmpBritTremNrm": {
"type":"amp",
"name":"Brit Trem Nrm"
},
"HD2_AmpBritTremBrt": {
"type":"amp",
"name":"Brit Trem Brt"
},
"HD2_AmpBritTremJump": {
"type":"amp",
"name":"Brit Trem Jump"
},
"HD2_AmpBritPlexiNrm": {
"type":"amp",
"name":"Brit Plexi Nrm"
},
"HD2_AmpBritPlexiBrt": {
"type":"amp",
"name":"Brit Plexi Brt"
},
"HD2_AmpBritPlexiJump": {
"type":"amp",
"name":"Brit Plexi Jump"
},
"HD2_AmpBritP75Nrm": {
"type":"amp",
"name":"Brit P75 Nrm"
},
"HD2_AmpBritP75Brt": {
"type":"amp",
"name":"Brit P75 Brt"
},
"HD2_AmpBrit2204": {
"type":"amp",
"name":"Brit 2204"
},
"HD2_AmpPlacaterClean": {
"type":"amp",
"name":"Placater Clean"
},
"HD2_AmpPlacaterDirty": {
"type":"amp",
"name":"Placater Dirty"
},
"HD2_AmpCartographer": {
"type":"amp",
"name":"Cartographer"
},
"HD2_AmpGermanMahadeva": {
"type":"amp",
"name":"German Mahadeva"
},
"HD2_AmpGermanUbersonic": {
"type":"amp",
"name":"German Ubersonic"
},
"HD2_AmpCaliTexasCh1": {
"type":"amp",
"name":"Cali Texas Ch1"
},
"HD2_AmpCaliTexasCh2": {
"type":"amp",
"name":"Cali Texas Ch2"
},
"HD2_AmpCaliIVR1": {
"type":"amp",
"name":"Cali IV Rhythm 1"
},
"HD2_AmpCaliIVR2": {
"type":"amp",
"name":"Cali IV Rhythm 2"
},
"HD2_AmpCaliIVLead": {
"type":"amp",
"name":"Cali IV Lead"
},
"HD2_AmpCaliRectifire": {
"type":"amp",
"name":"Cali Rectifire"
},
"HD2_AmpArchetypeClean": {
"type":"amp",
"name":"Archetype Clean"
},
"HD2_AmpArchetypeLead": {
"type":"amp",
"name":"Archetype Lead"
},
"HD2_AmpANGLMeteor": {
"type":"amp",
"name":"ANGL Meteor"
},
"HD2_AmpSoloLeadClean": {
"type":"amp",
"name":"Solo Lead Clean"
},
"HD2_AmpSoloLeadCrunch": {
"type":"amp",
"name":"Solo Lead Crunch"
},
"HD2_AmpSoloLeadOD": {
"type":"amp",
"name":"Solo Lead OD"
},
"HD2_AmpPVPanama": {
"type":"amp",
"name":"PV Panama"
},
"HD2_AmpLine6Elektrik": {
"type":"amp",
"name":"Line 6 Elektrik"
},
"HD2_AmpLine6Doom": {
"type":"amp",
"name":"Line 6 Doom"
},
"HD2_AmpLine6Epic": {
"type":"amp",
"name":"Line 6 Epic"
},
"HD2_AmpLine62204Mod": {
"type":"amp",
"name":"Line 6 2204 Mod"
},
"HD2_AmpLine6Fatality": {
"type":"amp",
"name":"Line 6 Fatality"
},
"HD2_AmpLine6Litigator": {
"type":"amp",
"name":"Line 6 Litigator"
},
"HD2_AmpLine6Badonk": {
"type":"amp",
"name":"Line 6 Badonk"
},
"HD2_AmpTucknGo": {
"type":"amp",
"name":"Tuck n' Go"
},
"HD2_AmpSVBeastNrm": {
"type":"amp",
"name":"SV Beast Nrm"
},
"HD2_AmpSVBeastBrt": {
"type":"amp",
"name":"SV Beast Brt"
},
"HD2_AmpWoodyBlue": {
"type":"amp",
"name":"Woody Blue"
},
"HD2_AmpAgua51": {
"type":"amp",
"name":"Agua 51"
},
"HD2_AmpCaliBass": {
"type":"amp",
"name":"Cali Bass"
},
"HD2_AmpCali400Ch1": {
"type":"amp",
"name":"Cali 400 Ch1"
},
"HD2_AmpCali400Ch2": {
"type":"amp",
"name":"Cali 400 Ch2"
},
"HD2_AmpGCougar800": {
"type":"amp",
"name":"G Cougar 800"
},
"HD2_AmpDelSol300": {
"type":"amp",
"name":"Del Sol 300"
},
"HD2_AmpBusyOneCh1": {
"type":"amp",
"name":"Busy One Ch1"
},
"HD2_AmpBusyOneCh2": {
"type":"amp",
"name":"Busy One Ch2"
},
"HD2_AmpBusyOneJump": {
"type":"amp",
"name":"Busy One Jump"
},
/* Preamps */
"HD2_PreampWhoWatt100": {
"type":"preamp",
"name":"WhoWatt 100"
},
"HD2_PreampSoupPro": {
"type":"preamp",
"name":"Soup Pro"
},
"HD2_PreampStoneAge185": {
"type":"preamp",
"name":"Stone Age 185"
},
"HD2_PreampVoltageQueen": {
"type":"preamp",
"name":"Voltage Queen"
},
"HD2_PreampTweedBluesNrm": {
"type":"preamp",
"name":"Tweed Blues Nrm"
},
"HD2_PreampTweedBluesBrt": {
"type":"preamp",
"name":"Tweed Blues Brt"
},
"HD2_PreampUSSmallTweed": {
"type":"preamp",
"name":"US Small Tweed"
},
"HD2_PreampUSDeluxeNrm": {
"type":"preamp",
"name":"US Deluxe Nrm"
},
"HD2_PreampUSDeluxeVib": {
"type":"preamp",
"name":"US Deluxe Vib"
},
"HD2_PreampUSDoubleNrm": {
"type":"preamp",
"name":"US Double Nrm"
},
"HD2_PreampUSDoubleVib": {
"type":"preamp",
"name":"US Double Vib"
},
"HD2_PreampMailOrderTwin": {
"type":"preamp",
"name":"Mail Order Twin"
},
"HD2_PreampDividedDuo": {
"type":"preamp",
"name":"Divided Duo"
},
"HD2_PreampInterstateZed": {
"type":"preamp",
"name":"Interstate Zed"
},
"HD2_PreampDerailedIngrid": {
"type":"preamp",
"name":"Derailed Ingrid"
},
"HD2_PreampJazzRivet120": {
"type":"preamp",
"name":"Jazz Rivet 120"
},
"HD2_PreampEssexA15": {
"type":"preamp",
"name":"Essex A15"
},
"HD2_PreampEssexA30": {
"type":"preamp",
"name":"Essex A30"
},
"HD2_PreampA30FawnNrm": {
"type":"preamp",
"name":"A30 Fawn Nrm"
},
"HD2_PreampA30FawnBrt": {
"type":"preamp",
"name":"A30 Fawn Brt"
},
"HD2_PreampMatchstickCh1": {
"type":"preamp",
"name":"Matchstick Ch1"
},
"HD2_PreampMatchstickCh2": {
"type":"preamp",
"name":"Matchstick Ch2"
},
"HD2_PreampMatchstickJump": {
"type":"preamp",
"name":"Matchstick Jump"
},
"HD2_PreampMandarin80": {
"type":"preamp",
"name":"Mandarin 80"
},
"HD2_PreampBritJ45Nrm": {
"type":"preamp",
"name":"Brit J45 Nrm"
},
"HD2_PreampBritJ45Brt": {
"type":"preamp",
"name":"Brit J45 Brt"
},
"HD2_PreampBritTremNrm": {
"type":"preamp",
"name":"Brit Trem Nrm"
},
"HD2_PreampBritTremBrt": {
"type":"preamp",
"name":"Brit Trem Brt"
},
"HD2_PreampBritTremJump": {
"type":"preamp",
"name":"Brit Trem Jump"
},
"HD2_PreampBritPlexiNrm": {
"type":"preamp",
"name":"Brit Plexi Nrm"
},
"HD2_PreampBritPlexiBrt": {
"type":"preamp",
"name":"Brit Plexi Brt"
},
"HD2_PreampBritPlexiJump": {
"type":"preamp",
"name":"Brit Plexi Jump"
},
"HD2_PreampBritP75Nrm": {
"type":"preamp",
"name":"Brit P75 Nrm"
},
"HD2_PreampBritP75Brt": {
"type":"preamp",
"name":"Brit P75 Brt"
},
"HD2_PreampBrit2204": {
"type":"preamp",
"name":"Brit 2204"
},
"HD2_PreampPlacaterClean": {
"type":"preamp",
"name":"Placater Clean"
},
"HD2_PreampPlacaterDirty": {
"type":"preamp",
"name":"Placater Dirty"
},
"HD2_PreampCartographer": {
"type":"preamp",
"name":"Cartographer"
},
"HD2_PreampGermanMahadeva": {
"type":"preamp",
"name":"German Mahadeva"
},
"HD2_PreampGermanUbersonic": {
"type":"preamp",
"name":"German Ubersonic"
},
"HD2_PreampCaliTexasCh1": {
"type":"preamp",
"name":"Cali Texas Ch1"
},
"HD2_PreampCaliTexasCh2": {
"type":"preamp",
"name":"Cali Texas Ch2"
},
"HD2_PreampCaliIVR1": {
"type":"preamp",
"name":"Cali IV Rhythm 1"
},
"HD2_PreampCaliIVR2": {
"type":"preamp",
"name":"Cali IV Rhythm 2"
},
"HD2_PreampCaliIVLead": {
"type":"preamp",
"name":"Cali IV Lead"
},
"HD2_PreampCaliRectifire": {
"type":"preamp",
"name":"Cali Rectifire"
},
"HD2_PreampArchetypeClean": {
"type":"preamp",
"name":"Archetype Clean"
},
"HD2_PreampArchetypeLead": {
"type":"preamp",
"name":"Archetype Lead"
},
"HD2_PreampANGLMeteor": {
"type":"preamp",
"name":"ANGL Meteor"
},
"HD2_PreampSoloLeadClean": {
"type":"preamp",
"name":"Solo Lead Clean"
},
"HD2_PreampSoloLeadCrunch": {
"type":"preamp",
"name":"Solo Lead Crunch"
},
"HD2_PreampSoloLeadOD": {
"type":"preamp",
"name":"Solo Lead OD"
},
"HD2_PreampPVPanama": {
"type":"preamp",
"name":"PV Panama"
},
"HD2_PreampLine6Elektrik": {
"type":"preamp",
"name":"Line 6 Elektrik"
},
"HD2_PreampLine6Doom": {
"type":"preamp",
"name":"Line 6 Doom"
},
"HD2_PreampLine6Epic": {
"type":"preamp",
"name":"Line 6 Epic"
},
"HD2_PreampLine62204Mod": {
"type":"preamp",
"name":"Line 6 2204 Mod"
},
"HD2_PreampLine6Fatality": {
"type":"preamp",
"name":"Line 6 Fatality"
},
"HD2_PreampLine6Litigator": {
"type":"preamp",
"name":"Line 6 Litigator"
},
"HD2_PreampLine6Badonk": {
"type":"preamp",
"name":"Line 6 Badonk"
},
"HD2_PreampTucknGo": {
"type":"preamp",
"name":"Tuck n' Go"
},
"HD2_PreampSVBeastNrm": {
"type":"preamp",
"name":"SV Beast Nrm"
},
"HD2_PreampSVBeastBrt": {
"type":"preamp",
"name":"SV Beast Brt"
},
"HD2_PreampWoodyBlue": {
"type":"preamp",
"name":"Woody Blue"
},
"HD2_PreampAgua51": {
"type":"preamp",
"name":"Agua 51"
},
"HD2_PreampCaliBass": {
"type":"preamp",
"name":"Cali Bass"
},
"HD2_PreampCali400Ch1": {
"type":"preamp",
"name":"Cali 400 Ch1"
},
"HD2_PreampCali400Ch2": {
"type":"preamp",
"name":"Cali 400 Ch2"
},
"HD2_PreampGCougar800": {
"type":"preamp",
"name":"G Cougar 800"
},
"HD2_PreampDelSol300": {
"type":"preamp",
"name":"Del Sol 300"
},
"HD2_PreampBusyOneCh1": {
"type":"preamp",
"name":"Busy One Ch1"
},
"HD2_PreampBusyOneCh2": {
"type":"preamp",
"name":"Busy One Ch2"
},
"HD2_PreampBusyOneJump": {
"type":"preamp",
"name":"Busy One Jump"
},
"HD2_PreampVintagePre": {
"type":"preamp",
"name":"Studio Tube Pre"
},
/* Delays */
"HD2_DelaySimpleDelay": {
"type": "delay",
"name": "Simple Delay"
},
"HD2_DelayModChorusEcho": {
"type": "delay",
"name": "Mod/Cho Echo"
},
"HD2_DelayDualDelay": {
"type": "delay",
"name": "Dual Delay"
},
"HD2_DelayMultitap4": {
"type": "delay",
"name": "Multitap 4"
},
"HD2_DelayMultitap6": {
"type": "delay",
"name": "Multitap 6"
},
"HD2_DelayPingPong": {
"type": "delay",
"name": "Ping Pong"
},
"HD2_DelaySweepEcho": {
"type": "delay",
"name": "Sweep Echo"
},
"HD2_DelayDuckedDelay": {
"type": "delay",
"name": "Ducked Delay"
},
"HD2_DelayReverseDelay": {
"type": "delay",
"name": "Reverse Delay"
},
"HD2_DelayVintageDigitalV2": {
"type": "delay",
"name": "Vintage Digital"
},
"HD2_DelaySwellVintageDigital": {
"type": "delay",
"name": "Vintage Swell"
},
"HD2_DelayPitch": {
"type": "delay",
"name": "Pitch Echo"
},
"HD2_DelayTransistorTape": {
"type": "delay",
"name": "Transistor Tape"
},
"HD2_DelayCosmosEcho": {
"type": "delay",
"name": "Cosmos Echo"
},
"HD2_DelayHarmonyDelay": {
"type": "delay",
"name": "Harmony Delay"
},
"HD2_DelayBucketBrigade": {
"type": "delay",
"name": "Bucket Brigade"
},
"HD2_DelayAdriaticDelay": {
"type": "delay",
"name": "Adriatic Delay"
},
"HD2_DelaySwellAdriatic": {
"type": "delay",
"name": "Adriatic Swell"
},
"HD2_DelayElephantMan": {
"type": "delay",
"name": "Elephant Man"
},
"HD2_DelayMultiPass": {
"type": "delay",
"name": "Multi Pass"
},
"HD2_DL4PingPong": {
"type": "delay",
"name": "Ping Pong"
},
"HD2_DL4DynamicDelayStereo": {
"type": "delay",
"name": "Dynamic"
},
"HD2_DL4StereoDelay": {
"type": "delay",
"name": "Stereo"
},
"HD2_DL4DigDelay": {
"type": "delay",
"name": "Digital"
},
"HD2_DL4DigDelayWithMod": {
"type": "delay",
"name": "Dig w/Mod"
},
"HD2_DL4Reverse": {
"type": "delay",
"name": "Reverse"
},
"HD2_DL4LowResDelay": {
"type": "delay",
"name": "Lo Res"
},
"HD2_DL4TubeEchoStereo": {
"type": "delay",
"name": "Tube Echo"
},
"HD2_DL4TapeEchoStereo": {
"type": "delay",
"name": "Tape Echo"
},
"HD2_DL4SweepEchoStereo": {
"type": "delay",
"name": "Sweep Echo"
},
"HD2_DL4EchoPlatterStereo": {
"type": "delay",
"name": "Echo Platter"
},
"HD2_DL4AnalogDelayStereo": {
"type": "delay",
"name": "Analog Echo"
},
"HD2_DL4AnalogDelayStereoMod": {
"type": "delay",
"name": "Analog w/Mod"
},
"HD2_DL4AutoVolStereo": {
"type": "delay",
"name": "Auto-Vol Echo"
},
"HD2_DL4MultiheadStereo": {
"type": "delay",
"name": "Multi-Head"
},
/* Mod */
"HD2_TremoloOpticalTrem": {
"type": "mod",
"name": "Optical Trem"
},
"HD2_ChorusTrinityChorus": {
"type": "mod",
"name": "Trinity Chorus"
},
"HD2_RotaryVibeRotary": {
"type": "mod",
"name": "Vibe Rotary"
},
"HD2_RingModulatorAMRingMod": {
"type": "mod",
"name": "AM Ring Mod"
},
"HD2_RingModulatorPitchRingMod": {
"type": "mod",
"name": "Pitch Ring Mod"
},
"HD2_DelayDoubleDouble": {
"type": "mod",
"name": "Double Take"
},
"HD2_Rotary145Rotary": {
"type": "mod",
"name": "145 Rotary"
},
"HD2_Rotary122Rotary": {
"type": "mod",
"name": "122 Rotary"
},
"HD2_Chorus70sChorus": {
"type": "mod",
"name": "70s Chorus"
},
"HD2_FlangerGrayFlanger": {
"type": "mod",
"name": "Gray Flanger"
},
"HD2_PhaserDeluxePhaser": {
"type": "mod",
"name": "Deluxe Phaser"
},
"HD2_Tremolo60sBiasTrem": {
"type": "mod",
"name": "60s Bias Trem"
},
"HD2_FlangerCourtesanFlange": {
"type": "mod",
"name": "Courtesan Flange"
},
"HD2_TremoloTremolo": {
"type": "mod",
"name": "Tremolo"
},
"HD2_Chorus": {
"type": "mod",
"name": "Chorus"
},
"HD2_VibratoBubbleVibrato": {
"type": "mod",
"name": "Bubble Vibrato"
},
"HD2_TremoloHarmonic": {
"type": "mod",
"name": "Harmonic Tremolo"
},
"HD2_ChorusPlastiChorus": {
"type": "mod",
"name": "PlastiChorus"
},
"HD2_TremoloPattern": {
"type": "mod",
"name": "Pattern Tremolo"
},
"HD2_FlangerHarmonicFlanger": {
"type": "mod",
"name": "Harmonic Flanger"
},
"HD2_PhaserScriptModPhase": {
"type": "mod",
"name": "Script Mod Phase"
},
"HD2_FlangerDynamixFlanger": {
"type": "mod",
"name": "Dynamix Flanger"
},
"HD2_PhaserUbiquitousVibe": {
"type": "mod",
"name": "Ubiquitous Vibe"
},
"HD2_MM4RingModulator": {
"type": "mod",
"name": "Ring Modulator"
},
"HD2_MM4FrequencyShifter": {
"type": "mod",
"name": "Frequency Shifter"
},
"HD2_M1380AFlanger": {
"type": "mod",
"name": "80A Flanger"
},
"HD2_M13ACFlanger": {
"type": "mod",
"name": "AC Flanger"
},
"HD2_MM4RotaryDrumHorn": {
"type": "mod",
"name": "Rotary Drum/Horn"
},
"HD2_MM4RotaryDrum": {
"type": "mod",
"name": "RotaryDrum"
},
"HD2_MM4TriChorus": {
"type": "mod",
"name": "Tri Chorus"
},
"HD2_MM4UVibe": {
"type": "mod",
"name": "UVibe"
},
"HD2_MM4JetFlanger": {
"type": "mod",
"name": "Jet Flanger"
},
"HD2_MM4Panner": {
"type": "mod",
"name": "Panner"
},
"HD2_MM4PitchVibrato": {
"type": "mod",
"name": "Pitch Vibrato"
},
"HD2_MM4BiasTremolo": {
"type": "mod",
"name": "Bias Tremolo"
},
"HD2_MM4AnalogChorus": {
"type": "mod",
"name": "Analog Chorus"
},
"HD2_MM4DualPhaser": {
"type": "mod",
"name": "Dual Phaser"
},
"HD2_MM4OptoTremolo": {
"type": "mod",
"name": "Opto Tremolo"
},
"HD2_MM4AnalogFlanger": {
"type": "mod",
"name": "Analog Flanger"
},
"HD2_MM4ScriptPhase": {
"type": "mod",
"name": "Script Phase"
},
"HD2_MM4Phaser": {
"type": "mod",
"name": "Phaser"
},
"HD2_MM4PatternTrem": {
"type": "mod",
"name": "Pattern Trem"
},
"HD2_MM4PannedPhaser": {
"type": "mod",
"name": "Panned Phaser"
},
"HD2_MM4Dimension": {
"type": "mod",
"name": "Dimension"
},
"HD2_MM4BarberpolePhaser": {
"type": "mod",
"name": "Barberpole Phaser"
},
/* IR */
"HD2_ImpulseResponse1024": {
"type": "ir",
"name": "IR 1024"
},
"HD2_ImpulseResponse2048": {
"type": "ir",
"name": "IR 2048"
},
/* Cabs */
"HD2_Cab1x6x9SoupProEllipse": {
"type": "cab",
"name": "Soup Pro Ellipse"
},
"HD2_Cab1x8SmallTweed": {
"type": "cab",
"name": "1x8 Small Tweed"
},
"HD2_Cab1x12FieldCoil": {
"type": "cab",
"name": "1x12 Field Coil"
},
"HD2_Cab1x12USDeluxe": {
"type": "cab",
"name": "1x12 US Deluxe"
},
"HD2_Cab1x12Celest12H": {
"type": "cab",
"name": "1x12 Celest 12H"
},
"HD2_Cab1x12BlueBell": {
"type": "cab",
"name": "1x12 Blue Bell"
},
"HD2_Cab1x12Lead80": {
"type": "cab",
"name": "1x12 Lead 80"
},
"HD2_Cab1x12CaliExt": {
"type": "cab",
"name": "1x12 Cali Ext"
},
"HD2_Cab1x12CaliIV": {
"type": "cab",
"name": "1x12 Cali IV"
},
"HD2_Cab1x12DelSol": {
"type": "cab",
"name": "1x12 Del Sol"
},
"HD2_Cab1x12MatchH30": {
"type": "cab",
"name": "1x12 Match H30"
},
"HD2_Cab1x12MatchG25": {
"type": "cab",
"name": "1x12 Match G25"
},
"HD2_Cab2x12DoubleC12N": {
"type": "cab",
"name": "2x12 Double C12N"
},
"HD2_Cab2x12MailC12Q": {
"type": "cab",
"name": "2x12 Mail C12Q"
},
"HD2_Cab2x12Interstate": {
"type": "cab",
"name": "2x12 Interstate"
},
"HD2_Cab2x12JazzRivet": {
"type": "cab",
"name": "2x12 Jazz Rivet"
},
"HD2_Cab2x12SilverBell": {
"type": "cab",
"name": "2x12 Silver Bell"
},
"HD2_Cab2x12BlueBell": {
"type": "cab",
"name": "2x12 Blue Bell"
},
"HD2_Cab4x10TweedP10R": {
"type": "cab",
"name": "4x10 Tweed P10R"
},
"HD2_Cab4x12WhoWatt100": {
"type": "cab",
"name": "4x12 WhoWatt 100"
},
"HD2_Cab4x12MandarinEM": {
"type": "cab",
"name": "4x12 Mandarin EM"
},
"HD2_Cab4x12Greenback25": {
"type": "cab",
"name": "4x12 Greenback25"
},
"HD2_Cab4x12Greenback20": {
"type": "cab",
"name": "4x12 Greenback20"
},
"HD2_Cab4x12Blackback30": {
"type": "cab",
"name": "4x12 Blackback30"
},
"HD2_Cab4x121960T75": {
"type": "cab",
"name": "4x12 1960 T75"
},
"HD2_Cab4x12UberV30": {
"type": "cab",
"name": "4x12 Uber V30"
},
"HD2_Cab4x12UberT75": {
"type": "cab",
"name": "4x12 Uber T75"
},
"HD2_Cab4X12CaliV30": {
"type": "cab",
"name": "4x12 Cali V30"
},
"HD2_Cab4x12XXLV30": {
"type": "cab",
"name": "4x12 XXL V30"
},
"HD2_Cab4x12SoloLeadEM": {
"type": "cab",
"name": "4x12 SoloLead EM"
},
"HD2_Cab1x15TucknGo": {
"type": "cab",
"name": "1x15 Tuck n' Go"
},
"HD2_Cab1x18DelSol": {
"type": "cab",
"name": "1x18 Del Sol"
},
"HD2_Cab1x18WoodyBlue": {
"type": "cab", "name": "1x18 Woody Blue"
},
"HD2_Cab2x15Brute": {
"type": "cab", "name": "2x15 Brute"
},
"HD2_Cab4x10Rhino": {
"type": "cab", "name": "4x10 Rhino"
},
"HD2_Cab6x10CaliPower": {
"type": "cab", "name": "6x10 Cali Power"
},
"HD2_Cab8x10SVBeast": {
"type": "cab", "name": "8x10 SV Beast"
},
/* Pitch */
"HD2_PitchPitchWham": {
"type": "pitch",
"name": "Pitch Wham"
},
"HD2_PitchTwinHarmony": {
"type": "pitch",
"name": "Twin Harmony"
},
"HD2_PitchSimplePitch": {
"type": "pitch", "name":
"Simple Pitch"
},
"HD2_PitchDualPitch": {
"type": "pitch",
"name": "Dual Pitch"
},
"HD2_SynthSubtractive": {
"type": "pitch",
"name": "3 OSC Synth"
},
"HD2_Synth3NoteGenerator": {
"type": "pitch",
"name": "3 Note Generator"
},
"HD2_Synth4OSCGenerator": {
"type": "pitch",
"name": "4 OSC Generator"
},
"HD2_DM4BassOctaver": {
"type": "pitch",
"name": "Bass Octaver"
},
"HD2_M13TwoVoiceHarmony": {
"type": "pitch",
"name": "Smart Harmony"
},
"HD2_FM4OctiSynth": {
"type": "pitch",
"name": "Octi Synth"
},
"HD2_FM4SynthOMatic": {
"type": "pitch",
"name": "Synth O Matic"
},
"HD2_FM4AttackSynth": {
"type": "pitch",
"name": "Attack Synth"
},
"HD2_FM4SynthString": {
"type": "pitch",
"name": "Synth String"
},
"HD2_FM4Growler": {
"type": "pitch",
"name": "Growler"
},
/* Filter */
"HD2_FilterMutantFilter": {
"type": "filter",
"name": "Mutant Filter"
},
"HD2_FilterMysterFilter": {
"type": "filter",
"name": "Mystery Filter"
},
"HD2_FilterAutoFilter": {
"type": "filter",
"name": "Autofilter"
},
"HD2_FM4VoiceBox": {
"type": "filter",
"name": "Voice Box"
},
"HD2_FM4VTron": {
"type": "filter",
"name": "V Tron"
},
"HD2_FM4QFilter": {
"type": "filter",
"name": "Q Filter"
},
"HD2_FM4Seeker": {
"type": "filter",
"name": "Seeker"
},
"HD2_FM4ObiWah": {
"type": "filter",
"name": "Obi Wah"
},
"HD2_FM4TronUp": {
"type": "filter",
"name": "Tron Up"
},
"HD2_FM4TronDown": {
"type": "filter",
"name": "Tron Down"
},
"HD2_FM4Throbber": {
"type": "filter",
"name": "Throbber"
},
"HD2_FM4SlowFilter": {
"type": "filter",
"name": "Slow Filter"
},
"HD2_FM4SpinCycle": {
"type": "filter",
"name": "Spin Cycle"
},
"HD2_FM4CometTrails": {
"type": "filter",
"name": "Comet Trails"
},
/* Comp */
"HD2_CompressorDeluxeComp": {
"type": "comp",
"name": "Deluxe Comp"
},
"HD2_CompressorRedSqueeze": {
"type": "comp",
"name": "Red Squeeze"
},
"HD2_CompressorKinkyComp": {
"type": "comp",
"name": "Kinky Comp"
},
"HD2_CompressorLAStudioComp": {
"type": "comp",
"name": "LA Studio Comp"
},
"HD2_Compressor3BandComp": {
"type": "comp",
"name": "3-Band Comp"
},
"HD2_GateNoiseGate": {
"type": "comp",
"name": "Noise Gate"
},
"HD2_GateHardGate": {
"type": "comp",
"name": "Hard Gate"
},
"HD2_CompressorAutoSwell": {
"type": "comp",
"name": "Autoswell"
},
"HD2_DM4TubeComp": {
"type": "comp",
"name": "Tube Comp"
},
"HD2_DM4RedComp": {
"type": "comp",
"name": "Red Comp"
},
"HD2_DM4BlueComp": {
"type": "comp",
"name": "Blue Comp"
},
"HD2_DM4BlueCompTreb": {
"type": "comp",
"name": "Blue Comp Treb"
},
"HD2_DM4VettaComp": {
"type": "comp",
"name": "Vetta Comp"
},
"HD2_DM4VettaJuice": {
"type": "comp",
"name": "Vetta Juice"
},
"HD2_DM4BoostComp": {
"type": "comp",
"name": "Boost Comp"
},
/* Vol-Pan */
"HD2_VolPanVol": {
"type": "vol-pan",
"name": "Volume"
},
"HD2_VolPanGain": {
"type": "vol-pan",
"name": "Gain"
},
"HD2_VolPanPan": {
"type": "vol-pan",
"name": "Pan"
},
"HD2_VolPanStereoWidth": {
"type": "vol-pan",
"name": "Stereo Width"
},
/* Looper */
"HD2_Looper": {
"type": "looper",
"name": "6 Switch Looper"
},
"HD2_LooperOneSwitch": {
"type": "looper",
"name": "1 Switch Looper"
},
/* Send-Return */
"HD2_SendMono1": {
"type": "send-return",
"name": "Send 1"
},
"HD2_SendMono2": {
"type": "send-return",
"name": "Send 2"
},
"HD2_SendMono3": {
"type": "send-return",
"name": "Send 3"
},
"HD2_SendMono4": {
"type": "send-return",
"name": "Send 4"
},
"HD2_ReturnMono1": {
"type": "send-return",
"name": "Return 1"
},
"HD2_ReturnMono2": {
"type": "send-return",
"name": "Return 2"
},
"HD2_ReturnMono3": {
"type": "send-return",
"name": "Return 3"
},
"HD2_ReturnMono4": {
"type": "send-return",
"name": "Return 4"
},
"HD2_FXLoopMono1": {
"type": "send-return",
"name": "FX Loop 1"
},
"HD2_FXLoopMono2": {
"type": "send-return",
"name": "FX Loop 2"
},
"HD2_FXLoopMono3": {
"type": "send-return",
"name": "FX Loop 3"
},
"HD2_FXLoopMono4": {
"type": "send-return",
"name": "FX Loop 4"
},
"HD2_SendStereo1_2": {
"type": "send-return",
"name": "Send 1/2"
},
"HD2_SendStereo3_4": {
"type": "send-return",
"name": "Send 3/4"
},
"HD2_ReturnStereo1_2": {
"type": "send-return",
"name": "Return 1/2"
},
"HD2_ReturnStereo3_4": {
"type": "send-return",
"name": "Return 3/4"
},
"HD2_FXLoopStereo1_2": {
"type": "send-return",
"name": "FX Loop 1/2"
},
"HD2_FXLoopStereo3_4": {
"type": "send-return",
"name": "FX Loop 3/4"
},
/* Reverb */
"HD2_ReverbGlitz": {
"type": "reverb",
"name": "Glitz"
},
"HD2_ReverbGanymede": {
"type": "reverb",
"name": "Ganymede"
},
"HD2_ReverbSearchlights": {
"type": "reverb",
"name": "Searchlights"
},
"HD2_ReverbPlateaux": {
"type": "reverb",
"name": "Plateaux"
},
"HD2_ReverbDoubleTank": {
"type": "reverb",
"name": "Double Tank"
},
"HD2_ReverbPlate": {
"type": "reverb",
"name": "Plate"
},
"HD2_ReverbRoom": {
"type": "reverb",
"name": "Room"
},
"HD2_ReverbChamber": {
"type": "reverb",
"name": "Chamber"
},
"HD2_ReverbHall": {
"type": "reverb",
"name": "Hall"
},
"HD2_ReverbEcho": {
"type": "reverb",
"name": "Echo"
},
"HD2_ReverbTile": {
"type": "reverb",
"name": "Tile"
},
"HD2_ReverbCave": {
"type": "reverb",
"name": "Cave"
},
"HD2_ReverbDucking": {
"type": "reverb",
"name": "Ducking"
},
"HD2_ReverbOcto": {
"type": "reverb",
"name": "Octo"
},
"HD2_Reverb63Spring": {
"type": "reverb",
"name": "'63 Spring"
},
"HD2_ReverbSpring": {
"type": "reverb",
"name": "Spring"
},
"HD2_ReverbParticle": {
"type": "reverb",
"name": "Particle Verb"
},
/* Wah */
"HD2_WahUKWah846": {
"type": "wah",
"name": "UK Wah 846"
},
"HD2_WahTeardrop310": {
"type": "wah",
"name": "Teardrop 310"
},
"HD2_WahFassel": {
"type": "wah",
"name": "Fassel"
},
"HD2_WahWeeper": {
"type": "wah",
"name": "Weeper"
},
"HD2_WahChrome": {
"type": "wah",
"name": "Chrome"
},
"HD2_WahChromeCustom": {
"type": "wah",
"name": "Chrome Custom"
},
"HD2_WahThroaty": {
"type": "wah",
"name": "Throaty"
},
"HD2_WahVettaWah": {
"type": "wah",
"name": "Vetta Wah"
},
"HD2_WahColorful": {
"type": "wah",
"name": "Colorful"
},
"HD2_WahConductor": {
"type": "wah",
"name": "Conductor"
},
/* Ins, Outs, Splits, and Joins */
"HD2_AppDSPFlowSplitY": {
"type": "split",
"name": "Split Y"
},
"HD2_AppDSPFlowSplitAB": {
"type": "split",
"name": "Split A/B"
},
"HD2_AppDSPFlowSplitXOver": {
"type": "split",
"name": "Split Crossover"
},
"HD2_AppDSPFlowJoin": {
"type": "join",
"name": "Mixer"
},
"HD2_AppDSPFlow1Input": {
"type": "input",
"name": "Flow 1 Input"
},
"HD2_AppDSPFlow2Input": {
"type": "input",
"name": "Flow 2 Input"
},
"HD2_AppDSPFlowOutput": {
"type": "output",
"name": "Output"
}
};
var hxLabels = {
"@bypassvolume": "Bypass Volume",
"@cab": "Cab",
"@enabled": "Enabled",
"@model": "Model",
"@path": "Path",
"@position": "Position",
"@stereo": "Stereo",
"@trails": "Trails",
"@type": "Type",
"125Hz": "125Hz",
"16kHz": "16kHz",
"1kHz": "1kHz",
"2200Hz": "2200Hz",
"240Hz": "240Hz",
"250Hz": "250Hz",
"2kHz": "2kHz",
"31p25Hz": "31p25Hz",
"4kHz": "4kHz",
"500Hz": "500Hz",
"62p5Hz": "62p5Hz",
"6600Hz": "6600Hz",
"750Hz": "750Hz",
"80Hz": "80Hz",
"8kHz": "8kHz",
"AM": "AM",
"AM/FM": "AM/FM",
"AMFreq": "AM Frequency",
"Amount": "Amount",
"Asym": "Asym",
"Attack": "Attack",
"Auto": "Auto",
"Balance": "Balance",
"Bass": "Bass",
"BassFreq": "Bass Frequency",
"BBD Size": "BBD Size",
"Bias": "Bias",
"BiasX": "Bias X",
"BitDepth": "Bit Depth",
"Blend": "Blend",
"Boost": "Boost",
"Bright": "Bright",
"C45": "C45",
"Cents1": "Cents 1",
"Cents2": "Cents 2",
"ChorusIntensity": "Chorus Intensity",
"CH Vib": "Chorus Vibration",
"ChVol": "Channel Volume",
"Clipping": "Clipping",
"CloseThreshold": "Close Threshold",
"Color": "Color",
"Comp": "Compression",
"Compress": "Compression",
"Condition": "Condition",
"CV Decay": "CV Decay",
"CV Dynamics": "CV Dynamics",
"CV Tracking": "CV Tracking",
"Decay": "Decay",
"Delay": "Delay",
"DelayVoice1": "Delay Voice 1",
"DelayVoice2": "Delay Voice 2",
"Depth": "Depth",
"Depth1": "Depth 1",
"Depth2": "Depth 2",
"Depth3": "Depth 3",
"Detector": "Detector",
"Diffusion": "Diffusion",
"Direction": "Direction",
"Distortion": "Distortion",
"Doubles": "Doubles",
"Drive": "Drive",
"Dry Level": "Dry Level",
"DryLevel": "Dry Level",
"DryPan": "Dry Pan",
"DryThru": "Dry Thru",
"Ducking": "Ducking",
"DutyCycle": "DutyCycle",
"DutyVoice1": "Duty Voice 1",
"DutyVoice2": "Duty Voice 2",
"DutyVoice3": "Duty Voice 3",
"DynAttack": "Dyn Attack",
"DynRel": "Dyn Release",
"DynType": "Dyn Type",
"Emphasis": "Emphasis",
"End": "End",
"Enhance": "Enhance",
"Env Input": "Envelope Input",
"Env Lag": "Envelope Lag",
"FM Voice3to1": "FM Voice 3 to 1",
"FastSpeed": "Fast Speed",
"Fat": "Fat",
"FBTone": "Feedback Tone",
"FcHigh": "Fc High",
"FcLow": "Fc Low",
"Feedback": "Feedback",
"Filter": "Filter",
"FilterGain": "FilterGain",
"FilterMatrix": "Filter Matrix",
"FilterQ": "FilterQ",
"FilterType": "Filter Type",
"FMAmount": "FM Amount",
"FMDuty": "FM Duty",
"FMOctave": "FM Octave",
"FMPitch": "FM Pitch",
"FMShape": "FM Shape",
"Focus": "Focus",
"Freq": "Freq",
"FreqDepth": "Freq Depth",
"Frequency": "Frequency",
"Fuzz": "Fuzz",
"FuzzGain": "Fuzz Gain",
"FuzzLevel": "FuzzLevel",
"FuzzOct": "Fuzz Oct",
"FuzzTone": "Fuzz Tone",
"FuzzType": "Fuzz Type",
"Gain": "Gain",
"Gate": "Gate",
"Grit": "Grit",
"Grunt": "Grunt",
"Harmonic": "Harmonic",
"HBE": "HBE",
"Headroom": "Headroom",
"Heads 1-2": "Heads 1-2",
"Heads 3-4": "Heads 3-4",
"Heel": "Heel",
"Hi Gain": "High Gain",
"Hi Thresh": "High Threshold",
"Hi X Freq": "High Crossover Frequency",
"HiMid": "High Mid",
"HiMidFreq": "High Mid Freq",
"HighCut": "High Cut",
"highCut": "High Cut",
"HighFreq": "High Frequency",
"HighGain": "High Gain",
"HighQ": "High Q",
"HoldTime": "Hold Time",
"Horn Depth": "Horn Depth",
"Index": "Index",
"Intensity": "Intensity",
"Interval1": "Interval 1",
"Interval2": "Interval 2",
"IntervalVoice1": "Interval Voice 1",
"IntervalVoice2": "Interval Voice 2",
"Key": "Key",
"KeyVoice1": "Key Voice 1",
"KeyVoice2": "Key Voice 2",
"Knee": "Knee",
"LampBias": "Lamp Bias",
"Left": "Left",
"Left Time": "Left Time",
"LeftBoost": "Left Boost",
"LeftFeedback": "Left Feedback",
"Level": "Level",
"LevelRootVoice": "Level Root Voice",
"LevelVoice1": "Level Voice 1",
"LevelVoice2": "Level Voice 2",
"LevelVoice3": "Level Voice 3",
"LFeedback": "Left Feedback",
"LFO": "LFO",
"LFORate": "LFO Rate",
"LFOShape": "LFO Shape",
"Lo Gain": "Low Gain",
"Lo Thresh": "Low Threshold",
"Lo X Freq": "Low Crossover Frequency",
"LoMid": "Lo Mid",
"LoMidFreq": "Low Mid Frequncy",
"LowCut": "Low Cut",
"LowFreq": "Low Frequency",
"LowGain": "Low Gain",
"LowQ": "Low Q",
"LPHP": "LPHP",
"LR In Swap": "LR In Swap",
"LTime": "Left Time",
"Manual": "Manual",
"Master": "Master",
"Max Delay": "Max Delay",
"Mid": "Mid",
"Mid Gain": "Mid Gain",
"Mid Thresh": "Mid Threshold",
"MidFreq": "Mid Frequency",
"MidGain": "Mid Gain",
"MidQ": "Mid Q",
"Mix": "Mix",
"MixL": "Mix Left",
"MixR": "Mix Right",
"Mod Mix": "Mod Mix",
"ModSpeed": "Mod Speed",
"Mode": "Mode",
"Modulation": "Modulation",
"ModulationMode": "Modulation Mode",
"Noise": "Noise",
"Normal": "Normal",
"Notch Freq": "Notch Freq",
"Notch Gain": "Notch Gain",
"ODGain": "OD Gain",
"ODLevel": "OD Level",
"ODLowBoost": "OD Low Boost",
"ODTone": "OD Tone",
"Octave": "Octave",
"OctaveVoice1": "Octave Voice 1",
"OctaveVoice2": "Octave Voice 2",
"OctaveVoice3": "Octave Voice 3",
"Offset": "Offset",
"OpenThreshold": "Open Threshold",
"Osc1Freq": "OSC Frequency 1",
"Osc1Glide": "OSC Glide 1",
"Osc1Level": "OSC Level 1",
"Osc1Note": "OSC Note 1",
"Osc1Octave": "OSC Octave 1",
"Osc1Pan": "OSC Pan 1",
"Osc1Shape": "OSC Shape 1",
"Osc2Freq": "OSC Frequency 2",
"Osc2Glide": "OSC Glide 2",
"Osc2Level": "OSC Level 2",
"Osc2Note": "OSC Note 2",
"Osc2Octave": "OSC Octave 2",
"Osc2Pan": "OSC Pan 2",
"Osc2Shape": "OSC Shape 2",
"Osc3Freq": "OSC Frequency 3",
"Osc3Glide": "OSC Glide 3",
"Osc3Level": "OSC Level 3",
"Osc3Note": "OSC Note 3",
"Osc3Octave": "OSC Octave 3",
"Osc3Pan": "OSC Pan 3",
"Osc3Shape": "OSC Shape 3",
"Osc4Freq": "OSC Frequency 4",
"Osc4Level": "OSC Level 4",
"Osc4Pan": "OSC Pan 4",
"Osc4Shape": "OSC Shape 4",
"Oscillator": "Oscillator",
"Output": "Output",
"Overdub": "Overdub",
"Pan": "Pan",
"Pan Speed": "Pan Speed",
"PanDry": "Pan Dry",
"PanRootVoice": "Pan Root Voice",
"PanVoice1": "Pan Voice 1",
"PanVoice2": "Pan Voice 2",
"PanVoice3": "Pan Voice 3",
"Pattern": "Pattern",
"Peak": "Peak",
"PeakReduction": "Peak Reduction",
"Pedal": "Pedal Position",
"Phasing": "Phasing",
"Pitch": "Pitch",
"Pitch2": "Pitch 2",
"PitchMix": "Pitch Mix",
"PitchVoice1": "Pitch Voice 1",
"PitchVoice2": "Pitch Voice 2",
"PitchVoice3": "Pitch Voice 3",
"Playback": "Playback",
"Predelay": "Pre-Delay",
"Presence": "Presence",
"Preset": "Preset",
"PullDiode": "Pull Diode",
"PushDiode": "Push Diode",
"Q": "Q",
"R Polarity": "R Polarity",
"Ramp": "Ramp",
"RampTime": "Ramp Time",
"Range": "Range",
"Rate": "Rate",
"Ratio": "Ratio",
"RealTimeSwitch": "Real Time Switch",
"Recycle": "Recycle",
"Regen": "Regen",
"Rel Offset": "Release Offset",
"Release": "Release",
"Res": "Res",
"Resonance": "Resonance",
"Return": "Return",
"Right": "Right",
"Right Time": "Right Time",
"RightBoost": "Right Boost",
"RightFeedback": "Right Feedback",
"RiseTime": "Rise Time",
"RiseTimeSwitch": "Rise Time Switch",
"RFeedback": "Right Feedback",
"Ripple": "Ripple",
"RTime": "Right Time",
"SSwitch": "SSwitch",
"Sag": "Sag",
"SampleRate": "Samplerate",
"Saturation": "Saturation",
"Scale": "Scale",
"ScaleVoice1": "Scale Voice 1",
"ScaleVoice2": "Scale Voice 2",
"Send": "Send",
"Sens": "Sensitivity",
"Sensitivity": "Sensitivity",
"Shape": "Shape",
"ShapeVoice1": "Shape Voice 1",
"ShapeVoice2": "Shape Voice 2",
"ShapeVoice3": "Shape Voice 3",
"Shift": "Shift",
"Slop": "Slop",
"SlowSpeed": "Slow Speed",
"Source": "Source",
"Space": "Space",
"Speed": "Speed",
"Splice": "Splice",
"Spread": "Spread",
"Stability": "Stability",
"Stage": "Stage",
"Stages": "Stages",
"Start": "Start",
"Step1": "Step 1",
"Step2": "Step 2",
"Step3": "Step 3",
"Step4": "Step 4",
"Steps": "Steps",
"Sub": "Sub",
"Sustain": "Sustain",
"SW1": "SW1",
"SW2": "SW2",
"SW3": "SW3",
"SW4": "SW4",
"SweepDepth": "Sweep Depth",
"SweepResonance": "Sweep Resonance",
"SweepShape": "Sweep Shape",
"SweepSpeed": "Sweep Speed",
"SweepSpread": "Sweep Spread",
"SweepStart": "Sweep Start",
"SweepSymmetry": "Sweep Symmetry",
"Swell": "Swell",
"SyncSelect1": "Sync Select 1",
"SyncSelect2": "Sync Select 2",
"SynthPreset": "Synth Preset",
"Tap1Delay": "Tap Delay 1",
"Tap1Level": "Tap Level 1",
"Tap1Pan": "Tap Pan 1",
"Tap2Delay": "Tap Delay 2",
"Tap2Level": "Tap Level 2",
"Tap2Pan": "Tap Pan 2",
"Tap3Delay": "Tap Delay 3",
"Tap3Level": "Tap Level 3",
"Tap3Pan": "Tap Pan 3",
"Tap4Delay": "Tap Delay 4",
"Tap4Level": "Tap Level 4",
"Tap4Pan": "Tap Pan 4",
"Tap5Delay": "Tap Delay 5",
"Tap5Level": "Tap Level 5",
"Tap5Pan": "Tap Pan 5",
"Tap6Delay": "Tap Delay 6",
"Tap6Level": "Tap Level 6",
"Tap6Pan": "Tap Pan 6",
"Taper": "Taper",
"TempoSync1": "Tempo Sync 1",
"TempoSync2": "Tempo Sync 2",
"Thick": "Thick",
"Thresh": "Threshold",
"Threshold": "Threshold",
"Time": "Time",
"Time1": "Time 1",
"Time2": "Time 2",
"Toe": "Toe",
"Tone": "Tone",
"TrebFreq": "Treble Frequency",
"Treble": "Treble",
"Type": "Type",
"Version": "Version",
"VibratoDepth": "Vibrato Depth",
"VibratoRate": "Vibrato Rate",
"Voice": "Voice",
"Vol Sens": "Volume Sensitivity",
"Volsens": "Volume Sensitivity",
"VolSens": "Volume Sensitivity",
"VolumeTaper": "Volume Taper Curve",
"Wave": "Wave",
"WaveShape": "Wave Shape",
"Wet Level": "Wet Level",
"Width": "Width",
"Wow Flt": "Wow Flt",
"WowFlutter": "Wow Flutter",
"Xover": "Crossover"
};
Vue.filter('getModel', function (value, prop) {
if (!value) return '';
value = value.toString();
if (typeof hxModels[value] !== "undefined") {
return hxModels[value][prop];
} else {
return "unknown";
}
});
Vue.filter('getLabel', function (value) {
if (!value) return '';
value = value.toString();
if (typeof hxLabels[value] !== "undefined") {
return hxLabels[value];
} else {
return value + "*";
}
});
new Vue({
render: h => h(App),
data: {
hxModels: hxModels,
hxLabels: hxLabels,
hxPreset: hxPreset
}
}).$mount('#app')
|
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
import React from 'react';
import styled from 'styled-components';
export var RemoveCircle = styled.svg.attrs({
children: function (props) { return (props.title != null
? [React.createElement("title", { key: "RemoveCircle-title" }, props.title), React.createElement("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z", key: "k0" })
]
: [React.createElement("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z", key: "k0" })
]); },
viewBox: '0 0 24 24',
height: function (props) { return (props.height !== undefined ? props.height : props.size); },
width: function (props) { return (props.width !== undefined ? props.width : props.size); },
// @ts-ignore - aria is not always defined on SVG in React TypeScript types
'aria-hidden': function (props) { return (props.title == null ? 'true' : undefined); },
focusable: 'false',
role: function (props) { return (props.title != null ? 'img' : undefined); },
"fill": "currentColor",
})(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n display: inline-block;\n vertical-align: middle;\n overflow: hidden;\n"], ["\n display: inline-block;\n vertical-align: middle;\n overflow: hidden;\n"])));
RemoveCircle.displayName = 'RemoveCircle';
export var RemoveCircleDimensions = { height: 24, width: 24 };
var templateObject_1;
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* This sample demonstrates how to get started by creating a data feed, checking ingestion status,
* creating detection and alerting configurations, and querying for alerts and anomalies.
*/
// Load the .env file if it exists
require("dotenv").config();
const {
MetricsAdvisorKeyCredential,
MetricsAdvisorClient,
MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");
async function main() {
// You will need to set these environment variables or edit the following values
const endpoint = process.env["METRICS_ADVISOR_ENDPOINT"] || "<service endpoint>";
const subscriptionKey = process.env["METRICS_ADVISOR_SUBSCRIPTION_KEY"] || "<subscription key>";
const apiKey = process.env["METRICS_ADVISOR_API_KEY"] || "<api key>";
const sqlServerConnectionString =
process.env["METRICS_ADVISOR_SQL_SERVER_CONNECTION_STRING"] ||
"<connection string to SQL Server>";
const sqlServerQuery =
process.env["METRICS_ADVISOR_AZURE_SQL_SERVER_QUERY"] || "<SQL Server query to retrive data>";
const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);
const client = new MetricsAdvisorClient(endpoint, credential);
const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);
const created = await createDataFeed(adminClient, sqlServerConnectionString, sqlServerQuery);
console.log(`Data feed created: ${created.id}`);
console.log(" metrics: ");
const datafeed = await adminClient.getDataFeed(created.id);
console.log(datafeed.schema.metrics);
console.log("Waiting for a minute before checking ingestion status...");
await delay(60 * 1000);
try {
await checkIngestionStatus(
adminClient,
created.id,
new Date(Date.UTC(2020, 8, 1)),
new Date(Date.UTC(2020, 8, 12))
);
const metricId = datafeed.schema.metrics[0].id;
const detectionConfig = await configureAnomalyDetectionConfiguration(adminClient, metricId);
console.log(`Detection configuration created: ${detectionConfig.id}`);
const hook = await createWebhookHook(adminClient);
console.log(`Webhook hook created: ${hook.id}`);
const alertConfig = await configureAlertConfiguration(adminClient, detectionConfig.id, [
hook.id
]);
console.log(`Alert configuration created: ${alertConfig.id}`);
// you can use alert configuration created in above step to query the alert.
const alerts = await queryAlerts(
client,
alertConfig.id,
new Date(Date.UTC(2020, 8, 1)),
new Date(Date.UTC(2020, 8, 12))
);
if (alerts.length > 1) {
// query anomalies using an alert id.
await queryAnomaliesByAlert(client, alerts[0]);
} else {
console.log("No alerts during the time period");
}
} finally {
console.log(`Deleting the data feed '${created.id}`);
await adminClient.deleteDataFeed(created.id);
}
}
async function createDataFeed(adminClient, sqlServerConnectionString, sqlServerQuery) {
console.log("Creating Datafeed...");
const dataFeed = {
name: "test_datafeed_" + new Date().getTime().toString(),
source: {
dataSourceType: "SqlServer",
dataSourceParameter: {
connectionString: sqlServerConnectionString,
query: sqlServerQuery
}
},
granularity: {
granularityType: "Daily"
},
schema: {
metrics: [
{
name: "revenue",
displayName: "revenue",
description: "Metric1 description"
},
{
name: "cost",
displayName: "cost",
description: "Metric2 description"
}
],
dimensions: [
{ name: "city", displayName: "city display" },
{ name: "category", displayName: "category display" }
],
timestampColumn: null
},
ingestionSettings: {
ingestionStartTime: new Date(Date.UTC(2020, 5, 1)),
ingestionStartOffsetInSeconds: 0,
dataSourceRequestConcurrency: -1,
ingestionRetryDelayInSeconds: -1,
stopRetryAfterInSeconds: -1
},
rollupSettings: {
rollupType: "AutoRollup",
rollupMethod: "Sum",
rollupIdentificationValue: "__SUM__"
},
missingDataPointFillSettings: {
fillType: "SmartFilling"
},
accessMode: "Private",
adminEmails: ["xyz@microsoft.com"]
};
const result = await adminClient.createDataFeed(dataFeed);
return result;
}
async function checkIngestionStatus(adminClient, datafeedId, startTime, endTime) {
// This shows how to use for-await-of syntax to list status
console.log("Checking ingestion status...");
const listIterator = adminClient.listDataFeedIngestionStatus(datafeedId, startTime, endTime);
for await (const status of listIterator) {
console.log(` [${status.timestamp}] ${status.status} - ${status.message}`);
}
}
async function configureAnomalyDetectionConfiguration(adminClient, metricId) {
console.log(`Creating an anomaly detection configuration on metric '${metricId}'...`);
const dataFeed = {
name: "test_detection_configuration" + new Date().getTime().toString(),
metricId,
wholeSeriesDetectionCondition: {
smartDetectionCondition: {
sensitivity: 100,
anomalyDetectorDirection: "Both",
suppressCondition: {
minNumber: 1,
minRatio: 1
}
}
},
description: "Detection configuration description"
};
return await adminClient.createDetectionConfig(dataFeed);
}
async function createWebhookHook(adminClient) {
console.log("Creating a webhook hook");
const hook = {
hookType: "Webhook",
name: "web hook " + new Date().getTime().toString(),
description: "description",
hookParameter: {
endpoint: "https://httpbin.org/post",
username: "user",
password: "pass"
// certificateKey: "k",
// certificatePassword: "kp"
}
};
return await adminClient.createHook(hook);
}
async function configureAlertConfiguration(adminClient, detectionConfigId, hookIds) {
console.log("Creating a new alerting configuration...");
const anomalyAlert = {
name: "test_alert_config_" + new Date().getTime().toString(),
crossMetricsOperator: "AND",
metricAlertConfigurations: [
{
detectionConfigurationId: detectionConfigId,
alertScope: {
scopeType: "All"
},
alertConditions: {
severityCondition: {
minAlertSeverity: "Medium",
maxAlertSeverity: "High"
}
},
snoozeCondition: {
autoSnooze: 0,
snoozeScope: "Metric",
onlyForSuccessive: true
}
}
],
hookIds,
description: "Alerting config description"
};
return await adminClient.createAlertConfig(anomalyAlert);
}
async function queryAlerts(client, alertConfigId, startTime, endTime) {
console.log(`Listing alerts for alert configuration '${alertConfigId}'`);
// This shows how to use `for-await-of` syntax to list alerts
console.log(" using for-await-of syntax");
let alerts = [];
const listIterator = client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime");
for await (const alert of listIterator) {
alerts.push(alert);
console.log(" Alert");
console.log(` id: ${alert.id}`);
console.log(` timestamp: ${alert.timestamp}`);
console.log(` created on: ${alert.createdOn}`);
}
// alternatively we could list results by pages
console.log(` by pages`);
const iterator = client
.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime")
.byPage({ maxPageSize: 2 });
let result = await iterator.next();
while (!result.done) {
console.log(" -- Page -- ");
console.table(result.value);
result = await iterator.next();
}
return alerts;
}
async function queryAnomaliesByAlert(client, alert) {
console.log(
`Listing anomalies for alert configuration '${alert.alertConfigId}' and alert '${alert.id}'`
);
const listIterator = client.listAnomalies(alert);
for await (const anomaly of listIterator) {
console.log(
` Anomaly ${anomaly.severity} ${anomaly.status} ${anomaly.seriesKey.dimension} ${anomaly.timestamp}`
);
}
}
async function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
main()
.then((_) => {
console.log("Succeeded");
})
.catch((err) => {
console.log("Error occurred:");
console.log(err);
});
|
""" 程序主入口 """
from ui import ui_fun
from PyQt5.QtGui import QMovie
from face_detection.test import face
import sys
import pyttsx3
import time
app = ui_fun.QtWidgets.QApplication(sys.argv)
window = ui_fun.mywindow()
window.show()
engine = pyttsx3.init()
while True:
if face():
engine.say('你好 点击侧面按钮即可提问')
engine.runAndWait()
window.gif = QMovie('ui/hello.gif')
window.ui.label.setMovie(window.gif)
window.gif.start()
time.sleep(5)
window.gif = QMovie('ui/normal.gif')
window.ui.label.setMovie(window.gif)
window.gif.start()
break
sys.exit(app.exec_())
|
import styled from "styled-components";
import { prop } from "styled-tools";
import as from "../../enhancers/as";
import Base from "../Base";
const TableCaption = styled(Base)`
display: table-caption;
text-transform: uppercase;
font-size: 0.9em;
color: #999;
${prop("theme.TableCaption")};
`;
export default as("caption")(TableCaption);
|
// Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// DESCRIPTION:
// All the global variables that store the internal state.
// Theoretically speaking, the internal state of the engine
// should be found by looking at the variables collected
// here, and every relevant module will have to include
// this header file.
// In practice, things are a bit messy.
//
//-----------------------------------------------------------------------------
#ifndef __D_STATE__
#define __D_STATE__
// We need globally shared data structures,
// for defining the global state variables.
#include "doomdata.h"
#include "d_net.h"
// We need the playr data structure as well.
#include "d_player.h"
#ifdef __GNUG__
#pragma interface
#endif
// ------------------------
// Command line parameters.
//
extern boolean nomonsters; // checkparm of -nomonsters
extern boolean respawnparm; // checkparm of -respawn
extern boolean fastparm; // checkparm of -fast
extern boolean devparm; // DEBUG: launched with -devparm
// -----------------------------------------------------
// Game Mode - identify IWAD as shareware, retail etc.
//
extern GameMode_t gamemode;
extern GameMission_t gamemission;
// Set if homebrew PWAD stuff has been added.
extern boolean modifiedgame;
// -------------------------------------------
// Language.
extern Language_t language;
// -------------------------------------------
// Selected skill type, map etc.
//
// Defaults for menu, methinks.
extern skill_t startskill;
extern int startepisode;
extern int startmap;
extern boolean autostart;
// Selected by user.
extern skill_t gameskill;
extern int gameepisode;
extern int gamemap;
// Nightmare mode flag, single player.
extern boolean respawnmonsters;
// Netgame? Only true if >1 player.
extern boolean netgame;
// Flag: true only if started as net deathmatch.
// An enum might handle altdeath/cooperative better.
extern boolean deathmatch;
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// These are not used, but should be (menu).
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
extern int snd_SfxVolume; // maximum volume for sound
extern int snd_MusicVolume; // maximum volume for music
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
extern int snd_MusicDevice;
extern int snd_SfxDevice;
// Config file? Same disclaimer as above.
extern int snd_DesiredMusicDevice;
extern int snd_DesiredSfxDevice;
// -------------------------
// Status flags for refresh.
//
// Depending on view size - no status bar?
// Note that there is no way to disable the
// status bar explicitely.
extern boolean statusbaractive;
extern boolean automapactive; // In AutoMap mode?
extern boolean menuactive; // Menu overlayed?
extern boolean paused; // Game Pause?
extern boolean viewactive;
extern boolean nodrawers;
extern boolean noblit;
extern int viewwindowx;
extern int viewwindowy;
extern int viewheight;
extern int viewwidth;
extern int scaledviewwidth;
// This one is related to the 3-screen display mode.
// ANG90 = left side, ANG270 = right
extern int viewangleoffset;
// Player taking events, and displaying.
extern int consoleplayer;
extern int displayplayer;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
extern int totalkills;
extern int totalitems;
extern int totalsecret;
// Timer, for scores.
extern int levelstarttic; // gametic at level start
extern int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
extern boolean usergame;
//?
extern boolean demoplayback;
extern boolean demorecording;
// Quit after playing a demo from cmdline.
extern boolean singledemo;
//?
extern gamestate_t gamestate;
//-----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
extern int gametic;
// Bookkeeping on players - state.
extern player_t players[MAXPLAYERS];
// Alive? Disconnected?
extern boolean playeringame[MAXPLAYERS];
// Player spawn spots for deathmatch.
#define MAX_DM_STARTS 10
extern mapthing_t deathmatchstarts[MAX_DM_STARTS];
extern mapthing_t* deathmatch_p;
// Player spawn spots.
extern mapthing_t playerstarts[MAXPLAYERS];
// Intermission stats.
// Parameters for world map / intermission.
extern wbstartstruct_t wminfo;
// LUT of ammunition limits for each kind.
// This doubles with BackPack powerup item.
extern int maxammo[NUMAMMO];
//-----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
extern char basedefault[1024];
extern FILE* debugfile;
// if true, load all graphics at level load
extern boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
extern gamestate_t wipegamestate;
extern int mouseSensitivity;
//?
// debug flag to cancel adaptiveness
extern boolean singletics;
extern int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
extern int skyflatnum;
// Netgame stuff (buffers and pointers, i.e. indices).
// This is ???
extern doomcom_t* doomcom;
// This points inside doomcom.
extern doomdata_t* netbuffer;
extern ticcmd_t localcmds[BACKUPTICS];
extern int rndindex;
extern int maketic;
extern int nettics[MAXNETNODES];
extern ticcmd_t netcmds[MAXPLAYERS][BACKUPTICS];
extern int ticdup;
#endif
//-----------------------------------------------------------------------------
//
// $Log:$
//
//-----------------------------------------------------------------------------
|
import csv
import json
from pathlib import Path
from urllib.request import urlopen
import yaml
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from indiaelections.settings import PROJECT_ROOT
WIKIPEDIA_LOKSABHA_CONSTITUENCIES_LIST_URL = "https://en.wikipedia.org/wiki/List_of_constituencies_of_the_Lok_Sabha"
DATA_DIR = Path(PROJECT_ROOT).parents[0] / "data"
STATES = 29
UNION_TERRITORIES = 7
STATES_AND_UNION_TERRITORIES = STATES + UNION_TERRITORIES
filename = "loksabha_constituencies_list.{}"
def write_json(data):
with open(DATA_DIR / filename.format("json"), "w") as jsonfile:
json.dump(data, jsonfile, indent=4)
def write_csv(data):
header = ["State/Union Territory", "Constituency Name"]
with open(DATA_DIR / filename.format("csv"), "w") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header)
writer.writerows([state_union, constituency] for state_union, constituencies in data.items()
for constituency in constituencies)
def write_yaml(data):
with open(DATA_DIR / filename.format("yaml"), "w") as yamlfile:
yaml.dump(data, yamlfile)
def write_output(data, output_format):
if output_format == "json":
write_json(data)
elif output_format == "csv":
write_csv(data)
elif output_format == "yaml":
write_yaml(data)
else:
print("Unsupported output format.")
class Command(BaseCommand):
help = "Scrape constituencies list from wikipedia and write them to a file."
def add_arguments(self, parser):
parser.add_argument("output_format", type=str)
def handle(self, *args, **kwargs):
output_format = kwargs.get("output_format", None)
data = urlopen(WIKIPEDIA_LOKSABHA_CONSTITUENCIES_LIST_URL).read()
soup = BeautifulSoup(data, features='html.parser')
table_rows = soup.find_all("tr")
# Get all table rows from the page
# the first table in the page contains list of states and their corresponding number of loksabha seats
# the rest of the tables contain loksabha constituencies list of
# first row of table (index 0) is header, skip that
# total 29 states and 7 union territories so from second row (index 1),
# iterate till 29 + 7 (add extra one to consider last one)
states_and_union_territories = table_rows[1:STATES_AND_UNION_TERRITORIES+1]
state_and_union_seat_count = dict()
for s in states_and_union_territories:
place, no_of_seats = s.text.strip().split("\n")
state_and_union_seat_count[place] = int(no_of_seats)
start = STATES_AND_UNION_TERRITORIES + 2 # skip first and second table header
data = dict()
for s, total_seats in state_and_union_seat_count.items():
end = start + total_seats
s_data = table_rows[start:end]
data[s] = list()
for d in s_data:
constituency_name, is_reserved = d.text.strip().split("\n")[1:]
data[s].append(constituency_name)
assert len(data[s]) == total_seats
start = end + 1
if output_format:
write_output(data, output_format)
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: IM.Buddy.proto
#ifndef PROTOBUF_IM_2eBuddy_2eproto__INCLUDED
#define PROTOBUF_IM_2eBuddy_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include "IM.BaseDefine.pb.h"
// @@protoc_insertion_point(includes)
namespace IM {
namespace Buddy {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_IM_2eBuddy_2eproto();
void protobuf_AssignDesc_IM_2eBuddy_2eproto();
void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
class IMRecentContactSessionReq;
class IMRecentContactSessionRsp;
class IMUserStatNotify;
class IMUsersInfoReq;
class IMUsersInfoRsp;
class IMRemoveSessionReq;
class IMRemoveSessionRsp;
class IMAllUserReq;
class IMAllUserRsp;
class IMUsersStatReq;
class IMUsersStatRsp;
class IMChangeAvatarReq;
class IMChangeAvatarRsp;
class IMPCLoginStatusNotify;
class IMRemoveSessionNotify;
class IMDepartmentReq;
class IMDepartmentRsp;
// ===================================================================
class IMRecentContactSessionReq : public ::google::protobuf::MessageLite {
public:
IMRecentContactSessionReq();
virtual ~IMRecentContactSessionReq();
IMRecentContactSessionReq(const IMRecentContactSessionReq& from);
inline IMRecentContactSessionReq& operator=(const IMRecentContactSessionReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMRecentContactSessionReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMRecentContactSessionReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMRecentContactSessionReq* other);
// implements Message ----------------------------------------------
IMRecentContactSessionReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMRecentContactSessionReq& from);
void MergeFrom(const IMRecentContactSessionReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 latest_update_time = 2;
inline bool has_latest_update_time() const;
inline void clear_latest_update_time();
static const int kLatestUpdateTimeFieldNumber = 2;
inline ::google::protobuf::uint32 latest_update_time() const;
inline void set_latest_update_time(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMRecentContactSessionReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_latest_update_time();
inline void clear_has_latest_update_time();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 latest_update_time_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMRecentContactSessionReq* default_instance_;
};
// -------------------------------------------------------------------
class IMRecentContactSessionRsp : public ::google::protobuf::MessageLite {
public:
IMRecentContactSessionRsp();
virtual ~IMRecentContactSessionRsp();
IMRecentContactSessionRsp(const IMRecentContactSessionRsp& from);
inline IMRecentContactSessionRsp& operator=(const IMRecentContactSessionRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMRecentContactSessionRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMRecentContactSessionRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMRecentContactSessionRsp* other);
// implements Message ----------------------------------------------
IMRecentContactSessionRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMRecentContactSessionRsp& from);
void MergeFrom(const IMRecentContactSessionRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// repeated .IM.BaseDefine.ContactSessionInfo contact_session_list = 2;
inline int contact_session_list_size() const;
inline void clear_contact_session_list();
static const int kContactSessionListFieldNumber = 2;
inline const ::IM::BaseDefine::ContactSessionInfo& contact_session_list(int index) const;
inline ::IM::BaseDefine::ContactSessionInfo* mutable_contact_session_list(int index);
inline ::IM::BaseDefine::ContactSessionInfo* add_contact_session_list();
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::ContactSessionInfo >&
contact_session_list() const;
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::ContactSessionInfo >*
mutable_contact_session_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMRecentContactSessionRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::ContactSessionInfo > contact_session_list_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMRecentContactSessionRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMUserStatNotify : public ::google::protobuf::MessageLite {
public:
IMUserStatNotify();
virtual ~IMUserStatNotify();
IMUserStatNotify(const IMUserStatNotify& from);
inline IMUserStatNotify& operator=(const IMUserStatNotify& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMUserStatNotify& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMUserStatNotify* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMUserStatNotify* other);
// implements Message ----------------------------------------------
IMUserStatNotify* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMUserStatNotify& from);
void MergeFrom(const IMUserStatNotify& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required .IM.BaseDefine.UserStat user_stat = 1;
inline bool has_user_stat() const;
inline void clear_user_stat();
static const int kUserStatFieldNumber = 1;
inline const ::IM::BaseDefine::UserStat& user_stat() const;
inline ::IM::BaseDefine::UserStat* mutable_user_stat();
inline ::IM::BaseDefine::UserStat* release_user_stat();
inline void set_allocated_user_stat(::IM::BaseDefine::UserStat* user_stat);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMUserStatNotify)
private:
inline void set_has_user_stat();
inline void clear_has_user_stat();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::IM::BaseDefine::UserStat* user_stat_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMUserStatNotify* default_instance_;
};
// -------------------------------------------------------------------
class IMUsersInfoReq : public ::google::protobuf::MessageLite {
public:
IMUsersInfoReq();
virtual ~IMUsersInfoReq();
IMUsersInfoReq(const IMUsersInfoReq& from);
inline IMUsersInfoReq& operator=(const IMUsersInfoReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMUsersInfoReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMUsersInfoReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMUsersInfoReq* other);
// implements Message ----------------------------------------------
IMUsersInfoReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMUsersInfoReq& from);
void MergeFrom(const IMUsersInfoReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// repeated uint32 user_id_list = 2;
inline int user_id_list_size() const;
inline void clear_user_id_list();
static const int kUserIdListFieldNumber = 2;
inline ::google::protobuf::uint32 user_id_list(int index) const;
inline void set_user_id_list(int index, ::google::protobuf::uint32 value);
inline void add_user_id_list(::google::protobuf::uint32 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >&
user_id_list() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >*
mutable_user_id_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMUsersInfoReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::uint32 > user_id_list_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMUsersInfoReq* default_instance_;
};
// -------------------------------------------------------------------
class IMUsersInfoRsp : public ::google::protobuf::MessageLite {
public:
IMUsersInfoRsp();
virtual ~IMUsersInfoRsp();
IMUsersInfoRsp(const IMUsersInfoRsp& from);
inline IMUsersInfoRsp& operator=(const IMUsersInfoRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMUsersInfoRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMUsersInfoRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMUsersInfoRsp* other);
// implements Message ----------------------------------------------
IMUsersInfoRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMUsersInfoRsp& from);
void MergeFrom(const IMUsersInfoRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// repeated .IM.BaseDefine.UserInfo user_info_list = 2;
inline int user_info_list_size() const;
inline void clear_user_info_list();
static const int kUserInfoListFieldNumber = 2;
inline const ::IM::BaseDefine::UserInfo& user_info_list(int index) const;
inline ::IM::BaseDefine::UserInfo* mutable_user_info_list(int index);
inline ::IM::BaseDefine::UserInfo* add_user_info_list();
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >&
user_info_list() const;
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >*
mutable_user_info_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMUsersInfoRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo > user_info_list_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMUsersInfoRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMRemoveSessionReq : public ::google::protobuf::MessageLite {
public:
IMRemoveSessionReq();
virtual ~IMRemoveSessionReq();
IMRemoveSessionReq(const IMRemoveSessionReq& from);
inline IMRemoveSessionReq& operator=(const IMRemoveSessionReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMRemoveSessionReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMRemoveSessionReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMRemoveSessionReq* other);
// implements Message ----------------------------------------------
IMRemoveSessionReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMRemoveSessionReq& from);
void MergeFrom(const IMRemoveSessionReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required .IM.BaseDefine.SessionType session_type = 2;
inline bool has_session_type() const;
inline void clear_session_type();
static const int kSessionTypeFieldNumber = 2;
inline ::IM::BaseDefine::SessionType session_type() const;
inline void set_session_type(::IM::BaseDefine::SessionType value);
// required uint32 session_id = 3;
inline bool has_session_id() const;
inline void clear_session_id();
static const int kSessionIdFieldNumber = 3;
inline ::google::protobuf::uint32 session_id() const;
inline void set_session_id(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMRemoveSessionReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_session_type();
inline void clear_has_session_type();
inline void set_has_session_id();
inline void clear_has_session_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
int session_type_;
::std::string* attach_data_;
::google::protobuf::uint32 session_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMRemoveSessionReq* default_instance_;
};
// -------------------------------------------------------------------
class IMRemoveSessionRsp : public ::google::protobuf::MessageLite {
public:
IMRemoveSessionRsp();
virtual ~IMRemoveSessionRsp();
IMRemoveSessionRsp(const IMRemoveSessionRsp& from);
inline IMRemoveSessionRsp& operator=(const IMRemoveSessionRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMRemoveSessionRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMRemoveSessionRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMRemoveSessionRsp* other);
// implements Message ----------------------------------------------
IMRemoveSessionRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMRemoveSessionRsp& from);
void MergeFrom(const IMRemoveSessionRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 result_code = 2;
inline bool has_result_code() const;
inline void clear_result_code();
static const int kResultCodeFieldNumber = 2;
inline ::google::protobuf::uint32 result_code() const;
inline void set_result_code(::google::protobuf::uint32 value);
// required .IM.BaseDefine.SessionType session_type = 3;
inline bool has_session_type() const;
inline void clear_session_type();
static const int kSessionTypeFieldNumber = 3;
inline ::IM::BaseDefine::SessionType session_type() const;
inline void set_session_type(::IM::BaseDefine::SessionType value);
// required uint32 session_id = 4;
inline bool has_session_id() const;
inline void clear_session_id();
static const int kSessionIdFieldNumber = 4;
inline ::google::protobuf::uint32 session_id() const;
inline void set_session_id(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMRemoveSessionRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_result_code();
inline void clear_has_result_code();
inline void set_has_session_type();
inline void clear_has_session_type();
inline void set_has_session_id();
inline void clear_has_session_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 result_code_;
int session_type_;
::google::protobuf::uint32 session_id_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMRemoveSessionRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMAllUserReq : public ::google::protobuf::MessageLite {
public:
IMAllUserReq();
virtual ~IMAllUserReq();
IMAllUserReq(const IMAllUserReq& from);
inline IMAllUserReq& operator=(const IMAllUserReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMAllUserReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMAllUserReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMAllUserReq* other);
// implements Message ----------------------------------------------
IMAllUserReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMAllUserReq& from);
void MergeFrom(const IMAllUserReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 latest_update_time = 2;
inline bool has_latest_update_time() const;
inline void clear_latest_update_time();
static const int kLatestUpdateTimeFieldNumber = 2;
inline ::google::protobuf::uint32 latest_update_time() const;
inline void set_latest_update_time(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMAllUserReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_latest_update_time();
inline void clear_has_latest_update_time();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 latest_update_time_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMAllUserReq* default_instance_;
};
// -------------------------------------------------------------------
class IMAllUserRsp : public ::google::protobuf::MessageLite {
public:
IMAllUserRsp();
virtual ~IMAllUserRsp();
IMAllUserRsp(const IMAllUserRsp& from);
inline IMAllUserRsp& operator=(const IMAllUserRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMAllUserRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMAllUserRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMAllUserRsp* other);
// implements Message ----------------------------------------------
IMAllUserRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMAllUserRsp& from);
void MergeFrom(const IMAllUserRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 latest_update_time = 2;
inline bool has_latest_update_time() const;
inline void clear_latest_update_time();
static const int kLatestUpdateTimeFieldNumber = 2;
inline ::google::protobuf::uint32 latest_update_time() const;
inline void set_latest_update_time(::google::protobuf::uint32 value);
// repeated .IM.BaseDefine.UserInfo user_list = 3;
inline int user_list_size() const;
inline void clear_user_list();
static const int kUserListFieldNumber = 3;
inline const ::IM::BaseDefine::UserInfo& user_list(int index) const;
inline ::IM::BaseDefine::UserInfo* mutable_user_list(int index);
inline ::IM::BaseDefine::UserInfo* add_user_list();
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >&
user_list() const;
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >*
mutable_user_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMAllUserRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_latest_update_time();
inline void clear_has_latest_update_time();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 latest_update_time_;
::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo > user_list_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMAllUserRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMUsersStatReq : public ::google::protobuf::MessageLite {
public:
IMUsersStatReq();
virtual ~IMUsersStatReq();
IMUsersStatReq(const IMUsersStatReq& from);
inline IMUsersStatReq& operator=(const IMUsersStatReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMUsersStatReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMUsersStatReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMUsersStatReq* other);
// implements Message ----------------------------------------------
IMUsersStatReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMUsersStatReq& from);
void MergeFrom(const IMUsersStatReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// repeated uint32 user_id_list = 2;
inline int user_id_list_size() const;
inline void clear_user_id_list();
static const int kUserIdListFieldNumber = 2;
inline ::google::protobuf::uint32 user_id_list(int index) const;
inline void set_user_id_list(int index, ::google::protobuf::uint32 value);
inline void add_user_id_list(::google::protobuf::uint32 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >&
user_id_list() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >*
mutable_user_id_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMUsersStatReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::uint32 > user_id_list_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMUsersStatReq* default_instance_;
};
// -------------------------------------------------------------------
class IMUsersStatRsp : public ::google::protobuf::MessageLite {
public:
IMUsersStatRsp();
virtual ~IMUsersStatRsp();
IMUsersStatRsp(const IMUsersStatRsp& from);
inline IMUsersStatRsp& operator=(const IMUsersStatRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMUsersStatRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMUsersStatRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMUsersStatRsp* other);
// implements Message ----------------------------------------------
IMUsersStatRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMUsersStatRsp& from);
void MergeFrom(const IMUsersStatRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// repeated .IM.BaseDefine.UserStat user_stat_list = 2;
inline int user_stat_list_size() const;
inline void clear_user_stat_list();
static const int kUserStatListFieldNumber = 2;
inline const ::IM::BaseDefine::UserStat& user_stat_list(int index) const;
inline ::IM::BaseDefine::UserStat* mutable_user_stat_list(int index);
inline ::IM::BaseDefine::UserStat* add_user_stat_list();
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserStat >&
user_stat_list() const;
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserStat >*
mutable_user_stat_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMUsersStatRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserStat > user_stat_list_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMUsersStatRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMChangeAvatarReq : public ::google::protobuf::MessageLite {
public:
IMChangeAvatarReq();
virtual ~IMChangeAvatarReq();
IMChangeAvatarReq(const IMChangeAvatarReq& from);
inline IMChangeAvatarReq& operator=(const IMChangeAvatarReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMChangeAvatarReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMChangeAvatarReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMChangeAvatarReq* other);
// implements Message ----------------------------------------------
IMChangeAvatarReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMChangeAvatarReq& from);
void MergeFrom(const IMChangeAvatarReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required string avatar_url = 2;
inline bool has_avatar_url() const;
inline void clear_avatar_url();
static const int kAvatarUrlFieldNumber = 2;
inline const ::std::string& avatar_url() const;
inline void set_avatar_url(const ::std::string& value);
inline void set_avatar_url(const char* value);
inline void set_avatar_url(const char* value, size_t size);
inline ::std::string* mutable_avatar_url();
inline ::std::string* release_avatar_url();
inline void set_allocated_avatar_url(::std::string* avatar_url);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMChangeAvatarReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_avatar_url();
inline void clear_has_avatar_url();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::std::string* avatar_url_;
::std::string* attach_data_;
::google::protobuf::uint32 user_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMChangeAvatarReq* default_instance_;
};
// -------------------------------------------------------------------
class IMChangeAvatarRsp : public ::google::protobuf::MessageLite {
public:
IMChangeAvatarRsp();
virtual ~IMChangeAvatarRsp();
IMChangeAvatarRsp(const IMChangeAvatarRsp& from);
inline IMChangeAvatarRsp& operator=(const IMChangeAvatarRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMChangeAvatarRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMChangeAvatarRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMChangeAvatarRsp* other);
// implements Message ----------------------------------------------
IMChangeAvatarRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMChangeAvatarRsp& from);
void MergeFrom(const IMChangeAvatarRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 result_code = 2;
inline bool has_result_code() const;
inline void clear_result_code();
static const int kResultCodeFieldNumber = 2;
inline ::google::protobuf::uint32 result_code() const;
inline void set_result_code(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMChangeAvatarRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_result_code();
inline void clear_has_result_code();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 result_code_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMChangeAvatarRsp* default_instance_;
};
// -------------------------------------------------------------------
class IMPCLoginStatusNotify : public ::google::protobuf::MessageLite {
public:
IMPCLoginStatusNotify();
virtual ~IMPCLoginStatusNotify();
IMPCLoginStatusNotify(const IMPCLoginStatusNotify& from);
inline IMPCLoginStatusNotify& operator=(const IMPCLoginStatusNotify& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMPCLoginStatusNotify& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMPCLoginStatusNotify* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMPCLoginStatusNotify* other);
// implements Message ----------------------------------------------
IMPCLoginStatusNotify* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMPCLoginStatusNotify& from);
void MergeFrom(const IMPCLoginStatusNotify& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required .IM.BaseDefine.UserStatType login_stat = 2;
inline bool has_login_stat() const;
inline void clear_login_stat();
static const int kLoginStatFieldNumber = 2;
inline ::IM::BaseDefine::UserStatType login_stat() const;
inline void set_login_stat(::IM::BaseDefine::UserStatType value);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMPCLoginStatusNotify)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_login_stat();
inline void clear_has_login_stat();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
int login_stat_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMPCLoginStatusNotify* default_instance_;
};
// -------------------------------------------------------------------
class IMRemoveSessionNotify : public ::google::protobuf::MessageLite {
public:
IMRemoveSessionNotify();
virtual ~IMRemoveSessionNotify();
IMRemoveSessionNotify(const IMRemoveSessionNotify& from);
inline IMRemoveSessionNotify& operator=(const IMRemoveSessionNotify& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMRemoveSessionNotify& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMRemoveSessionNotify* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMRemoveSessionNotify* other);
// implements Message ----------------------------------------------
IMRemoveSessionNotify* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMRemoveSessionNotify& from);
void MergeFrom(const IMRemoveSessionNotify& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required .IM.BaseDefine.SessionType session_type = 2;
inline bool has_session_type() const;
inline void clear_session_type();
static const int kSessionTypeFieldNumber = 2;
inline ::IM::BaseDefine::SessionType session_type() const;
inline void set_session_type(::IM::BaseDefine::SessionType value);
// required uint32 session_id = 3;
inline bool has_session_id() const;
inline void clear_session_id();
static const int kSessionIdFieldNumber = 3;
inline ::google::protobuf::uint32 session_id() const;
inline void set_session_id(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMRemoveSessionNotify)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_session_type();
inline void clear_has_session_type();
inline void set_has_session_id();
inline void clear_has_session_id();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
int session_type_;
::google::protobuf::uint32 session_id_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMRemoveSessionNotify* default_instance_;
};
// -------------------------------------------------------------------
class IMDepartmentReq : public ::google::protobuf::MessageLite {
public:
IMDepartmentReq();
virtual ~IMDepartmentReq();
IMDepartmentReq(const IMDepartmentReq& from);
inline IMDepartmentReq& operator=(const IMDepartmentReq& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMDepartmentReq& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMDepartmentReq* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMDepartmentReq* other);
// implements Message ----------------------------------------------
IMDepartmentReq* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMDepartmentReq& from);
void MergeFrom(const IMDepartmentReq& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 latest_update_time = 2;
inline bool has_latest_update_time() const;
inline void clear_latest_update_time();
static const int kLatestUpdateTimeFieldNumber = 2;
inline ::google::protobuf::uint32 latest_update_time() const;
inline void set_latest_update_time(::google::protobuf::uint32 value);
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMDepartmentReq)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_latest_update_time();
inline void clear_has_latest_update_time();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 latest_update_time_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMDepartmentReq* default_instance_;
};
// -------------------------------------------------------------------
class IMDepartmentRsp : public ::google::protobuf::MessageLite {
public:
IMDepartmentRsp();
virtual ~IMDepartmentRsp();
IMDepartmentRsp(const IMDepartmentRsp& from);
inline IMDepartmentRsp& operator=(const IMDepartmentRsp& from) {
CopyFrom(from);
return *this;
}
inline const ::std::string& unknown_fields() const {
return _unknown_fields_;
}
inline ::std::string* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const IMDepartmentRsp& default_instance();
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Returns the internal default instance pointer. This function can
// return NULL thus should not be used by the user. This is intended
// for Protobuf internal code. Please use default_instance() declared
// above instead.
static inline const IMDepartmentRsp* internal_default_instance() {
return default_instance_;
}
#endif
void Swap(IMDepartmentRsp* other);
// implements Message ----------------------------------------------
IMDepartmentRsp* New() const;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
void CopyFrom(const IMDepartmentRsp& from);
void MergeFrom(const IMDepartmentRsp& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
void DiscardUnknownFields();
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::std::string GetTypeName() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint32 user_id = 1;
inline bool has_user_id() const;
inline void clear_user_id();
static const int kUserIdFieldNumber = 1;
inline ::google::protobuf::uint32 user_id() const;
inline void set_user_id(::google::protobuf::uint32 value);
// required uint32 latest_update_time = 2;
inline bool has_latest_update_time() const;
inline void clear_latest_update_time();
static const int kLatestUpdateTimeFieldNumber = 2;
inline ::google::protobuf::uint32 latest_update_time() const;
inline void set_latest_update_time(::google::protobuf::uint32 value);
// repeated .IM.BaseDefine.DepartInfo dept_list = 3;
inline int dept_list_size() const;
inline void clear_dept_list();
static const int kDeptListFieldNumber = 3;
inline const ::IM::BaseDefine::DepartInfo& dept_list(int index) const;
inline ::IM::BaseDefine::DepartInfo* mutable_dept_list(int index);
inline ::IM::BaseDefine::DepartInfo* add_dept_list();
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::DepartInfo >&
dept_list() const;
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::DepartInfo >*
mutable_dept_list();
// optional bytes attach_data = 20;
inline bool has_attach_data() const;
inline void clear_attach_data();
static const int kAttachDataFieldNumber = 20;
inline const ::std::string& attach_data() const;
inline void set_attach_data(const ::std::string& value);
inline void set_attach_data(const char* value);
inline void set_attach_data(const void* value, size_t size);
inline ::std::string* mutable_attach_data();
inline ::std::string* release_attach_data();
inline void set_allocated_attach_data(::std::string* attach_data);
// @@protoc_insertion_point(class_scope:IM.Buddy.IMDepartmentRsp)
private:
inline void set_has_user_id();
inline void clear_has_user_id();
inline void set_has_latest_update_time();
inline void clear_has_latest_update_time();
inline void set_has_attach_data();
inline void clear_has_attach_data();
::std::string _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint32 user_id_;
::google::protobuf::uint32 latest_update_time_;
::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::DepartInfo > dept_list_;
::std::string* attach_data_;
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
friend void protobuf_AddDesc_IM_2eBuddy_2eproto_impl();
#else
friend void protobuf_AddDesc_IM_2eBuddy_2eproto();
#endif
friend void protobuf_AssignDesc_IM_2eBuddy_2eproto();
friend void protobuf_ShutdownFile_IM_2eBuddy_2eproto();
void InitAsDefaultInstance();
static IMDepartmentRsp* default_instance_;
};
// ===================================================================
// ===================================================================
// IMRecentContactSessionReq
// required uint32 user_id = 1;
inline bool IMRecentContactSessionReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMRecentContactSessionReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMRecentContactSessionReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMRecentContactSessionReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMRecentContactSessionReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionReq.user_id)
return user_id_;
}
inline void IMRecentContactSessionReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRecentContactSessionReq.user_id)
}
// required uint32 latest_update_time = 2;
inline bool IMRecentContactSessionReq::has_latest_update_time() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMRecentContactSessionReq::set_has_latest_update_time() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMRecentContactSessionReq::clear_has_latest_update_time() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMRecentContactSessionReq::clear_latest_update_time() {
latest_update_time_ = 0u;
clear_has_latest_update_time();
}
inline ::google::protobuf::uint32 IMRecentContactSessionReq::latest_update_time() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionReq.latest_update_time)
return latest_update_time_;
}
inline void IMRecentContactSessionReq::set_latest_update_time(::google::protobuf::uint32 value) {
set_has_latest_update_time();
latest_update_time_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRecentContactSessionReq.latest_update_time)
}
// optional bytes attach_data = 20;
inline bool IMRecentContactSessionReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMRecentContactSessionReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMRecentContactSessionReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMRecentContactSessionReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMRecentContactSessionReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionReq.attach_data)
return *attach_data_;
}
inline void IMRecentContactSessionReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMRecentContactSessionReq.attach_data)
}
inline void IMRecentContactSessionReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMRecentContactSessionReq.attach_data)
}
inline void IMRecentContactSessionReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMRecentContactSessionReq.attach_data)
}
inline ::std::string* IMRecentContactSessionReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMRecentContactSessionReq.attach_data)
return attach_data_;
}
inline ::std::string* IMRecentContactSessionReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMRecentContactSessionReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMRecentContactSessionReq.attach_data)
}
// -------------------------------------------------------------------
// IMRecentContactSessionRsp
// required uint32 user_id = 1;
inline bool IMRecentContactSessionRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMRecentContactSessionRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMRecentContactSessionRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMRecentContactSessionRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMRecentContactSessionRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionRsp.user_id)
return user_id_;
}
inline void IMRecentContactSessionRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRecentContactSessionRsp.user_id)
}
// repeated .IM.BaseDefine.ContactSessionInfo contact_session_list = 2;
inline int IMRecentContactSessionRsp::contact_session_list_size() const {
return contact_session_list_.size();
}
inline void IMRecentContactSessionRsp::clear_contact_session_list() {
contact_session_list_.Clear();
}
inline const ::IM::BaseDefine::ContactSessionInfo& IMRecentContactSessionRsp::contact_session_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionRsp.contact_session_list)
return contact_session_list_.Get(index);
}
inline ::IM::BaseDefine::ContactSessionInfo* IMRecentContactSessionRsp::mutable_contact_session_list(int index) {
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMRecentContactSessionRsp.contact_session_list)
return contact_session_list_.Mutable(index);
}
inline ::IM::BaseDefine::ContactSessionInfo* IMRecentContactSessionRsp::add_contact_session_list() {
// @@protoc_insertion_point(field_add:IM.Buddy.IMRecentContactSessionRsp.contact_session_list)
return contact_session_list_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::ContactSessionInfo >&
IMRecentContactSessionRsp::contact_session_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMRecentContactSessionRsp.contact_session_list)
return contact_session_list_;
}
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::ContactSessionInfo >*
IMRecentContactSessionRsp::mutable_contact_session_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMRecentContactSessionRsp.contact_session_list)
return &contact_session_list_;
}
// optional bytes attach_data = 20;
inline bool IMRecentContactSessionRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMRecentContactSessionRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMRecentContactSessionRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMRecentContactSessionRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMRecentContactSessionRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRecentContactSessionRsp.attach_data)
return *attach_data_;
}
inline void IMRecentContactSessionRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMRecentContactSessionRsp.attach_data)
}
inline void IMRecentContactSessionRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMRecentContactSessionRsp.attach_data)
}
inline void IMRecentContactSessionRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMRecentContactSessionRsp.attach_data)
}
inline ::std::string* IMRecentContactSessionRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMRecentContactSessionRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMRecentContactSessionRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMRecentContactSessionRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMRecentContactSessionRsp.attach_data)
}
// -------------------------------------------------------------------
// IMUserStatNotify
// required .IM.BaseDefine.UserStat user_stat = 1;
inline bool IMUserStatNotify::has_user_stat() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMUserStatNotify::set_has_user_stat() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMUserStatNotify::clear_has_user_stat() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMUserStatNotify::clear_user_stat() {
if (user_stat_ != NULL) user_stat_->::IM::BaseDefine::UserStat::Clear();
clear_has_user_stat();
}
inline const ::IM::BaseDefine::UserStat& IMUserStatNotify::user_stat() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUserStatNotify.user_stat)
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
return user_stat_ != NULL ? *user_stat_ : *default_instance().user_stat_;
#else
return user_stat_ != NULL ? *user_stat_ : *default_instance_->user_stat_;
#endif
}
inline ::IM::BaseDefine::UserStat* IMUserStatNotify::mutable_user_stat() {
set_has_user_stat();
if (user_stat_ == NULL) user_stat_ = new ::IM::BaseDefine::UserStat;
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUserStatNotify.user_stat)
return user_stat_;
}
inline ::IM::BaseDefine::UserStat* IMUserStatNotify::release_user_stat() {
clear_has_user_stat();
::IM::BaseDefine::UserStat* temp = user_stat_;
user_stat_ = NULL;
return temp;
}
inline void IMUserStatNotify::set_allocated_user_stat(::IM::BaseDefine::UserStat* user_stat) {
delete user_stat_;
user_stat_ = user_stat;
if (user_stat) {
set_has_user_stat();
} else {
clear_has_user_stat();
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMUserStatNotify.user_stat)
}
// -------------------------------------------------------------------
// IMUsersInfoReq
// required uint32 user_id = 1;
inline bool IMUsersInfoReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMUsersInfoReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMUsersInfoReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMUsersInfoReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMUsersInfoReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoReq.user_id)
return user_id_;
}
inline void IMUsersInfoReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersInfoReq.user_id)
}
// repeated uint32 user_id_list = 2;
inline int IMUsersInfoReq::user_id_list_size() const {
return user_id_list_.size();
}
inline void IMUsersInfoReq::clear_user_id_list() {
user_id_list_.Clear();
}
inline ::google::protobuf::uint32 IMUsersInfoReq::user_id_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoReq.user_id_list)
return user_id_list_.Get(index);
}
inline void IMUsersInfoReq::set_user_id_list(int index, ::google::protobuf::uint32 value) {
user_id_list_.Set(index, value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersInfoReq.user_id_list)
}
inline void IMUsersInfoReq::add_user_id_list(::google::protobuf::uint32 value) {
user_id_list_.Add(value);
// @@protoc_insertion_point(field_add:IM.Buddy.IMUsersInfoReq.user_id_list)
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >&
IMUsersInfoReq::user_id_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMUsersInfoReq.user_id_list)
return user_id_list_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >*
IMUsersInfoReq::mutable_user_id_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMUsersInfoReq.user_id_list)
return &user_id_list_;
}
// optional bytes attach_data = 20;
inline bool IMUsersInfoReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMUsersInfoReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMUsersInfoReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMUsersInfoReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMUsersInfoReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoReq.attach_data)
return *attach_data_;
}
inline void IMUsersInfoReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersInfoReq.attach_data)
}
inline void IMUsersInfoReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMUsersInfoReq.attach_data)
}
inline void IMUsersInfoReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMUsersInfoReq.attach_data)
}
inline ::std::string* IMUsersInfoReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersInfoReq.attach_data)
return attach_data_;
}
inline ::std::string* IMUsersInfoReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMUsersInfoReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMUsersInfoReq.attach_data)
}
// -------------------------------------------------------------------
// IMUsersInfoRsp
// required uint32 user_id = 1;
inline bool IMUsersInfoRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMUsersInfoRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMUsersInfoRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMUsersInfoRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMUsersInfoRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoRsp.user_id)
return user_id_;
}
inline void IMUsersInfoRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersInfoRsp.user_id)
}
// repeated .IM.BaseDefine.UserInfo user_info_list = 2;
inline int IMUsersInfoRsp::user_info_list_size() const {
return user_info_list_.size();
}
inline void IMUsersInfoRsp::clear_user_info_list() {
user_info_list_.Clear();
}
inline const ::IM::BaseDefine::UserInfo& IMUsersInfoRsp::user_info_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoRsp.user_info_list)
return user_info_list_.Get(index);
}
inline ::IM::BaseDefine::UserInfo* IMUsersInfoRsp::mutable_user_info_list(int index) {
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersInfoRsp.user_info_list)
return user_info_list_.Mutable(index);
}
inline ::IM::BaseDefine::UserInfo* IMUsersInfoRsp::add_user_info_list() {
// @@protoc_insertion_point(field_add:IM.Buddy.IMUsersInfoRsp.user_info_list)
return user_info_list_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >&
IMUsersInfoRsp::user_info_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMUsersInfoRsp.user_info_list)
return user_info_list_;
}
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >*
IMUsersInfoRsp::mutable_user_info_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMUsersInfoRsp.user_info_list)
return &user_info_list_;
}
// optional bytes attach_data = 20;
inline bool IMUsersInfoRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMUsersInfoRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMUsersInfoRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMUsersInfoRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMUsersInfoRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersInfoRsp.attach_data)
return *attach_data_;
}
inline void IMUsersInfoRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersInfoRsp.attach_data)
}
inline void IMUsersInfoRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMUsersInfoRsp.attach_data)
}
inline void IMUsersInfoRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMUsersInfoRsp.attach_data)
}
inline ::std::string* IMUsersInfoRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersInfoRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMUsersInfoRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMUsersInfoRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMUsersInfoRsp.attach_data)
}
// -------------------------------------------------------------------
// IMRemoveSessionReq
// required uint32 user_id = 1;
inline bool IMRemoveSessionReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMRemoveSessionReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMRemoveSessionReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMRemoveSessionReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionReq.user_id)
return user_id_;
}
inline void IMRemoveSessionReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionReq.user_id)
}
// required .IM.BaseDefine.SessionType session_type = 2;
inline bool IMRemoveSessionReq::has_session_type() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMRemoveSessionReq::set_has_session_type() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMRemoveSessionReq::clear_has_session_type() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMRemoveSessionReq::clear_session_type() {
session_type_ = 1;
clear_has_session_type();
}
inline ::IM::BaseDefine::SessionType IMRemoveSessionReq::session_type() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionReq.session_type)
return static_cast< ::IM::BaseDefine::SessionType >(session_type_);
}
inline void IMRemoveSessionReq::set_session_type(::IM::BaseDefine::SessionType value) {
assert(::IM::BaseDefine::SessionType_IsValid(value));
set_has_session_type();
session_type_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionReq.session_type)
}
// required uint32 session_id = 3;
inline bool IMRemoveSessionReq::has_session_id() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMRemoveSessionReq::set_has_session_id() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMRemoveSessionReq::clear_has_session_id() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMRemoveSessionReq::clear_session_id() {
session_id_ = 0u;
clear_has_session_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionReq::session_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionReq.session_id)
return session_id_;
}
inline void IMRemoveSessionReq::set_session_id(::google::protobuf::uint32 value) {
set_has_session_id();
session_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionReq.session_id)
}
// optional bytes attach_data = 20;
inline bool IMRemoveSessionReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void IMRemoveSessionReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000008u;
}
inline void IMRemoveSessionReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000008u;
}
inline void IMRemoveSessionReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMRemoveSessionReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionReq.attach_data)
return *attach_data_;
}
inline void IMRemoveSessionReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionReq.attach_data)
}
inline void IMRemoveSessionReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMRemoveSessionReq.attach_data)
}
inline void IMRemoveSessionReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMRemoveSessionReq.attach_data)
}
inline ::std::string* IMRemoveSessionReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMRemoveSessionReq.attach_data)
return attach_data_;
}
inline ::std::string* IMRemoveSessionReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMRemoveSessionReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMRemoveSessionReq.attach_data)
}
// -------------------------------------------------------------------
// IMRemoveSessionRsp
// required uint32 user_id = 1;
inline bool IMRemoveSessionRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMRemoveSessionRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMRemoveSessionRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMRemoveSessionRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionRsp.user_id)
return user_id_;
}
inline void IMRemoveSessionRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionRsp.user_id)
}
// required uint32 result_code = 2;
inline bool IMRemoveSessionRsp::has_result_code() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMRemoveSessionRsp::set_has_result_code() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMRemoveSessionRsp::clear_has_result_code() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMRemoveSessionRsp::clear_result_code() {
result_code_ = 0u;
clear_has_result_code();
}
inline ::google::protobuf::uint32 IMRemoveSessionRsp::result_code() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionRsp.result_code)
return result_code_;
}
inline void IMRemoveSessionRsp::set_result_code(::google::protobuf::uint32 value) {
set_has_result_code();
result_code_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionRsp.result_code)
}
// required .IM.BaseDefine.SessionType session_type = 3;
inline bool IMRemoveSessionRsp::has_session_type() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMRemoveSessionRsp::set_has_session_type() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMRemoveSessionRsp::clear_has_session_type() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMRemoveSessionRsp::clear_session_type() {
session_type_ = 1;
clear_has_session_type();
}
inline ::IM::BaseDefine::SessionType IMRemoveSessionRsp::session_type() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionRsp.session_type)
return static_cast< ::IM::BaseDefine::SessionType >(session_type_);
}
inline void IMRemoveSessionRsp::set_session_type(::IM::BaseDefine::SessionType value) {
assert(::IM::BaseDefine::SessionType_IsValid(value));
set_has_session_type();
session_type_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionRsp.session_type)
}
// required uint32 session_id = 4;
inline bool IMRemoveSessionRsp::has_session_id() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void IMRemoveSessionRsp::set_has_session_id() {
_has_bits_[0] |= 0x00000008u;
}
inline void IMRemoveSessionRsp::clear_has_session_id() {
_has_bits_[0] &= ~0x00000008u;
}
inline void IMRemoveSessionRsp::clear_session_id() {
session_id_ = 0u;
clear_has_session_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionRsp::session_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionRsp.session_id)
return session_id_;
}
inline void IMRemoveSessionRsp::set_session_id(::google::protobuf::uint32 value) {
set_has_session_id();
session_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionRsp.session_id)
}
// optional bytes attach_data = 20;
inline bool IMRemoveSessionRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void IMRemoveSessionRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000010u;
}
inline void IMRemoveSessionRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000010u;
}
inline void IMRemoveSessionRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMRemoveSessionRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionRsp.attach_data)
return *attach_data_;
}
inline void IMRemoveSessionRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionRsp.attach_data)
}
inline void IMRemoveSessionRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMRemoveSessionRsp.attach_data)
}
inline void IMRemoveSessionRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMRemoveSessionRsp.attach_data)
}
inline ::std::string* IMRemoveSessionRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMRemoveSessionRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMRemoveSessionRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMRemoveSessionRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMRemoveSessionRsp.attach_data)
}
// -------------------------------------------------------------------
// IMAllUserReq
// required uint32 user_id = 1;
inline bool IMAllUserReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMAllUserReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMAllUserReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMAllUserReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMAllUserReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserReq.user_id)
return user_id_;
}
inline void IMAllUserReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserReq.user_id)
}
// required uint32 latest_update_time = 2;
inline bool IMAllUserReq::has_latest_update_time() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMAllUserReq::set_has_latest_update_time() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMAllUserReq::clear_has_latest_update_time() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMAllUserReq::clear_latest_update_time() {
latest_update_time_ = 0u;
clear_has_latest_update_time();
}
inline ::google::protobuf::uint32 IMAllUserReq::latest_update_time() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserReq.latest_update_time)
return latest_update_time_;
}
inline void IMAllUserReq::set_latest_update_time(::google::protobuf::uint32 value) {
set_has_latest_update_time();
latest_update_time_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserReq.latest_update_time)
}
// optional bytes attach_data = 20;
inline bool IMAllUserReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMAllUserReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMAllUserReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMAllUserReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMAllUserReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserReq.attach_data)
return *attach_data_;
}
inline void IMAllUserReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserReq.attach_data)
}
inline void IMAllUserReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMAllUserReq.attach_data)
}
inline void IMAllUserReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMAllUserReq.attach_data)
}
inline ::std::string* IMAllUserReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMAllUserReq.attach_data)
return attach_data_;
}
inline ::std::string* IMAllUserReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMAllUserReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMAllUserReq.attach_data)
}
// -------------------------------------------------------------------
// IMAllUserRsp
// required uint32 user_id = 1;
inline bool IMAllUserRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMAllUserRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMAllUserRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMAllUserRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMAllUserRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserRsp.user_id)
return user_id_;
}
inline void IMAllUserRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserRsp.user_id)
}
// required uint32 latest_update_time = 2;
inline bool IMAllUserRsp::has_latest_update_time() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMAllUserRsp::set_has_latest_update_time() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMAllUserRsp::clear_has_latest_update_time() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMAllUserRsp::clear_latest_update_time() {
latest_update_time_ = 0u;
clear_has_latest_update_time();
}
inline ::google::protobuf::uint32 IMAllUserRsp::latest_update_time() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserRsp.latest_update_time)
return latest_update_time_;
}
inline void IMAllUserRsp::set_latest_update_time(::google::protobuf::uint32 value) {
set_has_latest_update_time();
latest_update_time_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserRsp.latest_update_time)
}
// repeated .IM.BaseDefine.UserInfo user_list = 3;
inline int IMAllUserRsp::user_list_size() const {
return user_list_.size();
}
inline void IMAllUserRsp::clear_user_list() {
user_list_.Clear();
}
inline const ::IM::BaseDefine::UserInfo& IMAllUserRsp::user_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserRsp.user_list)
return user_list_.Get(index);
}
inline ::IM::BaseDefine::UserInfo* IMAllUserRsp::mutable_user_list(int index) {
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMAllUserRsp.user_list)
return user_list_.Mutable(index);
}
inline ::IM::BaseDefine::UserInfo* IMAllUserRsp::add_user_list() {
// @@protoc_insertion_point(field_add:IM.Buddy.IMAllUserRsp.user_list)
return user_list_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >&
IMAllUserRsp::user_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMAllUserRsp.user_list)
return user_list_;
}
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserInfo >*
IMAllUserRsp::mutable_user_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMAllUserRsp.user_list)
return &user_list_;
}
// optional bytes attach_data = 20;
inline bool IMAllUserRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void IMAllUserRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000008u;
}
inline void IMAllUserRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000008u;
}
inline void IMAllUserRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMAllUserRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMAllUserRsp.attach_data)
return *attach_data_;
}
inline void IMAllUserRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMAllUserRsp.attach_data)
}
inline void IMAllUserRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMAllUserRsp.attach_data)
}
inline void IMAllUserRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMAllUserRsp.attach_data)
}
inline ::std::string* IMAllUserRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMAllUserRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMAllUserRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMAllUserRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMAllUserRsp.attach_data)
}
// -------------------------------------------------------------------
// IMUsersStatReq
// required uint32 user_id = 1;
inline bool IMUsersStatReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMUsersStatReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMUsersStatReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMUsersStatReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMUsersStatReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatReq.user_id)
return user_id_;
}
inline void IMUsersStatReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersStatReq.user_id)
}
// repeated uint32 user_id_list = 2;
inline int IMUsersStatReq::user_id_list_size() const {
return user_id_list_.size();
}
inline void IMUsersStatReq::clear_user_id_list() {
user_id_list_.Clear();
}
inline ::google::protobuf::uint32 IMUsersStatReq::user_id_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatReq.user_id_list)
return user_id_list_.Get(index);
}
inline void IMUsersStatReq::set_user_id_list(int index, ::google::protobuf::uint32 value) {
user_id_list_.Set(index, value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersStatReq.user_id_list)
}
inline void IMUsersStatReq::add_user_id_list(::google::protobuf::uint32 value) {
user_id_list_.Add(value);
// @@protoc_insertion_point(field_add:IM.Buddy.IMUsersStatReq.user_id_list)
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >&
IMUsersStatReq::user_id_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMUsersStatReq.user_id_list)
return user_id_list_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >*
IMUsersStatReq::mutable_user_id_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMUsersStatReq.user_id_list)
return &user_id_list_;
}
// optional bytes attach_data = 20;
inline bool IMUsersStatReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMUsersStatReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMUsersStatReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMUsersStatReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMUsersStatReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatReq.attach_data)
return *attach_data_;
}
inline void IMUsersStatReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersStatReq.attach_data)
}
inline void IMUsersStatReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMUsersStatReq.attach_data)
}
inline void IMUsersStatReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMUsersStatReq.attach_data)
}
inline ::std::string* IMUsersStatReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersStatReq.attach_data)
return attach_data_;
}
inline ::std::string* IMUsersStatReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMUsersStatReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMUsersStatReq.attach_data)
}
// -------------------------------------------------------------------
// IMUsersStatRsp
// required uint32 user_id = 1;
inline bool IMUsersStatRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMUsersStatRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMUsersStatRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMUsersStatRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMUsersStatRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatRsp.user_id)
return user_id_;
}
inline void IMUsersStatRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersStatRsp.user_id)
}
// repeated .IM.BaseDefine.UserStat user_stat_list = 2;
inline int IMUsersStatRsp::user_stat_list_size() const {
return user_stat_list_.size();
}
inline void IMUsersStatRsp::clear_user_stat_list() {
user_stat_list_.Clear();
}
inline const ::IM::BaseDefine::UserStat& IMUsersStatRsp::user_stat_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatRsp.user_stat_list)
return user_stat_list_.Get(index);
}
inline ::IM::BaseDefine::UserStat* IMUsersStatRsp::mutable_user_stat_list(int index) {
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersStatRsp.user_stat_list)
return user_stat_list_.Mutable(index);
}
inline ::IM::BaseDefine::UserStat* IMUsersStatRsp::add_user_stat_list() {
// @@protoc_insertion_point(field_add:IM.Buddy.IMUsersStatRsp.user_stat_list)
return user_stat_list_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserStat >&
IMUsersStatRsp::user_stat_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMUsersStatRsp.user_stat_list)
return user_stat_list_;
}
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::UserStat >*
IMUsersStatRsp::mutable_user_stat_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMUsersStatRsp.user_stat_list)
return &user_stat_list_;
}
// optional bytes attach_data = 20;
inline bool IMUsersStatRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMUsersStatRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMUsersStatRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMUsersStatRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMUsersStatRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMUsersStatRsp.attach_data)
return *attach_data_;
}
inline void IMUsersStatRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMUsersStatRsp.attach_data)
}
inline void IMUsersStatRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMUsersStatRsp.attach_data)
}
inline void IMUsersStatRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMUsersStatRsp.attach_data)
}
inline ::std::string* IMUsersStatRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMUsersStatRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMUsersStatRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMUsersStatRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMUsersStatRsp.attach_data)
}
// -------------------------------------------------------------------
// IMChangeAvatarReq
// required uint32 user_id = 1;
inline bool IMChangeAvatarReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMChangeAvatarReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMChangeAvatarReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMChangeAvatarReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMChangeAvatarReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarReq.user_id)
return user_id_;
}
inline void IMChangeAvatarReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarReq.user_id)
}
// required string avatar_url = 2;
inline bool IMChangeAvatarReq::has_avatar_url() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMChangeAvatarReq::set_has_avatar_url() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMChangeAvatarReq::clear_has_avatar_url() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMChangeAvatarReq::clear_avatar_url() {
if (avatar_url_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
avatar_url_->clear();
}
clear_has_avatar_url();
}
inline const ::std::string& IMChangeAvatarReq::avatar_url() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarReq.avatar_url)
return *avatar_url_;
}
inline void IMChangeAvatarReq::set_avatar_url(const ::std::string& value) {
set_has_avatar_url();
if (avatar_url_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
avatar_url_ = new ::std::string;
}
avatar_url_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarReq.avatar_url)
}
inline void IMChangeAvatarReq::set_avatar_url(const char* value) {
set_has_avatar_url();
if (avatar_url_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
avatar_url_ = new ::std::string;
}
avatar_url_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMChangeAvatarReq.avatar_url)
}
inline void IMChangeAvatarReq::set_avatar_url(const char* value, size_t size) {
set_has_avatar_url();
if (avatar_url_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
avatar_url_ = new ::std::string;
}
avatar_url_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMChangeAvatarReq.avatar_url)
}
inline ::std::string* IMChangeAvatarReq::mutable_avatar_url() {
set_has_avatar_url();
if (avatar_url_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
avatar_url_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMChangeAvatarReq.avatar_url)
return avatar_url_;
}
inline ::std::string* IMChangeAvatarReq::release_avatar_url() {
clear_has_avatar_url();
if (avatar_url_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = avatar_url_;
avatar_url_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMChangeAvatarReq::set_allocated_avatar_url(::std::string* avatar_url) {
if (avatar_url_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete avatar_url_;
}
if (avatar_url) {
set_has_avatar_url();
avatar_url_ = avatar_url;
} else {
clear_has_avatar_url();
avatar_url_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMChangeAvatarReq.avatar_url)
}
// optional bytes attach_data = 20;
inline bool IMChangeAvatarReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMChangeAvatarReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMChangeAvatarReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMChangeAvatarReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMChangeAvatarReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarReq.attach_data)
return *attach_data_;
}
inline void IMChangeAvatarReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarReq.attach_data)
}
inline void IMChangeAvatarReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMChangeAvatarReq.attach_data)
}
inline void IMChangeAvatarReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMChangeAvatarReq.attach_data)
}
inline ::std::string* IMChangeAvatarReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMChangeAvatarReq.attach_data)
return attach_data_;
}
inline ::std::string* IMChangeAvatarReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMChangeAvatarReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMChangeAvatarReq.attach_data)
}
// -------------------------------------------------------------------
// IMChangeAvatarRsp
// required uint32 user_id = 1;
inline bool IMChangeAvatarRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMChangeAvatarRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMChangeAvatarRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMChangeAvatarRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMChangeAvatarRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarRsp.user_id)
return user_id_;
}
inline void IMChangeAvatarRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarRsp.user_id)
}
// required uint32 result_code = 2;
inline bool IMChangeAvatarRsp::has_result_code() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMChangeAvatarRsp::set_has_result_code() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMChangeAvatarRsp::clear_has_result_code() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMChangeAvatarRsp::clear_result_code() {
result_code_ = 0u;
clear_has_result_code();
}
inline ::google::protobuf::uint32 IMChangeAvatarRsp::result_code() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarRsp.result_code)
return result_code_;
}
inline void IMChangeAvatarRsp::set_result_code(::google::protobuf::uint32 value) {
set_has_result_code();
result_code_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarRsp.result_code)
}
// optional bytes attach_data = 20;
inline bool IMChangeAvatarRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMChangeAvatarRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMChangeAvatarRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMChangeAvatarRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMChangeAvatarRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMChangeAvatarRsp.attach_data)
return *attach_data_;
}
inline void IMChangeAvatarRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMChangeAvatarRsp.attach_data)
}
inline void IMChangeAvatarRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMChangeAvatarRsp.attach_data)
}
inline void IMChangeAvatarRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMChangeAvatarRsp.attach_data)
}
inline ::std::string* IMChangeAvatarRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMChangeAvatarRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMChangeAvatarRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMChangeAvatarRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMChangeAvatarRsp.attach_data)
}
// -------------------------------------------------------------------
// IMPCLoginStatusNotify
// required uint32 user_id = 1;
inline bool IMPCLoginStatusNotify::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMPCLoginStatusNotify::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMPCLoginStatusNotify::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMPCLoginStatusNotify::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMPCLoginStatusNotify::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMPCLoginStatusNotify.user_id)
return user_id_;
}
inline void IMPCLoginStatusNotify::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMPCLoginStatusNotify.user_id)
}
// required .IM.BaseDefine.UserStatType login_stat = 2;
inline bool IMPCLoginStatusNotify::has_login_stat() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMPCLoginStatusNotify::set_has_login_stat() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMPCLoginStatusNotify::clear_has_login_stat() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMPCLoginStatusNotify::clear_login_stat() {
login_stat_ = 1;
clear_has_login_stat();
}
inline ::IM::BaseDefine::UserStatType IMPCLoginStatusNotify::login_stat() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMPCLoginStatusNotify.login_stat)
return static_cast< ::IM::BaseDefine::UserStatType >(login_stat_);
}
inline void IMPCLoginStatusNotify::set_login_stat(::IM::BaseDefine::UserStatType value) {
assert(::IM::BaseDefine::UserStatType_IsValid(value));
set_has_login_stat();
login_stat_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMPCLoginStatusNotify.login_stat)
}
// -------------------------------------------------------------------
// IMRemoveSessionNotify
// required uint32 user_id = 1;
inline bool IMRemoveSessionNotify::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMRemoveSessionNotify::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMRemoveSessionNotify::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMRemoveSessionNotify::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionNotify::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionNotify.user_id)
return user_id_;
}
inline void IMRemoveSessionNotify::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionNotify.user_id)
}
// required .IM.BaseDefine.SessionType session_type = 2;
inline bool IMRemoveSessionNotify::has_session_type() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMRemoveSessionNotify::set_has_session_type() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMRemoveSessionNotify::clear_has_session_type() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMRemoveSessionNotify::clear_session_type() {
session_type_ = 1;
clear_has_session_type();
}
inline ::IM::BaseDefine::SessionType IMRemoveSessionNotify::session_type() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionNotify.session_type)
return static_cast< ::IM::BaseDefine::SessionType >(session_type_);
}
inline void IMRemoveSessionNotify::set_session_type(::IM::BaseDefine::SessionType value) {
assert(::IM::BaseDefine::SessionType_IsValid(value));
set_has_session_type();
session_type_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionNotify.session_type)
}
// required uint32 session_id = 3;
inline bool IMRemoveSessionNotify::has_session_id() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMRemoveSessionNotify::set_has_session_id() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMRemoveSessionNotify::clear_has_session_id() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMRemoveSessionNotify::clear_session_id() {
session_id_ = 0u;
clear_has_session_id();
}
inline ::google::protobuf::uint32 IMRemoveSessionNotify::session_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMRemoveSessionNotify.session_id)
return session_id_;
}
inline void IMRemoveSessionNotify::set_session_id(::google::protobuf::uint32 value) {
set_has_session_id();
session_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMRemoveSessionNotify.session_id)
}
// -------------------------------------------------------------------
// IMDepartmentReq
// required uint32 user_id = 1;
inline bool IMDepartmentReq::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMDepartmentReq::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMDepartmentReq::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMDepartmentReq::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMDepartmentReq::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentReq.user_id)
return user_id_;
}
inline void IMDepartmentReq::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentReq.user_id)
}
// required uint32 latest_update_time = 2;
inline bool IMDepartmentReq::has_latest_update_time() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMDepartmentReq::set_has_latest_update_time() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMDepartmentReq::clear_has_latest_update_time() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMDepartmentReq::clear_latest_update_time() {
latest_update_time_ = 0u;
clear_has_latest_update_time();
}
inline ::google::protobuf::uint32 IMDepartmentReq::latest_update_time() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentReq.latest_update_time)
return latest_update_time_;
}
inline void IMDepartmentReq::set_latest_update_time(::google::protobuf::uint32 value) {
set_has_latest_update_time();
latest_update_time_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentReq.latest_update_time)
}
// optional bytes attach_data = 20;
inline bool IMDepartmentReq::has_attach_data() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void IMDepartmentReq::set_has_attach_data() {
_has_bits_[0] |= 0x00000004u;
}
inline void IMDepartmentReq::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000004u;
}
inline void IMDepartmentReq::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMDepartmentReq::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentReq.attach_data)
return *attach_data_;
}
inline void IMDepartmentReq::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentReq.attach_data)
}
inline void IMDepartmentReq::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMDepartmentReq.attach_data)
}
inline void IMDepartmentReq::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMDepartmentReq.attach_data)
}
inline ::std::string* IMDepartmentReq::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMDepartmentReq.attach_data)
return attach_data_;
}
inline ::std::string* IMDepartmentReq::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMDepartmentReq::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMDepartmentReq.attach_data)
}
// -------------------------------------------------------------------
// IMDepartmentRsp
// required uint32 user_id = 1;
inline bool IMDepartmentRsp::has_user_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void IMDepartmentRsp::set_has_user_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void IMDepartmentRsp::clear_has_user_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void IMDepartmentRsp::clear_user_id() {
user_id_ = 0u;
clear_has_user_id();
}
inline ::google::protobuf::uint32 IMDepartmentRsp::user_id() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentRsp.user_id)
return user_id_;
}
inline void IMDepartmentRsp::set_user_id(::google::protobuf::uint32 value) {
set_has_user_id();
user_id_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentRsp.user_id)
}
// required uint32 latest_update_time = 2;
inline bool IMDepartmentRsp::has_latest_update_time() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void IMDepartmentRsp::set_has_latest_update_time() {
_has_bits_[0] |= 0x00000002u;
}
inline void IMDepartmentRsp::clear_has_latest_update_time() {
_has_bits_[0] &= ~0x00000002u;
}
inline void IMDepartmentRsp::clear_latest_update_time() {
latest_update_time_ = 0u;
clear_has_latest_update_time();
}
inline ::google::protobuf::uint32 IMDepartmentRsp::latest_update_time() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentRsp.latest_update_time)
return latest_update_time_;
}
inline void IMDepartmentRsp::set_latest_update_time(::google::protobuf::uint32 value) {
set_has_latest_update_time();
latest_update_time_ = value;
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentRsp.latest_update_time)
}
// repeated .IM.BaseDefine.DepartInfo dept_list = 3;
inline int IMDepartmentRsp::dept_list_size() const {
return dept_list_.size();
}
inline void IMDepartmentRsp::clear_dept_list() {
dept_list_.Clear();
}
inline const ::IM::BaseDefine::DepartInfo& IMDepartmentRsp::dept_list(int index) const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentRsp.dept_list)
return dept_list_.Get(index);
}
inline ::IM::BaseDefine::DepartInfo* IMDepartmentRsp::mutable_dept_list(int index) {
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMDepartmentRsp.dept_list)
return dept_list_.Mutable(index);
}
inline ::IM::BaseDefine::DepartInfo* IMDepartmentRsp::add_dept_list() {
// @@protoc_insertion_point(field_add:IM.Buddy.IMDepartmentRsp.dept_list)
return dept_list_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::DepartInfo >&
IMDepartmentRsp::dept_list() const {
// @@protoc_insertion_point(field_list:IM.Buddy.IMDepartmentRsp.dept_list)
return dept_list_;
}
inline ::google::protobuf::RepeatedPtrField< ::IM::BaseDefine::DepartInfo >*
IMDepartmentRsp::mutable_dept_list() {
// @@protoc_insertion_point(field_mutable_list:IM.Buddy.IMDepartmentRsp.dept_list)
return &dept_list_;
}
// optional bytes attach_data = 20;
inline bool IMDepartmentRsp::has_attach_data() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void IMDepartmentRsp::set_has_attach_data() {
_has_bits_[0] |= 0x00000008u;
}
inline void IMDepartmentRsp::clear_has_attach_data() {
_has_bits_[0] &= ~0x00000008u;
}
inline void IMDepartmentRsp::clear_attach_data() {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_->clear();
}
clear_has_attach_data();
}
inline const ::std::string& IMDepartmentRsp::attach_data() const {
// @@protoc_insertion_point(field_get:IM.Buddy.IMDepartmentRsp.attach_data)
return *attach_data_;
}
inline void IMDepartmentRsp::set_attach_data(const ::std::string& value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set:IM.Buddy.IMDepartmentRsp.attach_data)
}
inline void IMDepartmentRsp::set_attach_data(const char* value) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(value);
// @@protoc_insertion_point(field_set_char:IM.Buddy.IMDepartmentRsp.attach_data)
}
inline void IMDepartmentRsp::set_attach_data(const void* value, size_t size) {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
attach_data_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:IM.Buddy.IMDepartmentRsp.attach_data)
}
inline ::std::string* IMDepartmentRsp::mutable_attach_data() {
set_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
attach_data_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:IM.Buddy.IMDepartmentRsp.attach_data)
return attach_data_;
}
inline ::std::string* IMDepartmentRsp::release_attach_data() {
clear_has_attach_data();
if (attach_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = attach_data_;
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void IMDepartmentRsp::set_allocated_attach_data(::std::string* attach_data) {
if (attach_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete attach_data_;
}
if (attach_data) {
set_has_attach_data();
attach_data_ = attach_data;
} else {
clear_has_attach_data();
attach_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:IM.Buddy.IMDepartmentRsp.attach_data)
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Buddy
} // namespace IM
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_IM_2eBuddy_2eproto__INCLUDED
|
import clone from 'lodash/clone';
import map from 'lodash/map';
angular.module('controllers').controller(
'controllers.Domain.Tasks',
class DomainTasksCtrl {
constructor($scope, $q, $state, $stateParams, Domain) {
this.$scope = $scope;
this.$q = $q;
this.$state = $state;
this.$stateParams = $stateParams;
this.Domain = Domain;
}
$onInit() {
this.getTasks();
}
getTasks() {
return this.$q
.all({
zoneDnsTasks: this.Domain.getZoneDnsTasks(
this.$stateParams.productId,
).catch(() => []),
tasks: this.Domain.getTasks(
this.$stateParams.productId,
).catch(() => []),
})
.then(({ zoneDnsTasks, tasks }) => {
this.tasks = this.constructor
.getTaskStruct(zoneDnsTasks, true)
.concat(this.constructor.getTaskStruct(tasks, false));
});
}
static getTaskStruct(tasks, isZone) {
return map(tasks, (task) => ({ id: task, zone: isZone }));
}
transformItem(item) {
if (item.zone) {
return this.Domain.getZoneDnsTask(
this.$stateParams.productId,
item.id,
).then((originalResult) => {
const result = clone(originalResult);
result.status = result.status.toUpperCase();
return result;
});
}
return this.Domain.getTask(this.$stateParams.productId, item.id);
}
},
);
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 04:27
from __future__ import unicode_literals
from django.db import migrations
def update_forum_last_topic_and_last_post(apps, schema_editor):
Forum = apps.get_model("forum", "Forum")
Topic = apps.get_model("forum_conversation", "Topic")
for forum in Forum.objects.all():
topics = Topic.objects.filter(forum=forum, approved=True)
if topics.exists():
forum.last_post_id = topics[0].last_post_id
forum.save()
class Migration(migrations.Migration):
dependencies = [
("forum", "0008_forum_last_post"),
]
operations = [
migrations.RunPython(
update_forum_last_topic_and_last_post,
reverse_code=migrations.RunPython.noop,
),
]
|
'use strict';
/*********************************************************************************************
* *
* Plese read the following tutorial before implementing tasks: *
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array *
* *
* NOTE : Please do not use loops! All tasks can be implmeneted using standard Array methods *
* *
*********************************************************************************************/
/**
* Returns an index of the specified element in array or -1 if element is not found
*
* @param {array} arr
* @param {any} value
* @return {number}
*
* @example
* ['Ace', 10, true], 10 => 1
* ['Array', 'Number', 'string'], 'Date' => -1
* [0, 1, 2, 3, 4, 5], 5 => 5
*/
function findElement(arr, value) {
return arr.indexOf(value);
}
/**
* Generates an array of odd numbers of the specified length
*
* @param {number} len
* @return {array}
*
* @example
* 1 => [ 1 ]
* 2 => [ 1, 3 ]
* 5 => [ 1, 3, 5, 7, 9 ]
*/
function generateOdds(len) {
return Array.from({length: len}, (elem, i) => (i * 2) + 1);
}
/**
* Returns the doubled array - elements of the specified array are repeated twice using original order
*
* @param {array} arr
* @return {array}
*
* @example
* ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true]
* [0, 1, 2, 3, 4, 5] => [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
* [] => []
*/
function doubleArray(arr) {
return arr.concat(arr);
}
/**
* Returns an array of positive numbers from the specified array in original order
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, 1, 2, 3, 4, 5 ] => [ 1, 2, 3, 4, 5 ]
* [-1, 2, -5, -4, 0] => [ 2 ]
* [] => []
*/
function getArrayOfPositives(arr) {
return arr.filter(index => index > 0);
}
/**
* Returns the array with strings only in the specified array (in original order)
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, 1, 'cat', 3, true, 'dog' ] => [ 'cat', 'dog' ]
* [ 1, 2, 3, 4, 5 ] => []
* [ 'cat', 'dog', 'raccon' ] => [ 'cat', 'dog', 'racoon' ]
*/
function getArrayOfStrings(arr) {
// instanceof для custom types
// typeof for simple built in types
return arr.filter(elem => typeof elem == 'string');
}
/**
* Removes falsy values from the specified array
* Falsy values: false, null, 0, "", undefined, and NaN.
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description)
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, false, 'cat', NaN, true, '' ] => [ 'cat', true ]
* [ 1, 2, 3, 4, 5, 'false' ] => [ 1, 2, 3, 4, 5, 'false' ]
* [ false, 0, NaN, '', undefined ] => [ ]
*/
function removeFalsyValues(arr) {
return arr.filter(elem => elem);
}
/**
* Returns the array of useprcase strings from the specified array
*
* @param {array} arr
* @return {array}
*
* @example
* [ 'permanent-internship', 'glutinous-shriek', 'multiplicative-elevation' ] => [ 'PERMANENT-INTERNSHIP', 'GLUTINOUS-SHRIEK', 'MULTIPLICATIVE-ELEVATION' ]
* [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] => [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ]
*/
function getUpperCaseStrings(arr) {
return arr.map(elem => elem.toUpperCase());
}
/**
* Returns the array of string lengths from the specified string array.
*
* @param {array} arr
* @return {array}
*
* @example
* [ '', 'a', 'bc', 'def', 'ghij' ] => [ 0, 1, 2, 3, 4 ]
* [ 'angular', 'react', 'ember' ] => [ 7, 5, 5 ]
*/
function getStringsLength(arr) {
return arr.map(elem => elem.length);
}
/**
* Inserts the item into specified array at specified index
*
* @param {array} arr
* @param {any} item
* @param {number} index
*
* @example
* [ 1, 3, 4, 5 ], 2, 1 => [ 1, 2, 3, 4, 5 ]
* [ 1, 'b', 'c'], 0, 'x' => [ 'x', 1, 'b', 'c' ]
*/
function insertItem(arr, item, index) {
return arr.splice(index, 0, item);
}
/**
* Returns the n first items of the specified array
*
* @param {array} arr
* @param {number} n
*
* @example
* [ 1, 3, 4, 5 ], 2 => [ 1, 2 ]
* [ 'a', 'b', 'c', 'd'], 3 => [ 'a', 'b', 'c' ]
*/
function getHead(arr, n) {
return arr.slice(0, n);
}
/**
* Returns the n last items of the specified array
*
* @param {array} arr
* @param {number} n
*
* @example
* [ 1, 3, 4, 5 ], 2 => [ 4, 5 ]
* [ 'a', 'b', 'c', 'd'], 3 => [ 'b', 'c', 'd' ]
*/
function getTail(arr, n) {
return arr.slice(arr.length - n);
}
/**
* Returns CSV represebtation of two-dimentional numeric array.
* https://en.wikipedia.org/wiki/Comma-separated_values
*
* @param {array} arr
* @return {string}
*
* @example
* [
* [ 0, 1, 2, 3, 4 ],
* [ 10,11,12,13,14 ],
* [ 20,21,22,23,24 ],
* [ 30,31,32,33,34 ]
* ]
* =>
* '0,1,2,3,4\n'
* +'10,11,12,13,14\n'
* +'20,21,22,23,24\n'
* +'30,31,32,33,34'
*/
function toCsvText(arr) {
return arr.join('\n');
}
/**
* Transforms the numeric array into the according array of squares:
* f(x) = x * x
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, 1, 2, 3, 4, 5 ] => [ 0, 1, 4, 9, 16, 25 ]
* [ 10, 100, -1 ] => [ 100, 10000, 1 ]
*/
function toArrayOfSquares(arr) {
return arr.map(elem => elem * elem);
}
/**
* Transforms the numeric array to the according moving sum array:
* f[n] = x[0] + x[1] + x[2] +...+ x[n]
* or f[n] = f[n-1] + x[n]
*
* @param {array} arr
* @return {array}
*
* Example :
* [ 1, 1, 1, 1, 1 ] => [ 1, 2, 3, 4, 5 ]
* [ 10, -10, 10, -10, 10 ] => [ 10, 0, 10, 0, 10 ]
* [ 0, 0, 0, 0, 0] => [ 0, 0, 0, 0, 0]
* [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 ]
*/
function getMovingSum(arr) {
let sum = 0;
return arr.map(elem => sum += elem);
}
/**
* Returns every second item from the specified array:
*
* @param {array} arr
* @return {array}
*
* Example :
* [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 2, 4, 6, 8, 10 ]
* [ 'a', 'b', 'c' , null ] => [ "b", null ]
* [ "a" ] => []
*/
function getSecondItems(arr) {
return arr.filter((elem, index) => index % 2);
}
/**
* Propagates every item in sequence its position times
* Returns an array that consists of: one first item, two second items, tree third items etc.
*
* @param {array} arr
* @return {array}
*
* @example :
* [] => []
* [ 1 ] => [ 1 ]
* [ 'a', 'b' ] => [ 'a', 'b','b' ]
* [ 'a', 'b', 'c', null ] => [ 'a', 'b','b', 'c','c','c', null,null,null,null ]
* [ 1,2,3,4,5 ] => [ 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5 ]
*/
function propagateItemsByPositionIndex(arr) {
return arr.reduce((accumulator, currentValue, index) => accumulator.concat(
Array.from({length: index + 1}, () => currentValue)), []
);
}
/**
* Returns the 3 largest numbers from the specified array
*
* @param {array} arr
* @return {array}
*
* @example
* [] => []
* [ 1, 2 ] => [ 2, 1 ]
* [ 1, 2, 3 ] => [ 3, 2, 1 ]
* [ 1,2,3,4,5,6,7,8,9,10 ] => [ 10, 9, 8 ]
* [ 10, 10, 10, 10 ] => [ 10, 10, 10 ]
*/
function get3TopItems(arr) {
arr.sort((a, b) => b - a);
return arr.slice(0, 3);
}
/**
* Returns the number of positive numbers from specified array
*
* @param {array} arr
* @return {number}
*
* @example
* [ ] => 0
* [ -1, 0, 1 ] => 1
* [ 1, 2, 3] => 3
* [ null, 1, 'elephant' ] => 1
* [ 1, '2' ] => 1
*/
function getPositivesCount(arr) {
let resArr = arr.filter(currentValue => (currentValue > 0) &&
(Number.parseFloat(currentValue) === currentValue));
return resArr.length;
}
/**
* Sorts digit names
*
* @param {array} arr
* @return {array}
*
* @example
* [] => []
* [ 'nine','one' ] => [ 'one', 'nine' ]
* [ 'one','two','three' ] => [ 'one','two', 'three' ]
* [ 'nine','eight','nine','eight'] => [ 'eight','eight','nine','nine']
* [ 'one','one','one','zero' ] => [ 'zero','one','one','one' ]
*/
function sortDigitNamesByNumericOrder(arr) {
const dig = ['zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine'];
return arr.sort((a, b) => dig.indexOf(a) - dig.indexOf(b));
}
/**
* Returns the sum of all items in the specified array of numbers
*
* @param {array} arr
* @return {number}
*
* @example
* [] => 0
* [ 1, 2, 3 ] => 6
* [ -1, 1, -1, 1 ] => 0
* [ 1, 10, 100, 1000 ] => 1111
*/
function getItemsSum(arr) {
let sum = 0;
arr.map(currentValue => sum += currentValue);
return sum;
}
/**
* Returns the number of all falsy value in the specified array
*
* @param {array} arr
* @return {array}
*
* @example
* [] => 0
* [ 1, '', 3 ] => 1
* [ -1, 'false', null, 0 ] => 2
* [ null, undefined, NaN, false, 0, '' ] => 6
*/
function getFalsyValuesCount(arr) {
return arr.filter(currentValue => !currentValue).length;
}
/**
* Returns a number of all occurences of the specified item in an array
*
* @param {array} arr
* @param {any} item
* @return {number}
*
* @example
* [ 0, 0, 1, 1, 1, 2 ], 1 => 3
* [ 1, 2, 3, 4, 5 ], 0 => 0
* [ 'a','b','c','c' ], 'c'=> 2
* [ null, undefined, null ], null => 2
* [ true, 0, 1, 'true' ], true => 1
*/
function findAllOccurences(arr, item) {
// оператор == сравнивает на равенство и может осуществить приведение типов
// оператор === сравнивает на идентичность и точно не будет осуществлено приведение типов
return arr.filter(currentValue => currentValue === item).length;
}
/**
* Concatenates all elements from specified array into single string with ',' delimeter
*
* @param {array} arr
* @return {string}
*
* @example
* [0, false, 'cat', NaN, true, ''] => '0,false,cat,NaN,true,'
* [1, 2, 3, 4, 5] => '1,2,3,4,5'
* ['rock', 'paper', 'scissors'] => 'rock,paper,scissors'
*/
function toStringList(arr) {
return arr.join(',');
}
/**
* Sorts the specified array by country name first and city name (if countries are equal) in ascending order.
*
* @param {array} arr
* @return {array}
*
* @example
* [
* { country: 'Russia', city: 'Moscow' },
* { country: 'Belarus', city: 'Minsk' },
* { country: 'Poland', city: 'Warsaw' },
* { country: 'Russia', city: 'Saint Petersburg' },
* { country: 'Poland', city: 'Krakow' },
* { country: 'Belarus', city: 'Brest' }
* ]
* =>
* [
* { country: 'Belarus', city: 'Brest' },
* { country: 'Belarus', city: 'Minsk' },
* { country: 'Poland', city: 'Krakow' },
* { country: 'Poland', city: 'Warsaw' },
* { country: 'Russia', city: 'Moscow' },
* { country: 'Russia', city: 'Saint Petersburg' }
*/
function sortCitiesArray(arr) {
return arr.sort((a, b) => a.country == b.country ?
a.city.localeCompare(b.city) : a.country.localeCompare(b.country));
}
/**
* Creates an indentity matrix of the specified size
*
* @param {number} n
* @return {array}
*
* @example
* 1 => [[1]]
*
* 2 => [[1,0],
* [0,1]]
*
* [[1,0,0,0,0],
* [0,1,0,0,0],
* 5 => [0,0,1,0,0],
* [0,0,0,1,0],
* [0,0,0,0,1]]
*/
function getIdentityMatrix(n) {
return Array.from({length: n}, (thisArg, index) => {
let row = new Array(n).fill(0, 0, n);
row[index] = 1;
return row;
});
}
/**
* Creates an array of integers from the specified start to end (inclusive)
*
* @param {number} start
* @param {number} end
* @return {array}
*
* @example
* 1, 5 => [ 1, 2, 3, 4, 5 ]
* -2, 2 => [ -2, -1, 0, 1, 2 ]
* 0, 100 => [ 0, 1, 2, ..., 100 ]
* 3, 3 => [ 3 ]
*/
function getIntervalArray(start, end) {
return Array.from({length: end - start + 1}, (thisArg, index) => start + index);
}
/**
* Returns array containing only unique values from the specified array.
*
* @param {array} arr
* @return {array}
*
* @example
* [ 1, 2, 3, 3, 2, 1 ] => [ 1, 2, 3 ]
* [ 'a', 'a', 'a', 'a' ] => [ 'a' ]
* [ 1, 1, 2, 2, 3, 3, 4, 4] => [ 1, 2, 3, 4]
*/
function distinct(arr) {
return arr.filter((currentValue, index) => arr.indexOf(currentValue) === index);
}
/**
* Groups elements of the specified array by key.
* Returns multimap of keys extracted from array elements via keySelector callback
* and values extracted via valueSelector callback.
* See: https://en.wikipedia.org/wiki/Multimap
*
* @param {array} array
* @param {Function} keySelector
* @param {Function} valueSelector
* @return {Map}
*
* @example
* group([
* { country: 'Belarus', city: 'Brest' },
* { country: 'Russia', city: 'Omsk' },
* { country: 'Russia', city: 'Samara' },
* { country: 'Belarus', city: 'Grodno' },
* { country: 'Belarus', city: 'Minsk' },
* { country: 'Poland', city: 'Lodz' }
* ],
* item => item.country,
* item => item.city
* )
* =>
* Map {
* "Belarus" => ["Brest", "Grodno", "Minsk"],
* "Russia" => ["Omsk", "Samara"],
* "Poland" => ["Lodz"]
* }
*/
function group(array, keySelector, valueSelector) {
//Объект Map содержит пары ключ-значение и сохраняет порядок вставки.
const cityMap = new Map();
array.map( (currentValue) => {
const key = keySelector(currentValue);
const value = valueSelector(currentValue);
const entry = cityMap.get(key);
if (entry === undefined) {
cityMap.set(key, [value]);
} else {
entry.push(value);
}
});
return cityMap;
}
/**
* Projects each element of the specified array to a sequence and flattens the resulting sequences into one array.
*
* @param {array} arr
* @param {Function} childrenSelector, a transform function to apply to each element that returns an array of children
* @return {array}
*
* @example
* [[1, 2], [3, 4], [5, 6]], (x) => x => [ 1, 2, 3, 4, 5, 6 ]
* ['one','two','three'], x=>x.split('') => ['o','n','e','t','w','o','t','h','r','e','e']
*/
function selectMany(arr, childrenSelector) {
return arr.reduce((temp, elem) => temp.concat(childrenSelector(elem)), []);
}
/**
* Returns an element from the multidimentional array by the specified indexes.
*
* @param {array} arr
* @param {array} indexes
* @return {any} element from array
*
* @example
* [[1, 2], [3, 4], [5, 6]], [0,0] => 1 (arr[0][0])
* ['one','two','three'], [2] => 'three' (arr[2])
* [[[ 1, 2, 3]]], [ 0, 0, 1 ] => 2 (arr[0][0][1])
*/
function getElementByIndexes(arr, indexes) {
return indexes.map(elem => arr = arr[elem])[indexes.length - 1];
}
/**
* Swaps the head and tail of the specified array:
* the head (first half) of array move to the end, the tail (last half) move to the start.
* The middle element (if exists) leave on the same position.
*
*
* @param {array} arr
* @return {array}
*
* @example
* [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ]
* \----/ \----/
* head tail
*
* [ 1, 2 ] => [ 2, 1 ]
* [ 1, 2, 3, 4, 5, 6, 7, 8 ] => [ 5, 6, 7, 8, 1, 2, 3, 4 ]
*
*/
function swapHeadAndTail(arr) {
// ceil - окргуление вверх
// Math.floor() возвращает наибольшее целое число, которое меньше или равно данному числу.
const tail = arr.slice(Math.ceil(arr.length / 2), arr.length);
const mid = arr.slice(Math.floor(arr.length / 2), Math.ceil(arr.length / 2));
const head = arr.slice(0, Math.floor(arr.length / 2));
return tail.concat(mid).concat(head);
}
module.exports = {
findElement: findElement,
generateOdds: generateOdds,
doubleArray: doubleArray,
getArrayOfPositives: getArrayOfPositives,
getArrayOfStrings: getArrayOfStrings,
removeFalsyValues: removeFalsyValues,
getUpperCaseStrings: getUpperCaseStrings,
getStringsLength: getStringsLength,
insertItem: insertItem,
getHead: getHead,
getTail: getTail,
toCsvText: toCsvText,
toStringList: toStringList,
toArrayOfSquares: toArrayOfSquares,
getMovingSum: getMovingSum,
getSecondItems: getSecondItems,
propagateItemsByPositionIndex: propagateItemsByPositionIndex,
get3TopItems: get3TopItems,
getPositivesCount: getPositivesCount,
sortDigitNamesByNumericOrder: sortDigitNamesByNumericOrder,
getItemsSum: getItemsSum,
getFalsyValuesCount: getFalsyValuesCount,
findAllOccurences: findAllOccurences,
sortCitiesArray: sortCitiesArray,
getIdentityMatrix: getIdentityMatrix,
getIntervalArray: getIntervalArray,
distinct: distinct,
group: group,
selectMany: selectMany,
getElementByIndexes: getElementByIndexes,
swapHeadAndTail: swapHeadAndTail
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("rxjs-compat/add/operator/timeoutWith");
|
#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "x86.h"
#include "traps.h"
#include "spinlock.h"
// Interrupt descriptor table (shared by all CPUs).
struct gatedesc idt[256];
extern uint vectors[]; // in vectors.S: array of 256 entry pointers
struct spinlock tickslock;
uint ticks;
void
tvinit(void)
{
int i;
for(i = 0; i < 256; i++)
SETGATE(idt[i], 0, SEG_KCODE<<3, vectors[i], 0);
SETGATE(idt[T_SYSCALL], 1, SEG_KCODE<<3, vectors[T_SYSCALL], DPL_USER);
initlock(&tickslock, "time");
}
void
idtinit(void)
{
lidt(idt, sizeof(idt));
}
//PAGEBREAK: 41
void
trap(struct trapframe *tf)
{
if(tf->trapno == T_SYSCALL){
if(myproc()->killed)
exit();
myproc()->tf = tf;
syscall();
if(myproc()->killed)
exit();
return;
}
switch(tf->trapno){
case T_IRQ0 + IRQ_TIMER:
if(cpuid() == 0){
acquire(&tickslock);
ticks++;
wakeup(&ticks);
release(&tickslock);
}
lapiceoi();
break;
case T_IRQ0 + IRQ_IDE:
ideintr();
lapiceoi();
break;
case T_IRQ0 + IRQ_IDE+1:
// Bochs generates spurious IDE1 interrupts.
break;
case T_IRQ0 + IRQ_KBD:
kbdintr();
lapiceoi();
break;
case T_IRQ0 + IRQ_COM1:
uartintr();
lapiceoi();
break;
case T_IRQ0 + 7:
case T_IRQ0 + IRQ_SPURIOUS:
cprintf("cpu%d: spurious interrupt at %x:%x\n",
cpuid(), tf->cs, tf->eip);
lapiceoi();
break;
case T_PGFLT:; // Lab 3 Changes
uint pages = rcr2();
struct proc *p = myproc();
if (pages > KERNBASE - 1) { // Lab 3 Changes subtract 10000 from kernbase for part 2 to work
cprintf("Trap access is greater than the kernbase\n"); // Lab 3 Changes
exit(); // Lab 3 Changes
} // Lab 3 Changes
pages = PGROUNDDOWN(pages); // Lab 3 Changes
if (allocuvm(p->pgdir, pages, pages + (PGSIZE * p->stackPages)) == 0) { // Lab 3 Changes
cprintf("allocuvm failed, number of allocated pages: %p", pages); // Lab 3 Changes
exit(); // Lab 3 Changes
} // Lab 3 Changes
else {
p->stackPages++; // Lab 3 Changes
cprintf("allocuvm succeeded, number of allocated pages: %d\n", pages); // Lab 3 Changes
cprintf("Address of new page is: 0x%p", pages); // Lab 3 Changes
}
break;
//PAGEBREAK: 13
default:
if(myproc() == 0 || (tf->cs&3) == 0){
// In kernel, it must be our mistake.
cprintf("unexpected trap %d from cpu %d eip %x (cr2=0x%x)\n",
tf->trapno, cpuid(), tf->eip, rcr2());
panic("trap");
}
// In user space, assume process misbehaved.
cprintf("pid %d %s: trap %d err %d on cpu %d "
"eip 0x%x addr 0x%x--kill proc\n",
myproc()->pid, myproc()->name, tf->trapno,
tf->err, cpuid(), tf->eip, rcr2());
myproc()->killed = 1;
}
// Force process exit if it has been killed and is in user space.
// (If it is still executing in the kernel, let it keep running
// until it gets to the regular system call return.)
if(myproc() && myproc()->killed && (tf->cs&3) == DPL_USER)
exit();
// Force process to give up CPU on clock tick.
// If interrupts were on while locks held, would need to check nlock.
if(myproc() && myproc()->state == RUNNING &&
tf->trapno == T_IRQ0+IRQ_TIMER)
yield();
// Check if the process has been killed since we yielded
if(myproc() && myproc()->killed && (tf->cs&3) == DPL_USER)
exit();
}
|
function emitWarning() {
if (!emitWarning.warned) {
emitWarning.warned = true;
console.log(
'Deprecation (warning): Using file extension in specifier is deprecated, use "highlight.js/lib/languages/haml" instead of "highlight.js/lib/languages/haml.js"'
);
}
}
emitWarning();
import lang from './haml.js';
export default lang;
|
# coding: utf-8
"""
Paragon Insights APIs
API interface for PI application # noqa: E501
OpenAPI spec version: 4.0.0
Contact: healthbot-feedback@juniper.net
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class RuleSchemaWhere(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'query': 'str'
}
attribute_map = {
'query': 'query'
}
def __init__(self, query=None): # noqa: E501
"""RuleSchemaWhere - a model defined in Swagger""" # noqa: E501
self._query = None
self.discriminator = None
self.query = query
@property
def query(self):
"""Gets the query of this RuleSchemaWhere. # noqa: E501
Query to filter ingest data # noqa: E501
:return: The query of this RuleSchemaWhere. # noqa: E501
:rtype: str
"""
return self._query
@query.setter
def query(self, query):
"""Sets the query of this RuleSchemaWhere.
Query to filter ingest data # noqa: E501
:param query: The query of this RuleSchemaWhere. # noqa: E501
:type: str
"""
if query is None:
raise ValueError("Invalid value for `query`, must not be `None`") # noqa: E501
self._query = query
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(RuleSchemaWhere, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RuleSchemaWhere):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
#!/usr/bin/env python3
import numpy as np
from scipy.spatial.distance import pdist
from sympy.utilities.iterables import multiset_permutations
def distance(x1, y1, x2, y2):
"""
The Squared Euclidean Distance is given by the following formula:
round(math.pow((x1-x2), 2) + math.pow((y1-y2), 2))
"""
return pdist(np.array([[x1, y1], [x2, y2]]), metric='sqeuclidean')
def distance_for_array(array):
return distance(*array)
def solution(A, B, C, D):
"""
Finds the maximum squared distance between two points,
created assigning the integers A, B, C and D to the coordinates
(A, B, C and D must be used one time each).
:return:
Maximum squared distance for points created with A, B, C and D (used one time each).
"""
# Creates all possible permutations
p_array = list(multiset_permutations(np.array([A, B, C, D])))
# Calculates the distance for each permutation
distances = np.apply_along_axis(distance_for_array, 1, p_array)
# Returns the maximum distance
return np.nanmax(distances)
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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.
"""Utility function for nq evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import glob
from gzip import GzipFile
import json
import multiprocessing
from absl import flags
from absl import logging
flags.DEFINE_integer(
'long_non_null_threshold', 2,
'Require this many non-null long answer annotations '
'to count gold as containing a long answer.')
flags.DEFINE_integer(
'short_non_null_threshold', 2,
'Require this many non-null short answer annotations '
'to count gold as containing a short answer.')
FLAGS = flags.FLAGS
# A data structure for storing prediction and annotation.
# When a example has multiple annotations, multiple NQLabel will be used.
NQLabel = collections.namedtuple(
'NQLabel',
[
'example_id', # the unique id for each NQ example.
'long_answer_span', # A Span object for long answer.
'short_answer_span_list', # A list of Spans for short answer.
# Note that In NQ, the short answers
# do not need to be in a single span.
'yes_no_answer', # Indicate if the short answer is an yes/no answer
# The possible values are "yes", "no", "none".
# (case insensitive)
# If the field is "yes", short_answer_span_list
# should be empty or only contain null spans.
'long_score', # The prediction score for the long answer prediction.
'short_score' # The prediction score for the short answer prediction.
])
class Span(object):
"""A class for handling token and byte spans.
The logic is:
1) if both start_byte != -1 and end_byte != -1 then the span is defined
by byte offsets
2) else, if start_token != -1 and end_token != -1 then the span is define
by token offsets
3) else, this is a null span.
Null spans means that there is no (long or short) answers.
If your systems only care about token spans rather than byte spans, set all
byte spans to -1.
"""
def __init__(self, start_byte, end_byte, start_token_idx, end_token_idx):
if ((start_byte < 0 and end_byte >= 0) or
(start_byte >= 0 and end_byte < 0)):
raise ValueError('Inconsistent Null Spans (Byte).')
if ((start_token_idx < 0 and end_token_idx >= 0) or
(start_token_idx >= 0 and end_token_idx < 0)):
raise ValueError('Inconsistent Null Spans (Token).')
if start_byte >= 0 and end_byte >= 0 and start_byte >= end_byte:
raise ValueError('Invalid byte spans (start_byte >= end_byte).')
if ((start_token_idx >= 0 and end_token_idx >= 0) and
(start_token_idx >= end_token_idx)):
raise ValueError('Invalid token spans (start_token_idx >= end_token_idx)')
self.start_byte = start_byte
self.end_byte = end_byte
self.start_token_idx = start_token_idx
self.end_token_idx = end_token_idx
def is_null_span(self):
"""A span is a null span if the start and end are both -1."""
if (self.start_byte < 0 and self.end_byte < 0 and
self.start_token_idx < 0 and self.end_token_idx < 0):
return True
return False
def __str__(self):
byte_str = 'byte: [' + str(self.start_byte) + ',' + str(self.end_byte) + ')'
tok_str = ('tok: [' + str(self.start_token_idx) + ',' + str(
self.end_token_idx) + ')')
return byte_str + ' ' + tok_str
def __repr__(self):
return self.__str__()
def is_null_span_list(span_list):
"""Returns true iff all spans in span_list are null or span_list is empty."""
if not span_list or all([span.is_null_span() for span in span_list]):
return True
return False
def nonnull_span_equal(span_a, span_b):
"""Given two spans, return if they are equal.
Args:
span_a: a Span object.
span_b: a Span object. Only compare non-null spans. First, if the bytes are
not negative, compare byte offsets, Otherwise, compare token offsets.
Returns:
True or False
"""
assert isinstance(span_a, Span)
assert isinstance(span_b, Span)
assert not span_a.is_null_span()
assert not span_b.is_null_span()
# if byte offsets are not negative, compare byte offsets
if ((span_a.start_byte >= 0 and span_a.end_byte >= 0) and
(span_b.start_byte >= 0 and span_b.end_byte >= 0)):
if ((span_a.start_byte == span_b.start_byte) and
(span_a.end_byte == span_b.end_byte)):
return True
# if token offsets are not negative, compare token offsets
if ((span_a.start_token_idx >= 0 and span_a.end_token_idx >= 0) and
(span_b.start_token_idx >= 0 and span_b.end_token_idx >= 0)):
if ((span_a.start_token_idx == span_b.start_token_idx) and
(span_a.end_token_idx == span_b.end_token_idx)):
return True
return False
def span_set_equal(gold_span_list, pred_span_list):
"""Make the spans are completely equal besides null spans."""
gold_span_list = [span for span in gold_span_list if not span.is_null_span()]
pred_span_list = [span for span in pred_span_list if not span.is_null_span()]
for pspan in pred_span_list:
# not finding pspan equal to any spans in gold_span_list
if not any([nonnull_span_equal(pspan, gspan) for gspan in gold_span_list]):
return False
for gspan in gold_span_list:
# not finding gspan equal to any spans in pred_span_list
if not any([nonnull_span_equal(pspan, gspan) for pspan in pred_span_list]):
return False
return True
def gold_has_short_answer(gold_label_list):
"""Gets vote from multi-annotators for judging if there is a short answer."""
# We consider if there is a short answer if there is an short answer span or
# the yes/no answer is not none.
gold_has_answer = gold_label_list and sum([
((not is_null_span_list(label.short_answer_span_list)) or
(label.yes_no_answer != 'none')) for label in gold_label_list
]) >= FLAGS.short_non_null_threshold
return gold_has_answer
def gold_has_long_answer(gold_label_list):
"""Gets vote from multi-annotators for judging if there is a long answer."""
gold_has_answer = gold_label_list and (sum([
not label.long_answer_span.is_null_span() # long answer not null
for label in gold_label_list # for each annotator
]) >= FLAGS.long_non_null_threshold)
return gold_has_answer
def read_prediction_json(predictions_path):
"""Read the prediction json with scores.
Args:
predictions_path: the path for the prediction json.
Returns:
A dictionary with key = example_id, value = NQInstancePrediction.
"""
logging.info('Reading predictions from file: %s', format(predictions_path))
with open(predictions_path, 'r') as f:
predictions = json.loads(f.read())
nq_pred_dict = {}
for single_prediction in predictions['predictions']:
if 'long_answer' in single_prediction:
long_span = Span(single_prediction['long_answer']['start_byte'],
single_prediction['long_answer']['end_byte'],
single_prediction['long_answer']['start_token'],
single_prediction['long_answer']['end_token'])
else:
long_span = Span(-1, -1, -1, -1) # Span is null if not presented.
short_span_list = []
if 'short_answers' in single_prediction:
for short_item in single_prediction['short_answers']:
short_span_list.append(
Span(short_item['start_byte'], short_item['end_byte'],
short_item['start_token'], short_item['end_token']))
yes_no_answer = 'none'
if 'yes_no_answer' in single_prediction:
yes_no_answer = single_prediction['yes_no_answer'].lower()
if yes_no_answer not in ['yes', 'no', 'none']:
raise ValueError('Invalid yes_no_answer value in prediction')
if yes_no_answer != 'none' and not is_null_span_list(short_span_list):
raise ValueError('yes/no prediction and short answers cannot coexist.')
pred_item = NQLabel(
example_id=single_prediction['example_id'],
long_answer_span=long_span,
short_answer_span_list=short_span_list,
yes_no_answer=yes_no_answer,
long_score=single_prediction['long_answer_score'],
short_score=single_prediction['short_answers_score'])
nq_pred_dict[single_prediction['example_id']] = pred_item
return nq_pred_dict
import json_lines
def read_annotation_from_one_split(gzipped_input_file):
"""Read annotation from one split of file."""
# if isinstance(gzipped_input_file, str):
# gzipped_input_file = open(gzipped_input_file)
# logging.info('parsing %s ..... ', gzipped_input_file.name)
annotation_dict = {}
# with GzipFile(fileobj=gzipped_input_file) as input_file:
# read jsonl, because reading gzip gives UnicodeDecodeError
with open(gzipped_input_file) as input_file:
for line in input_file:
json_example = json.loads(line)
example_id = json_example['example_id']
# There are multiple annotations for one nq example.
annotation_list = []
for annotation in json_example['annotations']:
long_span_rec = annotation['long_answer']
long_span = Span(long_span_rec['start_byte'], long_span_rec['end_byte'],
long_span_rec['start_token'],
long_span_rec['end_token'])
short_span_list = []
for short_span_rec in annotation['short_answers']:
short_span = Span(
short_span_rec['start_byte'], short_span_rec['end_byte'],
short_span_rec['start_token'], short_span_rec['end_token'])
short_span_list.append(short_span)
gold_label = NQLabel(
example_id=example_id,
long_answer_span=long_span,
short_answer_span_list=short_span_list,
long_score=0,
short_score=0,
yes_no_answer=annotation['yes_no_answer'].lower())
annotation_list.append(gold_label)
annotation_dict[example_id] = annotation_list
return annotation_dict
def read_annotation(path_name, n_threads=10):
"""Read annotations with real multiple processes."""
input_paths = glob.glob(path_name)
pool = multiprocessing.Pool(n_threads)
try:
dict_list = pool.map(read_annotation_from_one_split, input_paths)
finally:
pool.close()
pool.join()
final_dict = {}
for single_dict in dict_list:
final_dict.update(single_dict)
return final_dict
|
#!/usr/bin/env python
import dataproc
import itertools
import numpy as np
import random
import time
import sys
import tensorflow as tf
from collections import defaultdict
from ltrdnn import LTRDNN
flags = tf.flags
FLAGS = flags.FLAGS
# model related:
flags.DEFINE_integer('vocab_size', 1532783, 'vocabulary size')
flags.DEFINE_integer('emb_dim', 256, 'embedding dimension')
flags.DEFINE_integer('repr_dim', 256, 'sentence representing dimension')
flags.DEFINE_string('combiner', 'sum', 'how to combine words in a sentence')
# training related:
flags.DEFINE_integer('train_bs', 128, 'train batch size')
flags.DEFINE_integer('max_epoch', 1, 'max epoch')
flags.DEFINE_integer('max_iter', 1000, 'max iteration')
flags.DEFINE_float('eps', 1.0, 'zero-loss threshold epsilon in hinge loss')
flags.DEFINE_integer('eval_steps', 20, 'every how many steps to evaluate')
flags.DEFINE_string('predict_file', '', 'file for prediction')
flags.DEFINE_string('model_dir', './model_ckpt/', 'model dir')
def eval_fn(inst):
def _max_len(lst): return max([len(x) for x in lst])
flds = inst.split('\t')
qrys = flds[0:1]
pos_num = int(flds[1])
poss = flds[2:2+pos_num]
neg_num = int(flds[2+pos_num])
negs = flds[2+pos_num+1:]
qrys = [map(int, x.split(' ')) for x in qrys]
poss = [map(int, x.split(' ')) for x in poss]
negs = [map(int, x.split(' ')) for x in negs]
seq_len = max(_max_len(qrys), _max_len(poss), _max_len(negs))
batch_size = len(poss) + len(negs)
# all titles
titles = poss + negs
sp_feed = defaultdict(list)
for i, (qry, titles) in enumerate(itertools.product(qrys, titles)):
for j, word_id in enumerate(qry):
sp_feed['qry_idx'].append([i, j])
sp_feed['qry_val'].append(word_id)
for j, word_id in enumerate(titles):
sp_feed['pos_idx'].append([i, j])
sp_feed['pos_val'].append(word_id)
return (sp_feed['qry_idx'], sp_feed['qry_val'], [batch_size, seq_len]), \
(sp_feed['pos_idx'], sp_feed['pos_val'], [batch_size, seq_len]), \
mdl = LTRDNN(
vocab_size=FLAGS.vocab_size,
emb_dim=FLAGS.emb_dim,
repr_dim=FLAGS.repr_dim,
combiner=FLAGS.combiner,
eps=FLAGS.eps)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
mdl.saver.restore(sess, tf.train.latest_checkpoint(FLAGS.model_dir))
predict_freader = dataproc.BatchReader(FLAGS.predict_file, 1)
data = predict_freader.get_batch(1)
while data:
pred_q, pred_pt = eval_fn(data[0].rstrip('\r\n'))
pred_eval = mdl.predict_sim_qt(sess, pred_q, pred_pt)
print pred_eval
data = predict_freader.get_batch(1)
# acc = mdl.pairwise_accuracy(sess, feval, eval_fn)
# print 'pairwise accuracy:', acc
sess.close()
|
############ Valores Booleanos #########
#Você pode avaliar qualquer expressão em python e obter uma de duas respostas, 'True' ou 'False'.
# Exemplo:
"""
print (10 > 9)
print (10 == 9)
print (10 < 9)
"""
# Quando voce executa uma condição em uma instrução 'if', o python retorna True ou Falso:
#Exemplo:
# Imprima uma mensagem com base em se a condição é True ou False:
"""
a = 200
b = 33
if b > a:
print("b é maior que a")
else:
print("b não é maior que a")
"""
############# Avalie Valores e Variáveis ########
# A bool() função permite que voce avalie qualquer valor e de a voce 'True' ou 'False' em troca.
# Exemplo:
# Avalie uma string e um número:
"""
print(bool("hello"))
print(bool(15))
"""
# Exemplo:
# Avalie duas variáveis:
"""
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
"""
######## A maioria dos valores são verdadeiros ############
#Exemplo
# O seguinte retornará Verdadeiro:
"""
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
"""
############ Alguns Valores são Falsos ##########
# Exemplo:
# O seguinte retornará False:
"""
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
"""
# Mais um valor, ou objeto neste caso, é avaliado 'False', e isto é, se voce tiver um objeto que é feito de uma classe com uma _len_ função que retorna 0 ou False:
# Exemplo:
"""
class myclass():
def _len_(self):
return 0
myobj = myclass ()
print(bool (myobj))
"""
######## Funções podem retornar um booleano #######
# Voce pode criar funções que retornam um valor booleano;
# Exemplo
#Imprima a resposta de uma função:
"""
def myFunction():
return True
print(myFunction())
"""
# Voce pode executar o código com base na resposta booleana de uma função:
# Exemplo:
#Imprima "SIM!" se a função retornar True, caso contrário imprima "Não":
'''
def myFunction():
return True
if myFunction():
print("SIM!")
else:
print("NÃO!")
'''
# Python também tem muitos funções integradas que retornam um valor booleano, como a 'isinstance()' função, que pode ser usada para determinar se um objeto é de um determinado tipo de dados:
# Exemplo:
# Verifique se um objeto é um número interio ou não:
"""
x = 200
print(isinstance(x, int))
"""
|
import React from "react"
import cx from "classname"
export default function TextInput({
name,
label,
isRequired,
containerClassName,
inputClassName,
type,
onChange,
value,
options,
}) {
return (
<div className={cx("measure", containerClassName)}>
<label htmlFor={name} className="f6 b db mb2">
{label}{" "}
<span className="normal black-60">{`(${
isRequired ? "required" : "optional"
})`}</span>
</label>
<select
id={name}
name={name}
className={cx(inputClassName)}
type={type}
onChange={onChange}
value={value || ""}
aria-describedby={name}
value={value}
>
{[
<option key={-10}>Please select a number...</option>,
...options.map((_value, i) => (
<option key={i} value={_value}>
{_value}
</option>
)),
]}
</select>
</div>
)
}
|
// Copyright 2020 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "Input/Reply.h"
#include "IDetailCustomization.h"
class AVoxelMeshImporter;
// See sky light details in the engine code
class FVoxelMeshImporterDetails : public IDetailCustomization
{
public:
/** Makes a new instance of this detail layout class for a specific detail view requesting it */
static TSharedRef<IDetailCustomization> MakeInstance();
private:
/** IDetailCustomization interface */
virtual void CustomizeDetails(IDetailLayoutBuilder& DetailLayout) override;
FReply OnCreateFromMesh();
private:
TWeakObjectPtr<AVoxelMeshImporter> MeshImporter;
};
|