text
stringlengths 1
1.05M
|
|---|
<reponame>leftcoding/GankLy<gh_stars>10-100
package com.gank.gankly.mvp.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
/**
* Create by LingYan on 2016-10-21
* Email:<EMAIL>
*/
public abstract class FetchFragment extends ThemeFragment {
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
initPresenter();
super.onViewCreated(view, savedInstanceState);
}
protected abstract void initPresenter();
}
|
/*
* Copyright (c) 2004-2021, University of Oslo
* 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 HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.call.factories.internal.QueryCallFactory;
import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCall;
import org.hisp.dhis.android.core.trackedentity.internal.ReservedValueSettingDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeCall;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeReservedValueEndpointCallFactory;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeReservedValueEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeReservedValueQuery;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeService;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceEventFilterEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceFilterCall;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceFilterEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceFilterService;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceSyncEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityModuleImpl;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityTypeAttributeEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityTypeCall;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityTypeEntityDIModule;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityTypeService;
import org.hisp.dhis.android.core.trackedentity.search.TrackedEntityInstanceQueryEntityDIModule;
import dagger.Module;
import dagger.Provides;
import dagger.Reusable;
import retrofit2.Retrofit;
@Module(includes = {
ReservedValueSettingDIModule.class,
TrackedEntityAttributeEntityDIModule.class,
TrackedEntityAttributeReservedValueEntityDIModule.class,
TrackedEntityAttributeValueEntityDIModule.class,
TrackedEntityDataValueEntityDIModule.class,
TrackedEntityInstanceEntityDIModule.class,
TrackedEntityInstanceEventFilterEntityDIModule.class,
TrackedEntityInstanceFilterEntityDIModule.class,
TrackedEntityInstanceQueryEntityDIModule.class,
TrackedEntityInstanceSyncEntityDIModule.class,
TrackedEntityTypeEntityDIModule.class,
TrackedEntityTypeAttributeEntityDIModule.class
})
public final class TrackedEntityPackageDIModule {
@Provides
@Reusable
UidsCall<TrackedEntityType> trackedEntityTypeCall(TrackedEntityTypeCall impl) {
return impl;
}
@Provides
@Reusable
TrackedEntityTypeService trackedEntityTypeService(Retrofit retrofit) {
return retrofit.create(TrackedEntityTypeService.class);
}
@Provides
@Reusable
UidsCall<TrackedEntityAttribute> trackedEntityAttributeCall(TrackedEntityAttributeCall impl) {
return impl;
}
@Provides
@Reusable
TrackedEntityAttributeService trackedEntityAttributeService(Retrofit retrofit) {
return retrofit.create(TrackedEntityAttributeService.class);
}
@Provides
@Reusable
QueryCallFactory<TrackedEntityAttributeReservedValue,
TrackedEntityAttributeReservedValueQuery> dataValueCallFactory(
TrackedEntityAttributeReservedValueEndpointCallFactory impl) {
return impl;
}
@Provides
@Reusable
UidsCall<TrackedEntityInstanceFilter> trackedEntityInstanceFilterCall(TrackedEntityInstanceFilterCall impl) {
return impl;
}
@Provides
@Reusable
TrackedEntityInstanceFilterService trackedEntityInstanceFilterService(Retrofit retrofit) {
return retrofit.create(TrackedEntityInstanceFilterService.class);
}
@Provides
@Reusable
TrackedEntityModule module(TrackedEntityModuleImpl impl) {
return impl;
}
}
|
package net.community.chest.util.map;
import java.util.Collection;
import java.util.Comparator;
import java.util.SortedMap;
/**
* Copyright 2007 as per GPLv2
*
* Helper class for {@link SortedMap} implementors - provides some useful
* common functionality
*
* @param <K> Generic key type
* @param <V> Generic value type
* @author <NAME>.
* @since Jun 13, 2007 11:57:53 AM
*/
public abstract class AbstractSortedMap<K,V> extends ExtendedAbstractMap<K,V> implements SortedMap<K,V> {
protected AbstractSortedMap (Class<K> kClass, Class<V> objClass)
{
super(kClass, objClass);
}
/**
* @param fromKey key value to start with (inclusive)
* @param toKey key value to end (exclusive)
* @return number of keys in range
* @throws NullPointerException if either range key is null
* @throws IllegalStateException if no {@link Comparator} instance
* returned by call to {@link SortedMap#comparator()} method
* @throws IllegalArgumentException if range is inverted (i.e., 'from' key
* is greater than 'to' key)
*/
public int countKeysInRange (final K fromKey, final K toKey)
throws NullPointerException, IllegalStateException, IllegalArgumentException
{
if ((null == fromKey) || (null == toKey))
throw new NullPointerException("countKeysInRange() null from(" + fromKey + ")/to(" + toKey + ") key(s)");
final Comparator<? super K> c=comparator();
if (null == c)
throw new IllegalStateException("countKeysInRange(" + fromKey + " - " + toKey + ") no comparator instance");
final int kRes=c.compare(fromKey, toKey);
if (kRes > 0)
throw new IllegalArgumentException("countKeysInRange(" + fromKey + " - " + toKey + ") inverted range");
if (0 == kRes)
return 0;
final Collection<? extends K> ks=keySet();
if ((null == ks) || (ks.size() <= 0)) // check the obvious
return 0;
int numKeys=0;
for (final K k : ks)
{
// if reached/exceeded top key, stop here
if (c.compare(k, toKey) >= 0)
return numKeys;
// count keys that are greater or equal to the low key
if (c.compare(fromKey, k) <= 0)
numKeys++;
}
return numKeys;
}
}
|
<reponame>NullaDev/WebGL-STG-Engine<filename>src/stg/entity/ComplexListener.ts
import { SCR_HALF_HEIGHT, SCR_HALF_WIDTH } from "../../platform/Screen";
import { EntityPool } from "../stage/EntityPool";
import { State } from "./Entity";
import { MovePoint, MovePointEventListener } from "./MovePoint";
import { RayLaser, RayLaserConfig, RayLaserEventListener, RayLaserMotion, SSRay } from "./RayLaser";
export const move_point_event_listener_template: () => MovePointEventListener = () => ({
onInit: [],
onUpdate: [],
onPostMotion: [],
onPostUpdate: [],
onAttack: [],
onDestroy: [],
onExitScreen: [],
onKill: []
});
export const ray_laser_event_listener_template: () => RayLaserEventListener = () => ({
onInit: [],
onUpdate: [],
onPostMotion: [],
onStateChange: [],
onPostUpdate: [],
onAttack: [],
onContact: [],
onDestroy: []
});
export type Adder<Config> = (config: Config) => (lst: MovePointEventListener) => void;
export type RLAdder<Config> = (config: Config) => (lst: RayLaserEventListener) => void;
type CS_REF = {
in_screen: boolean;
ref_count: number;
};
export type ReflectConfig = {
w0: number,
w1: number,
h0: number,
h1: number,
max: number,
inner_bound: boolean,
outer_bound: boolean
}
export const reflect_config_default: ReflectConfig = {
w0: -SCR_HALF_WIDTH,
w1: SCR_HALF_WIDTH,
h0: -SCR_HALF_HEIGHT,
h1: SCR_HALF_HEIGHT,
max: Infinity,
inner_bound: true,
outer_bound: false
}
export const reflect_linear: Adder<ReflectConfig> = (config: ReflectConfig) => (lst: MovePointEventListener) => {
lst.onInit.push((self: MovePoint<any>) => {
const cs = <CS_REF>self.custom_fields;
cs.in_screen = self.px > config.w0 && self.px < config.w1 && self.py > config.h0 && self.py < config.h1;
cs.ref_count = 0;
});
lst.onPostMotion.push((self: MovePoint<any>, rate: number) => {
const cs = <CS_REF>self.custom_fields;
const pre = cs.in_screen;
cs.in_screen = self.px > config.w0 && self.px < config.w1 && self.py > config.h0 && self.py < config.h1;
if (pre && !cs.in_screen && config.inner_bound) {
if (cs.ref_count < config.max && self.px <= config.w0) {
cs.ref_count++;
self.vx = -self.vx;
self.px = 2 * config.w0 - self.px;
}
if (cs.ref_count < config.max && self.px >= config.w1) {
cs.ref_count++;
self.vx = -self.vx;
self.px = 2 * config.w1 - self.px;
}
if (cs.ref_count < config.max && self.py <= config.h0) {
cs.ref_count++;
self.vy = -self.vy;
self.py = 2 * config.h0 - self.py;
}
if (cs.ref_count < config.max && self.py >= config.h1) {
cs.ref_count++;
self.vy = -self.vy;
self.py = 2 * config.h1 - self.py;
}
self.dir = Math.atan2(self.vy, self.vx);
cs.in_screen = true;
}
if (!pre && cs.in_screen && config.outer_bound) {
if (cs.ref_count < config.max && self.px >= config.w0) {
cs.ref_count++;
self.vx = -self.vx;
self.px = 2 * config.w0 - self.px;
}
if (cs.ref_count < config.max && self.px <= config.w1) {
cs.ref_count++;
self.vx = -self.vx;
self.px = 2 * config.w1 - self.px;
}
if (cs.ref_count < config.max && self.py >= config.h0) {
cs.ref_count++;
self.vy = -self.vy;
self.py = 2 * config.h0 - self.py;
}
if (cs.ref_count < config.max && self.py <= config.h1) {
cs.ref_count++;
self.vy = -self.vy;
self.py = 2 * config.h1 - self.py;
}
self.dir = Math.atan2(self.vy, self.vx);
cs.in_screen = false;
}
})
}
export const reflect_disable: (config: ReflectConfig) => (e: MovePoint<any>) => void =
(config: ReflectConfig) => (e: MovePoint<any>) => (<CS_REF>e.custom_fields).ref_count = config.max
type CS_RL_REF = {
vx: number,
vy: number,
ref_count: number,
togrow: number,
toshrink: number
}
export type RLReflectConfig = {
name: string,
w0: number,
w1: number,
h0: number,
h1: number,
max: number,
v: number,
maxlen: number,
body: SSRay,
cf: RayLaserConfig,
}
export const rl_reflect_config_default: RLReflectConfig = {
name: "",
w0: -SCR_HALF_WIDTH,
w1: SCR_HALF_WIDTH,
h0: -SCR_HALF_HEIGHT,
h1: SCR_HALF_HEIGHT,
max: Infinity, maxlen: NaN,
v: NaN, body: null, cf: null
}
export const reflect_rl: RLAdder<RLReflectConfig> = (config: RLReflectConfig) => (lst: RayLaserEventListener) => {
const motion: RayLaserMotion = (self: RayLaser, time_rate: number) => {
const cs = <CS_RL_REF>self.custom_fields;
if (cs.togrow > 0) {
const g = Math.min(cs.togrow, config.v * time_rate);
time_rate -= g / config.v;
self.len += g;
cs.togrow -= g;
}
if (time_rate > 0) {
self.px += time_rate * cs.vx;
self.py += time_rate * cs.vy;
}
if (self.shaped_sprite.end.shape.rawExitScreen(
self.px + self.len * Math.cos(self.dir),
self.py + self.len * Math.sin(self.dir),
self.shaped_sprite.base, SCR_HALF_WIDTH, SCR_HALF_HEIGHT) &&
self.shaped_sprite.base.shape.rawExitScreen(
self.px, self.py, self.shaped_sprite.base, SCR_HALF_WIDTH, SCR_HALF_HEIGHT))
self.state = State.DEAD;
}
const within = (px: number, py: number) => px > config.w0 && px < config.w1 && py > config.h0 && py < config.h1
const bmotion: RayLaserMotion = (self: RayLaser, time_rate: number) => {
const cs = <CS_RL_REF>self.custom_fields;
if (cs.toshrink > 0) {
const g = Math.min(cs.toshrink, config.v * time_rate);
self.len -= g;
cs.toshrink -= g;
if (cs.toshrink <= 0)
self.state = State.DEAD;
}
if (cs.togrow > 0) {
const g = Math.min(cs.togrow, config.v * time_rate);
time_rate -= g / config.v;
self.len += g;
cs.togrow -= g;
}
if (time_rate > 0) {
self.px += time_rate * cs.vx;
self.py += time_rate * cs.vy;
}
if (self.shaped_sprite.base.shape.rawExitScreen(self.px, self.py, self.shaped_sprite.base, SCR_HALF_WIDTH, SCR_HALF_HEIGHT))
self.state = State.DEAD;
}
lst.onInit.push((self: RayLaser) => {
const cs = <CS_RL_REF>self.custom_fields;
cs.ref_count = 0;
cs.vx = config.v * Math.cos(self.dir);
cs.vy = config.v * Math.sin(self.dir);
cs.togrow = config.maxlen;
cs.toshrink = 0;
self.motion = motion;
});
lst.onPostMotion.push((self: RayLaser, rate: number) => {
const cs = <CS_RL_REF>self.custom_fields;
const headw = within(self.px, self.py);
const ex = self.px + self.len * Math.cos(self.dir);
const ey = self.py + self.len * Math.sin(self.dir);
const endw = within(ex, ey);
if (!endw && cs.ref_count < config.max) {
const rl = new RayLaser(config.body, config.cf, bmotion);
rl.init(self.px, self.py, self.dir, self.len);
const subcs = <CS_RL_REF>rl.custom_fields;
subcs.vx = cs.vx;
subcs.vy = cs.vy;
subcs.togrow = cs.togrow;
EntityPool.INSTANCE.add(rl);
var mx = 0, my = 0;
if (cs.ref_count < config.max && ex <= config.w0) {
mx = config.w0;
my = self.py + (config.w0 - self.px) * cs.vy / cs.vx;
cs.ref_count++;
cs.vx = -cs.vx;
self.px = 2 * config.w0 - self.px;
}
if (cs.ref_count < config.max && ex >= config.w1) {
mx = config.w1;
my = self.py + (config.w1 - self.px) * cs.vy / cs.vx;
cs.ref_count++;
cs.vx = -cs.vx;
self.px = 2 * config.w1 - self.px;
}
if (cs.ref_count < config.max && ey <= config.h0) {
my = config.h0;
mx = self.px + (config.h0 - self.py) * cs.vx / cs.vy;
cs.ref_count++;
cs.vy = -cs.vy;
self.py = 2 * config.h0 - self.py;
}
if (cs.ref_count < config.max && ey >= config.h1) {
my = config.h1;
mx = self.px + (config.h1 - self.py) * cs.vx / cs.vy;
cs.ref_count++;
cs.vy = -cs.vy;
self.py = 2 * config.h1 - self.py;
}
const dlen = Math.sqrt((self.px - mx) ** 2 + (self.py - my) ** 2);
self.len -= dlen;
self.px = mx;
self.py = my;
cs.togrow += dlen;
rl.len = dlen;
subcs.toshrink = dlen + subcs.togrow;
self.dir = Math.atan2(cs.vy, cs.vx);
}
})
}
|
<filename>src/assets/build.asset.spec.ts
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { CxEntry, cxRecent } from '@proc7ts/context-values';
import { Supply } from '@proc7ts/supply';
import { CxBuilder } from '../builder';
import { CxPeerBuilder } from '../peer-builder';
import { cxBuildAsset } from './build.asset';
import { cxConstAsset } from './const.asset';
describe('cxBuildAsset', () => {
let peer1: CxPeerBuilder;
let builder1: CxBuilder;
let peer2: CxPeerBuilder;
let builder2: CxBuilder;
beforeEach(() => {
peer1 = new CxPeerBuilder();
peer2 = new CxPeerBuilder();
});
let entry1: CxEntry<string>;
let entry2: CxEntry<string>;
beforeEach(() => {
entry1 = { perContext: cxRecent(), toString: () => '[CxEntry 1]' };
entry2 = { perContext: cxRecent(), toString: () => '[CxEntry 2]' };
});
it('evaluates asset once per context', () => {
builder1 = new CxBuilder(get => ({ get }), peer1);
builder2 = new CxBuilder(get => ({ get }), peer1);
const build = jest.fn((target: CxEntry.Target<string>) => target.get(entry1) + '!');
builder1.provide(cxConstAsset(entry1, '1'));
builder2.provide(cxConstAsset(entry1, '2'));
peer1.provide(cxBuildAsset(entry2, build));
expect(builder1.get(entry1)).toBe('1');
expect(builder2.get(entry1)).toBe('2');
expect(builder1.get(entry2)).toBe('1!');
expect(builder2.get(entry2)).toBe('2!');
expect(builder2.get(entry2)).toBe('2!');
expect(builder1.get(entry2)).toBe('1!');
expect(build).toHaveBeenCalledTimes(2);
});
it('evaluates asset once in bound context', () => {
builder1 = new CxBuilder(get => ({ get }), peer1);
builder2 = new CxBuilder(get => ({ get }), builder1.boundPeer, peer2);
const build = jest.fn((target: CxEntry.Target<string>) => target.get(entry1) + '!');
peer1.provide(cxConstAsset(entry1, '1'));
peer1.provide(cxBuildAsset(entry2, build));
peer2.provide(cxConstAsset(entry1, '2'));
expect(builder2.get(entry1)).toBe('2');
expect(builder1.get(entry1)).toBe('1');
expect(builder1.get(entry2)).toBe('1!');
expect(builder2.get(entry2)).toBe('1!');
expect(builder2.get(entry2)).toBe('1!');
expect(builder1.get(entry2)).toBe('1!');
expect(build).toHaveBeenCalledTimes(1);
});
it('clears cache once revoked', () => {
builder1 = new CxBuilder(get => ({ get }), peer1);
builder2 = new CxBuilder(get => ({ get }), peer1);
const supply = new Supply();
const build1 = jest.fn((target: CxEntry.Target<string>) => target.get(entry1) + '.1');
const build2 = jest.fn((target: CxEntry.Target<string>) => target.get(entry1) + '.2');
builder1.provide(cxConstAsset(entry1, '1'));
builder2.provide(cxConstAsset(entry1, '2'));
peer1.provide(cxBuildAsset(entry2, build1));
builder2.provide(cxBuildAsset(entry2, build2, supply));
expect(builder1.get(entry1)).toBe('1');
expect(builder2.get(entry1)).toBe('2');
expect(builder1.get(entry2)).toBe('1.1');
expect(builder2.get(entry2)).toBe('2.2');
expect(builder2.get(entry2)).toBe('2.2');
expect(builder1.get(entry2)).toBe('1.1');
expect(build1).toHaveBeenCalledTimes(1);
expect(build2).toHaveBeenCalledTimes(1);
supply.off();
expect(builder1.get(entry2)).toBe('1.1');
expect(builder2.get(entry2)).toBe('2.1');
expect(builder2.get(entry2)).toBe('2.1');
expect(builder1.get(entry2)).toBe('1.1');
expect(build1).toHaveBeenCalledTimes(2);
expect(build2).toHaveBeenCalledTimes(1);
});
});
|
import { Button, Card, Form, Input, Row, Col, InputNumber, message } from 'antd';
import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import styles from './index.less';
const nzhcn = require('nzh/cn');
const FormItem = Form.Item;
const { TextArea } = Input;
interface BasicFormProps extends FormComponentProps {
submitting: boolean;
dispatch: Dispatch<any>;
}
class BasicForm extends Component<BasicFormProps> {
state = {
money: '',
};
handleSubmit = (e: React.FormEvent) => {
const { dispatch, form } = this.props;
e.preventDefault();
form.validateFieldsAndScroll((err, values) => {
if (!err) {
message.success('提交成功');
window.history.back();
}
});
};
changeMoney = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({
money: event.target.value,
});
};
render() {
const {
form: { getFieldDecorator },
} = this.props;
const { money } = this.state;
const halfItemLayout = {
labelCol: {
sm: {
span: 4,
},
},
wrapperCol: {
sm: {
span: 20,
},
},
};
const formItemLayout = {
labelCol: {
sm: {
span: 8,
},
},
wrapperCol: {
sm: {
span: 16,
},
},
};
return (
<PageHeaderWrapper>
<Card bordered={false}>
<div className={styles.box}>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="企业名称">
上海高重信息科技有限公司
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="统一社会信用代码">
913101103246443123
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="登记机关">
普陀区市场监管局
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="所属地区">
江苏银行
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="金融机构">
江苏银行
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="金融产品名称">
快易贷
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="贷款金额(万元)" required>
{getFieldDecorator('money')(<Input onChange={this.changeMoney} />)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="金额大写">
{nzhcn.encodeB(money)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="利率范围" required>
<div
style={{
display: 'inline-block',
width: 'calc(50% - 12px)',
}}
>
<InputNumber style={{ width: '100%' }} />
</div>
<span
style={{
display: 'inline-block',
width: '24px',
textAlign: 'center',
}}
>
-
</span>
<div
style={{
display: 'inline-block',
width: 'calc(50% - 12px)',
}}
>
<InputNumber style={{ width: '100%' }} />
</div>
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="贷款期限" required>
{getFieldDecorator('title')(<Input />)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="担保方式">
<Input />
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="贷款用途" required>
{getFieldDecorator('yt')(<Input />)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={24}>
<FormItem {...halfItemLayout} label="项目情况">
{getFieldDecorator('qk')(
<TextArea
rows={3}
style={{
margin: '6px auto',
}}
/>,
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={24}>
<FormItem {...halfItemLayout} label="备注">
{getFieldDecorator('resk')(
<TextArea
rows={3}
style={{
margin: '6px auto',
}}
/>,
)}
</FormItem>
</Col>
</Row>
</div>
<div className={styles.bottom}>
<Button>返回</Button>
<Button type="primary" onClick={this.handleSubmit}>
提交
</Button>
</div>
</Card>
</PageHeaderWrapper>
);
}
}
export default Form.create<BasicFormProps>()(
connect(({ loading }: { loading: { effects: { [key: string]: boolean } } }) => ({
submitting: loading.effects['formBasicForm/submitRegularForm'],
}))(BasicForm),
);
|
import component from './Switch'
export default component
|
class MergeSort:
def __init__(self, list1, list2):
self.list1 = list1
self.list2 = list2
def merge_lists(self):
sorted_list = self.list1 + self.list2
sorted_list.sort()
return sorted_list
|
import datetime
print(str(datetime.datetime.now())[:10])
|
def func_name(param1, param2):
# Add two parameters
a = param1 + param2
# Multiply two parameters
b = param1 * param2
# Return a and b
return a, b
|
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// Create posts array
let posts = [
{ id: 1, title: 'First Post', content: 'This is my first post' },
{ id: 2, title: 'Second Post', content: 'This is my second post' }
];
// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Landing page
app.get('/', (req, res) => {
res.json({
message: 'Welcome to the Blog API!'
});
});
// Retrieve all posts
app.get('/posts', (req, res) => {
res.status(200).json({
message: 'Posts retrieved successfully',
posts: posts
});
});
// Create new post
app.post('/posts', (req, res) => {
const post = {
id: posts.length + 1,
title: req.body.title,
content: req.body.content
};
posts.push(post);
res.status(201).json({
message: 'Post created successfully',
post: post
});
});
// Retrieve single post
app.get('/posts/:id', (req, res) => {
const post = posts.find(post => post.id === parseInt(req.params.id));
if (!post)
return res.status(404).json({ message: 'Post not found' });
res.status(200).json({
message: 'Post retrieved successfully',
post: post
});
});
// Update Post
app.put('/posts/:id', (req, res) => {
const post = posts.find(post => post.id === parseInt(req.params.id));
if (!post)
return res.status(404).json({ message: 'Post not found' });
post.title = req.body.title;
post.content = req.body.content;
res.status(200).json({
message: 'Post updated successfully',
post: post
});
});
// Delete Post
app.delete('/posts/:id', (req, res) => {
const post = posts.find(post => post.id === parseInt(req.params.id));
if (!post)
return res.status(404).json({ message: 'Post not found' });
const index = posts.indexOf(post);
posts.splice(index, 1);
res.status(200).json({
message: 'Post deleted successfully',
posts: posts
});
});
// Create a port
const port = process.env.PORT || 3000;
// Start an instance of the server
app.listen(port, () =>
console.log(`Server running on port ${port}`)
);
|
#!/bin/sh
. ./test-pre.sh
AFL_GCC=afl-gcc
$ECHO "$BLUE[*] Testing: ${AFL_GCC}, afl-showmap, afl-fuzz, afl-cmin and afl-tmin"
test "$SYS" = "i686" -o "$SYS" = "x86_64" -o "$SYS" = "amd64" -o "$SYS" = "i86pc" -o "$SYS" = "i386" && {
test -e ../${AFL_GCC} -a -e ../afl-showmap -a -e ../afl-fuzz && {
../${AFL_GCC} -o test-instr.plain ../test-instr.c > /dev/null 2>&1
AFL_HARDEN=1 ../${AFL_GCC} -o test-compcov.harden test-compcov.c > /dev/null 2>&1
test -e test-instr.plain && {
$ECHO "$GREEN[+] ${AFL_GCC} compilation succeeded"
echo 0 | ../afl-showmap -m ${MEM_LIMIT} -o test-instr.plain.0 -r -- ./test-instr.plain > /dev/null 2>&1
../afl-showmap -m ${MEM_LIMIT} -o test-instr.plain.1 -r -- ./test-instr.plain < /dev/null > /dev/null 2>&1
test -e test-instr.plain.0 -a -e test-instr.plain.1 && {
diff test-instr.plain.0 test-instr.plain.1 > /dev/null 2>&1 && {
$ECHO "$RED[!] ${AFL_GCC} instrumentation should be different on different input but is not"
CODE=1
} || {
$ECHO "$GREEN[+] ${AFL_GCC} instrumentation present and working correctly"
}
} || {
$ECHO "$RED[!] ${AFL_GCC} instrumentation failed"
CODE=1
}
rm -f test-instr.plain.0 test-instr.plain.1
SKIP=
TUPLES=`echo 1|../afl-showmap -m ${MEM_LIMIT} -o /dev/null -- ./test-instr.plain 2>&1 | grep Captur | awk '{print$3}'`
test "$TUPLES" -gt 2 -a "$TUPLES" -lt 12 && {
$ECHO "$GREEN[+] ${AFL_GCC} run reported $TUPLES instrumented locations which is fine"
} || {
$ECHO "$RED[!] ${AFL_GCC} instrumentation produces weird numbers: $TUPLES"
CODE=1
}
test "$TUPLES" -lt 4 && SKIP=1
true # this is needed because of the test above
} || {
$ECHO "$RED[!] ${AFL_GCC} failed"
echo CUT------------------------------------------------------------------CUT
uname -a
../${AFL_GCC} -o test-instr.plain ../test-instr.c
echo CUT------------------------------------------------------------------CUT
CODE=1
}
test -e test-compcov.harden && {
grep -Eq$GREPAOPTION 'stack_chk_fail|fstack-protector-all|fortified' test-compcov.harden > /dev/null 2>&1 && {
$ECHO "$GREEN[+] ${AFL_GCC} hardened mode succeeded and is working"
} || {
$ECHO "$RED[!] ${AFL_GCC} hardened mode is not hardened"
CODE=1
}
rm -f test-compcov.harden
} || {
$ECHO "$RED[!] ${AFL_GCC} hardened mode compilation failed"
CODE=1
}
# now we want to be sure that afl-fuzz is working
# make sure core_pattern is set to core on linux
(test "$(uname -s)" = "Linux" && test "$(sysctl kernel.core_pattern)" != "kernel.core_pattern = core" && {
$ECHO "$YELLOW[-] we should not run afl-fuzz with enabled core dumps. Run 'sudo sh afl-system-config'.$RESET"
true
}) ||
# make sure crash reporter is disabled on Mac OS X
(test "$(uname -s)" = "Darwin" && test $(launchctl list 2>/dev/null | grep -q '\.ReportCrash$') && {
$ECHO "$RED[!] we cannot run afl-fuzz with enabled crash reporter. Run 'sudo sh afl-system-config'.$RESET"
true
}) || {
mkdir -p in
echo 0 > in/in
test -z "$SKIP" && {
$ECHO "$GREY[*] running afl-fuzz for ${AFL_GCC}, this will take approx 10 seconds"
{
../afl-fuzz -V10 -m ${MEM_LIMIT} -i in -o out -D -- ./test-instr.plain >>errors 2>&1
} >>errors 2>&1
test -n "$( ls out/default/queue/id:000002* 2>/dev/null )" && {
$ECHO "$GREEN[+] afl-fuzz is working correctly with ${AFL_GCC}"
} || {
echo CUT------------------------------------------------------------------CUT
cat errors
echo CUT------------------------------------------------------------------CUT
$ECHO "$RED[!] afl-fuzz is not working correctly with ${AFL_GCC}"
CODE=1
}
}
echo 000000000000000000000000 > in/in2
echo 111 > in/in3
mkdir -p in2
../afl-cmin -m ${MEM_LIMIT} -i in -o in2 -- ./test-instr.plain >/dev/null 2>&1 # why is afl-forkserver writing to stderr?
CNT=`ls in2/* 2>/dev/null | wc -l`
case "$CNT" in
*2) $ECHO "$GREEN[+] afl-cmin correctly minimized the number of testcases" ;;
*) $ECHO "$RED[!] afl-cmin did not correctly minimize the number of testcases ($CNT)"
CODE=1
;;
esac
rm -f in2/in*
export AFL_QUIET=1
if command -v bash >/dev/null ; then {
../afl-cmin.bash -m ${MEM_LIMIT} -i in -o in2 -- ./test-instr.plain >/dev/null
CNT=`ls in2/* 2>/dev/null | wc -l`
case "$CNT" in
*2) $ECHO "$GREEN[+] afl-cmin.bash correctly minimized the number of testcases" ;;
*) $ECHO "$RED[!] afl-cmin.bash did not correctly minimize the number of testcases ($CNT)"
CODE=1
;;
esac
} else {
$ECHO "$GRAY[*] no bash available, cannot test afl-cmin.bash"
}
fi
../afl-tmin -m ${MEM_LIMIT} -i in/in2 -o in2/in2 -- ./test-instr.plain > /dev/null 2>&1
SIZE=`ls -l in2/in2 2>/dev/null | awk '{print$5}'`
test "$SIZE" = 1 && $ECHO "$GREEN[+] afl-tmin correctly minimized the testcase"
test "$SIZE" = 1 || {
$ECHO "$RED[!] afl-tmin did incorrectly minimize the testcase to $SIZE"
CODE=1
}
rm -rf in out errors in2
unset AFL_QUIET
}
rm -f test-instr.plain
} || {
$ECHO "$YELLOW[-] afl is not compiled, cannot test"
INCOMPLETE=1
}
if [ ${AFL_GCC} = "afl-gcc" ] ; then AFL_GCC=afl-clang ; else AFL_GCC=afl-gcc ; fi
$ECHO "$BLUE[*] Testing: ${AFL_GCC}, afl-showmap, afl-fuzz, afl-cmin and afl-tmin"
SKIP=
test -e ../${AFL_GCC} -a -e ../afl-showmap -a -e ../afl-fuzz && {
../${AFL_GCC} -o test-instr.plain ../test-instr.c > /dev/null 2>&1
AFL_HARDEN=1 ../${AFL_GCC} -o test-compcov.harden test-compcov.c > /dev/null 2>&1
test -e test-instr.plain && {
$ECHO "$GREEN[+] ${AFL_GCC} compilation succeeded"
echo 0 | ../afl-showmap -m ${MEM_LIMIT} -o test-instr.plain.0 -r -- ./test-instr.plain > /dev/null 2>&1
../afl-showmap -m ${MEM_LIMIT} -o test-instr.plain.1 -r -- ./test-instr.plain < /dev/null > /dev/null 2>&1
test -e test-instr.plain.0 -a -e test-instr.plain.1 && {
diff test-instr.plain.0 test-instr.plain.1 > /dev/null 2>&1 && {
$ECHO "$RED[!] ${AFL_GCC} instrumentation should be different on different input but is not"
CODE=1
} || {
$ECHO "$GREEN[+] ${AFL_GCC} instrumentation present and working correctly"
}
} || {
$ECHO "$RED[!] ${AFL_GCC} instrumentation failed"
CODE=1
}
rm -f test-instr.plain.0 test-instr.plain.1
TUPLES=`echo 1|../afl-showmap -m ${MEM_LIMIT} -o /dev/null -- ./test-instr.plain 2>&1 | grep Captur | awk '{print$3}'`
test "$TUPLES" -gt 2 -a "$TUPLES" -lt 12 && {
$ECHO "$GREEN[+] ${AFL_GCC} run reported $TUPLES instrumented locations which is fine"
} || {
$ECHO "$RED[!] ${AFL_GCC} instrumentation produces weird numbers: $TUPLES"
CODE=1
}
test "$TUPLES" -lt 4 && SKIP=1
true # this is needed because of the test above
} || {
$ECHO "$RED[!] ${AFL_GCC} failed"
echo CUT------------------------------------------------------------------CUT
uname -a
../${AFL_GCC} -o test-instr.plain ../test-instr.c
echo CUT------------------------------------------------------------------CUT
CODE=1
}
test -e test-compcov.harden && {
grep -Eq$GREPAOPTION 'stack_chk_fail|fstack-protector-all|fortified' test-compcov.harden > /dev/null 2>&1 && {
$ECHO "$GREEN[+] ${AFL_GCC} hardened mode succeeded and is working"
} || {
$ECHO "$RED[!] ${AFL_GCC} hardened mode is not hardened"
CODE=1
}
rm -f test-compcov.harden
} || {
$ECHO "$RED[!] ${AFL_GCC} hardened mode compilation failed"
CODE=1
}
# now we want to be sure that afl-fuzz is working
# make sure core_pattern is set to core on linux
(test "$(uname -s)" = "Linux" && test "$(sysctl kernel.core_pattern)" != "kernel.core_pattern = core" && {
$ECHO "$YELLOW[-] we should not run afl-fuzz with enabled core dumps. Run 'sudo sh afl-system-config'.$RESET"
true
}) ||
# make sure crash reporter is disabled on Mac OS X
(test "$(uname -s)" = "Darwin" && test $(launchctl list 2>/dev/null | grep -q '\.ReportCrash$') && {
$ECHO "$RED[!] we cannot run afl-fuzz with enabled crash reporter. Run 'sudo sh afl-system-config'.$RESET"
true
}) || {
mkdir -p in
echo 0 > in/in
test -z "$SKIP" && {
$ECHO "$GREY[*] running afl-fuzz for ${AFL_GCC}, this will take approx 10 seconds"
{
../afl-fuzz -V10 -m ${MEM_LIMIT} -i in -o out -D -- ./test-instr.plain >>errors 2>&1
} >>errors 2>&1
test -n "$( ls out/default/queue/id:000002* 2>/dev/null )" && {
$ECHO "$GREEN[+] afl-fuzz is working correctly with ${AFL_GCC}"
} || {
echo CUT------------------------------------------------------------------CUT
cat errors
echo CUT------------------------------------------------------------------CUT
$ECHO "$RED[!] afl-fuzz is not working correctly with ${AFL_GCC}"
CODE=1
}
}
echo 000000000000000000000000 > in/in2
echo AAA > in/in3
mkdir -p in2
../afl-cmin -m ${MEM_LIMIT} -i in -o in2 -- ./test-instr.plain >/dev/null 2>&1 # why is afl-forkserver writing to stderr?
CNT=`ls in2/* 2>/dev/null | wc -l`
case "$CNT" in
*2) $ECHO "$GREEN[+] afl-cmin correctly minimized the number of testcases" ;;
1) {
test -s in2/* && $ECHO "$YELLOW[?] afl-cmin did minimize to one testcase. This can be a bug or due compiler optimization."
test -s in2/* || {
$ECHO "$RED[!] afl-cmin did not correctly minimize the number of testcases ($CNT)"
CODE=1
}
}
;;
*) $ECHO "$RED[!] afl-cmin did not correctly minimize the number of testcases ($CNT)"
CODE=1
;;
esac
rm -f in2/in*
export AFL_QUIET=1
if command -v bash >/dev/null ; then {
../afl-cmin.bash -m ${MEM_LIMIT} -i in -o in2 -- ./test-instr.plain >/dev/null
CNT=`ls in2/* 2>/dev/null | wc -l`
case "$CNT" in
*2) $ECHO "$GREEN[+] afl-cmin.bash correctly minimized the number of testcases" ;;
1) {
test -s in2/* && $ECHO "$YELLOW[?] afl-cmin.bash did minimize to one testcase. This can be a bug or due compiler optimization."
test -s in2/* || {
$ECHO "$RED[!] afl-cmin.bash did not correctly minimize the number of testcases ($CNT)"
CODE=1
}
}
;;
*) $ECHO "$RED[!] afl-cmin.bash did not correctly minimize the number of testcases ($CNT)"
CODE=1
;;
esac
} else {
$ECHO "$GRAY[*] no bash available, cannot test afl-cmin.bash"
}
fi
../afl-tmin -m ${MEM_LIMIT} -i in/in2 -o in2/in2 -- ./test-instr.plain > /dev/null 2>&1
SIZE=`ls -l in2/in2 2>/dev/null | awk '{print$5}'`
test "$SIZE" = 1 && $ECHO "$GREEN[+] afl-tmin correctly minimized the testcase"
test "$SIZE" = 1 || {
$ECHO "$RED[!] afl-tmin did incorrectly minimize the testcase to $SIZE"
CODE=1
}
rm -rf in out errors in2
unset AFL_QUIET
}
rm -f test-instr.plain
} || {
$ECHO "$YELLOW[-] afl is not compiled, cannot test"
INCOMPLETE=1
}
} || {
$ECHO "$GREY[*] not an intel platform, skipped tests of afl-gcc"
#this is not incomplete as this feature doesnt exist, so all good
AFL_TEST_COUNT=$((AFL_TEST_COUNT-1))
}
. ./test-post.sh
|
function isPrime(num) {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
let num = 31;
let res = isPrime(num);
if (res)
console.log(num + " is Prime");
else
console.log(num + " is not Prime");
|
<reponame>wested/surveyor<gh_stars>0
class Validation < ApplicationRecord
include Surveyor::Models::ValidationMethods
end
|
<gh_stars>0
/*
* loader di element jquery
* per HTML5
*/
$(document).ready(function(){
$.canvas = {
support_canvas: function(){
return !!document.createElement('canvas').getContext;
},
supports_canvas_text: function(){
if (!$.canvas.support_canvas()) {return false;}
var emi_canv = document.createElement('canvas');
var emi_contx = emi_canv.getContext('2d');
return typeof emi_contx.fillText == 'function';
}
};
/*
* parte custom
*/
/*
if($.canvas.supports_canvas_text()){*/
/*titleobj.init('titleobj');*/
/*backblogo.init('backg-logo');
} else {
var dv = document.getElementById('backg-logo');
var fig = document.createElement('figure');
var imger = document.createElement('img');
imger.setAttribute('src','/images/er.png');
fig.appendChild(imger);
dv.appendChild(fig);
}
*/
});
|
CREATE TABLE BPM_TASK_DEF(
ID BIGINT NOT NULL,
TASK_DEFINITION_KEY VARCHAR(200),
ASSIGNEE VARCHAR(200),
CANDIDATE VARCHAR(200),
PROCESS_ID BIGINT,
CONSTRAINT PK_BPM_TASK_DEF PRIMARY KEY(ID),
CONSTRAINT FK_BPM_TASK_DEF_ID FOREIGN KEY(PROCESS_ID) REFERENCES BPM_PROCESS(ID)
) ENGINE=INNODB CHARSET=UTF8;
|
#!/bin/bash
set -ex
MY_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
cd $MY_DIR/edge_device
# serve fastapi app
python3 -m uvicorn fastapi_app:app --port 8778
|
/*
* Copyright (C) 2016 Lightbend Inc. <http://www.lightbend.com>
*/
package docs.home.scaladsl.persistence
import akka.Done
import com.lightbend.lagom.scaladsl.persistence.AggregateEvent
import com.lightbend.lagom.scaladsl.persistence.AggregateEventShards
import com.lightbend.lagom.scaladsl.persistence.AggregateEventTag
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
// FIXME move to docs project when API has settled
object Post {
// FIXME Jsonable
sealed trait BlogCommand
final case class AddPost(content: PostContent) extends BlogCommand with ReplyType[AddPostDone]
final case class AddPostDone(postId: String)
case object GetPost extends BlogCommand with ReplyType[PostContent]
final case class ChangeBody(body: String) extends BlogCommand with ReplyType[Done]
case object Publish extends BlogCommand with ReplyType[Done]
object BlogEvent {
val NumShards = 20
// second param is optional, defaults to the class name
val aggregateEventShards = AggregateEventTag.sharded[BlogEvent](NumShards)
}
sealed trait BlogEvent extends AggregateEvent[BlogEvent] {
override def aggregateTag: AggregateEventShards[BlogEvent] = BlogEvent.aggregateEventShards
}
final case class PostAdded(postId: String, content: PostContent) extends BlogEvent
final case class BodyChanged(postId: String, body: String) extends BlogEvent
final case class PostPublished(postId: String) extends BlogEvent
final case class PostContent(title: String, body: String)
object BlogState {
val empty = BlogState(None, published = false)
}
final case class BlogState(content: Option[PostContent], published: Boolean) {
def withBody(body: String): BlogState = {
content match {
case Some(c) =>
copy(content = Some(c.copy(body = body)))
case None =>
throw new IllegalStateException("Can't set body without content")
}
}
def isEmpty: Boolean = content.isEmpty
}
}
final class Post extends PersistentEntity[Post.BlogCommand, Post.BlogEvent, Post.BlogState] {
import Post._
override def initialState: BlogState = BlogState.empty
override def behavior: Behavior = {
case state if state.isEmpty => initial
case state if !state.isEmpty => postAdded
}
private val initial: Actions = {
Actions()
// Command handlers are invoked for incoming messages (commands).
// A command handler must "return" the events to be persisted (if any).
.onCommand {
case (cmd @ AddPost(content), ctx, state) =>
if (content.title == null || content.title.equals("")) {
ctx.invalidCommand("Title must be defined")
ctx.done
} else {
ctx.thenPersist(PostAdded(entityId, content), evt =>
// After persist is done additional side effects can be performed
ctx.reply(cmd, AddPostDone(entityId)))
}
}
// Event handlers are used both when persisting new events and when replaying
// events.
.onEvent {
case (PostAdded(postId, content), state) =>
BlogState(Some(content), published = false)
}
}
private val postAdded: Actions = {
Actions()
.onCommand {
case (cmd @ ChangeBody(body), ctx, state) =>
ctx.thenPersist(BodyChanged(entityId, body), _ => ctx.reply(cmd, Done))
}
}
}
|
#!/bin/bash -xeu
# Usage:
#
# $ ./scripts/release.sh v1.2.3 GITHUB_USER upstream
#
if [[ $1 != v* ]]; then
echo "Argument does not start with 'v'"
exit 1
fi
VERSION=${1#v}
GITHUB_USER=$2
REMOTE=$3
find . -type f -iname "*.pyc" -exec rm {} +
find . -type f -iname "*.o" -exec rm {} +
find . -type f -iname "*.so" -exec rm {} +
find . -type d -name "__pycache__" -exec rmdir {} +
find . -type f -iname ".coverage.*" -exec rm {} +
./scripts/check_clean_repo_on_master.sh
cd $(dirname $0)/..
# PKG will be name of the directory one level up containing "__init__.py"
PKG=$(find . -maxdepth 2 -name __init__.py -print0 | xargs -0 -n1 dirname | xargs basename)
PKG_UPPER=$(echo $PKG | tr '[:lower:]' '[:upper:]')
${PYTHON:-python3} setup.py build_ext -i
./scripts/run_tests.sh
env ${PKG_UPPER}_RELEASE_VERSION=v$VERSION ${PYTHON:-python3} setup.py sdist
if [[ -e ./scripts/generate_docs.sh ]]; then
env ${PKG_UPPER}_RELEASE_VERSION=v$VERSION ./scripts/generate_docs.sh
fi
# All went well, add a tag and push it.
git tag -a v$VERSION -m v$VERSION
git push $REMOTE
git push $REMOTE --tags
twine upload dist/${PKG}-$VERSION.tar.gz
set +x
echo ""
echo " You may now create a new github release at with the tag \"v$VERSION\" and name"
echo " it \"${PKG}-${VERSION}\". Here is a link:"
echo " https://github.com/${GITHUB_USER}/${PKG}/releases/new "
echo " name the release \"${PKG}-${VERSION}\", and don't foreget to manually attach the file:"
echo " $(openssl sha256 $(pwd)/dist/${PKG}-${VERSION}.tar.gz)"
echo " Then run:"
echo ""
echo " $ ./scripts/post_release.sh v${VERSION} <myserver.examples.com> ${GITHUB_USER} ${REMOTE}"
echo ""
|
export function calendar(yearArg: any, monthArg: any, flatParam?: boolean, formatParam?: string, locale?: string): any;
export function daysInCalendar(yearArg: any, monthArg: any, formatParam?: string): any[];
export function prevDaysInCalendar(yearArg: any, monthArg: any, formatParam?: string): any[];
export function nextDaysInCalendar(yearArg: any, monthArg: any, formatParam?: string): any[];
export function weeklyCalendar(yearParam: any, monthParam: any, dateParam: any, formatParam?: string, locale?: string): any;
export function calendarWithWeeks(yearArg: any, monthArg: any, flatParam?: boolean, formatParam?: string, locale?: string): any;
|
#!/bin/bash -u
JSFILE="$(mktemp --suffix=.js)"
function cleanup {
rm -rf -- "$JSFILE"
rm -rf -- "/home/ctf$JSFILE"
}
trap cleanup EXIT
cat > "$JSFILE"
cp "$JSFILE" "/home/ctf$JSFILE"
chmod 644 "/home/ctf$JSFILE"
/usr/sbin/chroot --userspec=1000:1000 /home/ctf timeout 600 ./ch "$JSFILE" 2>&1
|
<filename>projects/pezng/threejs/src/lib/components/camera/cube-camera/cube-camera.directive.spec.ts<gh_stars>0
import { CubeCameraDirective } from './cube-camera.directive';
describe('CubeCameraDirective', () => {
it('should create an instance', () => {
const directive = new CubeCameraDirective();
expect(directive).toBeTruthy();
});
});
|
!function(n, t) {
"object" == typeof module && "object" == typeof module.exports ? module.exports = n.document ? t(n, !0) : function(n) {
if (!n.document)
throw new Error("jQuery requires a window with a document");
return t(n)
}
: t(n)
}("undefined" != typeof window ? window : this, function(n, t) {
function ri(n) {
var t = n.length
, r = i.type(n);
return "function" === r || i.isWindow(n) ? !1 : 1 === n.nodeType && t ? !0 : "array" === r || 0 === t || "number" == typeof t && t > 0 && t - 1 in n
}
function ui(n, t, r) {
if (i.isFunction(t))
return i.grep(n, function(n, i) {
return !!t.call(n, i, n) !== r
});
if (t.nodeType)
return i.grep(n, function(n) {
return n === t !== r
});
if ("string" == typeof t) {
if (ef.test(t))
return i.filter(t, n, r);
t = i.filter(t, n)
}
return i.grep(n, function(n) {
return ft.call(t, n) >= 0 !== r
})
}
function ur(n, t) {
while ((n = n[t]) && 1 !== n.nodeType)
;
return n
}
function of(n) {
var t = fi[n] = {};
return i.each(n.match(c) || [], function(n, i) {
t[i] = !0
}),
t
}
function ht() {
u.removeEventListener("DOMContentLoaded", ht, !1);
n.removeEventListener("load", ht, !1);
i.ready()
}
function v() {
Object.defineProperty(this.cache = {}, 0, {
get: function() {
return {}
}
});
this.expando = i.expando + v.uid++
}
function fr(n, t, r) {
var u;
if (void 0 === r && 1 === n.nodeType)
if (u = "data-" + t.replace(hf, "-$1").toLowerCase(),
r = n.getAttribute(u),
"string" == typeof r) {
try {
r = "true" === r ? !0 : "false" === r ? !1 : "null" === r ? null : +r + "" === r ? +r : sf.test(r) ? i.parseJSON(r) : r
} catch (f) {}
e.set(n, t, r)
} else
r = void 0;
return r
}
function lt() {
return !0
}
function k() {
return !1
}
function hr() {
try {
return u.activeElement
} catch (n) {}
}
function vr(n, t) {
return i.nodeName(n, "table") && i.nodeName(11 !== t.nodeType ? t : t.firstChild, "tr") ? n.getElementsByTagName("tbody")[0] || n.appendChild(n.ownerDocument.createElement("tbody")) : n
}
function bf(n) {
return n.type = (null !== n.getAttribute("type")) + "/" + n.type,
n
}
function kf(n) {
var t = pf.exec(n.type);
return t ? n.type = t[1] : n.removeAttribute("type"),
n
}
function ei(n, t) {
for (var i = 0, u = n.length; u > i; i++)
r.set(n[i], "globalEval", !t || r.get(t[i], "globalEval"))
}
function yr(n, t) {
var u, c, f, s, h, l, a, o;
if (1 === t.nodeType) {
if (r.hasData(n) && (s = r.access(n),
h = r.set(t, s),
o = s.events)) {
delete h.handle;
h.events = {};
for (f in o)
for (u = 0,
c = o[f].length; c > u; u++)
i.event.add(t, f, o[f][u])
}
e.hasData(n) && (l = e.access(n),
a = i.extend({}, l),
e.set(t, a))
}
}
function o(n, t) {
var r = n.getElementsByTagName ? n.getElementsByTagName(t || "*") : n.querySelectorAll ? n.querySelectorAll(t || "*") : [];
return void 0 === t || t && i.nodeName(n, t) ? i.merge([n], r) : r
}
function df(n, t) {
var i = t.nodeName.toLowerCase();
"input" === i && er.test(n.type) ? t.checked = n.checked : ("input" === i || "textarea" === i) && (t.defaultValue = n.defaultValue)
}
function pr(t, r) {
var f, u = i(r.createElement(t)).appendTo(r.body), e = n.getDefaultComputedStyle && (f = n.getDefaultComputedStyle(u[0])) ? f.display : i.css(u[0], "display");
return u.detach(),
e
}
function si(n) {
var r = u
, t = oi[n];
return t || (t = pr(n, r),
"none" !== t && t || (at = (at || i("<iframe frameborder='0' width='0' height='0'/>")).appendTo(r.documentElement),
r = at[0].contentDocument,
r.write(),
r.close(),
t = pr(n, r),
at.detach()),
oi[n] = t),
t
}
function it(n, t, r) {
var e, o, s, u, f = n.style;
return r = r || vt(n),
r && (u = r.getPropertyValue(t) || r[t]),
r && ("" !== u || i.contains(n.ownerDocument, n) || (u = i.style(n, t)),
hi.test(u) && wr.test(t) && (e = f.width,
o = f.minWidth,
s = f.maxWidth,
f.minWidth = f.maxWidth = f.width = u,
u = r.width,
f.width = e,
f.minWidth = o,
f.maxWidth = s)),
void 0 !== u ? u + "" : u
}
function br(n, t) {
return {
get: function() {
return n() ? void delete this.get : (this.get = t).apply(this, arguments)
}
}
}
function gr(n, t) {
if (t in n)
return t;
for (var r = t[0].toUpperCase() + t.slice(1), u = t, i = dr.length; i--; )
if (t = dr[i] + r,
t in n)
return t;
return u
}
function nu(n, t, i) {
var r = ne.exec(t);
return r ? Math.max(0, r[1] - (i || 0)) + (r[2] || "px") : t
}
function tu(n, t, r, u, f) {
for (var e = r === (u ? "border" : "content") ? 4 : "width" === t ? 1 : 0, o = 0; 4 > e; e += 2)
"margin" === r && (o += i.css(n, r + p[e], !0, f)),
u ? ("content" === r && (o -= i.css(n, "padding" + p[e], !0, f)),
"margin" !== r && (o -= i.css(n, "border" + p[e] + "Width", !0, f))) : (o += i.css(n, "padding" + p[e], !0, f),
"padding" !== r && (o += i.css(n, "border" + p[e] + "Width", !0, f)));
return o
}
function iu(n, t, r) {
var o = !0
, u = "width" === t ? n.offsetWidth : n.offsetHeight
, e = vt(n)
, s = "border-box" === i.css(n, "boxSizing", !1, e);
if (0 >= u || null == u) {
if (u = it(n, t, e),
(0 > u || null == u) && (u = n.style[t]),
hi.test(u))
return u;
o = s && (f.boxSizingReliable() || u === n.style[t]);
u = parseFloat(u) || 0
}
return u + tu(n, t, r || (s ? "border" : "content"), o, e) + "px"
}
function ru(n, t) {
for (var e, u, s, o = [], f = 0, h = n.length; h > f; f++)
u = n[f],
u.style && (o[f] = r.get(u, "olddisplay"),
e = u.style.display,
t ? (o[f] || "none" !== e || (u.style.display = ""),
"" === u.style.display && tt(u) && (o[f] = r.access(u, "olddisplay", si(u.nodeName)))) : (s = tt(u),
"none" === e && s || r.set(u, "olddisplay", s ? e : i.css(u, "display"))));
for (f = 0; h > f; f++)
u = n[f],
u.style && (t && "none" !== u.style.display && "" !== u.style.display || (u.style.display = t ? o[f] || "" : "none"));
return n
}
function s(n, t, i, r, u) {
return new s.prototype.init(n,t,i,r,u)
}
function fu() {
return setTimeout(function() {
d = void 0
}),
d = i.now()
}
function wt(n, t) {
var r, u = 0, i = {
height: n
};
for (t = t ? 1 : 0; 4 > u; u += 2 - t)
r = p[u],
i["margin" + r] = i["padding" + r] = n;
return t && (i.opacity = i.width = n),
i
}
function eu(n, t, i) {
for (var u, f = (rt[t] || []).concat(rt["*"]), r = 0, e = f.length; e > r; r++)
if (u = f[r].call(i, t, n))
return u
}
function fe(n, t, u) {
var f, a, p, v, o, w, h, b, l = this, y = {}, s = n.style, c = n.nodeType && tt(n), e = r.get(n, "fxshow");
u.queue || (o = i._queueHooks(n, "fx"),
null == o.unqueued && (o.unqueued = 0,
w = o.empty.fire,
o.empty.fire = function() {
o.unqueued || w()
}
),
o.unqueued++,
l.always(function() {
l.always(function() {
o.unqueued--;
i.queue(n, "fx").length || o.empty.fire()
})
}));
1 === n.nodeType && ("height"in t || "width"in t) && (u.overflow = [s.overflow, s.overflowX, s.overflowY],
h = i.css(n, "display"),
b = "none" === h ? r.get(n, "olddisplay") || si(n.nodeName) : h,
"inline" === b && "none" === i.css(n, "float") && (s.display = "inline-block"));
u.overflow && (s.overflow = "hidden",
l.always(function() {
s.overflow = u.overflow[0];
s.overflowX = u.overflow[1];
s.overflowY = u.overflow[2]
}));
for (f in t)
if (a = t[f],
re.exec(a)) {
if (delete t[f],
p = p || "toggle" === a,
a === (c ? "hide" : "show")) {
if ("show" !== a || !e || void 0 === e[f])
continue;
c = !0
}
y[f] = e && e[f] || i.style(n, f)
} else
h = void 0;
if (i.isEmptyObject(y))
"inline" === ("none" === h ? si(n.nodeName) : h) && (s.display = h);
else {
e ? "hidden"in e && (c = e.hidden) : e = r.access(n, "fxshow", {});
p && (e.hidden = !c);
c ? i(n).show() : l.done(function() {
i(n).hide()
});
l.done(function() {
var t;
r.remove(n, "fxshow");
for (t in y)
i.style(n, t, y[t])
});
for (f in y)
v = eu(c ? e[f] : 0, f, l),
f in e || (e[f] = v.start,
c && (v.end = v.start,
v.start = "width" === f || "height" === f ? 1 : 0))
}
}
function ee(n, t) {
var r, f, e, u, o;
for (r in n)
if (f = i.camelCase(r),
e = t[f],
u = n[r],
i.isArray(u) && (e = u[1],
u = n[r] = u[0]),
r !== f && (n[f] = u,
delete n[r]),
o = i.cssHooks[f],
o && "expand"in o) {
u = o.expand(u);
delete n[f];
for (r in u)
r in n || (n[r] = u[r],
t[r] = e)
} else
t[f] = e
}
function ou(n, t, r) {
var h, e, o = 0, l = pt.length, f = i.Deferred().always(function() {
delete c.elem
}), c = function() {
if (e)
return !1;
for (var s = d || fu(), t = Math.max(0, u.startTime + u.duration - s), h = t / u.duration || 0, i = 1 - h, r = 0, o = u.tweens.length; o > r; r++)
u.tweens[r].run(i);
return f.notifyWith(n, [u, i, t]),
1 > i && o ? t : (f.resolveWith(n, [u]),
!1)
}, u = f.promise({
elem: n,
props: i.extend({}, t),
opts: i.extend(!0, {
specialEasing: {}
}, r),
originalProperties: t,
originalOptions: r,
startTime: d || fu(),
duration: r.duration,
tweens: [],
createTween: function(t, r) {
var f = i.Tween(n, u.opts, t, r, u.opts.specialEasing[t] || u.opts.easing);
return u.tweens.push(f),
f
},
stop: function(t) {
var i = 0
, r = t ? u.tweens.length : 0;
if (e)
return this;
for (e = !0; r > i; i++)
u.tweens[i].run(1);
return t ? f.resolveWith(n, [u, t]) : f.rejectWith(n, [u, t]),
this
}
}), s = u.props;
for (ee(s, u.opts.specialEasing); l > o; o++)
if (h = pt[o].call(u, n, s, u.opts))
return h;
return i.map(s, eu, u),
i.isFunction(u.opts.start) && u.opts.start.call(n, u),
i.fx.timer(i.extend(c, {
elem: n,
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 pu(n) {
return function(t, r) {
"string" != typeof t && (r = t,
t = "*");
var u, f = 0, e = t.toLowerCase().match(c) || [];
if (i.isFunction(r))
while (u = e[f++])
"+" === u[0] ? (u = u.slice(1) || "*",
(n[u] = n[u] || []).unshift(r)) : (n[u] = n[u] || []).push(r)
}
}
function wu(n, t, r, u) {
function e(s) {
var h;
return f[s] = !0,
i.each(n[s] || [], function(n, i) {
var s = i(t, r, u);
return "string" != typeof s || o || f[s] ? o ? !(h = s) : void 0 : (t.dataTypes.unshift(s),
e(s),
!1)
}),
h
}
var f = {}
, o = n === ci;
return e(t.dataTypes[0]) || !f["*"] && e("*")
}
function ai(n, t) {
var r, u, f = i.ajaxSettings.flatOptions || {};
for (r in t)
void 0 !== t[r] && ((f[r] ? n : u || (u = {}))[r] = t[r]);
return u && i.extend(!0, n, u),
n
}
function ae(n, t, i) {
for (var e, u, f, o, s = n.contents, r = n.dataTypes; "*" === r[0]; )
r.shift(),
void 0 === e && (e = n.mimeType || t.getResponseHeader("Content-Type"));
if (e)
for (u in s)
if (s[u] && s[u].test(e)) {
r.unshift(u);
break
}
if (r[0]in i)
f = r[0];
else {
for (u in i) {
if (!r[0] || n.converters[u + " " + r[0]]) {
f = u;
break
}
o || (o = u)
}
f = f || o
}
if (f)
return (f !== r[0] && r.unshift(f),
i[f])
}
function ve(n, t, i, r) {
var h, u, f, s, e, o = {}, c = n.dataTypes.slice();
if (c[1])
for (f in n.converters)
o[f.toLowerCase()] = n.converters[f];
for (u = c.shift(); u; )
if (n.responseFields[u] && (i[n.responseFields[u]] = t),
!e && r && n.dataFilter && (t = n.dataFilter(t, n.dataType)),
e = u,
u = c.shift())
if ("*" === u)
u = e;
else if ("*" !== e && e !== u) {
if (f = o[e + " " + u] || o["* " + u],
!f)
for (h in o)
if (s = h.split(" "),
s[1] === u && (f = o[e + " " + s[0]] || o["* " + s[0]])) {
f === !0 ? f = o[h] : o[h] !== !0 && (u = s[0],
c.unshift(s[1]));
break
}
if (f !== !0)
if (f && n.throws)
t = f(t);
else
try {
t = f(t)
} catch (l) {
return {
state: "parsererror",
error: f ? l : "No conversion from " + e + " to " + u
}
}
}
return {
state: "success",
data: t
}
}
function vi(n, t, r, u) {
var f;
if (i.isArray(t))
i.each(t, function(t, i) {
r || pe.test(n) ? u(n, i) : vi(n + "[" + ("object" == typeof i ? t : "") + "]", i, r, u)
});
else if (r || "object" !== i.type(t))
u(n, t);
else
for (f in t)
vi(n + "[" + f + "]", t[f], r, u)
}
function ku(n) {
return i.isWindow(n) ? n : 9 === n.nodeType && n.defaultView
}
var w = [], a = w.slice, bi = w.concat, ti = w.push, ft = w.indexOf, et = {}, nf = et.toString, ii = et.hasOwnProperty, f = {}, u = n.document, ki = "2.1.3", i = function(n, t) {
return new i.fn.init(n,t)
}, tf = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, rf = /^-ms-/, uf = /-([\da-z])/gi, ff = function(n, t) {
return t.toUpperCase()
}, y, ot, nr, tr, ir, rr, c, fi, st, l, b, at, oi, oe, su, g, hu, bt, cu, kt, dt, yi, ni, pi, wi, du, gu;
i.fn = i.prototype = {
jquery: ki,
constructor: i,
selector: "",
length: 0,
toArray: function() {
return a.call(this)
},
get: function(n) {
return null != n ? 0 > n ? this[n + this.length] : this[n] : a.call(this)
},
pushStack: function(n) {
var t = i.merge(this.constructor(), n);
return t.prevObject = this,
t.context = this.context,
t
},
each: function(n, t) {
return i.each(this, n, t)
},
map: function(n) {
return this.pushStack(i.map(this, function(t, i) {
return n.call(t, i, t)
}))
},
slice: function() {
return this.pushStack(a.apply(this, arguments))
},
first: function() {
return this.eq(0)
},
last: function() {
return this.eq(-1)
},
eq: function(n) {
var i = this.length
, t = +n + (0 > n ? i : 0);
return this.pushStack(t >= 0 && i > t ? [this[t]] : [])
},
end: function() {
return this.prevObject || this.constructor(null)
},
push: ti,
sort: w.sort,
splice: w.splice
};
i.extend = i.fn.extend = function() {
var e, f, r, t, o, s, n = arguments[0] || {}, u = 1, c = arguments.length, h = !1;
for ("boolean" == typeof n && (h = n,
n = arguments[u] || {},
u++),
"object" == typeof n || i.isFunction(n) || (n = {}),
u === c && (n = this,
u--); c > u; u++)
if (null != (e = arguments[u]))
for (f in e)
r = n[f],
t = e[f],
n !== t && (h && t && (i.isPlainObject(t) || (o = i.isArray(t))) ? (o ? (o = !1,
s = r && i.isArray(r) ? r : []) : s = r && i.isPlainObject(r) ? r : {},
n[f] = i.extend(h, s, t)) : void 0 !== t && (n[f] = t));
return n
}
;
i.extend({
expando: "jQuery" + (ki + Math.random()).replace(/\D/g, ""),
isReady: !0,
error: function(n) {
throw new Error(n);
},
noop: function() {},
isFunction: function(n) {
return "function" === i.type(n)
},
isArray: Array.isArray,
isWindow: function(n) {
return null != n && n === n.window
},
isNumeric: function(n) {
return !i.isArray(n) && n - parseFloat(n) + 1 >= 0
},
isPlainObject: function(n) {
return "object" !== i.type(n) || n.nodeType || i.isWindow(n) ? !1 : n.constructor && !ii.call(n.constructor.prototype, "isPrototypeOf") ? !1 : !0
},
isEmptyObject: function(n) {
var t;
for (t in n)
return !1;
return !0
},
type: function(n) {
return null == n ? n + "" : "object" == typeof n || "function" == typeof n ? et[nf.call(n)] || "object" : typeof n
},
globalEval: function(n) {
var t, r = eval;
n = i.trim(n);
n && (1 === n.indexOf("use strict") ? (t = u.createElement("script"),
t.text = n,
u.head.appendChild(t).parentNode.removeChild(t)) : r(n))
},
camelCase: function(n) {
return n.replace(rf, "ms-").replace(uf, ff)
},
nodeName: function(n, t) {
return n.nodeName && n.nodeName.toLowerCase() === t.toLowerCase()
},
each: function(n, t, i) {
var u, r = 0, f = n.length, e = ri(n);
if (i) {
if (e) {
for (; f > r; r++)
if (u = t.apply(n[r], i),
u === !1)
break
} else
for (r in n)
if (u = t.apply(n[r], i),
u === !1)
break
} else if (e) {
for (; f > r; r++)
if (u = t.call(n[r], r, n[r]),
u === !1)
break
} else
for (r in n)
if (u = t.call(n[r], r, n[r]),
u === !1)
break;
return n
},
trim: function(n) {
return null == n ? "" : (n + "").replace(tf, "")
},
makeArray: function(n, t) {
var r = t || [];
return null != n && (ri(Object(n)) ? i.merge(r, "string" == typeof n ? [n] : n) : ti.call(r, n)),
r
},
inArray: function(n, t, i) {
return null == t ? -1 : ft.call(t, n, i)
},
merge: function(n, t) {
for (var u = +t.length, i = 0, r = n.length; u > i; i++)
n[r++] = t[i];
return n.length = r,
n
},
grep: function(n, t, i) {
for (var u, f = [], r = 0, e = n.length, o = !i; e > r; r++)
u = !t(n[r], r),
u !== o && f.push(n[r]);
return f
},
map: function(n, t, i) {
var u, r = 0, e = n.length, o = ri(n), f = [];
if (o)
for (; e > r; r++)
u = t(n[r], r, i),
null != u && f.push(u);
else
for (r in n)
u = t(n[r], r, i),
null != u && f.push(u);
return bi.apply([], f)
},
guid: 1,
proxy: function(n, t) {
var u, f, r;
return "string" == typeof t && (u = n[t],
t = n,
n = u),
i.isFunction(n) ? (f = a.call(arguments, 2),
r = function() {
return n.apply(t || this, f.concat(a.call(arguments)))
}
,
r.guid = n.guid = n.guid || i.guid++,
r) : void 0
},
now: Date.now,
support: f
});
i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(n, t) {
et["[object " + t + "]"] = t.toLowerCase()
});
y = function(n) {
function r(n, t, i, r) {
var p, s, a, c, w, y, d, v, nt, g;
if ((t ? t.ownerDocument || t : h) !== o && k(t),
t = t || o,
i = i || [],
c = t.nodeType,
"string" != typeof n || !n || 1 !== c && 9 !== c && 11 !== c)
return i;
if (!r && l) {
if (11 !== c && (p = hr.exec(n)))
if (a = p[1]) {
if (9 === c) {
if (s = t.getElementById(a),
!s || !s.parentNode)
return i;
if (s.id === a)
return i.push(s),
i
} else if (t.ownerDocument && (s = t.ownerDocument.getElementById(a)) && et(t, s) && s.id === a)
return i.push(s),
i
} else {
if (p[2])
return b.apply(i, t.getElementsByTagName(n)),
i;
if ((a = p[3]) && u.getElementsByClassName)
return b.apply(i, t.getElementsByClassName(a)),
i
}
if (u.qsa && (!e || !e.test(n))) {
if (v = d = f,
nt = t,
g = 1 !== c && n,
1 === c && "object" !== t.nodeName.toLowerCase()) {
for (y = ft(n),
(d = t.getAttribute("id")) ? v = d.replace(cr, "\\$&") : t.setAttribute("id", v),
v = "[id='" + v + "'] ",
w = y.length; w--; )
y[w] = v + vt(y[w]);
nt = dt.test(n) && ti(t.parentNode) || t;
g = y.join(",")
}
if (g)
try {
return b.apply(i, nt.querySelectorAll(g)),
i
} catch (tt) {} finally {
d || t.removeAttribute("id")
}
}
}
return oi(n.replace(lt, "$1"), t, i, r)
}
function gt() {
function n(r, u) {
return i.push(r + " ") > t.cacheLength && delete n[i.shift()],
n[r + " "] = u
}
var i = [];
return n
}
function c(n) {
return n[f] = !0,
n
}
function v(n) {
var t = o.createElement("div");
try {
return !!n(t)
} catch (i) {
return !1
} finally {
t.parentNode && t.parentNode.removeChild(t);
t = null
}
}
function ni(n, i) {
for (var u = n.split("|"), r = n.length; r--; )
t.attrHandle[u[r]] = i
}
function wi(n, t) {
var i = t && n
, r = i && 1 === n.nodeType && 1 === t.nodeType && (~t.sourceIndex || li) - (~n.sourceIndex || li);
if (r)
return r;
if (i)
while (i = i.nextSibling)
if (i === t)
return -1;
return n ? 1 : -1
}
function lr(n) {
return function(t) {
var i = t.nodeName.toLowerCase();
return "input" === i && t.type === n
}
}
function ar(n) {
return function(t) {
var i = t.nodeName.toLowerCase();
return ("input" === i || "button" === i) && t.type === n
}
}
function tt(n) {
return c(function(t) {
return t = +t,
c(function(i, r) {
for (var u, f = n([], i.length, t), e = f.length; e--; )
i[u = f[e]] && (i[u] = !(r[u] = i[u]))
})
})
}
function ti(n) {
return n && "undefined" != typeof n.getElementsByTagName && n
}
function bi() {}
function vt(n) {
for (var t = 0, r = n.length, i = ""; r > t; t++)
i += n[t].value;
return i
}
function ii(n, t, i) {
var r = t.dir
, u = i && "parentNode" === r
, e = ki++;
return t.first ? function(t, i, f) {
while (t = t[r])
if (1 === t.nodeType || u)
return n(t, i, f)
}
: function(t, i, o) {
var s, h, c = [a, e];
if (o) {
while (t = t[r])
if ((1 === t.nodeType || u) && n(t, i, o))
return !0
} else
while (t = t[r])
if (1 === t.nodeType || u) {
if (h = t[f] || (t[f] = {}),
(s = h[r]) && s[0] === a && s[1] === e)
return c[2] = s[2];
if (h[r] = c,
c[2] = n(t, i, o))
return !0
}
}
}
function ri(n) {
return n.length > 1 ? function(t, i, r) {
for (var u = n.length; u--; )
if (!n[u](t, i, r))
return !1;
return !0
}
: n[0]
}
function vr(n, t, i) {
for (var u = 0, f = t.length; f > u; u++)
r(n, t[u], i);
return i
}
function yt(n, t, i, r, u) {
for (var e, o = [], f = 0, s = n.length, h = null != t; s > f; f++)
(e = n[f]) && (!i || i(e, r, u)) && (o.push(e),
h && t.push(f));
return o
}
function ui(n, t, i, r, u, e) {
return r && !r[f] && (r = ui(r)),
u && !u[f] && (u = ui(u, e)),
c(function(f, e, o, s) {
var l, c, a, p = [], y = [], w = e.length, k = f || vr(t || "*", o.nodeType ? [o] : o, []), v = !n || !f && t ? k : yt(k, p, n, o, s), h = i ? u || (f ? n : w || r) ? [] : e : v;
if (i && i(v, h, o, s),
r)
for (l = yt(h, y),
r(l, [], o, s),
c = l.length; c--; )
(a = l[c]) && (h[y[c]] = !(v[y[c]] = a));
if (f) {
if (u || n) {
if (u) {
for (l = [],
c = h.length; c--; )
(a = h[c]) && l.push(v[c] = a);
u(null, h = [], l, s)
}
for (c = h.length; c--; )
(a = h[c]) && (l = u ? nt(f, a) : p[c]) > -1 && (f[l] = !(e[l] = a))
}
} else
h = yt(h === e ? h.splice(w, h.length) : h),
u ? u(null, e, h, s) : b.apply(e, h)
})
}
function fi(n) {
for (var o, u, r, s = n.length, h = t.relative[n[0].type], c = h || t.relative[" "], i = h ? 1 : 0, l = ii(function(n) {
return n === o
}, c, !0), a = ii(function(n) {
return nt(o, n) > -1
}, c, !0), e = [function(n, t, i) {
var r = !h && (i || t !== ht) || ((o = t).nodeType ? l(n, t, i) : a(n, t, i));
return o = null,
r
}
]; s > i; i++)
if (u = t.relative[n[i].type])
e = [ii(ri(e), u)];
else {
if (u = t.filter[n[i].type].apply(null, n[i].matches),
u[f]) {
for (r = ++i; s > r; r++)
if (t.relative[n[r].type])
break;
return ui(i > 1 && ri(e), i > 1 && vt(n.slice(0, i - 1).concat({
value: " " === n[i - 2].type ? "*" : ""
})).replace(lt, "$1"), u, r > i && fi(n.slice(i, r)), s > r && fi(n = n.slice(r)), s > r && vt(n))
}
e.push(u)
}
return ri(e)
}
function yr(n, i) {
var u = i.length > 0
, f = n.length > 0
, e = function(e, s, h, c, l) {
var y, d, w, k = 0, v = "0", g = e && [], p = [], nt = ht, tt = e || f && t.find.TAG("*", l), it = a += null == nt ? 1 : Math.random() || .1, rt = tt.length;
for (l && (ht = s !== o && s); v !== rt && null != (y = tt[v]); v++) {
if (f && y) {
for (d = 0; w = n[d++]; )
if (w(y, s, h)) {
c.push(y);
break
}
l && (a = it)
}
u && ((y = !w && y) && k--,
e && g.push(y))
}
if (k += v,
u && v !== k) {
for (d = 0; w = i[d++]; )
w(g, p, s, h);
if (e) {
if (k > 0)
while (v--)
g[v] || p[v] || (p[v] = gi.call(c));
p = yt(p)
}
b.apply(c, p);
l && !e && p.length > 0 && k + i.length > 1 && r.uniqueSort(c)
}
return l && (a = it,
ht = nt),
g
};
return u ? c(e) : e
}
var it, u, t, st, ei, ft, pt, oi, ht, w, rt, k, o, s, l, e, d, ct, et, f = "sizzle" + 1 * new Date, h = n.document, a = 0, ki = 0, si = gt(), hi = gt(), ci = gt(), wt = function(n, t) {
return n === t && (rt = !0),
0
}, li = -2147483648, di = {}.hasOwnProperty, g = [], gi = g.pop, nr = g.push, b = g.push, ai = g.slice, nt = function(n, t) {
for (var i = 0, r = n.length; r > i; i++)
if (n[i] === t)
return i;
return -1
}, bt = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", i = "[\\x20\\t\\r\\n\\f]", ut = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", vi = ut.replace("w", "w#"), yi = "\\[" + i + "*(" + ut + ")(?:" + i + "*([*^$|!~]?=)" + i + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + vi + "))|)" + i + "*\\]", kt = ":(" + ut + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + yi + ")*)|.*)\\)|)", tr = new RegExp(i + "+","g"), lt = new RegExp("^" + i + "+|((?:^|[^\\\\])(?:\\\\.)*)" + i + "+$","g"), ir = new RegExp("^" + i + "*," + i + "*"), rr = new RegExp("^" + i + "*([>+~]|" + i + ")" + i + "*"), ur = new RegExp("=" + i + "*([^\\]'\"]*?)" + i + "*\\]","g"), fr = new RegExp(kt), er = new RegExp("^" + vi + "$"), at = {
ID: new RegExp("^#(" + ut + ")"),
CLASS: new RegExp("^\\.(" + ut + ")"),
TAG: new RegExp("^(" + ut.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + yi),
PSEUDO: new RegExp("^" + kt),
CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + i + "*(even|odd|(([+-]|)(\\d*)n|)" + i + "*(?:([+-]|)" + i + "*(\\d+)|))" + i + "*\\)|)","i"),
bool: new RegExp("^(?:" + bt + ")$","i"),
needsContext: new RegExp("^" + i + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + i + "*((?:-\\d)?\\d*)" + i + "*\\)|)(?=[^-]|$)","i")
}, or = /^(?:input|select|textarea|button)$/i, sr = /^h\d$/i, ot = /^[^{]+\{\s*\[native \w/, hr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, dt = /[+~]/, cr = /'|\\/g, y = new RegExp("\\\\([\\da-f]{1,6}" + i + "?|(" + i + ")|.)","ig"), p = function(n, t, i) {
var r = "0x" + t - 65536;
return r !== r || i ? t : 0 > r ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, 1023 & r | 56320)
}, pi = function() {
k()
};
try {
b.apply(g = ai.call(h.childNodes), h.childNodes);
g[h.childNodes.length].nodeType
} catch (pr) {
b = {
apply: g.length ? function(n, t) {
nr.apply(n, ai.call(t))
}
: function(n, t) {
for (var i = n.length, r = 0; n[i++] = t[r++]; )
;
n.length = i - 1
}
}
}
u = r.support = {};
ei = r.isXML = function(n) {
var t = n && (n.ownerDocument || n).documentElement;
return t ? "HTML" !== t.nodeName : !1
}
;
k = r.setDocument = function(n) {
var a, c, r = n ? n.ownerDocument || n : h;
return r !== o && 9 === r.nodeType && r.documentElement ? (o = r,
s = r.documentElement,
c = r.defaultView,
c && c !== c.top && (c.addEventListener ? c.addEventListener("unload", pi, !1) : c.attachEvent && c.attachEvent("onunload", pi)),
l = !ei(r),
u.attributes = v(function(n) {
return n.className = "i",
!n.getAttribute("className")
}),
u.getElementsByTagName = v(function(n) {
return n.appendChild(r.createComment("")),
!n.getElementsByTagName("*").length
}),
u.getElementsByClassName = ot.test(r.getElementsByClassName),
u.getById = v(function(n) {
return s.appendChild(n).id = f,
!r.getElementsByName || !r.getElementsByName(f).length
}),
u.getById ? (t.find.ID = function(n, t) {
if ("undefined" != typeof t.getElementById && l) {
var i = t.getElementById(n);
return i && i.parentNode ? [i] : []
}
}
,
t.filter.ID = function(n) {
var t = n.replace(y, p);
return function(n) {
return n.getAttribute("id") === t
}
}
) : (delete t.find.ID,
t.filter.ID = function(n) {
var t = n.replace(y, p);
return function(n) {
var i = "undefined" != typeof n.getAttributeNode && n.getAttributeNode("id");
return i && i.value === t
}
}
),
t.find.TAG = u.getElementsByTagName ? function(n, t) {
return "undefined" != typeof t.getElementsByTagName ? t.getElementsByTagName(n) : u.qsa ? t.querySelectorAll(n) : void 0
}
: function(n, t) {
var i, r = [], f = 0, u = t.getElementsByTagName(n);
if ("*" === n) {
while (i = u[f++])
1 === i.nodeType && r.push(i);
return r
}
return u
}
,
t.find.CLASS = u.getElementsByClassName && function(n, t) {
if (l)
return t.getElementsByClassName(n)
}
,
d = [],
e = [],
(u.qsa = ot.test(r.querySelectorAll)) && (v(function(n) {
s.appendChild(n).innerHTML = "<a id='" + f + "'><\/a><select id='" + f + "-\f]' msallowcapture=''><option selected=''><\/option><\/select>";
n.querySelectorAll("[msallowcapture^='']").length && e.push("[*^$]=" + i + "*(?:''|\"\")");
n.querySelectorAll("[selected]").length || e.push("\\[" + i + "*(?:value|" + bt + ")");
n.querySelectorAll("[id~=" + f + "-]").length || e.push("~=");
n.querySelectorAll(":checked").length || e.push(":checked");
n.querySelectorAll("a#" + f + "+*").length || e.push(".#.+[+~]")
}),
v(function(n) {
var t = r.createElement("input");
t.setAttribute("type", "hidden");
n.appendChild(t).setAttribute("name", "D");
n.querySelectorAll("[name=d]").length && e.push("name" + i + "*[*^$|!~]?=");
n.querySelectorAll(":enabled").length || e.push(":enabled", ":disabled");
n.querySelectorAll("*,:x");
e.push(",.*:")
})),
(u.matchesSelector = ot.test(ct = s.matches || s.webkitMatchesSelector || s.mozMatchesSelector || s.oMatchesSelector || s.msMatchesSelector)) && v(function(n) {
u.disconnectedMatch = ct.call(n, "div");
ct.call(n, "[s!='']:x");
d.push("!=", kt)
}),
e = e.length && new RegExp(e.join("|")),
d = d.length && new RegExp(d.join("|")),
a = ot.test(s.compareDocumentPosition),
et = a || ot.test(s.contains) ? function(n, t) {
var r = 9 === n.nodeType ? n.documentElement : n
, i = t && t.parentNode;
return n === i || !(!i || 1 !== i.nodeType || !(r.contains ? r.contains(i) : n.compareDocumentPosition && 16 & n.compareDocumentPosition(i)))
}
: function(n, t) {
if (t)
while (t = t.parentNode)
if (t === n)
return !0;
return !1
}
,
wt = a ? function(n, t) {
if (n === t)
return rt = !0,
0;
var i = !n.compareDocumentPosition - !t.compareDocumentPosition;
return i ? i : (i = (n.ownerDocument || n) === (t.ownerDocument || t) ? n.compareDocumentPosition(t) : 1,
1 & i || !u.sortDetached && t.compareDocumentPosition(n) === i ? n === r || n.ownerDocument === h && et(h, n) ? -1 : t === r || t.ownerDocument === h && et(h, t) ? 1 : w ? nt(w, n) - nt(w, t) : 0 : 4 & i ? -1 : 1)
}
: function(n, t) {
if (n === t)
return rt = !0,
0;
var i, u = 0, o = n.parentNode, s = t.parentNode, f = [n], e = [t];
if (!o || !s)
return n === r ? -1 : t === r ? 1 : o ? -1 : s ? 1 : w ? nt(w, n) - nt(w, t) : 0;
if (o === s)
return wi(n, t);
for (i = n; i = i.parentNode; )
f.unshift(i);
for (i = t; i = i.parentNode; )
e.unshift(i);
while (f[u] === e[u])
u++;
return u ? wi(f[u], e[u]) : f[u] === h ? -1 : e[u] === h ? 1 : 0
}
,
r) : o
}
;
r.matches = function(n, t) {
return r(n, null, null, t)
}
;
r.matchesSelector = function(n, t) {
if ((n.ownerDocument || n) !== o && k(n),
t = t.replace(ur, "='$1']"),
!(!u.matchesSelector || !l || d && d.test(t) || e && e.test(t)))
try {
var i = ct.call(n, t);
if (i || u.disconnectedMatch || n.document && 11 !== n.document.nodeType)
return i
} catch (f) {}
return r(t, o, null, [n]).length > 0
}
;
r.contains = function(n, t) {
return (n.ownerDocument || n) !== o && k(n),
et(n, t)
}
;
r.attr = function(n, i) {
(n.ownerDocument || n) !== o && k(n);
var f = t.attrHandle[i.toLowerCase()]
, r = f && di.call(t.attrHandle, i.toLowerCase()) ? f(n, i, !l) : void 0;
return void 0 !== r ? r : u.attributes || !l ? n.getAttribute(i) : (r = n.getAttributeNode(i)) && r.specified ? r.value : null
}
;
r.error = function(n) {
throw new Error("Syntax error, unrecognized expression: " + n);
}
;
r.uniqueSort = function(n) {
var r, f = [], t = 0, i = 0;
if (rt = !u.detectDuplicates,
w = !u.sortStable && n.slice(0),
n.sort(wt),
rt) {
while (r = n[i++])
r === n[i] && (t = f.push(i));
while (t--)
n.splice(f[t], 1)
}
return w = null,
n
}
;
st = r.getText = function(n) {
var r, i = "", u = 0, t = n.nodeType;
if (t) {
if (1 === t || 9 === t || 11 === t) {
if ("string" == typeof n.textContent)
return n.textContent;
for (n = n.firstChild; n; n = n.nextSibling)
i += st(n)
} else if (3 === t || 4 === t)
return n.nodeValue
} else
while (r = n[u++])
i += st(r);
return i
}
;
t = r.selectors = {
cacheLength: 50,
createPseudo: c,
match: at,
attrHandle: {},
find: {},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(n) {
return n[1] = n[1].replace(y, p),
n[3] = (n[3] || n[4] || n[5] || "").replace(y, p),
"~=" === n[2] && (n[3] = " " + n[3] + " "),
n.slice(0, 4)
},
CHILD: function(n) {
return n[1] = n[1].toLowerCase(),
"nth" === n[1].slice(0, 3) ? (n[3] || r.error(n[0]),
n[4] = +(n[4] ? n[5] + (n[6] || 1) : 2 * ("even" === n[3] || "odd" === n[3])),
n[5] = +(n[7] + n[8] || "odd" === n[3])) : n[3] && r.error(n[0]),
n
},
PSEUDO: function(n) {
var i, t = !n[6] && n[2];
return at.CHILD.test(n[0]) ? null : (n[3] ? n[2] = n[4] || n[5] || "" : t && fr.test(t) && (i = ft(t, !0)) && (i = t.indexOf(")", t.length - i) - t.length) && (n[0] = n[0].slice(0, i),
n[2] = t.slice(0, i)),
n.slice(0, 3))
}
},
filter: {
TAG: function(n) {
var t = n.replace(y, p).toLowerCase();
return "*" === n ? function() {
return !0
}
: function(n) {
return n.nodeName && n.nodeName.toLowerCase() === t
}
},
CLASS: function(n) {
var t = si[n + " "];
return t || (t = new RegExp("(^|" + i + ")" + n + "(" + i + "|$)")) && si(n, function(n) {
return t.test("string" == typeof n.className && n.className || "undefined" != typeof n.getAttribute && n.getAttribute("class") || "")
})
},
ATTR: function(n, t, i) {
return function(u) {
var f = r.attr(u, n);
return null == f ? "!=" === t : t ? (f += "",
"=" === t ? f === i : "!=" === t ? f !== i : "^=" === t ? i && 0 === f.indexOf(i) : "*=" === t ? i && f.indexOf(i) > -1 : "$=" === t ? i && f.slice(-i.length) === i : "~=" === t ? (" " + f.replace(tr, " ") + " ").indexOf(i) > -1 : "|=" === t ? f === i || f.slice(0, i.length + 1) === i + "-" : !1) : !0
}
},
CHILD: function(n, t, i, r, u) {
var s = "nth" !== n.slice(0, 3)
, o = "last" !== n.slice(-4)
, e = "of-type" === t;
return 1 === r && 0 === u ? function(n) {
return !!n.parentNode
}
: function(t, i, h) {
var v, k, c, l, y, w, b = s !== o ? "nextSibling" : "previousSibling", p = t.parentNode, g = e && t.nodeName.toLowerCase(), d = !h && !e;
if (p) {
if (s) {
while (b) {
for (c = t; c = c[b]; )
if (e ? c.nodeName.toLowerCase() === g : 1 === c.nodeType)
return !1;
w = b = "only" === n && !w && "nextSibling"
}
return !0
}
if (w = [o ? p.firstChild : p.lastChild],
o && d) {
for (k = p[f] || (p[f] = {}),
v = k[n] || [],
y = v[0] === a && v[1],
l = v[0] === a && v[2],
c = y && p.childNodes[y]; c = ++y && c && c[b] || (l = y = 0) || w.pop(); )
if (1 === c.nodeType && ++l && c === t) {
k[n] = [a, y, l];
break
}
} else if (d && (v = (t[f] || (t[f] = {}))[n]) && v[0] === a)
l = v[1];
else
while (c = ++y && c && c[b] || (l = y = 0) || w.pop())
if ((e ? c.nodeName.toLowerCase() === g : 1 === c.nodeType) && ++l && (d && ((c[f] || (c[f] = {}))[n] = [a, l]),
c === t))
break;
return l -= u,
l === r || l % r == 0 && l / r >= 0
}
}
},
PSEUDO: function(n, i) {
var e, u = t.pseudos[n] || t.setFilters[n.toLowerCase()] || r.error("unsupported pseudo: " + n);
return u[f] ? u(i) : u.length > 1 ? (e = [n, n, "", i],
t.setFilters.hasOwnProperty(n.toLowerCase()) ? c(function(n, t) {
for (var r, f = u(n, i), e = f.length; e--; )
r = nt(n, f[e]),
n[r] = !(t[r] = f[e])
}) : function(n) {
return u(n, 0, e)
}
) : u
}
},
pseudos: {
not: c(function(n) {
var t = []
, r = []
, i = pt(n.replace(lt, "$1"));
return i[f] ? c(function(n, t, r, u) {
for (var e, o = i(n, null, u, []), f = n.length; f--; )
(e = o[f]) && (n[f] = !(t[f] = e))
}) : function(n, u, f) {
return t[0] = n,
i(t, null, f, r),
t[0] = null,
!r.pop()
}
}),
has: c(function(n) {
return function(t) {
return r(n, t).length > 0
}
}),
contains: c(function(n) {
return n = n.replace(y, p),
function(t) {
return (t.textContent || t.innerText || st(t)).indexOf(n) > -1
}
}),
lang: c(function(n) {
return er.test(n || "") || r.error("unsupported lang: " + n),
n = n.replace(y, p).toLowerCase(),
function(t) {
var i;
do
if (i = l ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang"))
return i = i.toLowerCase(),
i === n || 0 === i.indexOf(n + "-");
while ((t = t.parentNode) && 1 === t.nodeType);return !1
}
}),
target: function(t) {
var i = n.location && n.location.hash;
return i && i.slice(1) === t.id
},
root: function(n) {
return n === s
},
focus: function(n) {
return n === o.activeElement && (!o.hasFocus || o.hasFocus()) && !!(n.type || n.href || ~n.tabIndex)
},
enabled: function(n) {
return n.disabled === !1
},
disabled: function(n) {
return n.disabled === !0
},
checked: function(n) {
var t = n.nodeName.toLowerCase();
return "input" === t && !!n.checked || "option" === t && !!n.selected
},
selected: function(n) {
return n.parentNode && n.parentNode.selectedIndex,
n.selected === !0
},
empty: function(n) {
for (n = n.firstChild; n; n = n.nextSibling)
if (n.nodeType < 6)
return !1;
return !0
},
parent: function(n) {
return !t.pseudos.empty(n)
},
header: function(n) {
return sr.test(n.nodeName)
},
input: function(n) {
return or.test(n.nodeName)
},
button: function(n) {
var t = n.nodeName.toLowerCase();
return "input" === t && "button" === n.type || "button" === t
},
text: function(n) {
var t;
return "input" === n.nodeName.toLowerCase() && "text" === n.type && (null == (t = n.getAttribute("type")) || "text" === t.toLowerCase())
},
first: tt(function() {
return [0]
}),
last: tt(function(n, t) {
return [t - 1]
}),
eq: tt(function(n, t, i) {
return [0 > i ? i + t : i]
}),
even: tt(function(n, t) {
for (var i = 0; t > i; i += 2)
n.push(i);
return n
}),
odd: tt(function(n, t) {
for (var i = 1; t > i; i += 2)
n.push(i);
return n
}),
lt: tt(function(n, t, i) {
for (var r = 0 > i ? i + t : i; --r >= 0; )
n.push(r);
return n
}),
gt: tt(function(n, t, i) {
for (var r = 0 > i ? i + t : i; ++r < t; )
n.push(r);
return n
})
}
};
t.pseudos.nth = t.pseudos.eq;
for (it in {
radio: !0,
checkbox: !0,
file: !0,
password: !0,
image: !0
})
t.pseudos[it] = lr(it);
for (it in {
submit: !0,
reset: !0
})
t.pseudos[it] = ar(it);
return bi.prototype = t.filters = t.pseudos,
t.setFilters = new bi,
ft = r.tokenize = function(n, i) {
var e, f, s, o, u, h, c, l = hi[n + " "];
if (l)
return i ? 0 : l.slice(0);
for (u = n,
h = [],
c = t.preFilter; u; ) {
(!e || (f = ir.exec(u))) && (f && (u = u.slice(f[0].length) || u),
h.push(s = []));
e = !1;
(f = rr.exec(u)) && (e = f.shift(),
s.push({
value: e,
type: f[0].replace(lt, " ")
}),
u = u.slice(e.length));
for (o in t.filter)
(f = at[o].exec(u)) && (!c[o] || (f = c[o](f))) && (e = f.shift(),
s.push({
value: e,
type: o,
matches: f
}),
u = u.slice(e.length));
if (!e)
break
}
return i ? u.length : u ? r.error(n) : hi(n, h).slice(0)
}
,
pt = r.compile = function(n, t) {
var r, u = [], e = [], i = ci[n + " "];
if (!i) {
for (t || (t = ft(n)),
r = t.length; r--; )
i = fi(t[r]),
i[f] ? u.push(i) : e.push(i);
i = ci(n, yr(e, u));
i.selector = n
}
return i
}
,
oi = r.select = function(n, i, r, f) {
var s, e, o, a, v, c = "function" == typeof n && n, h = !f && ft(n = c.selector || n);
if (r = r || [],
1 === h.length) {
if (e = h[0] = h[0].slice(0),
e.length > 2 && "ID" === (o = e[0]).type && u.getById && 9 === i.nodeType && l && t.relative[e[1].type]) {
if (i = (t.find.ID(o.matches[0].replace(y, p), i) || [])[0],
!i)
return r;
c && (i = i.parentNode);
n = n.slice(e.shift().value.length)
}
for (s = at.needsContext.test(n) ? 0 : e.length; s--; ) {
if (o = e[s],
t.relative[a = o.type])
break;
if ((v = t.find[a]) && (f = v(o.matches[0].replace(y, p), dt.test(e[0].type) && ti(i.parentNode) || i))) {
if (e.splice(s, 1),
n = f.length && vt(e),
!n)
return b.apply(r, f),
r;
break
}
}
}
return (c || pt(n, h))(f, i, !l, r, dt.test(n) && ti(i.parentNode) || i),
r
}
,
u.sortStable = f.split("").sort(wt).join("") === f,
u.detectDuplicates = !!rt,
k(),
u.sortDetached = v(function(n) {
return 1 & n.compareDocumentPosition(o.createElement("div"))
}),
v(function(n) {
return n.innerHTML = "<a href='#'><\/a>",
"#" === n.firstChild.getAttribute("href")
}) || ni("type|href|height|width", function(n, t, i) {
if (!i)
return n.getAttribute(t, "type" === t.toLowerCase() ? 1 : 2)
}),
u.attributes && v(function(n) {
return n.innerHTML = "<input/>",
n.firstChild.setAttribute("value", ""),
"" === n.firstChild.getAttribute("value")
}) || ni("value", function(n, t, i) {
if (!i && "input" === n.nodeName.toLowerCase())
return n.defaultValue
}),
v(function(n) {
return null == n.getAttribute("disabled")
}) || ni(bt, function(n, t, i) {
var r;
if (!i)
return n[t] === !0 ? t.toLowerCase() : (r = n.getAttributeNode(t)) && r.specified ? r.value : null
}),
r
}(n);
i.find = y;
i.expr = y.selectors;
i.expr[":"] = i.expr.pseudos;
i.unique = y.uniqueSort;
i.text = y.getText;
i.isXMLDoc = y.isXML;
i.contains = y.contains;
var di = i.expr.match.needsContext
, gi = /^<(\w+)\s*\/?>(?:<\/\1>|)$/
, ef = /^.[^:#\[\.,]*$/;
i.filter = function(n, t, r) {
var u = t[0];
return r && (n = ":not(" + n + ")"),
1 === t.length && 1 === u.nodeType ? i.find.matchesSelector(u, n) ? [u] : [] : i.find.matches(n, i.grep(t, function(n) {
return 1 === n.nodeType
}))
}
;
i.fn.extend({
find: function(n) {
var t, u = this.length, r = [], f = this;
if ("string" != typeof n)
return this.pushStack(i(n).filter(function() {
for (t = 0; u > t; t++)
if (i.contains(f[t], this))
return !0
}));
for (t = 0; u > t; t++)
i.find(n, f[t], r);
return r = this.pushStack(u > 1 ? i.unique(r) : r),
r.selector = this.selector ? this.selector + " " + n : n,
r
},
filter: function(n) {
return this.pushStack(ui(this, n || [], !1))
},
not: function(n) {
return this.pushStack(ui(this, n || [], !0))
},
is: function(n) {
return !!ui(this, "string" == typeof n && di.test(n) ? i(n) : n || [], !1).length
}
});
nr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/;
tr = i.fn.init = function(n, t) {
var r, f;
if (!n)
return this;
if ("string" == typeof n) {
if (r = "<" === n[0] && ">" === n[n.length - 1] && n.length >= 3 ? [null, n, null] : nr.exec(n),
!r || !r[1] && t)
return !t || t.jquery ? (t || ot).find(n) : this.constructor(t).find(n);
if (r[1]) {
if (t = t instanceof i ? t[0] : t,
i.merge(this, i.parseHTML(r[1], t && t.nodeType ? t.ownerDocument || t : u, !0)),
gi.test(r[1]) && i.isPlainObject(t))
for (r in t)
i.isFunction(this[r]) ? this[r](t[r]) : this.attr(r, t[r]);
return this
}
return f = u.getElementById(r[2]),
f && f.parentNode && (this.length = 1,
this[0] = f),
this.context = u,
this.selector = n,
this
}
return n.nodeType ? (this.context = this[0] = n,
this.length = 1,
this) : i.isFunction(n) ? "undefined" != typeof ot.ready ? ot.ready(n) : n(i) : (void 0 !== n.selector && (this.selector = n.selector,
this.context = n.context),
i.makeArray(n, this))
}
;
tr.prototype = i.fn;
ot = i(u);
ir = /^(?:parents|prev(?:Until|All))/;
rr = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
i.extend({
dir: function(n, t, r) {
for (var u = [], f = void 0 !== r; (n = n[t]) && 9 !== n.nodeType; )
if (1 === n.nodeType) {
if (f && i(n).is(r))
break;
u.push(n)
}
return u
},
sibling: function(n, t) {
for (var i = []; n; n = n.nextSibling)
1 === n.nodeType && n !== t && i.push(n);
return i
}
});
i.fn.extend({
has: function(n) {
var t = i(n, this)
, r = t.length;
return this.filter(function() {
for (var n = 0; r > n; n++)
if (i.contains(this, t[n]))
return !0
})
},
closest: function(n, t) {
for (var r, f = 0, o = this.length, u = [], e = di.test(n) || "string" != typeof n ? i(n, t || this.context) : 0; o > f; f++)
for (r = this[f]; r && r !== t; r = r.parentNode)
if (r.nodeType < 11 && (e ? e.index(r) > -1 : 1 === r.nodeType && i.find.matchesSelector(r, n))) {
u.push(r);
break
}
return this.pushStack(u.length > 1 ? i.unique(u) : u)
},
index: function(n) {
return n ? "string" == typeof n ? ft.call(i(n), this[0]) : ft.call(this, n.jquery ? n[0] : n) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1
},
add: function(n, t) {
return this.pushStack(i.unique(i.merge(this.get(), i(n, t))))
},
addBack: function(n) {
return this.add(null == n ? this.prevObject : this.prevObject.filter(n))
}
});
i.each({
parent: function(n) {
var t = n.parentNode;
return t && 11 !== t.nodeType ? t : null
},
parents: function(n) {
return i.dir(n, "parentNode")
},
parentsUntil: function(n, t, r) {
return i.dir(n, "parentNode", r)
},
next: function(n) {
return ur(n, "nextSibling")
},
prev: function(n) {
return ur(n, "previousSibling")
},
nextAll: function(n) {
return i.dir(n, "nextSibling")
},
prevAll: function(n) {
return i.dir(n, "previousSibling")
},
nextUntil: function(n, t, r) {
return i.dir(n, "nextSibling", r)
},
prevUntil: function(n, t, r) {
return i.dir(n, "previousSibling", r)
},
siblings: function(n) {
return i.sibling((n.parentNode || {}).firstChild, n)
},
children: function(n) {
return i.sibling(n.firstChild)
},
contents: function(n) {
return n.contentDocument || i.merge([], n.childNodes)
}
}, function(n, t) {
i.fn[n] = function(r, u) {
var f = i.map(this, t, r);
return "Until" !== n.slice(-5) && (u = r),
u && "string" == typeof u && (f = i.filter(u, f)),
this.length > 1 && (rr[n] || i.unique(f),
ir.test(n) && f.reverse()),
this.pushStack(f)
}
});
c = /\S+/g;
fi = {};
i.Callbacks = function(n) {
n = "string" == typeof n ? fi[n] || of(n) : i.extend({}, n);
var u, h, o, c, f, e, t = [], r = !n.once && [], l = function(i) {
for (u = n.memory && i,
h = !0,
e = c || 0,
c = 0,
f = t.length,
o = !0; t && f > e; e++)
if (t[e].apply(i[0], i[1]) === !1 && n.stopOnFalse) {
u = !1;
break
}
o = !1;
t && (r ? r.length && l(r.shift()) : u ? t = [] : s.disable())
}, s = {
add: function() {
if (t) {
var r = t.length;
!function e(r) {
i.each(r, function(r, u) {
var f = i.type(u);
"function" === f ? n.unique && s.has(u) || t.push(u) : u && u.length && "string" !== f && e(u)
})
}(arguments);
o ? f = t.length : u && (c = r,
l(u))
}
return this
},
remove: function() {
return t && i.each(arguments, function(n, r) {
for (var u; (u = i.inArray(r, t, u)) > -1; )
t.splice(u, 1),
o && (f >= u && f--,
e >= u && e--)
}),
this
},
has: function(n) {
return n ? i.inArray(n, t) > -1 : !(!t || !t.length)
},
empty: function() {
return t = [],
f = 0,
this
},
disable: function() {
return t = r = u = void 0,
this
},
disabled: function() {
return !t
},
lock: function() {
return r = void 0,
u || s.disable(),
this
},
locked: function() {
return !r
},
fireWith: function(n, i) {
return !t || h && !r || (i = i || [],
i = [n, i.slice ? i.slice() : i],
o ? r.push(i) : l(i)),
this
},
fire: function() {
return s.fireWith(this, arguments),
this
},
fired: function() {
return !!h
}
};
return s
}
;
i.extend({
Deferred: function(n) {
var u = [["resolve", "done", i.Callbacks("once memory"), "resolved"], ["reject", "fail", i.Callbacks("once memory"), "rejected"], ["notify", "progress", i.Callbacks("memory")]]
, f = "pending"
, r = {
state: function() {
return f
},
always: function() {
return t.done(arguments).fail(arguments),
this
},
then: function() {
var n = arguments;
return i.Deferred(function(f) {
i.each(u, function(u, e) {
var o = i.isFunction(n[u]) && n[u];
t[e[1]](function() {
var n = o && o.apply(this, arguments);
n && i.isFunction(n.promise) ? n.promise().done(f.resolve).fail(f.reject).progress(f.notify) : f[e[0] + "With"](this === r ? f.promise() : this, o ? [n] : arguments)
})
});
n = null
}).promise()
},
promise: function(n) {
return null != n ? i.extend(n, r) : r
}
}
, t = {};
return r.pipe = r.then,
i.each(u, function(n, i) {
var e = i[2]
, o = i[3];
r[i[1]] = e.add;
o && e.add(function() {
f = o
}, u[1 ^ n][2].disable, u[2][2].lock);
t[i[0]] = function() {
return t[i[0] + "With"](this === t ? r : this, arguments),
this
}
;
t[i[0] + "With"] = e.fireWith
}),
r.promise(t),
n && n.call(t, t),
t
},
when: function(n) {
var t = 0, u = a.call(arguments), r = u.length, e = 1 !== r || n && i.isFunction(n.promise) ? r : 0, f = 1 === e ? n : i.Deferred(), h = function(n, t, i) {
return function(r) {
t[n] = this;
i[n] = arguments.length > 1 ? a.call(arguments) : r;
i === o ? f.notifyWith(t, i) : --e || f.resolveWith(t, i)
}
}, o, c, s;
if (r > 1)
for (o = new Array(r),
c = new Array(r),
s = new Array(r); r > t; t++)
u[t] && i.isFunction(u[t].promise) ? u[t].promise().done(h(t, s, u)).fail(f.reject).progress(h(t, c, o)) : --e;
return e || f.resolveWith(s, u),
f.promise()
}
});
i.fn.ready = function(n) {
return i.ready.promise().done(n),
this
}
;
i.extend({
isReady: !1,
readyWait: 1,
holdReady: function(n) {
n ? i.readyWait++ : i.ready(!0)
},
ready: function(n) {
(n === !0 ? --i.readyWait : i.isReady) || (i.isReady = !0,
n !== !0 && --i.readyWait > 0 || (st.resolveWith(u, [i]),
i.fn.triggerHandler && (i(u).triggerHandler("ready"),
i(u).off("ready"))))
}
});
i.ready.promise = function(t) {
return st || (st = i.Deferred(),
"complete" === u.readyState ? setTimeout(i.ready) : (u.addEventListener("DOMContentLoaded", ht, !1),
n.addEventListener("load", ht, !1))),
st.promise(t)
}
;
i.ready.promise();
l = i.access = function(n, t, r, u, f, e, o) {
var s = 0
, c = n.length
, h = null == r;
if ("object" === i.type(r)) {
f = !0;
for (s in r)
i.access(n, t, s, r[s], !0, e, o)
} else if (void 0 !== u && (f = !0,
i.isFunction(u) || (o = !0),
h && (o ? (t.call(n, u),
t = null) : (h = t,
t = function(n, t, r) {
return h.call(i(n), r)
}
)),
t))
for (; c > s; s++)
t(n[s], r, o ? u : u.call(n[s], s, t(n[s], r)));
return f ? n : h ? t.call(n) : c ? t(n[0], r) : e
}
;
i.acceptData = function(n) {
return 1 === n.nodeType || 9 === n.nodeType || !+n.nodeType
}
;
v.uid = 1;
v.accepts = i.acceptData;
v.prototype = {
key: function(n) {
if (!v.accepts(n))
return 0;
var r = {}
, t = n[this.expando];
if (!t) {
t = v.uid++;
try {
r[this.expando] = {
value: t
};
Object.defineProperties(n, r)
} catch (u) {
r[this.expando] = t;
i.extend(n, r)
}
}
return this.cache[t] || (this.cache[t] = {}),
t
},
set: function(n, t, r) {
var f, e = this.key(n), u = this.cache[e];
if ("string" == typeof t)
u[t] = r;
else if (i.isEmptyObject(u))
i.extend(this.cache[e], t);
else
for (f in t)
u[f] = t[f];
return u
},
get: function(n, t) {
var i = this.cache[this.key(n)];
return void 0 === t ? i : i[t]
},
access: function(n, t, r) {
var u;
return void 0 === t || t && "string" == typeof t && void 0 === r ? (u = this.get(n, t),
void 0 !== u ? u : this.get(n, i.camelCase(t))) : (this.set(n, t, r),
void 0 !== r ? r : t)
},
remove: function(n, t) {
var u, r, f, o = this.key(n), e = this.cache[o];
if (void 0 === t)
this.cache[o] = {};
else
for (i.isArray(t) ? r = t.concat(t.map(i.camelCase)) : (f = i.camelCase(t),
(t in e) ? r = [t, f] : (r = f,
r = (r in e) ? [r] : r.match(c) || [])),
u = r.length; u--; )
delete e[r[u]]
},
hasData: function(n) {
return !i.isEmptyObject(this.cache[n[this.expando]] || {})
},
discard: function(n) {
n[this.expando] && delete this.cache[n[this.expando]]
}
};
var r = new v
, e = new v
, sf = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/
, hf = /([A-Z])/g;
i.extend({
hasData: function(n) {
return e.hasData(n) || r.hasData(n)
},
data: function(n, t, i) {
return e.access(n, t, i)
},
removeData: function(n, t) {
e.remove(n, t)
},
_data: function(n, t, i) {
return r.access(n, t, i)
},
_removeData: function(n, t) {
r.remove(n, t)
}
});
i.fn.extend({
data: function(n, t) {
var o, f, s, u = this[0], h = u && u.attributes;
if (void 0 === n) {
if (this.length && (s = e.get(u),
1 === u.nodeType && !r.get(u, "hasDataAttrs"))) {
for (o = h.length; o--; )
h[o] && (f = h[o].name,
0 === f.indexOf("data-") && (f = i.camelCase(f.slice(5)),
fr(u, f, s[f])));
r.set(u, "hasDataAttrs", !0)
}
return s
}
return "object" == typeof n ? this.each(function() {
e.set(this, n)
}) : l(this, function(t) {
var r, f = i.camelCase(n);
if (u && void 0 === t) {
if ((r = e.get(u, n),
void 0 !== r) || (r = e.get(u, f),
void 0 !== r) || (r = fr(u, f, void 0),
void 0 !== r))
return r
} else
this.each(function() {
var i = e.get(this, f);
e.set(this, f, t);
-1 !== n.indexOf("-") && void 0 !== i && e.set(this, n, t)
})
}, null, t, arguments.length > 1, null, !0)
},
removeData: function(n) {
return this.each(function() {
e.remove(this, n)
})
}
});
i.extend({
queue: function(n, t, u) {
var f;
if (n)
return (t = (t || "fx") + "queue",
f = r.get(n, t),
u && (!f || i.isArray(u) ? f = r.access(n, t, i.makeArray(u)) : f.push(u)),
f || [])
},
dequeue: function(n, t) {
t = t || "fx";
var r = i.queue(n, t)
, e = r.length
, u = r.shift()
, f = i._queueHooks(n, t)
, o = function() {
i.dequeue(n, t)
};
"inprogress" === u && (u = r.shift(),
e--);
u && ("fx" === t && r.unshift("inprogress"),
delete f.stop,
u.call(n, o, f));
!e && f && f.empty.fire()
},
_queueHooks: function(n, t) {
var u = t + "queueHooks";
return r.get(n, u) || r.access(n, u, {
empty: i.Callbacks("once memory").add(function() {
r.remove(n, [t + "queue", u])
})
})
}
});
i.fn.extend({
queue: function(n, t) {
var r = 2;
return "string" != typeof n && (t = n,
n = "fx",
r--),
arguments.length < r ? i.queue(this[0], n) : void 0 === t ? this : this.each(function() {
var r = i.queue(this, n, t);
i._queueHooks(this, n);
"fx" === n && "inprogress" !== r[0] && i.dequeue(this, n)
})
},
dequeue: function(n) {
return this.each(function() {
i.dequeue(this, n)
})
},
clearQueue: function(n) {
return this.queue(n || "fx", [])
},
promise: function(n, t) {
var u, e = 1, o = i.Deferred(), f = this, s = this.length, h = function() {
--e || o.resolveWith(f, [f])
};
for ("string" != typeof n && (t = n,
n = void 0),
n = n || "fx"; s--; )
u = r.get(f[s], n + "queueHooks"),
u && u.empty && (e++,
u.empty.add(h));
return h(),
o.promise(t)
}
});
var ct = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source
, p = ["Top", "Right", "Bottom", "Left"]
, tt = function(n, t) {
return n = t || n,
"none" === i.css(n, "display") || !i.contains(n.ownerDocument, n)
}
, er = /^(?:checkbox|radio)$/i;
!function() {
var i = u.createDocumentFragment()
, n = i.appendChild(u.createElement("div"))
, t = u.createElement("input");
t.setAttribute("type", "radio");
t.setAttribute("checked", "checked");
t.setAttribute("name", "t");
n.appendChild(t);
f.checkClone = n.cloneNode(!0).cloneNode(!0).lastChild.checked;
n.innerHTML = "<textarea>x<\/textarea>";
f.noCloneChecked = !!n.cloneNode(!0).lastChild.defaultValue
}();
b = "undefined";
f.focusinBubbles = "onfocusin"in n;
var cf = /^key/
, lf = /^(?:mouse|pointer|contextmenu)|click/
, or = /^(?:focusinfocus|focusoutblur)$/
, sr = /^([^.]*)(?:\.(.+)|)$/;
i.event = {
global: {},
add: function(n, t, u, f, e) {
var v, y, w, p, k, h, s, l, o, d, g, a = r.get(n);
if (a)
for (u.handler && (v = u,
u = v.handler,
e = v.selector),
u.guid || (u.guid = i.guid++),
(p = a.events) || (p = a.events = {}),
(y = a.handle) || (y = a.handle = function(t) {
if (typeof i !== b && i.event.triggered !== t.type)
return i.event.dispatch.apply(n, arguments)
}
),
t = (t || "").match(c) || [""],
k = t.length; k--; )
w = sr.exec(t[k]) || [],
o = g = w[1],
d = (w[2] || "").split(".").sort(),
o && (s = i.event.special[o] || {},
o = (e ? s.delegateType : s.bindType) || o,
s = i.event.special[o] || {},
h = i.extend({
type: o,
origType: g,
data: f,
handler: u,
guid: u.guid,
selector: e,
needsContext: e && i.expr.match.needsContext.test(e),
namespace: d.join(".")
}, v),
(l = p[o]) || (l = p[o] = [],
l.delegateCount = 0,
s.setup && s.setup.call(n, f, d, y) !== !1 || n.addEventListener && n.addEventListener(o, y, !1)),
s.add && (s.add.call(n, h),
h.handler.guid || (h.handler.guid = u.guid)),
e ? l.splice(l.delegateCount++, 0, h) : l.push(h),
i.event.global[o] = !0)
},
remove: function(n, t, u, f, e) {
var p, k, h, v, w, s, l, a, o, b, d, y = r.hasData(n) && r.get(n);
if (y && (v = y.events)) {
for (t = (t || "").match(c) || [""],
w = t.length; w--; )
if (h = sr.exec(t[w]) || [],
o = d = h[1],
b = (h[2] || "").split(".").sort(),
o) {
for (l = i.event.special[o] || {},
o = (f ? l.delegateType : l.bindType) || o,
a = v[o] || [],
h = h[2] && new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)"),
k = p = a.length; p--; )
s = a[p],
!e && d !== s.origType || u && u.guid !== s.guid || h && !h.test(s.namespace) || f && f !== s.selector && ("**" !== f || !s.selector) || (a.splice(p, 1),
s.selector && a.delegateCount--,
l.remove && l.remove.call(n, s));
k && !a.length && (l.teardown && l.teardown.call(n, b, y.handle) !== !1 || i.removeEvent(n, o, y.handle),
delete v[o])
} else
for (o in v)
i.event.remove(n, o + t[w], u, f, !0);
i.isEmptyObject(v) && (delete y.handle,
r.remove(n, "events"))
}
},
trigger: function(t, f, e, o) {
var w, s, c, b, a, v, l, p = [e || u], h = ii.call(t, "type") ? t.type : t, y = ii.call(t, "namespace") ? t.namespace.split(".") : [];
if (s = c = e = e || u,
3 !== e.nodeType && 8 !== e.nodeType && !or.test(h + i.event.triggered) && (h.indexOf(".") >= 0 && (y = h.split("."),
h = y.shift(),
y.sort()),
a = h.indexOf(":") < 0 && "on" + h,
t = t[i.expando] ? t : new i.Event(h,"object" == typeof t && t),
t.isTrigger = o ? 2 : 3,
t.namespace = y.join("."),
t.namespace_re = t.namespace ? new RegExp("(^|\\.)" + y.join("\\.(?:.*\\.|)") + "(\\.|$)") : null,
t.result = void 0,
t.target || (t.target = e),
f = null == f ? [t] : i.makeArray(f, [t]),
l = i.event.special[h] || {},
o || !l.trigger || l.trigger.apply(e, f) !== !1)) {
if (!o && !l.noBubble && !i.isWindow(e)) {
for (b = l.delegateType || h,
or.test(b + h) || (s = s.parentNode); s; s = s.parentNode)
p.push(s),
c = s;
c === (e.ownerDocument || u) && p.push(c.defaultView || c.parentWindow || n)
}
for (w = 0; (s = p[w++]) && !t.isPropagationStopped(); )
t.type = w > 1 ? b : l.bindType || h,
v = (r.get(s, "events") || {})[t.type] && r.get(s, "handle"),
v && v.apply(s, f),
v = a && s[a],
v && v.apply && i.acceptData(s) && (t.result = v.apply(s, f),
t.result === !1 && t.preventDefault());
return t.type = h,
o || t.isDefaultPrevented() || l._default && l._default.apply(p.pop(), f) !== !1 || !i.acceptData(e) || a && i.isFunction(e[h]) && !i.isWindow(e) && (c = e[a],
c && (e[a] = null),
i.event.triggered = h,
e[h](),
i.event.triggered = void 0,
c && (e[a] = c)),
t.result
}
},
dispatch: function(n) {
n = i.event.fix(n);
var o, s, e, u, t, h = [], c = a.call(arguments), l = (r.get(this, "events") || {})[n.type] || [], f = i.event.special[n.type] || {};
if (c[0] = n,
n.delegateTarget = this,
!f.preDispatch || f.preDispatch.call(this, n) !== !1) {
for (h = i.event.handlers.call(this, n, l),
o = 0; (u = h[o++]) && !n.isPropagationStopped(); )
for (n.currentTarget = u.elem,
s = 0; (t = u.handlers[s++]) && !n.isImmediatePropagationStopped(); )
(!n.namespace_re || n.namespace_re.test(t.namespace)) && (n.handleObj = t,
n.data = t.data,
e = ((i.event.special[t.origType] || {}).handle || t.handler).apply(u.elem, c),
void 0 !== e && (n.result = e) === !1 && (n.preventDefault(),
n.stopPropagation()));
return f.postDispatch && f.postDispatch.call(this, n),
n.result
}
},
handlers: function(n, t) {
var e, u, f, o, h = [], s = t.delegateCount, r = n.target;
if (s && r.nodeType && (!n.button || "click" !== n.type))
for (; r !== this; r = r.parentNode || this)
if (r.disabled !== !0 || "click" !== n.type) {
for (u = [],
e = 0; s > e; e++)
o = t[e],
f = o.selector + " ",
void 0 === u[f] && (u[f] = o.needsContext ? i(f, this).index(r) >= 0 : i.find(f, this, null, [r]).length),
u[f] && u.push(o);
u.length && h.push({
elem: r,
handlers: u
})
}
return s < t.length && h.push({
elem: this,
handlers: t.slice(s)
}),
h
},
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(n, t) {
return null == n.which && (n.which = null != t.charCode ? t.charCode : t.keyCode),
n
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function(n, t) {
var e, i, r, f = t.button;
return null == n.pageX && null != t.clientX && (e = n.target.ownerDocument || u,
i = e.documentElement,
r = e.body,
n.pageX = t.clientX + (i && i.scrollLeft || r && r.scrollLeft || 0) - (i && i.clientLeft || r && r.clientLeft || 0),
n.pageY = t.clientY + (i && i.scrollTop || r && r.scrollTop || 0) - (i && i.clientTop || r && r.clientTop || 0)),
n.which || void 0 === f || (n.which = 1 & f ? 1 : 2 & f ? 3 : 4 & f ? 2 : 0),
n
}
},
fix: function(n) {
if (n[i.expando])
return n;
var f, e, o, r = n.type, s = n, t = this.fixHooks[r];
for (t || (this.fixHooks[r] = t = lf.test(r) ? this.mouseHooks : cf.test(r) ? this.keyHooks : {}),
o = t.props ? this.props.concat(t.props) : this.props,
n = new i.Event(s),
f = o.length; f--; )
e = o[f],
n[e] = s[e];
return n.target || (n.target = u),
3 === n.target.nodeType && (n.target = n.target.parentNode),
t.filter ? t.filter(n, s) : n
},
special: {
load: {
noBubble: !0
},
focus: {
trigger: function() {
if (this !== hr() && this.focus)
return (this.focus(),
!1)
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if (this === hr() && this.blur)
return (this.blur(),
!1)
},
delegateType: "focusout"
},
click: {
trigger: function() {
if ("checkbox" === this.type && this.click && i.nodeName(this, "input"))
return (this.click(),
!1)
},
_default: function(n) {
return i.nodeName(n.target, "a")
}
},
beforeunload: {
postDispatch: function(n) {
void 0 !== n.result && n.originalEvent && (n.originalEvent.returnValue = n.result)
}
}
},
simulate: function(n, t, r, u) {
var f = i.extend(new i.Event, r, {
type: n,
isSimulated: !0,
originalEvent: {}
});
u ? i.event.trigger(f, null, t) : i.event.dispatch.call(t, f);
f.isDefaultPrevented() && r.preventDefault()
}
};
i.removeEvent = function(n, t, i) {
n.removeEventListener && n.removeEventListener(t, i, !1)
}
;
i.Event = function(n, t) {
return this instanceof i.Event ? (n && n.type ? (this.originalEvent = n,
this.type = n.type,
this.isDefaultPrevented = n.defaultPrevented || void 0 === n.defaultPrevented && n.returnValue === !1 ? lt : k) : this.type = n,
t && i.extend(this, t),
this.timeStamp = n && n.timeStamp || i.now(),
void (this[i.expando] = !0)) : new i.Event(n,t)
}
;
i.Event.prototype = {
isDefaultPrevented: k,
isPropagationStopped: k,
isImmediatePropagationStopped: k,
preventDefault: function() {
var n = this.originalEvent;
this.isDefaultPrevented = lt;
n && n.preventDefault && n.preventDefault()
},
stopPropagation: function() {
var n = this.originalEvent;
this.isPropagationStopped = lt;
n && n.stopPropagation && n.stopPropagation()
},
stopImmediatePropagation: function() {
var n = this.originalEvent;
this.isImmediatePropagationStopped = lt;
n && n.stopImmediatePropagation && n.stopImmediatePropagation();
this.stopPropagation()
}
};
i.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function(n, t) {
i.event.special[n] = {
delegateType: t,
bindType: t,
handle: function(n) {
var u, f = this, r = n.relatedTarget, e = n.handleObj;
return (!r || r !== f && !i.contains(f, r)) && (n.type = e.origType,
u = e.handler.apply(this, arguments),
n.type = t),
u
}
}
});
f.focusinBubbles || i.each({
focus: "focusin",
blur: "focusout"
}, function(n, t) {
var u = function(n) {
i.event.simulate(t, n.target, i.event.fix(n), !0)
};
i.event.special[t] = {
setup: function() {
var i = this.ownerDocument || this
, f = r.access(i, t);
f || i.addEventListener(n, u, !0);
r.access(i, t, (f || 0) + 1)
},
teardown: function() {
var i = this.ownerDocument || this
, f = r.access(i, t) - 1;
f ? r.access(i, t, f) : (i.removeEventListener(n, u, !0),
r.remove(i, t))
}
}
});
i.fn.extend({
on: function(n, t, r, u, f) {
var e, o;
if ("object" == typeof n) {
"string" != typeof t && (r = r || t,
t = void 0);
for (o in n)
this.on(o, t, r, n[o], f);
return this
}
if (null == r && null == u ? (u = t,
r = t = void 0) : null == u && ("string" == typeof t ? (u = r,
r = void 0) : (u = r,
r = t,
t = void 0)),
u === !1)
u = k;
else if (!u)
return this;
return 1 === f && (e = u,
u = function(n) {
return i().off(n),
e.apply(this, arguments)
}
,
u.guid = e.guid || (e.guid = i.guid++)),
this.each(function() {
i.event.add(this, n, u, r, t)
})
},
one: function(n, t, i, r) {
return this.on(n, t, i, r, 1)
},
off: function(n, t, r) {
var u, f;
if (n && n.preventDefault && n.handleObj)
return u = n.handleObj,
i(n.delegateTarget).off(u.namespace ? u.origType + "." + u.namespace : u.origType, u.selector, u.handler),
this;
if ("object" == typeof n) {
for (f in n)
this.off(f, t, n[f]);
return this
}
return (t === !1 || "function" == typeof t) && (r = t,
t = void 0),
r === !1 && (r = k),
this.each(function() {
i.event.remove(this, n, r, t)
})
},
trigger: function(n, t) {
return this.each(function() {
i.event.trigger(n, t, this)
})
},
triggerHandler: function(n, t) {
var r = this[0];
if (r)
return i.event.trigger(n, t, r, !0)
}
});
var cr = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi
, lr = /<([\w:]+)/
, af = /<|&#?\w+;/
, vf = /<(?:script|style|link)/i
, yf = /checked\s*(?:[^=]|=\s*.checked.)/i
, ar = /^$|\/(?:java|ecma)script/i
, pf = /^true\/(.*)/
, wf = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g
, h = {
option: [1, "<select multiple='multiple'>", "<\/select>"],
thead: [1, "<table>", "<\/table>"],
col: [2, "<table><colgroup>", "<\/colgroup><\/table>"],
tr: [2, "<table><tbody>", "<\/tbody><\/table>"],
td: [3, "<table><tbody><tr>", "<\/tr><\/tbody><\/table>"],
_default: [0, "", ""]
};
h.optgroup = h.option;
h.tbody = h.tfoot = h.colgroup = h.caption = h.thead;
h.th = h.td;
i.extend({
clone: function(n, t, r) {
var u, c, s, e, h = n.cloneNode(!0), l = i.contains(n.ownerDocument, n);
if (!(f.noCloneChecked || 1 !== n.nodeType && 11 !== n.nodeType || i.isXMLDoc(n)))
for (e = o(h),
s = o(n),
u = 0,
c = s.length; c > u; u++)
df(s[u], e[u]);
if (t)
if (r)
for (s = s || o(n),
e = e || o(h),
u = 0,
c = s.length; c > u; u++)
yr(s[u], e[u]);
else
yr(n, h);
return e = o(h, "script"),
e.length > 0 && ei(e, !l && o(n, "script")),
h
},
buildFragment: function(n, t, r, u) {
for (var f, e, y, l, p, a, s = t.createDocumentFragment(), v = [], c = 0, w = n.length; w > c; c++)
if (f = n[c],
f || 0 === f)
if ("object" === i.type(f))
i.merge(v, f.nodeType ? [f] : f);
else if (af.test(f)) {
for (e = e || s.appendChild(t.createElement("div")),
y = (lr.exec(f) || ["", ""])[1].toLowerCase(),
l = h[y] || h._default,
e.innerHTML = l[1] + f.replace(cr, "<$1><\/$2>") + l[2],
a = l[0]; a--; )
e = e.lastChild;
i.merge(v, e.childNodes);
e = s.firstChild;
e.textContent = ""
} else
v.push(t.createTextNode(f));
for (s.textContent = "",
c = 0; f = v[c++]; )
if ((!u || -1 === i.inArray(f, u)) && (p = i.contains(f.ownerDocument, f),
e = o(s.appendChild(f), "script"),
p && ei(e),
r))
for (a = 0; f = e[a++]; )
ar.test(f.type || "") && r.push(f);
return s
},
cleanData: function(n) {
for (var f, t, o, u, h = i.event.special, s = 0; void 0 !== (t = n[s]); s++) {
if (i.acceptData(t) && (u = t[r.expando],
u && (f = r.cache[u]))) {
if (f.events)
for (o in f.events)
h[o] ? i.event.remove(t, o) : i.removeEvent(t, o, f.handle);
r.cache[u] && delete r.cache[u]
}
delete e.cache[t[e.expando]]
}
}
});
i.fn.extend({
text: function(n) {
return l(this, function(n) {
return void 0 === n ? i.text(this) : this.empty().each(function() {
(1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) && (this.textContent = n)
})
}, null, n, arguments.length)
},
append: function() {
return this.domManip(arguments, function(n) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = vr(this, n);
t.appendChild(n)
}
})
},
prepend: function() {
return this.domManip(arguments, function(n) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = vr(this, n);
t.insertBefore(n, t.firstChild)
}
})
},
before: function() {
return this.domManip(arguments, function(n) {
this.parentNode && this.parentNode.insertBefore(n, this)
})
},
after: function() {
return this.domManip(arguments, function(n) {
this.parentNode && this.parentNode.insertBefore(n, this.nextSibling)
})
},
remove: function(n, t) {
for (var r, f = n ? i.filter(n, this) : this, u = 0; null != (r = f[u]); u++)
t || 1 !== r.nodeType || i.cleanData(o(r)),
r.parentNode && (t && i.contains(r.ownerDocument, r) && ei(o(r, "script")),
r.parentNode.removeChild(r));
return this
},
empty: function() {
for (var n, t = 0; null != (n = this[t]); t++)
1 === n.nodeType && (i.cleanData(o(n, !1)),
n.textContent = "");
return this
},
clone: function(n, t) {
return n = null == n ? !1 : n,
t = null == t ? n : t,
this.map(function() {
return i.clone(this, n, t)
})
},
html: function(n) {
return l(this, function(n) {
var t = this[0] || {}
, r = 0
, u = this.length;
if (void 0 === n && 1 === t.nodeType)
return t.innerHTML;
if ("string" == typeof n && !vf.test(n) && !h[(lr.exec(n) || ["", ""])[1].toLowerCase()]) {
n = n.replace(cr, "<$1><\/$2>");
try {
for (; u > r; r++)
t = this[r] || {},
1 === t.nodeType && (i.cleanData(o(t, !1)),
t.innerHTML = n);
t = 0
} catch (f) {}
}
t && this.empty().append(n)
}, null, n, arguments.length)
},
replaceWith: function() {
var n = arguments[0];
return this.domManip(arguments, function(t) {
n = this.parentNode;
i.cleanData(o(this));
n && n.replaceChild(t, this)
}),
n && (n.length || n.nodeType) ? this : this.remove()
},
detach: function(n) {
return this.remove(n, !0)
},
domManip: function(n, t) {
n = bi.apply([], n);
var h, v, s, c, u, y, e = 0, l = this.length, w = this, b = l - 1, a = n[0], p = i.isFunction(a);
if (p || l > 1 && "string" == typeof a && !f.checkClone && yf.test(a))
return this.each(function(i) {
var r = w.eq(i);
p && (n[0] = a.call(this, i, r.html()));
r.domManip(n, t)
});
if (l && (h = i.buildFragment(n, this[0].ownerDocument, !1, this),
v = h.firstChild,
1 === h.childNodes.length && (h = v),
v)) {
for (s = i.map(o(h, "script"), bf),
c = s.length; l > e; e++)
u = h,
e !== b && (u = i.clone(u, !0, !0),
c && i.merge(s, o(u, "script"))),
t.call(this[e], u, e);
if (c)
for (y = s[s.length - 1].ownerDocument,
i.map(s, kf),
e = 0; c > e; e++)
u = s[e],
ar.test(u.type || "") && !r.access(u, "globalEval") && i.contains(y, u) && (u.src ? i._evalUrl && i._evalUrl(u.src) : i.globalEval(u.textContent.replace(wf, "")))
}
return this
}
});
i.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(n, t) {
i.fn[n] = function(n) {
for (var u, f = [], e = i(n), o = e.length - 1, r = 0; o >= r; r++)
u = r === o ? this : this.clone(!0),
i(e[r])[t](u),
ti.apply(f, u.get());
return this.pushStack(f)
}
});
oi = {};
var wr = /^margin/
, hi = new RegExp("^(" + ct + ")(?!px)[a-z%]+$","i")
, vt = function(t) {
return t.ownerDocument.defaultView.opener ? t.ownerDocument.defaultView.getComputedStyle(t, null) : n.getComputedStyle(t, null)
};
!function() {
var s, o, e = u.documentElement, r = u.createElement("div"), t = u.createElement("div");
if (t.style) {
t.style.backgroundClip = "content-box";
t.cloneNode(!0).style.backgroundClip = "";
f.clearCloneStyle = "content-box" === t.style.backgroundClip;
r.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute";
r.appendChild(t);
function h() {
t.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";
t.innerHTML = "";
e.appendChild(r);
var i = n.getComputedStyle(t, null);
s = "1%" !== i.top;
o = "4px" === i.width;
e.removeChild(r)
}
n.getComputedStyle && i.extend(f, {
pixelPosition: function() {
return h(),
s
},
boxSizingReliable: function() {
return null == o && h(),
o
},
reliableMarginRight: function() {
var f, i = t.appendChild(u.createElement("div"));
return i.style.cssText = t.style.cssText = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",
i.style.marginRight = i.style.width = "0",
t.style.width = "1px",
e.appendChild(r),
f = !parseFloat(n.getComputedStyle(i, null).marginRight),
e.removeChild(r),
t.removeChild(i),
f
}
})
}
}();
i.swap = function(n, t, i, r) {
var f, u, e = {};
for (u in t)
e[u] = n.style[u],
n.style[u] = t[u];
f = i.apply(n, r || []);
for (u in t)
n.style[u] = e[u];
return f
}
;
var gf = /^(none|table(?!-c[ea]).+)/
, ne = new RegExp("^(" + ct + ")(.*)$","i")
, te = new RegExp("^([+-])=(" + ct + ")","i")
, ie = {
position: "absolute",
visibility: "hidden",
display: "block"
}
, kr = {
letterSpacing: "0",
fontWeight: "400"
}
, dr = ["Webkit", "O", "Moz", "ms"];
i.extend({
cssHooks: {
opacity: {
get: function(n, t) {
if (t) {
var i = it(n, "opacity");
return "" === i ? "1" : i
}
}
}
},
cssNumber: {
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: "cssFloat"
},
style: function(n, t, r, u) {
if (n && 3 !== n.nodeType && 8 !== n.nodeType && n.style) {
var o, h, e, s = i.camelCase(t), c = n.style;
return t = i.cssProps[s] || (i.cssProps[s] = gr(c, s)),
e = i.cssHooks[t] || i.cssHooks[s],
void 0 === r ? e && "get"in e && void 0 !== (o = e.get(n, !1, u)) ? o : c[t] : (h = typeof r,
"string" === h && (o = te.exec(r)) && (r = (o[1] + 1) * o[2] + parseFloat(i.css(n, t)),
h = "number"),
null != r && r === r && ("number" !== h || i.cssNumber[s] || (r += "px"),
f.clearCloneStyle || "" !== r || 0 !== t.indexOf("background") || (c[t] = "inherit"),
e && "set"in e && void 0 === (r = e.set(n, r, u)) || (c[t] = r)),
void 0)
}
},
css: function(n, t, r, u) {
var f, s, e, o = i.camelCase(t);
return t = i.cssProps[o] || (i.cssProps[o] = gr(n.style, o)),
e = i.cssHooks[t] || i.cssHooks[o],
e && "get"in e && (f = e.get(n, !0, r)),
void 0 === f && (f = it(n, t, u)),
"normal" === f && t in kr && (f = kr[t]),
"" === r || r ? (s = parseFloat(f),
r === !0 || i.isNumeric(s) ? s || 0 : f) : f
}
});
i.each(["height", "width"], function(n, t) {
i.cssHooks[t] = {
get: function(n, r, u) {
if (r)
return gf.test(i.css(n, "display")) && 0 === n.offsetWidth ? i.swap(n, ie, function() {
return iu(n, t, u)
}) : iu(n, t, u)
},
set: function(n, r, u) {
var f = u && vt(n);
return nu(n, r, u ? tu(n, t, u, "border-box" === i.css(n, "boxSizing", !1, f), f) : 0)
}
}
});
i.cssHooks.marginRight = br(f.reliableMarginRight, function(n, t) {
if (t)
return i.swap(n, {
display: "inline-block"
}, it, [n, "marginRight"])
});
i.each({
margin: "",
padding: "",
border: "Width"
}, function(n, t) {
i.cssHooks[n + t] = {
expand: function(i) {
for (var r = 0, f = {}, u = "string" == typeof i ? i.split(" ") : [i]; 4 > r; r++)
f[n + p[r] + t] = u[r] || u[r - 2] || u[0];
return f
}
};
wr.test(n) || (i.cssHooks[n + t].set = nu)
});
i.fn.extend({
css: function(n, t) {
return l(this, function(n, t, r) {
var f, e, o = {}, u = 0;
if (i.isArray(t)) {
for (f = vt(n),
e = t.length; e > u; u++)
o[t[u]] = i.css(n, t[u], !1, f);
return o
}
return void 0 !== r ? i.style(n, t, r) : i.css(n, t)
}, n, t, arguments.length > 1)
},
show: function() {
return ru(this, !0)
},
hide: function() {
return ru(this)
},
toggle: function(n) {
return "boolean" == typeof n ? n ? this.show() : this.hide() : this.each(function() {
tt(this) ? i(this).show() : i(this).hide()
})
}
});
i.Tween = s;
s.prototype = {
constructor: s,
init: function(n, t, r, u, f, e) {
this.elem = n;
this.prop = r;
this.easing = f || "swing";
this.options = t;
this.start = this.now = this.cur();
this.end = u;
this.unit = e || (i.cssNumber[r] ? "" : "px")
},
cur: function() {
var n = s.propHooks[this.prop];
return n && n.get ? n.get(this) : s.propHooks._default.get(this)
},
run: function(n) {
var r, t = s.propHooks[this.prop];
return this.pos = r = this.options.duration ? i.easing[this.easing](n, this.options.duration * n, 0, 1, this.options.duration) : n,
this.now = (this.end - this.start) * r + this.start,
this.options.step && this.options.step.call(this.elem, this.now, this),
t && t.set ? t.set(this) : s.propHooks._default.set(this),
this
}
};
s.prototype.init.prototype = s.prototype;
s.propHooks = {
_default: {
get: function(n) {
var t;
return null == n.elem[n.prop] || n.elem.style && null != n.elem.style[n.prop] ? (t = i.css(n.elem, n.prop, ""),
t && "auto" !== t ? t : 0) : n.elem[n.prop]
},
set: function(n) {
i.fx.step[n.prop] ? i.fx.step[n.prop](n) : n.elem.style && (null != n.elem.style[i.cssProps[n.prop]] || i.cssHooks[n.prop]) ? i.style(n.elem, n.prop, n.now + n.unit) : n.elem[n.prop] = n.now
}
}
};
s.propHooks.scrollTop = s.propHooks.scrollLeft = {
set: function(n) {
n.elem.nodeType && n.elem.parentNode && (n.elem[n.prop] = n.now)
}
};
i.easing = {
linear: function(n) {
return n
},
swing: function(n) {
return .5 - Math.cos(n * Math.PI) / 2
}
};
i.fx = s.prototype.init;
i.fx.step = {};
var d, yt, re = /^(?:toggle|show|hide)$/, uu = new RegExp("^(?:([+-])=|)(" + ct + ")([a-z%]*)$","i"), ue = /queueHooks$/, pt = [fe], rt = {
"*": [function(n, t) {
var f = this.createTween(n, t)
, s = f.cur()
, r = uu.exec(t)
, e = r && r[3] || (i.cssNumber[n] ? "" : "px")
, u = (i.cssNumber[n] || "px" !== e && +s) && uu.exec(i.css(f.elem, n))
, o = 1
, h = 20;
if (u && u[3] !== e) {
e = e || u[3];
r = r || [];
u = +s || 1;
do
o = o || ".5",
u /= o,
i.style(f.elem, n, u + e);
while (o !== (o = f.cur() / s) && 1 !== o && --h)
}
return r && (u = f.start = +u || +s || 0,
f.unit = e,
f.end = r[1] ? u + (r[1] + 1) * r[2] : +r[2]),
f
}
]
};
i.Animation = i.extend(ou, {
tweener: function(n, t) {
i.isFunction(n) ? (t = n,
n = ["*"]) : n = n.split(" ");
for (var r, u = 0, f = n.length; f > u; u++)
r = n[u],
rt[r] = rt[r] || [],
rt[r].unshift(t)
},
prefilter: function(n, t) {
t ? pt.unshift(n) : pt.push(n)
}
});
i.speed = function(n, t, r) {
var u = n && "object" == typeof n ? i.extend({}, n) : {
complete: r || !r && t || i.isFunction(n) && n,
duration: n,
easing: r && t || t && !i.isFunction(t) && t
};
return u.duration = i.fx.off ? 0 : "number" == typeof u.duration ? u.duration : u.duration in i.fx.speeds ? i.fx.speeds[u.duration] : i.fx.speeds._default,
(null == u.queue || u.queue === !0) && (u.queue = "fx"),
u.old = u.complete,
u.complete = function() {
i.isFunction(u.old) && u.old.call(this);
u.queue && i.dequeue(this, u.queue)
}
,
u
}
;
i.fn.extend({
fadeTo: function(n, t, i, r) {
return this.filter(tt).css("opacity", 0).show().end().animate({
opacity: t
}, n, i, r)
},
animate: function(n, t, u, f) {
var s = i.isEmptyObject(n)
, o = i.speed(t, u, f)
, e = function() {
var t = ou(this, i.extend({}, n), o);
(s || r.get(this, "finish")) && t.stop(!0)
};
return e.finish = e,
s || o.queue === !1 ? this.each(e) : this.queue(o.queue, e)
},
stop: function(n, t, u) {
var f = function(n) {
var t = n.stop;
delete n.stop;
t(u)
};
return "string" != typeof n && (u = t,
t = n,
n = void 0),
t && n !== !1 && this.queue(n || "fx", []),
this.each(function() {
var s = !0
, t = null != n && n + "queueHooks"
, o = i.timers
, e = r.get(this);
if (t)
e[t] && e[t].stop && f(e[t]);
else
for (t in e)
e[t] && e[t].stop && ue.test(t) && f(e[t]);
for (t = o.length; t--; )
o[t].elem !== this || null != n && o[t].queue !== n || (o[t].anim.stop(u),
s = !1,
o.splice(t, 1));
(s || !u) && i.dequeue(this, n)
})
},
finish: function(n) {
return n !== !1 && (n = n || "fx"),
this.each(function() {
var t, e = r.get(this), u = e[n + "queue"], o = e[n + "queueHooks"], f = i.timers, s = u ? u.length : 0;
for (e.finish = !0,
i.queue(this, n, []),
o && o.stop && o.stop.call(this, !0),
t = f.length; t--; )
f[t].elem === this && f[t].queue === n && (f[t].anim.stop(!0),
f.splice(t, 1));
for (t = 0; s > t; t++)
u[t] && u[t].finish && u[t].finish.call(this);
delete e.finish
})
}
});
i.each(["toggle", "show", "hide"], function(n, t) {
var r = i.fn[t];
i.fn[t] = function(n, i, u) {
return null == n || "boolean" == typeof n ? r.apply(this, arguments) : this.animate(wt(t, !0), n, i, u)
}
});
i.each({
slideDown: wt("show"),
slideUp: wt("hide"),
slideToggle: wt("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(n, t) {
i.fn[n] = function(n, i, r) {
return this.animate(t, n, i, r)
}
});
i.timers = [];
i.fx.tick = function() {
var r, n = 0, t = i.timers;
for (d = i.now(); n < t.length; n++)
r = t[n],
r() || t[n] !== r || t.splice(n--, 1);
t.length || i.fx.stop();
d = void 0
}
;
i.fx.timer = function(n) {
i.timers.push(n);
n() ? i.fx.start() : i.timers.pop()
}
;
i.fx.interval = 13;
i.fx.start = function() {
yt || (yt = setInterval(i.fx.tick, i.fx.interval))
}
;
i.fx.stop = function() {
clearInterval(yt);
yt = null
}
;
i.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
};
i.fn.delay = function(n, t) {
return n = i.fx ? i.fx.speeds[n] || n : n,
t = t || "fx",
this.queue(t, function(t, i) {
var r = setTimeout(t, n);
i.stop = function() {
clearTimeout(r)
}
})
}
,
function() {
var n = u.createElement("input")
, t = u.createElement("select")
, i = t.appendChild(u.createElement("option"));
n.type = "checkbox";
f.checkOn = "" !== n.value;
f.optSelected = i.selected;
t.disabled = !0;
f.optDisabled = !i.disabled;
n = u.createElement("input");
n.value = "t";
n.type = "radio";
f.radioValue = "t" === n.value
}();
g = i.expr.attrHandle;
i.fn.extend({
attr: function(n, t) {
return l(this, i.attr, n, t, arguments.length > 1)
},
removeAttr: function(n) {
return this.each(function() {
i.removeAttr(this, n)
})
}
});
i.extend({
attr: function(n, t, r) {
var u, f, e = n.nodeType;
if (n && 3 !== e && 8 !== e && 2 !== e)
return typeof n.getAttribute === b ? i.prop(n, t, r) : (1 === e && i.isXMLDoc(n) || (t = t.toLowerCase(),
u = i.attrHooks[t] || (i.expr.match.bool.test(t) ? su : oe)),
void 0 === r ? u && "get"in u && null !== (f = u.get(n, t)) ? f : (f = i.find.attr(n, t),
null == f ? void 0 : f) : null !== r ? u && "set"in u && void 0 !== (f = u.set(n, r, t)) ? f : (n.setAttribute(t, r + ""),
r) : void i.removeAttr(n, t))
},
removeAttr: function(n, t) {
var r, u, e = 0, f = t && t.match(c);
if (f && 1 === n.nodeType)
while (r = f[e++])
u = i.propFix[r] || r,
i.expr.match.bool.test(r) && (n[u] = !1),
n.removeAttribute(r)
},
attrHooks: {
type: {
set: function(n, t) {
if (!f.radioValue && "radio" === t && i.nodeName(n, "input")) {
var r = n.value;
return n.setAttribute("type", t),
r && (n.value = r),
t
}
}
}
}
});
su = {
set: function(n, t, r) {
return t === !1 ? i.removeAttr(n, r) : n.setAttribute(r, r),
r
}
};
i.each(i.expr.match.bool.source.match(/\w+/g), function(n, t) {
var r = g[t] || i.find.attr;
g[t] = function(n, t, i) {
var u, f;
return i || (f = g[t],
g[t] = u,
u = null != r(n, t, i) ? t.toLowerCase() : null,
g[t] = f),
u
}
});
hu = /^(?:input|select|textarea|button)$/i;
i.fn.extend({
prop: function(n, t) {
return l(this, i.prop, n, t, arguments.length > 1)
},
removeProp: function(n) {
return this.each(function() {
delete this[i.propFix[n] || n]
})
}
});
i.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function(n, t, r) {
var f, u, o, e = n.nodeType;
if (n && 3 !== e && 8 !== e && 2 !== e)
return o = 1 !== e || !i.isXMLDoc(n),
o && (t = i.propFix[t] || t,
u = i.propHooks[t]),
void 0 !== r ? u && "set"in u && void 0 !== (f = u.set(n, r, t)) ? f : n[t] = r : u && "get"in u && null !== (f = u.get(n, t)) ? f : n[t]
},
propHooks: {
tabIndex: {
get: function(n) {
return n.hasAttribute("tabindex") || hu.test(n.nodeName) || n.href ? n.tabIndex : -1
}
}
}
});
f.optSelected || (i.propHooks.selected = {
get: function(n) {
var t = n.parentNode;
return t && t.parentNode && t.parentNode.selectedIndex,
null
}
});
i.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function() {
i.propFix[this.toLowerCase()] = this
});
bt = /[\t\r\n\f]/g;
i.fn.extend({
addClass: function(n) {
var o, t, r, u, s, f, h = "string" == typeof n && n, e = 0, l = this.length;
if (i.isFunction(n))
return this.each(function(t) {
i(this).addClass(n.call(this, t, this.className))
});
if (h)
for (o = (n || "").match(c) || []; l > e; e++)
if (t = this[e],
r = 1 === t.nodeType && (t.className ? (" " + t.className + " ").replace(bt, " ") : " ")) {
for (s = 0; u = o[s++]; )
r.indexOf(" " + u + " ") < 0 && (r += u + " ");
f = i.trim(r);
t.className !== f && (t.className = f)
}
return this
},
removeClass: function(n) {
var o, t, r, u, s, f, h = 0 === arguments.length || "string" == typeof n && n, e = 0, l = this.length;
if (i.isFunction(n))
return this.each(function(t) {
i(this).removeClass(n.call(this, t, this.className))
});
if (h)
for (o = (n || "").match(c) || []; l > e; e++)
if (t = this[e],
r = 1 === t.nodeType && (t.className ? (" " + t.className + " ").replace(bt, " ") : "")) {
for (s = 0; u = o[s++]; )
while (r.indexOf(" " + u + " ") >= 0)
r = r.replace(" " + u + " ", " ");
f = n ? i.trim(r) : "";
t.className !== f && (t.className = f)
}
return this
},
toggleClass: function(n, t) {
var u = typeof n;
return "boolean" == typeof t && "string" === u ? t ? this.addClass(n) : this.removeClass(n) : this.each(i.isFunction(n) ? function(r) {
i(this).toggleClass(n.call(this, r, this.className, t), t)
}
: function() {
if ("string" === u)
for (var t, e = 0, f = i(this), o = n.match(c) || []; t = o[e++]; )
f.hasClass(t) ? f.removeClass(t) : f.addClass(t);
else
(u === b || "boolean" === u) && (this.className && r.set(this, "__className__", this.className),
this.className = this.className || n === !1 ? "" : r.get(this, "__className__") || "")
}
)
},
hasClass: function(n) {
for (var i = " " + n + " ", t = 0, r = this.length; r > t; t++)
if (1 === this[t].nodeType && (" " + this[t].className + " ").replace(bt, " ").indexOf(i) >= 0)
return !0;
return !1
}
});
cu = /\r/g;
i.fn.extend({
val: function(n) {
var t, r, f, u = this[0];
return arguments.length ? (f = i.isFunction(n),
this.each(function(r) {
var u;
1 === this.nodeType && (u = f ? n.call(this, r, i(this).val()) : n,
null == u ? u = "" : "number" == typeof u ? u += "" : i.isArray(u) && (u = i.map(u, function(n) {
return null == n ? "" : n + ""
})),
t = i.valHooks[this.type] || i.valHooks[this.nodeName.toLowerCase()],
t && "set"in t && void 0 !== t.set(this, u, "value") || (this.value = u))
})) : u ? (t = i.valHooks[u.type] || i.valHooks[u.nodeName.toLowerCase()],
t && "get"in t && void 0 !== (r = t.get(u, "value")) ? r : (r = u.value,
"string" == typeof r ? r.replace(cu, "") : null == r ? "" : r)) : void 0
}
});
i.extend({
valHooks: {
option: {
get: function(n) {
var t = i.find.attr(n, "value");
return null != t ? t : i.trim(i.text(n))
}
},
select: {
get: function(n) {
for (var o, t, s = n.options, r = n.selectedIndex, u = "select-one" === n.type || 0 > r, h = u ? null : [], c = u ? r + 1 : s.length, e = 0 > r ? c : u ? r : 0; c > e; e++)
if (t = s[e],
!(!t.selected && e !== r || (f.optDisabled ? t.disabled : null !== t.getAttribute("disabled")) || t.parentNode.disabled && i.nodeName(t.parentNode, "optgroup"))) {
if (o = i(t).val(),
u)
return o;
h.push(o)
}
return h
},
set: function(n, t) {
for (var u, r, f = n.options, e = i.makeArray(t), o = f.length; o--; )
r = f[o],
(r.selected = i.inArray(r.value, e) >= 0) && (u = !0);
return u || (n.selectedIndex = -1),
e
}
}
}
});
i.each(["radio", "checkbox"], function() {
i.valHooks[this] = {
set: function(n, t) {
if (i.isArray(t))
return n.checked = i.inArray(i(n).val(), t) >= 0
}
};
f.checkOn || (i.valHooks[this].get = function(n) {
return null === n.getAttribute("value") ? "on" : n.value
}
)
});
i.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(n, t) {
i.fn[t] = function(n, i) {
return arguments.length > 0 ? this.on(t, null, n, i) : this.trigger(t)
}
});
i.fn.extend({
hover: function(n, t) {
return this.mouseenter(n).mouseleave(t || n)
},
bind: function(n, t, i) {
return this.on(n, null, t, i)
},
unbind: function(n, t) {
return this.off(n, null, t)
},
delegate: function(n, t, i, r) {
return this.on(t, n, i, r)
},
undelegate: function(n, t, i) {
return 1 === arguments.length ? this.off(n, "**") : this.off(t, n || "**", i)
}
});
kt = i.now();
dt = /\?/;
i.parseJSON = function(n) {
return JSON.parse(n + "")
}
;
i.parseXML = function(n) {
var t, r;
if (!n || "string" != typeof n)
return null;
try {
r = new DOMParser;
t = r.parseFromString(n, "text/xml")
} catch (u) {
t = void 0
}
return (!t || t.getElementsByTagName("parsererror").length) && i.error("Invalid XML: " + n),
t
}
;
var se = /#.*$/
, lu = /([?&])_=[^&]*/
, he = /^(.*?):[ \t]*([^\r\n]*)$/gm
, ce = /^(?:GET|HEAD)$/
, le = /^\/\//
, au = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/
, vu = {}
, ci = {}
, yu = "*/".concat("*")
, li = n.location.href
, nt = au.exec(li.toLowerCase()) || [];
i.extend({
active: 0,
lastModified: {},
etag: {},
ajaxSettings: {
url: li,
type: "GET",
isLocal: /^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(nt[1]),
global: !0,
processData: !0,
async: !0,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
accepts: {
"*": yu,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
converters: {
"* text": String,
"text html": !0,
"text json": i.parseJSON,
"text xml": i.parseXML
},
flatOptions: {
url: !0,
context: !0
}
},
ajaxSetup: function(n, t) {
return t ? ai(ai(n, i.ajaxSettings), t) : ai(i.ajaxSettings, n)
},
ajaxPrefilter: pu(vu),
ajaxTransport: pu(ci),
ajax: function(n, t) {
function p(n, t, s, h) {
var v, it, tt, p, nt, c = t;
2 !== e && (e = 2,
b && clearTimeout(b),
l = void 0,
w = h || "",
u.readyState = n > 0 ? 4 : 0,
v = n >= 200 && 300 > n || 304 === n,
s && (p = ae(r, u, s)),
p = ve(r, p, u, v),
v ? (r.ifModified && (nt = u.getResponseHeader("Last-Modified"),
nt && (i.lastModified[f] = nt),
nt = u.getResponseHeader("etag"),
nt && (i.etag[f] = nt)),
204 === n || "HEAD" === r.type ? c = "nocontent" : 304 === n ? c = "notmodified" : (c = p.state,
it = p.data,
tt = p.error,
v = !tt)) : (tt = c,
(n || !c) && (c = "error",
0 > n && (n = 0))),
u.status = n,
u.statusText = (t || c) + "",
v ? d.resolveWith(o, [it, c, u]) : d.rejectWith(o, [u, c, tt]),
u.statusCode(y),
y = void 0,
a && k.trigger(v ? "ajaxSuccess" : "ajaxError", [u, r, v ? it : tt]),
g.fireWith(o, [u, c]),
a && (k.trigger("ajaxComplete", [u, r]),
--i.active || i.event.trigger("ajaxStop")))
}
"object" == typeof n && (t = n,
n = void 0);
t = t || {};
var l, f, w, v, b, s, a, h, r = i.ajaxSetup({}, t), o = r.context || r, k = r.context && (o.nodeType || o.jquery) ? i(o) : i.event, d = i.Deferred(), g = i.Callbacks("once memory"), y = r.statusCode || {}, tt = {}, it = {}, e = 0, rt = "canceled", u = {
readyState: 0,
getResponseHeader: function(n) {
var t;
if (2 === e) {
if (!v)
for (v = {}; t = he.exec(w); )
v[t[1].toLowerCase()] = t[2];
t = v[n.toLowerCase()]
}
return null == t ? null : t
},
getAllResponseHeaders: function() {
return 2 === e ? w : null
},
setRequestHeader: function(n, t) {
var i = n.toLowerCase();
return e || (n = it[i] = it[i] || n,
tt[n] = t),
this
},
overrideMimeType: function(n) {
return e || (r.mimeType = n),
this
},
statusCode: function(n) {
var t;
if (n)
if (2 > e)
for (t in n)
y[t] = [y[t], n[t]];
else
u.always(n[u.status]);
return this
},
abort: function(n) {
var t = n || rt;
return l && l.abort(t),
p(0, t),
this
}
};
if (d.promise(u).complete = g.add,
u.success = u.done,
u.error = u.fail,
r.url = ((n || r.url || li) + "").replace(se, "").replace(le, nt[1] + "//"),
r.type = t.method || t.type || r.method || r.type,
r.dataTypes = i.trim(r.dataType || "*").toLowerCase().match(c) || [""],
null == r.crossDomain && (s = au.exec(r.url.toLowerCase()),
r.crossDomain = !(!s || s[1] === nt[1] && s[2] === nt[2] && (s[3] || ("http:" === s[1] ? "80" : "443")) === (nt[3] || ("http:" === nt[1] ? "80" : "443")))),
r.data && r.processData && "string" != typeof r.data && (r.data = i.param(r.data, r.traditional)),
wu(vu, r, t, u),
2 === e)
return u;
a = i.event && r.global;
a && 0 == i.active++ && i.event.trigger("ajaxStart");
r.type = r.type.toUpperCase();
r.hasContent = !ce.test(r.type);
f = r.url;
r.hasContent || (r.data && (f = r.url += (dt.test(f) ? "&" : "?") + r.data,
delete r.data),
r.cache === !1 && (r.url = lu.test(f) ? f.replace(lu, "$1_=" + kt++) : f + (dt.test(f) ? "&" : "?") + "_=" + kt++));
r.ifModified && (i.lastModified[f] && u.setRequestHeader("If-Modified-Since", i.lastModified[f]),
i.etag[f] && u.setRequestHeader("If-None-Match", i.etag[f]));
(r.data && r.hasContent && r.contentType !== !1 || t.contentType) && u.setRequestHeader("Content-Type", r.contentType);
u.setRequestHeader("Accept", r.dataTypes[0] && r.accepts[r.dataTypes[0]] ? r.accepts[r.dataTypes[0]] + ("*" !== r.dataTypes[0] ? ", " + yu + "; q=0.01" : "") : r.accepts["*"]);
for (h in r.headers)
u.setRequestHeader(h, r.headers[h]);
if (r.beforeSend && (r.beforeSend.call(o, u, r) === !1 || 2 === e))
return u.abort();
rt = "abort";
for (h in {
success: 1,
error: 1,
complete: 1
})
u[h](r[h]);
if (l = wu(ci, r, t, u)) {
u.readyState = 1;
a && k.trigger("ajaxSend", [u, r]);
r.async && r.timeout > 0 && (b = setTimeout(function() {
u.abort("timeout")
}, r.timeout));
try {
e = 1;
l.send(tt, p)
} catch (ut) {
if (!(2 > e))
throw ut;
p(-1, ut)
}
} else
p(-1, "No Transport");
return u
},
getJSON: function(n, t, r) {
return i.get(n, t, r, "json")
},
getScript: function(n, t) {
return i.get(n, void 0, t, "script")
}
});
i.each(["get", "post"], function(n, t) {
i[t] = function(n, r, u, f) {
return i.isFunction(r) && (f = f || u,
u = r,
r = void 0),
i.ajax({
url: n,
type: t,
dataType: f,
data: r,
success: u
})
}
});
i._evalUrl = function(n) {
return i.ajax({
url: n,
type: "GET",
dataType: "script",
async: !1,
global: !1,
throws: !0
})
}
;
i.fn.extend({
wrapAll: function(n) {
var t;
return i.isFunction(n) ? this.each(function(t) {
i(this).wrapAll(n.call(this, t))
}) : (this[0] && (t = i(n, this[0].ownerDocument).eq(0).clone(!0),
this[0].parentNode && t.insertBefore(this[0]),
t.map(function() {
for (var n = this; n.firstElementChild; )
n = n.firstElementChild;
return n
}).append(this)),
this)
},
wrapInner: function(n) {
return this.each(i.isFunction(n) ? function(t) {
i(this).wrapInner(n.call(this, t))
}
: function() {
var t = i(this)
, r = t.contents();
r.length ? r.wrapAll(n) : t.append(n)
}
)
},
wrap: function(n) {
var t = i.isFunction(n);
return this.each(function(r) {
i(this).wrapAll(t ? n.call(this, r) : n)
})
},
unwrap: function() {
return this.parent().each(function() {
i.nodeName(this, "body") || i(this).replaceWith(this.childNodes)
}).end()
}
});
i.expr.filters.hidden = function(n) {
return n.offsetWidth <= 0 && n.offsetHeight <= 0
}
;
i.expr.filters.visible = function(n) {
return !i.expr.filters.hidden(n)
}
;
var ye = /%20/g
, pe = /\[\]$/
, bu = /\r?\n/g
, we = /^(?:submit|button|image|reset|file)$/i
, be = /^(?:input|select|textarea|keygen)/i;
i.param = function(n, t) {
var r, u = [], f = function(n, t) {
t = i.isFunction(t) ? t() : null == t ? "" : t;
u[u.length] = encodeURIComponent(n) + "=" + encodeURIComponent(t)
};
if (void 0 === t && (t = i.ajaxSettings && i.ajaxSettings.traditional),
i.isArray(n) || n.jquery && !i.isPlainObject(n))
i.each(n, function() {
f(this.name, this.value)
});
else
for (r in n)
vi(r, n[r], t, f);
return u.join("&").replace(ye, "+")
}
;
i.fn.extend({
serialize: function() {
return i.param(this.serializeArray())
},
serializeArray: function() {
return this.map(function() {
var n = i.prop(this, "elements");
return n ? i.makeArray(n) : this
}).filter(function() {
var n = this.type;
return this.name && !i(this).is(":disabled") && be.test(this.nodeName) && !we.test(n) && (this.checked || !er.test(n))
}).map(function(n, t) {
var r = i(this).val();
return null == r ? null : i.isArray(r) ? i.map(r, function(n) {
return {
name: t.name,
value: n.replace(bu, "\r\n")
}
}) : {
name: t.name,
value: r.replace(bu, "\r\n")
}
}).get()
}
});
i.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest
} catch (n) {}
}
;
var ke = 0
, gt = {}
, de = {
0: 200,
1223: 204
}
, ut = i.ajaxSettings.xhr();
return n.attachEvent && n.attachEvent("onunload", function() {
for (var n in gt)
gt[n]()
}),
f.cors = !!ut && "withCredentials"in ut,
f.ajax = ut = !!ut,
i.ajaxTransport(function(n) {
var t;
if (f.cors || ut && !n.crossDomain)
return {
send: function(i, r) {
var f, u = n.xhr(), e = ++ke;
if (u.open(n.type, n.url, n.async, n.username, n.password),
n.xhrFields)
for (f in n.xhrFields)
u[f] = n.xhrFields[f];
n.mimeType && u.overrideMimeType && u.overrideMimeType(n.mimeType);
n.crossDomain || i["X-Requested-With"] || (i["X-Requested-With"] = "XMLHttpRequest");
for (f in i)
u.setRequestHeader(f, i[f]);
t = function(n) {
return function() {
t && (delete gt[e],
t = u.onload = u.onerror = null,
"abort" === n ? u.abort() : "error" === n ? r(u.status, u.statusText) : r(de[u.status] || u.status, u.statusText, "string" == typeof u.responseText ? {
text: u.responseText
} : void 0, u.getAllResponseHeaders()))
}
}
;
u.onload = t();
u.onerror = t("error");
t = gt[e] = t("abort");
try {
u.send(n.hasContent && n.data || null)
} catch (o) {
if (t)
throw o;
}
},
abort: function() {
t && t()
}
}
}),
i.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function(n) {
return i.globalEval(n),
n
}
}
}),
i.ajaxPrefilter("script", function(n) {
void 0 === n.cache && (n.cache = !1);
n.crossDomain && (n.type = "GET")
}),
i.ajaxTransport("script", function(n) {
if (n.crossDomain) {
var r, t;
return {
send: function(f, e) {
r = i("<script>").prop({
async: !0,
charset: n.scriptCharset,
src: n.url
}).on("load error", t = function(n) {
r.remove();
t = null;
n && e("error" === n.type ? 404 : 200, n.type)
}
);
u.head.appendChild(r[0])
},
abort: function() {
t && t()
}
}
}
}),
yi = [],
ni = /(=)\?(?=&|$)|\?\?/,
i.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var n = yi.pop() || i.expando + "_" + kt++;
return this[n] = !0,
n
}
}),
i.ajaxPrefilter("json jsonp", function(t, r, u) {
var f, o, e, s = t.jsonp !== !1 && (ni.test(t.url) ? "url" : "string" == typeof t.data && !(t.contentType || "").indexOf("application/x-www-form-urlencoded") && ni.test(t.data) && "data");
if (s || "jsonp" === t.dataTypes[0])
return (f = t.jsonpCallback = i.isFunction(t.jsonpCallback) ? t.jsonpCallback() : t.jsonpCallback,
s ? t[s] = t[s].replace(ni, "$1" + f) : t.jsonp !== !1 && (t.url += (dt.test(t.url) ? "&" : "?") + t.jsonp + "=" + f),
t.converters["script json"] = function() {
return e || i.error(f + " was not called"),
e[0]
}
,
t.dataTypes[0] = "json",
o = n[f],
n[f] = function() {
e = arguments
}
,
u.always(function() {
n[f] = o;
t[f] && (t.jsonpCallback = r.jsonpCallback,
yi.push(f));
e && i.isFunction(o) && o(e[0]);
e = o = void 0
}),
"script")
}),
i.parseHTML = function(n, t, r) {
if (!n || "string" != typeof n)
return null;
"boolean" == typeof t && (r = t,
t = !1);
t = t || u;
var f = gi.exec(n)
, e = !r && [];
return f ? [t.createElement(f[1])] : (f = i.buildFragment([n], t, e),
e && e.length && i(e).remove(),
i.merge([], f.childNodes))
}
,
pi = i.fn.load,
i.fn.load = function(n, t, r) {
if ("string" != typeof n && pi)
return pi.apply(this, arguments);
var u, o, s, f = this, e = n.indexOf(" ");
return e >= 0 && (u = i.trim(n.slice(e)),
n = n.slice(0, e)),
i.isFunction(t) ? (r = t,
t = void 0) : t && "object" == typeof t && (o = "POST"),
f.length > 0 && i.ajax({
url: n,
type: o,
dataType: "html",
data: t
}).done(function(n) {
s = arguments;
f.html(u ? i("<div>").append(i.parseHTML(n)).find(u) : n)
}).complete(r && function(n, t) {
f.each(r, s || [n.responseText, t, n])
}
),
this
}
,
i.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(n, t) {
i.fn[t] = function(n) {
return this.on(t, n)
}
}),
i.expr.filters.animated = function(n) {
return i.grep(i.timers, function(t) {
return n === t.elem
}).length
}
,
wi = n.document.documentElement,
i.offset = {
setOffset: function(n, t, r) {
var e, o, s, h, u, c, v, l = i.css(n, "position"), a = i(n), f = {};
"static" === l && (n.style.position = "relative");
u = a.offset();
s = i.css(n, "top");
c = i.css(n, "left");
v = ("absolute" === l || "fixed" === l) && (s + c).indexOf("auto") > -1;
v ? (e = a.position(),
h = e.top,
o = e.left) : (h = parseFloat(s) || 0,
o = parseFloat(c) || 0);
i.isFunction(t) && (t = t.call(n, r, u));
null != t.top && (f.top = t.top - u.top + h);
null != t.left && (f.left = t.left - u.left + o);
"using"in t ? t.using.call(n, f) : a.css(f)
}
},
i.fn.extend({
offset: function(n) {
if (arguments.length)
return void 0 === n ? this : this.each(function(t) {
i.offset.setOffset(this, n, t)
});
var r, f, t = this[0], u = {
top: 0,
left: 0
}, e = t && t.ownerDocument;
if (e)
return r = e.documentElement,
i.contains(r, t) ? (typeof t.getBoundingClientRect !== b && (u = t.getBoundingClientRect()),
f = ku(e),
{
top: u.top + f.pageYOffset - r.clientTop,
left: u.left + f.pageXOffset - r.clientLeft
}) : u
},
position: function() {
if (this[0]) {
var n, r, u = this[0], t = {
top: 0,
left: 0
};
return "fixed" === i.css(u, "position") ? r = u.getBoundingClientRect() : (n = this.offsetParent(),
r = this.offset(),
i.nodeName(n[0], "html") || (t = n.offset()),
t.top += i.css(n[0], "borderTopWidth", !0),
t.left += i.css(n[0], "borderLeftWidth", !0)),
{
top: r.top - t.top - i.css(u, "marginTop", !0),
left: r.left - t.left - i.css(u, "marginLeft", !0)
}
}
},
offsetParent: function() {
return this.map(function() {
for (var n = this.offsetParent || wi; n && !i.nodeName(n, "html") && "static" === i.css(n, "position"); )
n = n.offsetParent;
return n || wi
})
}
}),
i.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(t, r) {
var u = "pageYOffset" === r;
i.fn[t] = function(i) {
return l(this, function(t, i, f) {
var e = ku(t);
return void 0 === f ? e ? e[r] : t[i] : void (e ? e.scrollTo(u ? n.pageXOffset : f, u ? f : n.pageYOffset) : t[i] = f)
}, t, i, arguments.length, null)
}
}),
i.each(["top", "left"], function(n, t) {
i.cssHooks[t] = br(f.pixelPosition, function(n, r) {
if (r)
return (r = it(n, t),
hi.test(r) ? i(n).position()[t] + "px" : r)
})
}),
i.each({
Height: "height",
Width: "width"
}, function(n, t) {
i.each({
padding: "inner" + n,
content: t,
"": "outer" + n
}, function(r, u) {
i.fn[u] = function(u, f) {
var e = arguments.length && (r || "boolean" != typeof u)
, o = r || (u === !0 || f === !0 ? "margin" : "border");
return l(this, function(t, r, u) {
var f;
return i.isWindow(t) ? t.document.documentElement["client" + n] : 9 === t.nodeType ? (f = t.documentElement,
Math.max(t.body["scroll" + n], f["scroll" + n], t.body["offset" + n], f["offset" + n], f["client" + n])) : void 0 === u ? i.css(t, r, o) : i.style(t, r, u, o)
}, t, e ? u : void 0, e, null)
}
})
}),
i.fn.size = function() {
return this.length
}
,
i.fn.andSelf = i.fn.addBack,
"function" == typeof define && define.amd && define("jquery", [], function() {
return i
}),
du = n.jQuery,
gu = n.$,
i.noConflict = function(t) {
return n.$ === i && (n.$ = gu),
t && n.jQuery === i && (n.jQuery = du),
i
}
,
typeof t === b && (n.jQuery = n.$ = i),
i
});
!function(n, t) {
"object" == typeof module && "object" == typeof module.exports ? module.exports = n.document ? t(n, !0) : function(n) {
if (!n.document)
throw new Error("jQuery requires a window with a document");
return t(n)
}
: t(n)
}("undefined" != typeof window ? window : this, function(n, t) {
function ri(n) {
var t = "length"in n && n.length
, r = i.type(n);
return "function" === r || i.isWindow(n) ? !1 : 1 === n.nodeType && t ? !0 : "array" === r || 0 === t || "number" == typeof t && t > 0 && t - 1 in n
}
function ui(n, t, r) {
if (i.isFunction(t))
return i.grep(n, function(n, i) {
return !!t.call(n, i, n) !== r
});
if (t.nodeType)
return i.grep(n, function(n) {
return n === t !== r
});
if ("string" == typeof t) {
if (ef.test(t))
return i.filter(t, n, r);
t = i.filter(t, n)
}
return i.grep(n, function(n) {
return ft.call(t, n) >= 0 !== r
})
}
function ur(n, t) {
while ((n = n[t]) && 1 !== n.nodeType)
;
return n
}
function of(n) {
var t = fi[n] = {};
return i.each(n.match(c) || [], function(n, i) {
t[i] = !0
}),
t
}
function ht() {
u.removeEventListener("DOMContentLoaded", ht, !1);
n.removeEventListener("load", ht, !1);
i.ready()
}
function v() {
Object.defineProperty(this.cache = {}, 0, {
get: function() {
return {}
}
});
this.expando = i.expando + v.uid++
}
function fr(n, t, r) {
var u;
if (void 0 === r && 1 === n.nodeType)
if (u = "data-" + t.replace(hf, "-$1").toLowerCase(),
r = n.getAttribute(u),
"string" == typeof r) {
try {
r = "true" === r ? !0 : "false" === r ? !1 : "null" === r ? null : +r + "" === r ? +r : sf.test(r) ? i.parseJSON(r) : r
} catch (f) {}
e.set(n, t, r)
} else
r = void 0;
return r
}
function lt() {
return !0
}
function k() {
return !1
}
function hr() {
try {
return u.activeElement
} catch (n) {}
}
function vr(n, t) {
return i.nodeName(n, "table") && i.nodeName(11 !== t.nodeType ? t : t.firstChild, "tr") ? n.getElementsByTagName("tbody")[0] || n.appendChild(n.ownerDocument.createElement("tbody")) : n
}
function bf(n) {
return n.type = (null !== n.getAttribute("type")) + "/" + n.type,
n
}
function kf(n) {
var t = pf.exec(n.type);
return t ? n.type = t[1] : n.removeAttribute("type"),
n
}
function ei(n, t) {
for (var i = 0, u = n.length; u > i; i++)
r.set(n[i], "globalEval", !t || r.get(t[i], "globalEval"))
}
function yr(n, t) {
var u, c, f, s, h, l, a, o;
if (1 === t.nodeType) {
if (r.hasData(n) && (s = r.access(n),
h = r.set(t, s),
o = s.events)) {
delete h.handle;
h.events = {};
for (f in o)
for (u = 0,
c = o[f].length; c > u; u++)
i.event.add(t, f, o[f][u])
}
e.hasData(n) && (l = e.access(n),
a = i.extend({}, l),
e.set(t, a))
}
}
function o(n, t) {
var r = n.getElementsByTagName ? n.getElementsByTagName(t || "*") : n.querySelectorAll ? n.querySelectorAll(t || "*") : [];
return void 0 === t || t && i.nodeName(n, t) ? i.merge([n], r) : r
}
function df(n, t) {
var i = t.nodeName.toLowerCase();
"input" === i && er.test(n.type) ? t.checked = n.checked : ("input" === i || "textarea" === i) && (t.defaultValue = n.defaultValue)
}
function pr(t, r) {
var f, u = i(r.createElement(t)).appendTo(r.body), e = n.getDefaultComputedStyle && (f = n.getDefaultComputedStyle(u[0])) ? f.display : i.css(u[0], "display");
return u.detach(),
e
}
function si(n) {
var r = u
, t = oi[n];
return t || (t = pr(n, r),
"none" !== t && t || (at = (at || i("<iframe frameborder='0' width='0' height='0'/>")).appendTo(r.documentElement),
r = at[0].contentDocument,
r.write(),
r.close(),
t = pr(n, r),
at.detach()),
oi[n] = t),
t
}
function it(n, t, r) {
var e, o, s, u, f = n.style;
return r = r || vt(n),
r && (u = r.getPropertyValue(t) || r[t]),
r && ("" !== u || i.contains(n.ownerDocument, n) || (u = i.style(n, t)),
hi.test(u) && wr.test(t) && (e = f.width,
o = f.minWidth,
s = f.maxWidth,
f.minWidth = f.maxWidth = f.width = u,
u = r.width,
f.width = e,
f.minWidth = o,
f.maxWidth = s)),
void 0 !== u ? u + "" : u
}
function br(n, t) {
return {
get: function() {
return n() ? void delete this.get : (this.get = t).apply(this, arguments)
}
}
}
function gr(n, t) {
if (t in n)
return t;
for (var r = t[0].toUpperCase() + t.slice(1), u = t, i = dr.length; i--; )
if (t = dr[i] + r,
t in n)
return t;
return u
}
function nu(n, t, i) {
var r = ne.exec(t);
return r ? Math.max(0, r[1] - (i || 0)) + (r[2] || "px") : t
}
function tu(n, t, r, u, f) {
for (var e = r === (u ? "border" : "content") ? 4 : "width" === t ? 1 : 0, o = 0; 4 > e; e += 2)
"margin" === r && (o += i.css(n, r + p[e], !0, f)),
u ? ("content" === r && (o -= i.css(n, "padding" + p[e], !0, f)),
"margin" !== r && (o -= i.css(n, "border" + p[e] + "Width", !0, f))) : (o += i.css(n, "padding" + p[e], !0, f),
"padding" !== r && (o += i.css(n, "border" + p[e] + "Width", !0, f)));
return o
}
function iu(n, t, r) {
var o = !0
, u = "width" === t ? n.offsetWidth : n.offsetHeight
, e = vt(n)
, s = "border-box" === i.css(n, "boxSizing", !1, e);
if (0 >= u || null == u) {
if (u = it(n, t, e),
(0 > u || null == u) && (u = n.style[t]),
hi.test(u))
return u;
o = s && (f.boxSizingReliable() || u === n.style[t]);
u = parseFloat(u) || 0
}
return u + tu(n, t, r || (s ? "border" : "content"), o, e) + "px"
}
function ru(n, t) {
for (var e, u, s, o = [], f = 0, h = n.length; h > f; f++)
u = n[f],
u.style && (o[f] = r.get(u, "olddisplay"),
e = u.style.display,
t ? (o[f] || "none" !== e || (u.style.display = ""),
"" === u.style.display && tt(u) && (o[f] = r.access(u, "olddisplay", si(u.nodeName)))) : (s = tt(u),
"none" === e && s || r.set(u, "olddisplay", s ? e : i.css(u, "display"))));
for (f = 0; h > f; f++)
u = n[f],
u.style && (t && "none" !== u.style.display && "" !== u.style.display || (u.style.display = t ? o[f] || "" : "none"));
return n
}
function s(n, t, i, r, u) {
return new s.prototype.init(n,t,i,r,u)
}
function fu() {
return setTimeout(function() {
d = void 0
}),
d = i.now()
}
function wt(n, t) {
var r, u = 0, i = {
height: n
};
for (t = t ? 1 : 0; 4 > u; u += 2 - t)
r = p[u],
i["margin" + r] = i["padding" + r] = n;
return t && (i.opacity = i.width = n),
i
}
function eu(n, t, i) {
for (var u, f = (rt[t] || []).concat(rt["*"]), r = 0, e = f.length; e > r; r++)
if (u = f[r].call(i, t, n))
return u
}
function fe(n, t, u) {
var f, a, p, v, o, w, h, b, l = this, y = {}, s = n.style, c = n.nodeType && tt(n), e = r.get(n, "fxshow");
u.queue || (o = i._queueHooks(n, "fx"),
null == o.unqueued && (o.unqueued = 0,
w = o.empty.fire,
o.empty.fire = function() {
o.unqueued || w()
}
),
o.unqueued++,
l.always(function() {
l.always(function() {
o.unqueued--;
i.queue(n, "fx").length || o.empty.fire()
})
}));
1 === n.nodeType && ("height"in t || "width"in t) && (u.overflow = [s.overflow, s.overflowX, s.overflowY],
h = i.css(n, "display"),
b = "none" === h ? r.get(n, "olddisplay") || si(n.nodeName) : h,
"inline" === b && "none" === i.css(n, "float") && (s.display = "inline-block"));
u.overflow && (s.overflow = "hidden",
l.always(function() {
s.overflow = u.overflow[0];
s.overflowX = u.overflow[1];
s.overflowY = u.overflow[2]
}));
for (f in t)
if (a = t[f],
re.exec(a)) {
if (delete t[f],
p = p || "toggle" === a,
a === (c ? "hide" : "show")) {
if ("show" !== a || !e || void 0 === e[f])
continue;
c = !0
}
y[f] = e && e[f] || i.style(n, f)
} else
h = void 0;
if (i.isEmptyObject(y))
"inline" === ("none" === h ? si(n.nodeName) : h) && (s.display = h);
else {
e ? "hidden"in e && (c = e.hidden) : e = r.access(n, "fxshow", {});
p && (e.hidden = !c);
c ? i(n).show() : l.done(function() {
i(n).hide()
});
l.done(function() {
var t;
r.remove(n, "fxshow");
for (t in y)
i.style(n, t, y[t])
});
for (f in y)
v = eu(c ? e[f] : 0, f, l),
f in e || (e[f] = v.start,
c && (v.end = v.start,
v.start = "width" === f || "height" === f ? 1 : 0))
}
}
function ee(n, t) {
var r, f, e, u, o;
for (r in n)
if (f = i.camelCase(r),
e = t[f],
u = n[r],
i.isArray(u) && (e = u[1],
u = n[r] = u[0]),
r !== f && (n[f] = u,
delete n[r]),
o = i.cssHooks[f],
o && "expand"in o) {
u = o.expand(u);
delete n[f];
for (r in u)
r in n || (n[r] = u[r],
t[r] = e)
} else
t[f] = e
}
function ou(n, t, r) {
var h, e, o = 0, l = pt.length, f = i.Deferred().always(function() {
delete c.elem
}), c = function() {
if (e)
return !1;
for (var s = d || fu(), t = Math.max(0, u.startTime + u.duration - s), h = t / u.duration || 0, i = 1 - h, r = 0, o = u.tweens.length; o > r; r++)
u.tweens[r].run(i);
return f.notifyWith(n, [u, i, t]),
1 > i && o ? t : (f.resolveWith(n, [u]),
!1)
}, u = f.promise({
elem: n,
props: i.extend({}, t),
opts: i.extend(!0, {
specialEasing: {}
}, r),
originalProperties: t,
originalOptions: r,
startTime: d || fu(),
duration: r.duration,
tweens: [],
createTween: function(t, r) {
var f = i.Tween(n, u.opts, t, r, u.opts.specialEasing[t] || u.opts.easing);
return u.tweens.push(f),
f
},
stop: function(t) {
var i = 0
, r = t ? u.tweens.length : 0;
if (e)
return this;
for (e = !0; r > i; i++)
u.tweens[i].run(1);
return t ? f.resolveWith(n, [u, t]) : f.rejectWith(n, [u, t]),
this
}
}), s = u.props;
for (ee(s, u.opts.specialEasing); l > o; o++)
if (h = pt[o].call(u, n, s, u.opts))
return h;
return i.map(s, eu, u),
i.isFunction(u.opts.start) && u.opts.start.call(n, u),
i.fx.timer(i.extend(c, {
elem: n,
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 pu(n) {
return function(t, r) {
"string" != typeof t && (r = t,
t = "*");
var u, f = 0, e = t.toLowerCase().match(c) || [];
if (i.isFunction(r))
while (u = e[f++])
"+" === u[0] ? (u = u.slice(1) || "*",
(n[u] = n[u] || []).unshift(r)) : (n[u] = n[u] || []).push(r)
}
}
function wu(n, t, r, u) {
function e(s) {
var h;
return f[s] = !0,
i.each(n[s] || [], function(n, i) {
var s = i(t, r, u);
return "string" != typeof s || o || f[s] ? o ? !(h = s) : void 0 : (t.dataTypes.unshift(s),
e(s),
!1)
}),
h
}
var f = {}
, o = n === ci;
return e(t.dataTypes[0]) || !f["*"] && e("*")
}
function ai(n, t) {
var r, u, f = i.ajaxSettings.flatOptions || {};
for (r in t)
void 0 !== t[r] && ((f[r] ? n : u || (u = {}))[r] = t[r]);
return u && i.extend(!0, n, u),
n
}
function ae(n, t, i) {
for (var e, u, f, o, s = n.contents, r = n.dataTypes; "*" === r[0]; )
r.shift(),
void 0 === e && (e = n.mimeType || t.getResponseHeader("Content-Type"));
if (e)
for (u in s)
if (s[u] && s[u].test(e)) {
r.unshift(u);
break
}
if (r[0]in i)
f = r[0];
else {
for (u in i) {
if (!r[0] || n.converters[u + " " + r[0]]) {
f = u;
break
}
o || (o = u)
}
f = f || o
}
if (f)
return (f !== r[0] && r.unshift(f),
i[f])
}
function ve(n, t, i, r) {
var h, u, f, s, e, o = {}, c = n.dataTypes.slice();
if (c[1])
for (f in n.converters)
o[f.toLowerCase()] = n.converters[f];
for (u = c.shift(); u; )
if (n.responseFields[u] && (i[n.responseFields[u]] = t),
!e && r && n.dataFilter && (t = n.dataFilter(t, n.dataType)),
e = u,
u = c.shift())
if ("*" === u)
u = e;
else if ("*" !== e && e !== u) {
if (f = o[e + " " + u] || o["* " + u],
!f)
for (h in o)
if (s = h.split(" "),
s[1] === u && (f = o[e + " " + s[0]] || o["* " + s[0]])) {
f === !0 ? f = o[h] : o[h] !== !0 && (u = s[0],
c.unshift(s[1]));
break
}
if (f !== !0)
if (f && n.throws)
t = f(t);
else
try {
t = f(t)
} catch (l) {
return {
state: "parsererror",
error: f ? l : "No conversion from " + e + " to " + u
}
}
}
return {
state: "success",
data: t
}
}
function vi(n, t, r, u) {
var f;
if (i.isArray(t))
i.each(t, function(t, i) {
r || pe.test(n) ? u(n, i) : vi(n + "[" + ("object" == typeof i ? t : "") + "]", i, r, u)
});
else if (r || "object" !== i.type(t))
u(n, t);
else
for (f in t)
vi(n + "[" + f + "]", t[f], r, u)
}
function ku(n) {
return i.isWindow(n) ? n : 9 === n.nodeType && n.defaultView
}
var w = [], a = w.slice, bi = w.concat, ti = w.push, ft = w.indexOf, et = {}, nf = et.toString, ii = et.hasOwnProperty, f = {}, u = n.document, ki = "2.1.4", i = function(n, t) {
return new i.fn.init(n,t)
}, tf = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, rf = /^-ms-/, uf = /-([\da-z])/gi, ff = function(n, t) {
return t.toUpperCase()
}, y, ot, nr, tr, ir, rr, c, fi, st, l, b, at, oi, oe, su, g, hu, bt, cu, kt, dt, yi, ni, pi, wi, du, gu;
i.fn = i.prototype = {
jquery: ki,
constructor: i,
selector: "",
length: 0,
toArray: function() {
return a.call(this)
},
get: function(n) {
return null != n ? 0 > n ? this[n + this.length] : this[n] : a.call(this)
},
pushStack: function(n) {
var t = i.merge(this.constructor(), n);
return t.prevObject = this,
t.context = this.context,
t
},
each: function(n, t) {
return i.each(this, n, t)
},
map: function(n) {
return this.pushStack(i.map(this, function(t, i) {
return n.call(t, i, t)
}))
},
slice: function() {
return this.pushStack(a.apply(this, arguments))
},
first: function() {
return this.eq(0)
},
last: function() {
return this.eq(-1)
},
eq: function(n) {
var i = this.length
, t = +n + (0 > n ? i : 0);
return this.pushStack(t >= 0 && i > t ? [this[t]] : [])
},
end: function() {
return this.prevObject || this.constructor(null)
},
push: ti,
sort: w.sort,
splice: w.splice
};
i.extend = i.fn.extend = function() {
var e, f, r, t, o, s, n = arguments[0] || {}, u = 1, c = arguments.length, h = !1;
for ("boolean" == typeof n && (h = n,
n = arguments[u] || {},
u++),
"object" == typeof n || i.isFunction(n) || (n = {}),
u === c && (n = this,
u--); c > u; u++)
if (null != (e = arguments[u]))
for (f in e)
r = n[f],
t = e[f],
n !== t && (h && t && (i.isPlainObject(t) || (o = i.isArray(t))) ? (o ? (o = !1,
s = r && i.isArray(r) ? r : []) : s = r && i.isPlainObject(r) ? r : {},
n[f] = i.extend(h, s, t)) : void 0 !== t && (n[f] = t));
return n
}
;
i.extend({
expando: "jQuery" + (ki + Math.random()).replace(/\D/g, ""),
isReady: !0,
error: function(n) {
throw new Error(n);
},
noop: function() {},
isFunction: function(n) {
return "function" === i.type(n)
},
isArray: Array.isArray,
isWindow: function(n) {
return null != n && n === n.window
},
isNumeric: function(n) {
return !i.isArray(n) && n - parseFloat(n) + 1 >= 0
},
isPlainObject: function(n) {
return "object" !== i.type(n) || n.nodeType || i.isWindow(n) ? !1 : n.constructor && !ii.call(n.constructor.prototype, "isPrototypeOf") ? !1 : !0
},
isEmptyObject: function(n) {
var t;
for (t in n)
return !1;
return !0
},
type: function(n) {
return null == n ? n + "" : "object" == typeof n || "function" == typeof n ? et[nf.call(n)] || "object" : typeof n
},
globalEval: function(n) {
var t, r = eval;
n = i.trim(n);
n && (1 === n.indexOf("use strict") ? (t = u.createElement("script"),
t.text = n,
u.head.appendChild(t).parentNode.removeChild(t)) : r(n))
},
camelCase: function(n) {
return n.replace(rf, "ms-").replace(uf, ff)
},
nodeName: function(n, t) {
return n.nodeName && n.nodeName.toLowerCase() === t.toLowerCase()
},
each: function(n, t, i) {
var u, r = 0, f = n.length, e = ri(n);
if (i) {
if (e) {
for (; f > r; r++)
if (u = t.apply(n[r], i),
u === !1)
break
} else
for (r in n)
if (u = t.apply(n[r], i),
u === !1)
break
} else if (e) {
for (; f > r; r++)
if (u = t.call(n[r], r, n[r]),
u === !1)
break
} else
for (r in n)
if (u = t.call(n[r], r, n[r]),
u === !1)
break;
return n
},
trim: function(n) {
return null == n ? "" : (n + "").replace(tf, "")
},
makeArray: function(n, t) {
var r = t || [];
return null != n && (ri(Object(n)) ? i.merge(r, "string" == typeof n ? [n] : n) : ti.call(r, n)),
r
},
inArray: function(n, t, i) {
return null == t ? -1 : ft.call(t, n, i)
},
merge: function(n, t) {
for (var u = +t.length, i = 0, r = n.length; u > i; i++)
n[r++] = t[i];
return n.length = r,
n
},
grep: function(n, t, i) {
for (var u, f = [], r = 0, e = n.length, o = !i; e > r; r++)
u = !t(n[r], r),
u !== o && f.push(n[r]);
return f
},
map: function(n, t, i) {
var u, r = 0, e = n.length, o = ri(n), f = [];
if (o)
for (; e > r; r++)
u = t(n[r], r, i),
null != u && f.push(u);
else
for (r in n)
u = t(n[r], r, i),
null != u && f.push(u);
return bi.apply([], f)
},
guid: 1,
proxy: function(n, t) {
var u, f, r;
return "string" == typeof t && (u = n[t],
t = n,
n = u),
i.isFunction(n) ? (f = a.call(arguments, 2),
r = function() {
return n.apply(t || this, f.concat(a.call(arguments)))
}
,
r.guid = n.guid = n.guid || i.guid++,
r) : void 0
},
now: Date.now,
support: f
});
i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(n, t) {
et["[object " + t + "]"] = t.toLowerCase()
});
y = function(n) {
function r(n, t, i, r) {
var p, s, a, c, w, y, d, v, nt, g;
if ((t ? t.ownerDocument || t : h) !== o && k(t),
t = t || o,
i = i || [],
c = t.nodeType,
"string" != typeof n || !n || 1 !== c && 9 !== c && 11 !== c)
return i;
if (!r && l) {
if (11 !== c && (p = hr.exec(n)))
if (a = p[1]) {
if (9 === c) {
if (s = t.getElementById(a),
!s || !s.parentNode)
return i;
if (s.id === a)
return i.push(s),
i
} else if (t.ownerDocument && (s = t.ownerDocument.getElementById(a)) && et(t, s) && s.id === a)
return i.push(s),
i
} else {
if (p[2])
return b.apply(i, t.getElementsByTagName(n)),
i;
if ((a = p[3]) && u.getElementsByClassName)
return b.apply(i, t.getElementsByClassName(a)),
i
}
if (u.qsa && (!e || !e.test(n))) {
if (v = d = f,
nt = t,
g = 1 !== c && n,
1 === c && "object" !== t.nodeName.toLowerCase()) {
for (y = ft(n),
(d = t.getAttribute("id")) ? v = d.replace(cr, "\\$&") : t.setAttribute("id", v),
v = "[id='" + v + "'] ",
w = y.length; w--; )
y[w] = v + vt(y[w]);
nt = dt.test(n) && ti(t.parentNode) || t;
g = y.join(",")
}
if (g)
try {
return b.apply(i, nt.querySelectorAll(g)),
i
} catch (tt) {} finally {
d || t.removeAttribute("id")
}
}
}
return oi(n.replace(lt, "$1"), t, i, r)
}
function gt() {
function n(r, u) {
return i.push(r + " ") > t.cacheLength && delete n[i.shift()],
n[r + " "] = u
}
var i = [];
return n
}
function c(n) {
return n[f] = !0,
n
}
function v(n) {
var t = o.createElement("div");
try {
return !!n(t)
} catch (i) {
return !1
} finally {
t.parentNode && t.parentNode.removeChild(t);
t = null
}
}
function ni(n, i) {
for (var u = n.split("|"), r = n.length; r--; )
t.attrHandle[u[r]] = i
}
function wi(n, t) {
var i = t && n
, r = i && 1 === n.nodeType && 1 === t.nodeType && (~t.sourceIndex || li) - (~n.sourceIndex || li);
if (r)
return r;
if (i)
while (i = i.nextSibling)
if (i === t)
return -1;
return n ? 1 : -1
}
function lr(n) {
return function(t) {
var i = t.nodeName.toLowerCase();
return "input" === i && t.type === n
}
}
function ar(n) {
return function(t) {
var i = t.nodeName.toLowerCase();
return ("input" === i || "button" === i) && t.type === n
}
}
function tt(n) {
return c(function(t) {
return t = +t,
c(function(i, r) {
for (var u, f = n([], i.length, t), e = f.length; e--; )
i[u = f[e]] && (i[u] = !(r[u] = i[u]))
})
})
}
function ti(n) {
return n && "undefined" != typeof n.getElementsByTagName && n
}
function bi() {}
function vt(n) {
for (var t = 0, r = n.length, i = ""; r > t; t++)
i += n[t].value;
return i
}
function ii(n, t, i) {
var r = t.dir
, u = i && "parentNode" === r
, e = ki++;
return t.first ? function(t, i, f) {
while (t = t[r])
if (1 === t.nodeType || u)
return n(t, i, f)
}
: function(t, i, o) {
var s, h, c = [a, e];
if (o) {
while (t = t[r])
if ((1 === t.nodeType || u) && n(t, i, o))
return !0
} else
while (t = t[r])
if (1 === t.nodeType || u) {
if (h = t[f] || (t[f] = {}),
(s = h[r]) && s[0] === a && s[1] === e)
return c[2] = s[2];
if (h[r] = c,
c[2] = n(t, i, o))
return !0
}
}
}
function ri(n) {
return n.length > 1 ? function(t, i, r) {
for (var u = n.length; u--; )
if (!n[u](t, i, r))
return !1;
return !0
}
: n[0]
}
function vr(n, t, i) {
for (var u = 0, f = t.length; f > u; u++)
r(n, t[u], i);
return i
}
function yt(n, t, i, r, u) {
for (var e, o = [], f = 0, s = n.length, h = null != t; s > f; f++)
(e = n[f]) && (!i || i(e, r, u)) && (o.push(e),
h && t.push(f));
return o
}
function ui(n, t, i, r, u, e) {
return r && !r[f] && (r = ui(r)),
u && !u[f] && (u = ui(u, e)),
c(function(f, e, o, s) {
var l, c, a, p = [], y = [], w = e.length, k = f || vr(t || "*", o.nodeType ? [o] : o, []), v = !n || !f && t ? k : yt(k, p, n, o, s), h = i ? u || (f ? n : w || r) ? [] : e : v;
if (i && i(v, h, o, s),
r)
for (l = yt(h, y),
r(l, [], o, s),
c = l.length; c--; )
(a = l[c]) && (h[y[c]] = !(v[y[c]] = a));
if (f) {
if (u || n) {
if (u) {
for (l = [],
c = h.length; c--; )
(a = h[c]) && l.push(v[c] = a);
u(null, h = [], l, s)
}
for (c = h.length; c--; )
(a = h[c]) && (l = u ? nt(f, a) : p[c]) > -1 && (f[l] = !(e[l] = a))
}
} else
h = yt(h === e ? h.splice(w, h.length) : h),
u ? u(null, e, h, s) : b.apply(e, h)
})
}
function fi(n) {
for (var o, u, r, s = n.length, h = t.relative[n[0].type], c = h || t.relative[" "], i = h ? 1 : 0, l = ii(function(n) {
return n === o
}, c, !0), a = ii(function(n) {
return nt(o, n) > -1
}, c, !0), e = [function(n, t, i) {
var r = !h && (i || t !== ht) || ((o = t).nodeType ? l(n, t, i) : a(n, t, i));
return o = null,
r
}
]; s > i; i++)
if (u = t.relative[n[i].type])
e = [ii(ri(e), u)];
else {
if (u = t.filter[n[i].type].apply(null, n[i].matches),
u[f]) {
for (r = ++i; s > r; r++)
if (t.relative[n[r].type])
break;
return ui(i > 1 && ri(e), i > 1 && vt(n.slice(0, i - 1).concat({
value: " " === n[i - 2].type ? "*" : ""
})).replace(lt, "$1"), u, r > i && fi(n.slice(i, r)), s > r && fi(n = n.slice(r)), s > r && vt(n))
}
e.push(u)
}
return ri(e)
}
function yr(n, i) {
var u = i.length > 0
, f = n.length > 0
, e = function(e, s, h, c, l) {
var y, d, w, k = 0, v = "0", g = e && [], p = [], nt = ht, tt = e || f && t.find.TAG("*", l), it = a += null == nt ? 1 : Math.random() || .1, rt = tt.length;
for (l && (ht = s !== o && s); v !== rt && null != (y = tt[v]); v++) {
if (f && y) {
for (d = 0; w = n[d++]; )
if (w(y, s, h)) {
c.push(y);
break
}
l && (a = it)
}
u && ((y = !w && y) && k--,
e && g.push(y))
}
if (k += v,
u && v !== k) {
for (d = 0; w = i[d++]; )
w(g, p, s, h);
if (e) {
if (k > 0)
while (v--)
g[v] || p[v] || (p[v] = gi.call(c));
p = yt(p)
}
b.apply(c, p);
l && !e && p.length > 0 && k + i.length > 1 && r.uniqueSort(c)
}
return l && (a = it,
ht = nt),
g
};
return u ? c(e) : e
}
var it, u, t, st, ei, ft, pt, oi, ht, w, rt, k, o, s, l, e, d, ct, et, f = "sizzle" + 1 * new Date, h = n.document, a = 0, ki = 0, si = gt(), hi = gt(), ci = gt(), wt = function(n, t) {
return n === t && (rt = !0),
0
}, li = -2147483648, di = {}.hasOwnProperty, g = [], gi = g.pop, nr = g.push, b = g.push, ai = g.slice, nt = function(n, t) {
for (var i = 0, r = n.length; r > i; i++)
if (n[i] === t)
return i;
return -1
}, bt = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", i = "[\\x20\\t\\r\\n\\f]", ut = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", vi = ut.replace("w", "w#"), yi = "\\[" + i + "*(" + ut + ")(?:" + i + "*([*^$|!~]?=)" + i + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + vi + "))|)" + i + "*\\]", kt = ":(" + ut + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + yi + ")*)|.*)\\)|)", tr = new RegExp(i + "+","g"), lt = new RegExp("^" + i + "+|((?:^|[^\\\\])(?:\\\\.)*)" + i + "+$","g"), ir = new RegExp("^" + i + "*," + i + "*"), rr = new RegExp("^" + i + "*([>+~]|" + i + ")" + i + "*"), ur = new RegExp("=" + i + "*([^\\]'\"]*?)" + i + "*\\]","g"), fr = new RegExp(kt), er = new RegExp("^" + vi + "$"), at = {
ID: new RegExp("^#(" + ut + ")"),
CLASS: new RegExp("^\\.(" + ut + ")"),
TAG: new RegExp("^(" + ut.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + yi),
PSEUDO: new RegExp("^" + kt),
CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + i + "*(even|odd|(([+-]|)(\\d*)n|)" + i + "*(?:([+-]|)" + i + "*(\\d+)|))" + i + "*\\)|)","i"),
bool: new RegExp("^(?:" + bt + ")$","i"),
needsContext: new RegExp("^" + i + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + i + "*((?:-\\d)?\\d*)" + i + "*\\)|)(?=[^-]|$)","i")
}, or = /^(?:input|select|textarea|button)$/i, sr = /^h\d$/i, ot = /^[^{]+\{\s*\[native \w/, hr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, dt = /[+~]/, cr = /'|\\/g, y = new RegExp("\\\\([\\da-f]{1,6}" + i + "?|(" + i + ")|.)","ig"), p = function(n, t, i) {
var r = "0x" + t - 65536;
return r !== r || i ? t : 0 > r ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, 1023 & r | 56320)
}, pi = function() {
k()
};
try {
b.apply(g = ai.call(h.childNodes), h.childNodes);
g[h.childNodes.length].nodeType
} catch (pr) {
b = {
apply: g.length ? function(n, t) {
nr.apply(n, ai.call(t))
}
: function(n, t) {
for (var i = n.length, r = 0; n[i++] = t[r++]; )
;
n.length = i - 1
}
}
}
u = r.support = {};
ei = r.isXML = function(n) {
var t = n && (n.ownerDocument || n).documentElement;
return t ? "HTML" !== t.nodeName : !1
}
;
k = r.setDocument = function(n) {
var a, c, r = n ? n.ownerDocument || n : h;
return r !== o && 9 === r.nodeType && r.documentElement ? (o = r,
s = r.documentElement,
c = r.defaultView,
c && c !== c.top && (c.addEventListener ? c.addEventListener("unload", pi, !1) : c.attachEvent && c.attachEvent("onunload", pi)),
l = !ei(r),
u.attributes = v(function(n) {
return n.className = "i",
!n.getAttribute("className")
}),
u.getElementsByTagName = v(function(n) {
return n.appendChild(r.createComment("")),
!n.getElementsByTagName("*").length
}),
u.getElementsByClassName = ot.test(r.getElementsByClassName),
u.getById = v(function(n) {
return s.appendChild(n).id = f,
!r.getElementsByName || !r.getElementsByName(f).length
}),
u.getById ? (t.find.ID = function(n, t) {
if ("undefined" != typeof t.getElementById && l) {
var i = t.getElementById(n);
return i && i.parentNode ? [i] : []
}
}
,
t.filter.ID = function(n) {
var t = n.replace(y, p);
return function(n) {
return n.getAttribute("id") === t
}
}
) : (delete t.find.ID,
t.filter.ID = function(n) {
var t = n.replace(y, p);
return function(n) {
var i = "undefined" != typeof n.getAttributeNode && n.getAttributeNode("id");
return i && i.value === t
}
}
),
t.find.TAG = u.getElementsByTagName ? function(n, t) {
return "undefined" != typeof t.getElementsByTagName ? t.getElementsByTagName(n) : u.qsa ? t.querySelectorAll(n) : void 0
}
: function(n, t) {
var i, r = [], f = 0, u = t.getElementsByTagName(n);
if ("*" === n) {
while (i = u[f++])
1 === i.nodeType && r.push(i);
return r
}
return u
}
,
t.find.CLASS = u.getElementsByClassName && function(n, t) {
if (l)
return t.getElementsByClassName(n)
}
,
d = [],
e = [],
(u.qsa = ot.test(r.querySelectorAll)) && (v(function(n) {
s.appendChild(n).innerHTML = "<a id='" + f + "'><\/a><select id='" + f + "-\f]' msallowcapture=''><option selected=''><\/option><\/select>";
n.querySelectorAll("[msallowcapture^='']").length && e.push("[*^$]=" + i + "*(?:''|\"\")");
n.querySelectorAll("[selected]").length || e.push("\\[" + i + "*(?:value|" + bt + ")");
n.querySelectorAll("[id~=" + f + "-]").length || e.push("~=");
n.querySelectorAll(":checked").length || e.push(":checked");
n.querySelectorAll("a#" + f + "+*").length || e.push(".#.+[+~]")
}),
v(function(n) {
var t = r.createElement("input");
t.setAttribute("type", "hidden");
n.appendChild(t).setAttribute("name", "D");
n.querySelectorAll("[name=d]").length && e.push("name" + i + "*[*^$|!~]?=");
n.querySelectorAll(":enabled").length || e.push(":enabled", ":disabled");
n.querySelectorAll("*,:x");
e.push(",.*:")
})),
(u.matchesSelector = ot.test(ct = s.matches || s.webkitMatchesSelector || s.mozMatchesSelector || s.oMatchesSelector || s.msMatchesSelector)) && v(function(n) {
u.disconnectedMatch = ct.call(n, "div");
ct.call(n, "[s!='']:x");
d.push("!=", kt)
}),
e = e.length && new RegExp(e.join("|")),
d = d.length && new RegExp(d.join("|")),
a = ot.test(s.compareDocumentPosition),
et = a || ot.test(s.contains) ? function(n, t) {
var r = 9 === n.nodeType ? n.documentElement : n
, i = t && t.parentNode;
return n === i || !(!i || 1 !== i.nodeType || !(r.contains ? r.contains(i) : n.compareDocumentPosition && 16 & n.compareDocumentPosition(i)))
}
: function(n, t) {
if (t)
while (t = t.parentNode)
if (t === n)
return !0;
return !1
}
,
wt = a ? function(n, t) {
if (n === t)
return rt = !0,
0;
var i = !n.compareDocumentPosition - !t.compareDocumentPosition;
return i ? i : (i = (n.ownerDocument || n) === (t.ownerDocument || t) ? n.compareDocumentPosition(t) : 1,
1 & i || !u.sortDetached && t.compareDocumentPosition(n) === i ? n === r || n.ownerDocument === h && et(h, n) ? -1 : t === r || t.ownerDocument === h && et(h, t) ? 1 : w ? nt(w, n) - nt(w, t) : 0 : 4 & i ? -1 : 1)
}
: function(n, t) {
if (n === t)
return rt = !0,
0;
var i, u = 0, o = n.parentNode, s = t.parentNode, f = [n], e = [t];
if (!o || !s)
return n === r ? -1 : t === r ? 1 : o ? -1 : s ? 1 : w ? nt(w, n) - nt(w, t) : 0;
if (o === s)
return wi(n, t);
for (i = n; i = i.parentNode; )
f.unshift(i);
for (i = t; i = i.parentNode; )
e.unshift(i);
while (f[u] === e[u])
u++;
return u ? wi(f[u], e[u]) : f[u] === h ? -1 : e[u] === h ? 1 : 0
}
,
r) : o
}
;
r.matches = function(n, t) {
return r(n, null, null, t)
}
;
r.matchesSelector = function(n, t) {
if ((n.ownerDocument || n) !== o && k(n),
t = t.replace(ur, "='$1']"),
!(!u.matchesSelector || !l || d && d.test(t) || e && e.test(t)))
try {
var i = ct.call(n, t);
if (i || u.disconnectedMatch || n.document && 11 !== n.document.nodeType)
return i
} catch (f) {}
return r(t, o, null, [n]).length > 0
}
;
r.contains = function(n, t) {
return (n.ownerDocument || n) !== o && k(n),
et(n, t)
}
;
r.attr = function(n, i) {
(n.ownerDocument || n) !== o && k(n);
var f = t.attrHandle[i.toLowerCase()]
, r = f && di.call(t.attrHandle, i.toLowerCase()) ? f(n, i, !l) : void 0;
return void 0 !== r ? r : u.attributes || !l ? n.getAttribute(i) : (r = n.getAttributeNode(i)) && r.specified ? r.value : null
}
;
r.error = function(n) {
throw new Error("Syntax error, unrecognized expression: " + n);
}
;
r.uniqueSort = function(n) {
var r, f = [], t = 0, i = 0;
if (rt = !u.detectDuplicates,
w = !u.sortStable && n.slice(0),
n.sort(wt),
rt) {
while (r = n[i++])
r === n[i] && (t = f.push(i));
while (t--)
n.splice(f[t], 1)
}
return w = null,
n
}
;
st = r.getText = function(n) {
var r, i = "", u = 0, t = n.nodeType;
if (t) {
if (1 === t || 9 === t || 11 === t) {
if ("string" == typeof n.textContent)
return n.textContent;
for (n = n.firstChild; n; n = n.nextSibling)
i += st(n)
} else if (3 === t || 4 === t)
return n.nodeValue
} else
while (r = n[u++])
i += st(r);
return i
}
;
t = r.selectors = {
cacheLength: 50,
createPseudo: c,
match: at,
attrHandle: {},
find: {},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(n) {
return n[1] = n[1].replace(y, p),
n[3] = (n[3] || n[4] || n[5] || "").replace(y, p),
"~=" === n[2] && (n[3] = " " + n[3] + " "),
n.slice(0, 4)
},
CHILD: function(n) {
return n[1] = n[1].toLowerCase(),
"nth" === n[1].slice(0, 3) ? (n[3] || r.error(n[0]),
n[4] = +(n[4] ? n[5] + (n[6] || 1) : 2 * ("even" === n[3] || "odd" === n[3])),
n[5] = +(n[7] + n[8] || "odd" === n[3])) : n[3] && r.error(n[0]),
n
},
PSEUDO: function(n) {
var i, t = !n[6] && n[2];
return at.CHILD.test(n[0]) ? null : (n[3] ? n[2] = n[4] || n[5] || "" : t && fr.test(t) && (i = ft(t, !0)) && (i = t.indexOf(")", t.length - i) - t.length) && (n[0] = n[0].slice(0, i),
n[2] = t.slice(0, i)),
n.slice(0, 3))
}
},
filter: {
TAG: function(n) {
var t = n.replace(y, p).toLowerCase();
return "*" === n ? function() {
return !0
}
: function(n) {
return n.nodeName && n.nodeName.toLowerCase() === t
}
},
CLASS: function(n) {
var t = si[n + " "];
return t || (t = new RegExp("(^|" + i + ")" + n + "(" + i + "|$)")) && si(n, function(n) {
return t.test("string" == typeof n.className && n.className || "undefined" != typeof n.getAttribute && n.getAttribute("class") || "")
})
},
ATTR: function(n, t, i) {
return function(u) {
var f = r.attr(u, n);
return null == f ? "!=" === t : t ? (f += "",
"=" === t ? f === i : "!=" === t ? f !== i : "^=" === t ? i && 0 === f.indexOf(i) : "*=" === t ? i && f.indexOf(i) > -1 : "$=" === t ? i && f.slice(-i.length) === i : "~=" === t ? (" " + f.replace(tr, " ") + " ").indexOf(i) > -1 : "|=" === t ? f === i || f.slice(0, i.length + 1) === i + "-" : !1) : !0
}
},
CHILD: function(n, t, i, r, u) {
var s = "nth" !== n.slice(0, 3)
, o = "last" !== n.slice(-4)
, e = "of-type" === t;
return 1 === r && 0 === u ? function(n) {
return !!n.parentNode
}
: function(t, i, h) {
var v, k, c, l, y, w, b = s !== o ? "nextSibling" : "previousSibling", p = t.parentNode, g = e && t.nodeName.toLowerCase(), d = !h && !e;
if (p) {
if (s) {
while (b) {
for (c = t; c = c[b]; )
if (e ? c.nodeName.toLowerCase() === g : 1 === c.nodeType)
return !1;
w = b = "only" === n && !w && "nextSibling"
}
return !0
}
if (w = [o ? p.firstChild : p.lastChild],
o && d) {
for (k = p[f] || (p[f] = {}),
v = k[n] || [],
y = v[0] === a && v[1],
l = v[0] === a && v[2],
c = y && p.childNodes[y]; c = ++y && c && c[b] || (l = y = 0) || w.pop(); )
if (1 === c.nodeType && ++l && c === t) {
k[n] = [a, y, l];
break
}
} else if (d && (v = (t[f] || (t[f] = {}))[n]) && v[0] === a)
l = v[1];
else
while (c = ++y && c && c[b] || (l = y = 0) || w.pop())
if ((e ? c.nodeName.toLowerCase() === g : 1 === c.nodeType) && ++l && (d && ((c[f] || (c[f] = {}))[n] = [a, l]),
c === t))
break;
return l -= u,
l === r || l % r == 0 && l / r >= 0
}
}
},
PSEUDO: function(n, i) {
var e, u = t.pseudos[n] || t.setFilters[n.toLowerCase()] || r.error("unsupported pseudo: " + n);
return u[f] ? u(i) : u.length > 1 ? (e = [n, n, "", i],
t.setFilters.hasOwnProperty(n.toLowerCase()) ? c(function(n, t) {
for (var r, f = u(n, i), e = f.length; e--; )
r = nt(n, f[e]),
n[r] = !(t[r] = f[e])
}) : function(n) {
return u(n, 0, e)
}
) : u
}
},
pseudos: {
not: c(function(n) {
var t = []
, r = []
, i = pt(n.replace(lt, "$1"));
return i[f] ? c(function(n, t, r, u) {
for (var e, o = i(n, null, u, []), f = n.length; f--; )
(e = o[f]) && (n[f] = !(t[f] = e))
}) : function(n, u, f) {
return t[0] = n,
i(t, null, f, r),
t[0] = null,
!r.pop()
}
}),
has: c(function(n) {
return function(t) {
return r(n, t).length > 0
}
}),
contains: c(function(n) {
return n = n.replace(y, p),
function(t) {
return (t.textContent || t.innerText || st(t)).indexOf(n) > -1
}
}),
lang: c(function(n) {
return er.test(n || "") || r.error("unsupported lang: " + n),
n = n.replace(y, p).toLowerCase(),
function(t) {
var i;
do
if (i = l ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang"))
return i = i.toLowerCase(),
i === n || 0 === i.indexOf(n + "-");
while ((t = t.parentNode) && 1 === t.nodeType);return !1
}
}),
target: function(t) {
var i = n.location && n.location.hash;
return i && i.slice(1) === t.id
},
root: function(n) {
return n === s
},
focus: function(n) {
return n === o.activeElement && (!o.hasFocus || o.hasFocus()) && !!(n.type || n.href || ~n.tabIndex)
},
enabled: function(n) {
return n.disabled === !1
},
disabled: function(n) {
return n.disabled === !0
},
checked: function(n) {
var t = n.nodeName.toLowerCase();
return "input" === t && !!n.checked || "option" === t && !!n.selected
},
selected: function(n) {
return n.parentNode && n.parentNode.selectedIndex,
n.selected === !0
},
empty: function(n) {
for (n = n.firstChild; n; n = n.nextSibling)
if (n.nodeType < 6)
return !1;
return !0
},
parent: function(n) {
return !t.pseudos.empty(n)
},
header: function(n) {
return sr.test(n.nodeName)
},
input: function(n) {
return or.test(n.nodeName)
},
button: function(n) {
var t = n.nodeName.toLowerCase();
return "input" === t && "button" === n.type || "button" === t
},
text: function(n) {
var t;
return "input" === n.nodeName.toLowerCase() && "text" === n.type && (null == (t = n.getAttribute("type")) || "text" === t.toLowerCase())
},
first: tt(function() {
return [0]
}),
last: tt(function(n, t) {
return [t - 1]
}),
eq: tt(function(n, t, i) {
return [0 > i ? i + t : i]
}),
even: tt(function(n, t) {
for (var i = 0; t > i; i += 2)
n.push(i);
return n
}),
odd: tt(function(n, t) {
for (var i = 1; t > i; i += 2)
n.push(i);
return n
}),
lt: tt(function(n, t, i) {
for (var r = 0 > i ? i + t : i; --r >= 0; )
n.push(r);
return n
}),
gt: tt(function(n, t, i) {
for (var r = 0 > i ? i + t : i; ++r < t; )
n.push(r);
return n
})
}
};
t.pseudos.nth = t.pseudos.eq;
for (it in {
radio: !0,
checkbox: !0,
file: !0,
password: !0,
image: !0
})
t.pseudos[it] = lr(it);
for (it in {
submit: !0,
reset: !0
})
t.pseudos[it] = ar(it);
return bi.prototype = t.filters = t.pseudos,
t.setFilters = new bi,
ft = r.tokenize = function(n, i) {
var e, f, s, o, u, h, c, l = hi[n + " "];
if (l)
return i ? 0 : l.slice(0);
for (u = n,
h = [],
c = t.preFilter; u; ) {
(!e || (f = ir.exec(u))) && (f && (u = u.slice(f[0].length) || u),
h.push(s = []));
e = !1;
(f = rr.exec(u)) && (e = f.shift(),
s.push({
value: e,
type: f[0].replace(lt, " ")
}),
u = u.slice(e.length));
for (o in t.filter)
(f = at[o].exec(u)) && (!c[o] || (f = c[o](f))) && (e = f.shift(),
s.push({
value: e,
type: o,
matches: f
}),
u = u.slice(e.length));
if (!e)
break
}
return i ? u.length : u ? r.error(n) : hi(n, h).slice(0)
}
,
pt = r.compile = function(n, t) {
var r, u = [], e = [], i = ci[n + " "];
if (!i) {
for (t || (t = ft(n)),
r = t.length; r--; )
i = fi(t[r]),
i[f] ? u.push(i) : e.push(i);
i = ci(n, yr(e, u));
i.selector = n
}
return i
}
,
oi = r.select = function(n, i, r, f) {
var s, e, o, a, v, c = "function" == typeof n && n, h = !f && ft(n = c.selector || n);
if (r = r || [],
1 === h.length) {
if (e = h[0] = h[0].slice(0),
e.length > 2 && "ID" === (o = e[0]).type && u.getById && 9 === i.nodeType && l && t.relative[e[1].type]) {
if (i = (t.find.ID(o.matches[0].replace(y, p), i) || [])[0],
!i)
return r;
c && (i = i.parentNode);
n = n.slice(e.shift().value.length)
}
for (s = at.needsContext.test(n) ? 0 : e.length; s--; ) {
if (o = e[s],
t.relative[a = o.type])
break;
if ((v = t.find[a]) && (f = v(o.matches[0].replace(y, p), dt.test(e[0].type) && ti(i.parentNode) || i))) {
if (e.splice(s, 1),
n = f.length && vt(e),
!n)
return b.apply(r, f),
r;
break
}
}
}
return (c || pt(n, h))(f, i, !l, r, dt.test(n) && ti(i.parentNode) || i),
r
}
,
u.sortStable = f.split("").sort(wt).join("") === f,
u.detectDuplicates = !!rt,
k(),
u.sortDetached = v(function(n) {
return 1 & n.compareDocumentPosition(o.createElement("div"))
}),
v(function(n) {
return n.innerHTML = "<a href='#'><\/a>",
"#" === n.firstChild.getAttribute("href")
}) || ni("type|href|height|width", function(n, t, i) {
if (!i)
return n.getAttribute(t, "type" === t.toLowerCase() ? 1 : 2)
}),
u.attributes && v(function(n) {
return n.innerHTML = "<input/>",
n.firstChild.setAttribute("value", ""),
"" === n.firstChild.getAttribute("value")
}) || ni("value", function(n, t, i) {
if (!i && "input" === n.nodeName.toLowerCase())
return n.defaultValue
}),
v(function(n) {
return null == n.getAttribute("disabled")
}) || ni(bt, function(n, t, i) {
var r;
if (!i)
return n[t] === !0 ? t.toLowerCase() : (r = n.getAttributeNode(t)) && r.specified ? r.value : null
}),
r
}(n);
i.find = y;
i.expr = y.selectors;
i.expr[":"] = i.expr.pseudos;
i.unique = y.uniqueSort;
i.text = y.getText;
i.isXMLDoc = y.isXML;
i.contains = y.contains;
var di = i.expr.match.needsContext
, gi = /^<(\w+)\s*\/?>(?:<\/\1>|)$/
, ef = /^.[^:#\[\.,]*$/;
i.filter = function(n, t, r) {
var u = t[0];
return r && (n = ":not(" + n + ")"),
1 === t.length && 1 === u.nodeType ? i.find.matchesSelector(u, n) ? [u] : [] : i.find.matches(n, i.grep(t, function(n) {
return 1 === n.nodeType
}))
}
;
i.fn.extend({
find: function(n) {
var t, u = this.length, r = [], f = this;
if ("string" != typeof n)
return this.pushStack(i(n).filter(function() {
for (t = 0; u > t; t++)
if (i.contains(f[t], this))
return !0
}));
for (t = 0; u > t; t++)
i.find(n, f[t], r);
return r = this.pushStack(u > 1 ? i.unique(r) : r),
r.selector = this.selector ? this.selector + " " + n : n,
r
},
filter: function(n) {
return this.pushStack(ui(this, n || [], !1))
},
not: function(n) {
return this.pushStack(ui(this, n || [], !0))
},
is: function(n) {
return !!ui(this, "string" == typeof n && di.test(n) ? i(n) : n || [], !1).length
}
});
nr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/;
tr = i.fn.init = function(n, t) {
var r, f;
if (!n)
return this;
if ("string" == typeof n) {
if (r = "<" === n[0] && ">" === n[n.length - 1] && n.length >= 3 ? [null, n, null] : nr.exec(n),
!r || !r[1] && t)
return !t || t.jquery ? (t || ot).find(n) : this.constructor(t).find(n);
if (r[1]) {
if (t = t instanceof i ? t[0] : t,
i.merge(this, i.parseHTML(r[1], t && t.nodeType ? t.ownerDocument || t : u, !0)),
gi.test(r[1]) && i.isPlainObject(t))
for (r in t)
i.isFunction(this[r]) ? this[r](t[r]) : this.attr(r, t[r]);
return this
}
return f = u.getElementById(r[2]),
f && f.parentNode && (this.length = 1,
this[0] = f),
this.context = u,
this.selector = n,
this
}
return n.nodeType ? (this.context = this[0] = n,
this.length = 1,
this) : i.isFunction(n) ? "undefined" != typeof ot.ready ? ot.ready(n) : n(i) : (void 0 !== n.selector && (this.selector = n.selector,
this.context = n.context),
i.makeArray(n, this))
}
;
tr.prototype = i.fn;
ot = i(u);
ir = /^(?:parents|prev(?:Until|All))/;
rr = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
i.extend({
dir: function(n, t, r) {
for (var u = [], f = void 0 !== r; (n = n[t]) && 9 !== n.nodeType; )
if (1 === n.nodeType) {
if (f && i(n).is(r))
break;
u.push(n)
}
return u
},
sibling: function(n, t) {
for (var i = []; n; n = n.nextSibling)
1 === n.nodeType && n !== t && i.push(n);
return i
}
});
i.fn.extend({
has: function(n) {
var t = i(n, this)
, r = t.length;
return this.filter(function() {
for (var n = 0; r > n; n++)
if (i.contains(this, t[n]))
return !0
})
},
closest: function(n, t) {
for (var r, f = 0, o = this.length, u = [], e = di.test(n) || "string" != typeof n ? i(n, t || this.context) : 0; o > f; f++)
for (r = this[f]; r && r !== t; r = r.parentNode)
if (r.nodeType < 11 && (e ? e.index(r) > -1 : 1 === r.nodeType && i.find.matchesSelector(r, n))) {
u.push(r);
break
}
return this.pushStack(u.length > 1 ? i.unique(u) : u)
},
index: function(n) {
return n ? "string" == typeof n ? ft.call(i(n), this[0]) : ft.call(this, n.jquery ? n[0] : n) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1
},
add: function(n, t) {
return this.pushStack(i.unique(i.merge(this.get(), i(n, t))))
},
addBack: function(n) {
return this.add(null == n ? this.prevObject : this.prevObject.filter(n))
}
});
i.each({
parent: function(n) {
var t = n.parentNode;
return t && 11 !== t.nodeType ? t : null
},
parents: function(n) {
return i.dir(n, "parentNode")
},
parentsUntil: function(n, t, r) {
return i.dir(n, "parentNode", r)
},
next: function(n) {
return ur(n, "nextSibling")
},
prev: function(n) {
return ur(n, "previousSibling")
},
nextAll: function(n) {
return i.dir(n, "nextSibling")
},
prevAll: function(n) {
return i.dir(n, "previousSibling")
},
nextUntil: function(n, t, r) {
return i.dir(n, "nextSibling", r)
},
prevUntil: function(n, t, r) {
return i.dir(n, "previousSibling", r)
},
siblings: function(n) {
return i.sibling((n.parentNode || {}).firstChild, n)
},
children: function(n) {
return i.sibling(n.firstChild)
},
contents: function(n) {
return n.contentDocument || i.merge([], n.childNodes)
}
}, function(n, t) {
i.fn[n] = function(r, u) {
var f = i.map(this, t, r);
return "Until" !== n.slice(-5) && (u = r),
u && "string" == typeof u && (f = i.filter(u, f)),
this.length > 1 && (rr[n] || i.unique(f),
ir.test(n) && f.reverse()),
this.pushStack(f)
}
});
c = /\S+/g;
fi = {};
i.Callbacks = function(n) {
n = "string" == typeof n ? fi[n] || of(n) : i.extend({}, n);
var u, h, o, c, f, e, t = [], r = !n.once && [], l = function(i) {
for (u = n.memory && i,
h = !0,
e = c || 0,
c = 0,
f = t.length,
o = !0; t && f > e; e++)
if (t[e].apply(i[0], i[1]) === !1 && n.stopOnFalse) {
u = !1;
break
}
o = !1;
t && (r ? r.length && l(r.shift()) : u ? t = [] : s.disable())
}, s = {
add: function() {
if (t) {
var r = t.length;
!function e(r) {
i.each(r, function(r, u) {
var f = i.type(u);
"function" === f ? n.unique && s.has(u) || t.push(u) : u && u.length && "string" !== f && e(u)
})
}(arguments);
o ? f = t.length : u && (c = r,
l(u))
}
return this
},
remove: function() {
return t && i.each(arguments, function(n, r) {
for (var u; (u = i.inArray(r, t, u)) > -1; )
t.splice(u, 1),
o && (f >= u && f--,
e >= u && e--)
}),
this
},
has: function(n) {
return n ? i.inArray(n, t) > -1 : !(!t || !t.length)
},
empty: function() {
return t = [],
f = 0,
this
},
disable: function() {
return t = r = u = void 0,
this
},
disabled: function() {
return !t
},
lock: function() {
return r = void 0,
u || s.disable(),
this
},
locked: function() {
return !r
},
fireWith: function(n, i) {
return !t || h && !r || (i = i || [],
i = [n, i.slice ? i.slice() : i],
o ? r.push(i) : l(i)),
this
},
fire: function() {
return s.fireWith(this, arguments),
this
},
fired: function() {
return !!h
}
};
return s
}
;
i.extend({
Deferred: function(n) {
var u = [["resolve", "done", i.Callbacks("once memory"), "resolved"], ["reject", "fail", i.Callbacks("once memory"), "rejected"], ["notify", "progress", i.Callbacks("memory")]]
, f = "pending"
, r = {
state: function() {
return f
},
always: function() {
return t.done(arguments).fail(arguments),
this
},
then: function() {
var n = arguments;
return i.Deferred(function(f) {
i.each(u, function(u, e) {
var o = i.isFunction(n[u]) && n[u];
t[e[1]](function() {
var n = o && o.apply(this, arguments);
n && i.isFunction(n.promise) ? n.promise().done(f.resolve).fail(f.reject).progress(f.notify) : f[e[0] + "With"](this === r ? f.promise() : this, o ? [n] : arguments)
})
});
n = null
}).promise()
},
promise: function(n) {
return null != n ? i.extend(n, r) : r
}
}
, t = {};
return r.pipe = r.then,
i.each(u, function(n, i) {
var e = i[2]
, o = i[3];
r[i[1]] = e.add;
o && e.add(function() {
f = o
}, u[1 ^ n][2].disable, u[2][2].lock);
t[i[0]] = function() {
return t[i[0] + "With"](this === t ? r : this, arguments),
this
}
;
t[i[0] + "With"] = e.fireWith
}),
r.promise(t),
n && n.call(t, t),
t
},
when: function(n) {
var t = 0, u = a.call(arguments), r = u.length, e = 1 !== r || n && i.isFunction(n.promise) ? r : 0, f = 1 === e ? n : i.Deferred(), h = function(n, t, i) {
return function(r) {
t[n] = this;
i[n] = arguments.length > 1 ? a.call(arguments) : r;
i === o ? f.notifyWith(t, i) : --e || f.resolveWith(t, i)
}
}, o, c, s;
if (r > 1)
for (o = new Array(r),
c = new Array(r),
s = new Array(r); r > t; t++)
u[t] && i.isFunction(u[t].promise) ? u[t].promise().done(h(t, s, u)).fail(f.reject).progress(h(t, c, o)) : --e;
return e || f.resolveWith(s, u),
f.promise()
}
});
i.fn.ready = function(n) {
return i.ready.promise().done(n),
this
}
;
i.extend({
isReady: !1,
readyWait: 1,
holdReady: function(n) {
n ? i.readyWait++ : i.ready(!0)
},
ready: function(n) {
(n === !0 ? --i.readyWait : i.isReady) || (i.isReady = !0,
n !== !0 && --i.readyWait > 0 || (st.resolveWith(u, [i]),
i.fn.triggerHandler && (i(u).triggerHandler("ready"),
i(u).off("ready"))))
}
});
i.ready.promise = function(t) {
return st || (st = i.Deferred(),
"complete" === u.readyState ? setTimeout(i.ready) : (u.addEventListener("DOMContentLoaded", ht, !1),
n.addEventListener("load", ht, !1))),
st.promise(t)
}
;
i.ready.promise();
l = i.access = function(n, t, r, u, f, e, o) {
var s = 0
, c = n.length
, h = null == r;
if ("object" === i.type(r)) {
f = !0;
for (s in r)
i.access(n, t, s, r[s], !0, e, o)
} else if (void 0 !== u && (f = !0,
i.isFunction(u) || (o = !0),
h && (o ? (t.call(n, u),
t = null) : (h = t,
t = function(n, t, r) {
return h.call(i(n), r)
}
)),
t))
for (; c > s; s++)
t(n[s], r, o ? u : u.call(n[s], s, t(n[s], r)));
return f ? n : h ? t.call(n) : c ? t(n[0], r) : e
}
;
i.acceptData = function(n) {
return 1 === n.nodeType || 9 === n.nodeType || !+n.nodeType
}
;
v.uid = 1;
v.accepts = i.acceptData;
v.prototype = {
key: function(n) {
if (!v.accepts(n))
return 0;
var r = {}
, t = n[this.expando];
if (!t) {
t = v.uid++;
try {
r[this.expando] = {
value: t
};
Object.defineProperties(n, r)
} catch (u) {
r[this.expando] = t;
i.extend(n, r)
}
}
return this.cache[t] || (this.cache[t] = {}),
t
},
set: function(n, t, r) {
var f, e = this.key(n), u = this.cache[e];
if ("string" == typeof t)
u[t] = r;
else if (i.isEmptyObject(u))
i.extend(this.cache[e], t);
else
for (f in t)
u[f] = t[f];
return u
},
get: function(n, t) {
var i = this.cache[this.key(n)];
return void 0 === t ? i : i[t]
},
access: function(n, t, r) {
var u;
return void 0 === t || t && "string" == typeof t && void 0 === r ? (u = this.get(n, t),
void 0 !== u ? u : this.get(n, i.camelCase(t))) : (this.set(n, t, r),
void 0 !== r ? r : t)
},
remove: function(n, t) {
var u, r, f, o = this.key(n), e = this.cache[o];
if (void 0 === t)
this.cache[o] = {};
else
for (i.isArray(t) ? r = t.concat(t.map(i.camelCase)) : (f = i.camelCase(t),
(t in e) ? r = [t, f] : (r = f,
r = (r in e) ? [r] : r.match(c) || [])),
u = r.length; u--; )
delete e[r[u]]
},
hasData: function(n) {
return !i.isEmptyObject(this.cache[n[this.expando]] || {})
},
discard: function(n) {
n[this.expando] && delete this.cache[n[this.expando]]
}
};
var r = new v
, e = new v
, sf = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/
, hf = /([A-Z])/g;
i.extend({
hasData: function(n) {
return e.hasData(n) || r.hasData(n)
},
data: function(n, t, i) {
return e.access(n, t, i)
},
removeData: function(n, t) {
e.remove(n, t)
},
_data: function(n, t, i) {
return r.access(n, t, i)
},
_removeData: function(n, t) {
r.remove(n, t)
}
});
i.fn.extend({
data: function(n, t) {
var o, f, s, u = this[0], h = u && u.attributes;
if (void 0 === n) {
if (this.length && (s = e.get(u),
1 === u.nodeType && !r.get(u, "hasDataAttrs"))) {
for (o = h.length; o--; )
h[o] && (f = h[o].name,
0 === f.indexOf("data-") && (f = i.camelCase(f.slice(5)),
fr(u, f, s[f])));
r.set(u, "hasDataAttrs", !0)
}
return s
}
return "object" == typeof n ? this.each(function() {
e.set(this, n)
}) : l(this, function(t) {
var r, f = i.camelCase(n);
if (u && void 0 === t) {
if ((r = e.get(u, n),
void 0 !== r) || (r = e.get(u, f),
void 0 !== r) || (r = fr(u, f, void 0),
void 0 !== r))
return r
} else
this.each(function() {
var i = e.get(this, f);
e.set(this, f, t);
-1 !== n.indexOf("-") && void 0 !== i && e.set(this, n, t)
})
}, null, t, arguments.length > 1, null, !0)
},
removeData: function(n) {
return this.each(function() {
e.remove(this, n)
})
}
});
i.extend({
queue: function(n, t, u) {
var f;
if (n)
return (t = (t || "fx") + "queue",
f = r.get(n, t),
u && (!f || i.isArray(u) ? f = r.access(n, t, i.makeArray(u)) : f.push(u)),
f || [])
},
dequeue: function(n, t) {
t = t || "fx";
var r = i.queue(n, t)
, e = r.length
, u = r.shift()
, f = i._queueHooks(n, t)
, o = function() {
i.dequeue(n, t)
};
"inprogress" === u && (u = r.shift(),
e--);
u && ("fx" === t && r.unshift("inprogress"),
delete f.stop,
u.call(n, o, f));
!e && f && f.empty.fire()
},
_queueHooks: function(n, t) {
var u = t + "queueHooks";
return r.get(n, u) || r.access(n, u, {
empty: i.Callbacks("once memory").add(function() {
r.remove(n, [t + "queue", u])
})
})
}
});
i.fn.extend({
queue: function(n, t) {
var r = 2;
return "string" != typeof n && (t = n,
n = "fx",
r--),
arguments.length < r ? i.queue(this[0], n) : void 0 === t ? this : this.each(function() {
var r = i.queue(this, n, t);
i._queueHooks(this, n);
"fx" === n && "inprogress" !== r[0] && i.dequeue(this, n)
})
},
dequeue: function(n) {
return this.each(function() {
i.dequeue(this, n)
})
},
clearQueue: function(n) {
return this.queue(n || "fx", [])
},
promise: function(n, t) {
var u, e = 1, o = i.Deferred(), f = this, s = this.length, h = function() {
--e || o.resolveWith(f, [f])
};
for ("string" != typeof n && (t = n,
n = void 0),
n = n || "fx"; s--; )
u = r.get(f[s], n + "queueHooks"),
u && u.empty && (e++,
u.empty.add(h));
return h(),
o.promise(t)
}
});
var ct = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source
, p = ["Top", "Right", "Bottom", "Left"]
, tt = function(n, t) {
return n = t || n,
"none" === i.css(n, "display") || !i.contains(n.ownerDocument, n)
}
, er = /^(?:checkbox|radio)$/i;
!function() {
var i = u.createDocumentFragment()
, n = i.appendChild(u.createElement("div"))
, t = u.createElement("input");
t.setAttribute("type", "radio");
t.setAttribute("checked", "checked");
t.setAttribute("name", "t");
n.appendChild(t);
f.checkClone = n.cloneNode(!0).cloneNode(!0).lastChild.checked;
n.innerHTML = "<textarea>x<\/textarea>";
f.noCloneChecked = !!n.cloneNode(!0).lastChild.defaultValue
}();
b = "undefined";
f.focusinBubbles = "onfocusin"in n;
var cf = /^key/
, lf = /^(?:mouse|pointer|contextmenu)|click/
, or = /^(?:focusinfocus|focusoutblur)$/
, sr = /^([^.]*)(?:\.(.+)|)$/;
i.event = {
global: {},
add: function(n, t, u, f, e) {
var v, y, w, p, k, h, s, l, o, d, g, a = r.get(n);
if (a)
for (u.handler && (v = u,
u = v.handler,
e = v.selector),
u.guid || (u.guid = i.guid++),
(p = a.events) || (p = a.events = {}),
(y = a.handle) || (y = a.handle = function(t) {
if (typeof i !== b && i.event.triggered !== t.type)
return i.event.dispatch.apply(n, arguments)
}
),
t = (t || "").match(c) || [""],
k = t.length; k--; )
w = sr.exec(t[k]) || [],
o = g = w[1],
d = (w[2] || "").split(".").sort(),
o && (s = i.event.special[o] || {},
o = (e ? s.delegateType : s.bindType) || o,
s = i.event.special[o] || {},
h = i.extend({
type: o,
origType: g,
data: f,
handler: u,
guid: u.guid,
selector: e,
needsContext: e && i.expr.match.needsContext.test(e),
namespace: d.join(".")
}, v),
(l = p[o]) || (l = p[o] = [],
l.delegateCount = 0,
s.setup && s.setup.call(n, f, d, y) !== !1 || n.addEventListener && n.addEventListener(o, y, !1)),
s.add && (s.add.call(n, h),
h.handler.guid || (h.handler.guid = u.guid)),
e ? l.splice(l.delegateCount++, 0, h) : l.push(h),
i.event.global[o] = !0)
},
remove: function(n, t, u, f, e) {
var p, k, h, v, w, s, l, a, o, b, d, y = r.hasData(n) && r.get(n);
if (y && (v = y.events)) {
for (t = (t || "").match(c) || [""],
w = t.length; w--; )
if (h = sr.exec(t[w]) || [],
o = d = h[1],
b = (h[2] || "").split(".").sort(),
o) {
for (l = i.event.special[o] || {},
o = (f ? l.delegateType : l.bindType) || o,
a = v[o] || [],
h = h[2] && new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)"),
k = p = a.length; p--; )
s = a[p],
!e && d !== s.origType || u && u.guid !== s.guid || h && !h.test(s.namespace) || f && f !== s.selector && ("**" !== f || !s.selector) || (a.splice(p, 1),
s.selector && a.delegateCount--,
l.remove && l.remove.call(n, s));
k && !a.length && (l.teardown && l.teardown.call(n, b, y.handle) !== !1 || i.removeEvent(n, o, y.handle),
delete v[o])
} else
for (o in v)
i.event.remove(n, o + t[w], u, f, !0);
i.isEmptyObject(v) && (delete y.handle,
r.remove(n, "events"))
}
},
trigger: function(t, f, e, o) {
var w, s, c, b, a, v, l, p = [e || u], h = ii.call(t, "type") ? t.type : t, y = ii.call(t, "namespace") ? t.namespace.split(".") : [];
if (s = c = e = e || u,
3 !== e.nodeType && 8 !== e.nodeType && !or.test(h + i.event.triggered) && (h.indexOf(".") >= 0 && (y = h.split("."),
h = y.shift(),
y.sort()),
a = h.indexOf(":") < 0 && "on" + h,
t = t[i.expando] ? t : new i.Event(h,"object" == typeof t && t),
t.isTrigger = o ? 2 : 3,
t.namespace = y.join("."),
t.namespace_re = t.namespace ? new RegExp("(^|\\.)" + y.join("\\.(?:.*\\.|)") + "(\\.|$)") : null,
t.result = void 0,
t.target || (t.target = e),
f = null == f ? [t] : i.makeArray(f, [t]),
l = i.event.special[h] || {},
o || !l.trigger || l.trigger.apply(e, f) !== !1)) {
if (!o && !l.noBubble && !i.isWindow(e)) {
for (b = l.delegateType || h,
or.test(b + h) || (s = s.parentNode); s; s = s.parentNode)
p.push(s),
c = s;
c === (e.ownerDocument || u) && p.push(c.defaultView || c.parentWindow || n)
}
for (w = 0; (s = p[w++]) && !t.isPropagationStopped(); )
t.type = w > 1 ? b : l.bindType || h,
v = (r.get(s, "events") || {})[t.type] && r.get(s, "handle"),
v && v.apply(s, f),
v = a && s[a],
v && v.apply && i.acceptData(s) && (t.result = v.apply(s, f),
t.result === !1 && t.preventDefault());
return t.type = h,
o || t.isDefaultPrevented() || l._default && l._default.apply(p.pop(), f) !== !1 || !i.acceptData(e) || a && i.isFunction(e[h]) && !i.isWindow(e) && (c = e[a],
c && (e[a] = null),
i.event.triggered = h,
e[h](),
i.event.triggered = void 0,
c && (e[a] = c)),
t.result
}
},
dispatch: function(n) {
n = i.event.fix(n);
var o, s, e, u, t, h = [], c = a.call(arguments), l = (r.get(this, "events") || {})[n.type] || [], f = i.event.special[n.type] || {};
if (c[0] = n,
n.delegateTarget = this,
!f.preDispatch || f.preDispatch.call(this, n) !== !1) {
for (h = i.event.handlers.call(this, n, l),
o = 0; (u = h[o++]) && !n.isPropagationStopped(); )
for (n.currentTarget = u.elem,
s = 0; (t = u.handlers[s++]) && !n.isImmediatePropagationStopped(); )
(!n.namespace_re || n.namespace_re.test(t.namespace)) && (n.handleObj = t,
n.data = t.data,
e = ((i.event.special[t.origType] || {}).handle || t.handler).apply(u.elem, c),
void 0 !== e && (n.result = e) === !1 && (n.preventDefault(),
n.stopPropagation()));
return f.postDispatch && f.postDispatch.call(this, n),
n.result
}
},
handlers: function(n, t) {
var e, u, f, o, h = [], s = t.delegateCount, r = n.target;
if (s && r.nodeType && (!n.button || "click" !== n.type))
for (; r !== this; r = r.parentNode || this)
if (r.disabled !== !0 || "click" !== n.type) {
for (u = [],
e = 0; s > e; e++)
o = t[e],
f = o.selector + " ",
void 0 === u[f] && (u[f] = o.needsContext ? i(f, this).index(r) >= 0 : i.find(f, this, null, [r]).length),
u[f] && u.push(o);
u.length && h.push({
elem: r,
handlers: u
})
}
return s < t.length && h.push({
elem: this,
handlers: t.slice(s)
}),
h
},
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(n, t) {
return null == n.which && (n.which = null != t.charCode ? t.charCode : t.keyCode),
n
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function(n, t) {
var e, i, r, f = t.button;
return null == n.pageX && null != t.clientX && (e = n.target.ownerDocument || u,
i = e.documentElement,
r = e.body,
n.pageX = t.clientX + (i && i.scrollLeft || r && r.scrollLeft || 0) - (i && i.clientLeft || r && r.clientLeft || 0),
n.pageY = t.clientY + (i && i.scrollTop || r && r.scrollTop || 0) - (i && i.clientTop || r && r.clientTop || 0)),
n.which || void 0 === f || (n.which = 1 & f ? 1 : 2 & f ? 3 : 4 & f ? 2 : 0),
n
}
},
fix: function(n) {
if (n[i.expando])
return n;
var f, e, o, r = n.type, s = n, t = this.fixHooks[r];
for (t || (this.fixHooks[r] = t = lf.test(r) ? this.mouseHooks : cf.test(r) ? this.keyHooks : {}),
o = t.props ? this.props.concat(t.props) : this.props,
n = new i.Event(s),
f = o.length; f--; )
e = o[f],
n[e] = s[e];
return n.target || (n.target = u),
3 === n.target.nodeType && (n.target = n.target.parentNode),
t.filter ? t.filter(n, s) : n
},
special: {
load: {
noBubble: !0
},
focus: {
trigger: function() {
if (this !== hr() && this.focus)
return (this.focus(),
!1)
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if (this === hr() && this.blur)
return (this.blur(),
!1)
},
delegateType: "focusout"
},
click: {
trigger: function() {
if ("checkbox" === this.type && this.click && i.nodeName(this, "input"))
return (this.click(),
!1)
},
_default: function(n) {
return i.nodeName(n.target, "a")
}
},
beforeunload: {
postDispatch: function(n) {
void 0 !== n.result && n.originalEvent && (n.originalEvent.returnValue = n.result)
}
}
},
simulate: function(n, t, r, u) {
var f = i.extend(new i.Event, r, {
type: n,
isSimulated: !0,
originalEvent: {}
});
u ? i.event.trigger(f, null, t) : i.event.dispatch.call(t, f);
f.isDefaultPrevented() && r.preventDefault()
}
};
i.removeEvent = function(n, t, i) {
n.removeEventListener && n.removeEventListener(t, i, !1)
}
;
i.Event = function(n, t) {
return this instanceof i.Event ? (n && n.type ? (this.originalEvent = n,
this.type = n.type,
this.isDefaultPrevented = n.defaultPrevented || void 0 === n.defaultPrevented && n.returnValue === !1 ? lt : k) : this.type = n,
t && i.extend(this, t),
this.timeStamp = n && n.timeStamp || i.now(),
void (this[i.expando] = !0)) : new i.Event(n,t)
}
;
i.Event.prototype = {
isDefaultPrevented: k,
isPropagationStopped: k,
isImmediatePropagationStopped: k,
preventDefault: function() {
var n = this.originalEvent;
this.isDefaultPrevented = lt;
n && n.preventDefault && n.preventDefault()
},
stopPropagation: function() {
var n = this.originalEvent;
this.isPropagationStopped = lt;
n && n.stopPropagation && n.stopPropagation()
},
stopImmediatePropagation: function() {
var n = this.originalEvent;
this.isImmediatePropagationStopped = lt;
n && n.stopImmediatePropagation && n.stopImmediatePropagation();
this.stopPropagation()
}
};
i.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function(n, t) {
i.event.special[n] = {
delegateType: t,
bindType: t,
handle: function(n) {
var u, f = this, r = n.relatedTarget, e = n.handleObj;
return (!r || r !== f && !i.contains(f, r)) && (n.type = e.origType,
u = e.handler.apply(this, arguments),
n.type = t),
u
}
}
});
f.focusinBubbles || i.each({
focus: "focusin",
blur: "focusout"
}, function(n, t) {
var u = function(n) {
i.event.simulate(t, n.target, i.event.fix(n), !0)
};
i.event.special[t] = {
setup: function() {
var i = this.ownerDocument || this
, f = r.access(i, t);
f || i.addEventListener(n, u, !0);
r.access(i, t, (f || 0) + 1)
},
teardown: function() {
var i = this.ownerDocument || this
, f = r.access(i, t) - 1;
f ? r.access(i, t, f) : (i.removeEventListener(n, u, !0),
r.remove(i, t))
}
}
});
i.fn.extend({
on: function(n, t, r, u, f) {
var e, o;
if ("object" == typeof n) {
"string" != typeof t && (r = r || t,
t = void 0);
for (o in n)
this.on(o, t, r, n[o], f);
return this
}
if (null == r && null == u ? (u = t,
r = t = void 0) : null == u && ("string" == typeof t ? (u = r,
r = void 0) : (u = r,
r = t,
t = void 0)),
u === !1)
u = k;
else if (!u)
return this;
return 1 === f && (e = u,
u = function(n) {
return i().off(n),
e.apply(this, arguments)
}
,
u.guid = e.guid || (e.guid = i.guid++)),
this.each(function() {
i.event.add(this, n, u, r, t)
})
},
one: function(n, t, i, r) {
return this.on(n, t, i, r, 1)
},
off: function(n, t, r) {
var u, f;
if (n && n.preventDefault && n.handleObj)
return u = n.handleObj,
i(n.delegateTarget).off(u.namespace ? u.origType + "." + u.namespace : u.origType, u.selector, u.handler),
this;
if ("object" == typeof n) {
for (f in n)
this.off(f, t, n[f]);
return this
}
return (t === !1 || "function" == typeof t) && (r = t,
t = void 0),
r === !1 && (r = k),
this.each(function() {
i.event.remove(this, n, r, t)
})
},
trigger: function(n, t) {
return this.each(function() {
i.event.trigger(n, t, this)
})
},
triggerHandler: function(n, t) {
var r = this[0];
if (r)
return i.event.trigger(n, t, r, !0)
}
});
var cr = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi
, lr = /<([\w:]+)/
, af = /<|&#?\w+;/
, vf = /<(?:script|style|link)/i
, yf = /checked\s*(?:[^=]|=\s*.checked.)/i
, ar = /^$|\/(?:java|ecma)script/i
, pf = /^true\/(.*)/
, wf = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g
, h = {
option: [1, "<select multiple='multiple'>", "<\/select>"],
thead: [1, "<table>", "<\/table>"],
col: [2, "<table><colgroup>", "<\/colgroup><\/table>"],
tr: [2, "<table><tbody>", "<\/tbody><\/table>"],
td: [3, "<table><tbody><tr>", "<\/tr><\/tbody><\/table>"],
_default: [0, "", ""]
};
h.optgroup = h.option;
h.tbody = h.tfoot = h.colgroup = h.caption = h.thead;
h.th = h.td;
i.extend({
clone: function(n, t, r) {
var u, c, s, e, h = n.cloneNode(!0), l = i.contains(n.ownerDocument, n);
if (!(f.noCloneChecked || 1 !== n.nodeType && 11 !== n.nodeType || i.isXMLDoc(n)))
for (e = o(h),
s = o(n),
u = 0,
c = s.length; c > u; u++)
df(s[u], e[u]);
if (t)
if (r)
for (s = s || o(n),
e = e || o(h),
u = 0,
c = s.length; c > u; u++)
yr(s[u], e[u]);
else
yr(n, h);
return e = o(h, "script"),
e.length > 0 && ei(e, !l && o(n, "script")),
h
},
buildFragment: function(n, t, r, u) {
for (var f, e, y, l, p, a, s = t.createDocumentFragment(), v = [], c = 0, w = n.length; w > c; c++)
if (f = n[c],
f || 0 === f)
if ("object" === i.type(f))
i.merge(v, f.nodeType ? [f] : f);
else if (af.test(f)) {
for (e = e || s.appendChild(t.createElement("div")),
y = (lr.exec(f) || ["", ""])[1].toLowerCase(),
l = h[y] || h._default,
e.innerHTML = l[1] + f.replace(cr, "<$1><\/$2>") + l[2],
a = l[0]; a--; )
e = e.lastChild;
i.merge(v, e.childNodes);
e = s.firstChild;
e.textContent = ""
} else
v.push(t.createTextNode(f));
for (s.textContent = "",
c = 0; f = v[c++]; )
if ((!u || -1 === i.inArray(f, u)) && (p = i.contains(f.ownerDocument, f),
e = o(s.appendChild(f), "script"),
p && ei(e),
r))
for (a = 0; f = e[a++]; )
ar.test(f.type || "") && r.push(f);
return s
},
cleanData: function(n) {
for (var f, t, o, u, h = i.event.special, s = 0; void 0 !== (t = n[s]); s++) {
if (i.acceptData(t) && (u = t[r.expando],
u && (f = r.cache[u]))) {
if (f.events)
for (o in f.events)
h[o] ? i.event.remove(t, o) : i.removeEvent(t, o, f.handle);
r.cache[u] && delete r.cache[u]
}
delete e.cache[t[e.expando]]
}
}
});
i.fn.extend({
text: function(n) {
return l(this, function(n) {
return void 0 === n ? i.text(this) : this.empty().each(function() {
(1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) && (this.textContent = n)
})
}, null, n, arguments.length)
},
append: function() {
return this.domManip(arguments, function(n) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = vr(this, n);
t.appendChild(n)
}
})
},
prepend: function() {
return this.domManip(arguments, function(n) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = vr(this, n);
t.insertBefore(n, t.firstChild)
}
})
},
before: function() {
return this.domManip(arguments, function(n) {
this.parentNode && this.parentNode.insertBefore(n, this)
})
},
after: function() {
return this.domManip(arguments, function(n) {
this.parentNode && this.parentNode.insertBefore(n, this.nextSibling)
})
},
remove: function(n, t) {
for (var r, f = n ? i.filter(n, this) : this, u = 0; null != (r = f[u]); u++)
t || 1 !== r.nodeType || i.cleanData(o(r)),
r.parentNode && (t && i.contains(r.ownerDocument, r) && ei(o(r, "script")),
r.parentNode.removeChild(r));
return this
},
empty: function() {
for (var n, t = 0; null != (n = this[t]); t++)
1 === n.nodeType && (i.cleanData(o(n, !1)),
n.textContent = "");
return this
},
clone: function(n, t) {
return n = null == n ? !1 : n,
t = null == t ? n : t,
this.map(function() {
return i.clone(this, n, t)
})
},
html: function(n) {
return l(this, function(n) {
var t = this[0] || {}
, r = 0
, u = this.length;
if (void 0 === n && 1 === t.nodeType)
return t.innerHTML;
if ("string" == typeof n && !vf.test(n) && !h[(lr.exec(n) || ["", ""])[1].toLowerCase()]) {
n = n.replace(cr, "<$1><\/$2>");
try {
for (; u > r; r++)
t = this[r] || {},
1 === t.nodeType && (i.cleanData(o(t, !1)),
t.innerHTML = n);
t = 0
} catch (f) {}
}
t && this.empty().append(n)
}, null, n, arguments.length)
},
replaceWith: function() {
var n = arguments[0];
return this.domManip(arguments, function(t) {
n = this.parentNode;
i.cleanData(o(this));
n && n.replaceChild(t, this)
}),
n && (n.length || n.nodeType) ? this : this.remove()
},
detach: function(n) {
return this.remove(n, !0)
},
domManip: function(n, t) {
n = bi.apply([], n);
var h, v, s, c, u, y, e = 0, l = this.length, w = this, b = l - 1, a = n[0], p = i.isFunction(a);
if (p || l > 1 && "string" == typeof a && !f.checkClone && yf.test(a))
return this.each(function(i) {
var r = w.eq(i);
p && (n[0] = a.call(this, i, r.html()));
r.domManip(n, t)
});
if (l && (h = i.buildFragment(n, this[0].ownerDocument, !1, this),
v = h.firstChild,
1 === h.childNodes.length && (h = v),
v)) {
for (s = i.map(o(h, "script"), bf),
c = s.length; l > e; e++)
u = h,
e !== b && (u = i.clone(u, !0, !0),
c && i.merge(s, o(u, "script"))),
t.call(this[e], u, e);
if (c)
for (y = s[s.length - 1].ownerDocument,
i.map(s, kf),
e = 0; c > e; e++)
u = s[e],
ar.test(u.type || "") && !r.access(u, "globalEval") && i.contains(y, u) && (u.src ? i._evalUrl && i._evalUrl(u.src) : i.globalEval(u.textContent.replace(wf, "")))
}
return this
}
});
i.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(n, t) {
i.fn[n] = function(n) {
for (var u, f = [], e = i(n), o = e.length - 1, r = 0; o >= r; r++)
u = r === o ? this : this.clone(!0),
i(e[r])[t](u),
ti.apply(f, u.get());
return this.pushStack(f)
}
});
oi = {};
var wr = /^margin/
, hi = new RegExp("^(" + ct + ")(?!px)[a-z%]+$","i")
, vt = function(t) {
return t.ownerDocument.defaultView.opener ? t.ownerDocument.defaultView.getComputedStyle(t, null) : n.getComputedStyle(t, null)
};
!function() {
var s, o, e = u.documentElement, r = u.createElement("div"), t = u.createElement("div");
if (t.style) {
t.style.backgroundClip = "content-box";
t.cloneNode(!0).style.backgroundClip = "";
f.clearCloneStyle = "content-box" === t.style.backgroundClip;
r.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute";
r.appendChild(t);
function h() {
t.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";
t.innerHTML = "";
e.appendChild(r);
var i = n.getComputedStyle(t, null);
s = "1%" !== i.top;
o = "4px" === i.width;
e.removeChild(r)
}
n.getComputedStyle && i.extend(f, {
pixelPosition: function() {
return h(),
s
},
boxSizingReliable: function() {
return null == o && h(),
o
},
reliableMarginRight: function() {
var f, i = t.appendChild(u.createElement("div"));
return i.style.cssText = t.style.cssText = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",
i.style.marginRight = i.style.width = "0",
t.style.width = "1px",
e.appendChild(r),
f = !parseFloat(n.getComputedStyle(i, null).marginRight),
e.removeChild(r),
t.removeChild(i),
f
}
})
}
}();
i.swap = function(n, t, i, r) {
var f, u, e = {};
for (u in t)
e[u] = n.style[u],
n.style[u] = t[u];
f = i.apply(n, r || []);
for (u in t)
n.style[u] = e[u];
return f
}
;
var gf = /^(none|table(?!-c[ea]).+)/
, ne = new RegExp("^(" + ct + ")(.*)$","i")
, te = new RegExp("^([+-])=(" + ct + ")","i")
, ie = {
position: "absolute",
visibility: "hidden",
display: "block"
}
, kr = {
letterSpacing: "0",
fontWeight: "400"
}
, dr = ["Webkit", "O", "Moz", "ms"];
i.extend({
cssHooks: {
opacity: {
get: function(n, t) {
if (t) {
var i = it(n, "opacity");
return "" === i ? "1" : i
}
}
}
},
cssNumber: {
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: "cssFloat"
},
style: function(n, t, r, u) {
if (n && 3 !== n.nodeType && 8 !== n.nodeType && n.style) {
var o, h, e, s = i.camelCase(t), c = n.style;
return t = i.cssProps[s] || (i.cssProps[s] = gr(c, s)),
e = i.cssHooks[t] || i.cssHooks[s],
void 0 === r ? e && "get"in e && void 0 !== (o = e.get(n, !1, u)) ? o : c[t] : (h = typeof r,
"string" === h && (o = te.exec(r)) && (r = (o[1] + 1) * o[2] + parseFloat(i.css(n, t)),
h = "number"),
null != r && r === r && ("number" !== h || i.cssNumber[s] || (r += "px"),
f.clearCloneStyle || "" !== r || 0 !== t.indexOf("background") || (c[t] = "inherit"),
e && "set"in e && void 0 === (r = e.set(n, r, u)) || (c[t] = r)),
void 0)
}
},
css: function(n, t, r, u) {
var f, s, e, o = i.camelCase(t);
return t = i.cssProps[o] || (i.cssProps[o] = gr(n.style, o)),
e = i.cssHooks[t] || i.cssHooks[o],
e && "get"in e && (f = e.get(n, !0, r)),
void 0 === f && (f = it(n, t, u)),
"normal" === f && t in kr && (f = kr[t]),
"" === r || r ? (s = parseFloat(f),
r === !0 || i.isNumeric(s) ? s || 0 : f) : f
}
});
i.each(["height", "width"], function(n, t) {
i.cssHooks[t] = {
get: function(n, r, u) {
if (r)
return gf.test(i.css(n, "display")) && 0 === n.offsetWidth ? i.swap(n, ie, function() {
return iu(n, t, u)
}) : iu(n, t, u)
},
set: function(n, r, u) {
var f = u && vt(n);
return nu(n, r, u ? tu(n, t, u, "border-box" === i.css(n, "boxSizing", !1, f), f) : 0)
}
}
});
i.cssHooks.marginRight = br(f.reliableMarginRight, function(n, t) {
if (t)
return i.swap(n, {
display: "inline-block"
}, it, [n, "marginRight"])
});
i.each({
margin: "",
padding: "",
border: "Width"
}, function(n, t) {
i.cssHooks[n + t] = {
expand: function(i) {
for (var r = 0, f = {}, u = "string" == typeof i ? i.split(" ") : [i]; 4 > r; r++)
f[n + p[r] + t] = u[r] || u[r - 2] || u[0];
return f
}
};
wr.test(n) || (i.cssHooks[n + t].set = nu)
});
i.fn.extend({
css: function(n, t) {
return l(this, function(n, t, r) {
var f, e, o = {}, u = 0;
if (i.isArray(t)) {
for (f = vt(n),
e = t.length; e > u; u++)
o[t[u]] = i.css(n, t[u], !1, f);
return o
}
return void 0 !== r ? i.style(n, t, r) : i.css(n, t)
}, n, t, arguments.length > 1)
},
show: function() {
return ru(this, !0)
},
hide: function() {
return ru(this)
},
toggle: function(n) {
return "boolean" == typeof n ? n ? this.show() : this.hide() : this.each(function() {
tt(this) ? i(this).show() : i(this).hide()
})
}
});
i.Tween = s;
s.prototype = {
constructor: s,
init: function(n, t, r, u, f, e) {
this.elem = n;
this.prop = r;
this.easing = f || "swing";
this.options = t;
this.start = this.now = this.cur();
this.end = u;
this.unit = e || (i.cssNumber[r] ? "" : "px")
},
cur: function() {
var n = s.propHooks[this.prop];
return n && n.get ? n.get(this) : s.propHooks._default.get(this)
},
run: function(n) {
var t, r = s.propHooks[this.prop];
return this.pos = this.options.duration ? t = i.easing[this.easing](n, this.options.duration * n, 0, 1, this.options.duration) : t = n,
this.now = (this.end - this.start) * t + this.start,
this.options.step && this.options.step.call(this.elem, this.now, this),
r && r.set ? r.set(this) : s.propHooks._default.set(this),
this
}
};
s.prototype.init.prototype = s.prototype;
s.propHooks = {
_default: {
get: function(n) {
var t;
return null == n.elem[n.prop] || n.elem.style && null != n.elem.style[n.prop] ? (t = i.css(n.elem, n.prop, ""),
t && "auto" !== t ? t : 0) : n.elem[n.prop]
},
set: function(n) {
i.fx.step[n.prop] ? i.fx.step[n.prop](n) : n.elem.style && (null != n.elem.style[i.cssProps[n.prop]] || i.cssHooks[n.prop]) ? i.style(n.elem, n.prop, n.now + n.unit) : n.elem[n.prop] = n.now
}
}
};
s.propHooks.scrollTop = s.propHooks.scrollLeft = {
set: function(n) {
n.elem.nodeType && n.elem.parentNode && (n.elem[n.prop] = n.now)
}
};
i.easing = {
linear: function(n) {
return n
},
swing: function(n) {
return .5 - Math.cos(n * Math.PI) / 2
}
};
i.fx = s.prototype.init;
i.fx.step = {};
var d, yt, re = /^(?:toggle|show|hide)$/, uu = new RegExp("^(?:([+-])=|)(" + ct + ")([a-z%]*)$","i"), ue = /queueHooks$/, pt = [fe], rt = {
"*": [function(n, t) {
var f = this.createTween(n, t)
, s = f.cur()
, r = uu.exec(t)
, e = r && r[3] || (i.cssNumber[n] ? "" : "px")
, u = (i.cssNumber[n] || "px" !== e && +s) && uu.exec(i.css(f.elem, n))
, o = 1
, h = 20;
if (u && u[3] !== e) {
e = e || u[3];
r = r || [];
u = +s || 1;
do
o = o || ".5",
u /= o,
i.style(f.elem, n, u + e);
while (o !== (o = f.cur() / s) && 1 !== o && --h)
}
return r && (u = f.start = +u || +s || 0,
f.unit = e,
f.end = r[1] ? u + (r[1] + 1) * r[2] : +r[2]),
f
}
]
};
i.Animation = i.extend(ou, {
tweener: function(n, t) {
i.isFunction(n) ? (t = n,
n = ["*"]) : n = n.split(" ");
for (var r, u = 0, f = n.length; f > u; u++)
r = n[u],
rt[r] = rt[r] || [],
rt[r].unshift(t)
},
prefilter: function(n, t) {
t ? pt.unshift(n) : pt.push(n)
}
});
i.speed = function(n, t, r) {
var u = n && "object" == typeof n ? i.extend({}, n) : {
complete: r || !r && t || i.isFunction(n) && n,
duration: n,
easing: r && t || t && !i.isFunction(t) && t
};
return u.duration = i.fx.off ? 0 : "number" == typeof u.duration ? u.duration : u.duration in i.fx.speeds ? i.fx.speeds[u.duration] : i.fx.speeds._default,
(null == u.queue || u.queue === !0) && (u.queue = "fx"),
u.old = u.complete,
u.complete = function() {
i.isFunction(u.old) && u.old.call(this);
u.queue && i.dequeue(this, u.queue)
}
,
u
}
;
i.fn.extend({
fadeTo: function(n, t, i, r) {
return this.filter(tt).css("opacity", 0).show().end().animate({
opacity: t
}, n, i, r)
},
animate: function(n, t, u, f) {
var s = i.isEmptyObject(n)
, o = i.speed(t, u, f)
, e = function() {
var t = ou(this, i.extend({}, n), o);
(s || r.get(this, "finish")) && t.stop(!0)
};
return e.finish = e,
s || o.queue === !1 ? this.each(e) : this.queue(o.queue, e)
},
stop: function(n, t, u) {
var f = function(n) {
var t = n.stop;
delete n.stop;
t(u)
};
return "string" != typeof n && (u = t,
t = n,
n = void 0),
t && n !== !1 && this.queue(n || "fx", []),
this.each(function() {
var s = !0
, t = null != n && n + "queueHooks"
, o = i.timers
, e = r.get(this);
if (t)
e[t] && e[t].stop && f(e[t]);
else
for (t in e)
e[t] && e[t].stop && ue.test(t) && f(e[t]);
for (t = o.length; t--; )
o[t].elem !== this || null != n && o[t].queue !== n || (o[t].anim.stop(u),
s = !1,
o.splice(t, 1));
(s || !u) && i.dequeue(this, n)
})
},
finish: function(n) {
return n !== !1 && (n = n || "fx"),
this.each(function() {
var t, e = r.get(this), u = e[n + "queue"], o = e[n + "queueHooks"], f = i.timers, s = u ? u.length : 0;
for (e.finish = !0,
i.queue(this, n, []),
o && o.stop && o.stop.call(this, !0),
t = f.length; t--; )
f[t].elem === this && f[t].queue === n && (f[t].anim.stop(!0),
f.splice(t, 1));
for (t = 0; s > t; t++)
u[t] && u[t].finish && u[t].finish.call(this);
delete e.finish
})
}
});
i.each(["toggle", "show", "hide"], function(n, t) {
var r = i.fn[t];
i.fn[t] = function(n, i, u) {
return null == n || "boolean" == typeof n ? r.apply(this, arguments) : this.animate(wt(t, !0), n, i, u)
}
});
i.each({
slideDown: wt("show"),
slideUp: wt("hide"),
slideToggle: wt("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(n, t) {
i.fn[n] = function(n, i, r) {
return this.animate(t, n, i, r)
}
});
i.timers = [];
i.fx.tick = function() {
var r, n = 0, t = i.timers;
for (d = i.now(); n < t.length; n++)
r = t[n],
r() || t[n] !== r || t.splice(n--, 1);
t.length || i.fx.stop();
d = void 0
}
;
i.fx.timer = function(n) {
i.timers.push(n);
n() ? i.fx.start() : i.timers.pop()
}
;
i.fx.interval = 13;
i.fx.start = function() {
yt || (yt = setInterval(i.fx.tick, i.fx.interval))
}
;
i.fx.stop = function() {
clearInterval(yt);
yt = null
}
;
i.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
};
i.fn.delay = function(n, t) {
return n = i.fx ? i.fx.speeds[n] || n : n,
t = t || "fx",
this.queue(t, function(t, i) {
var r = setTimeout(t, n);
i.stop = function() {
clearTimeout(r)
}
})
}
,
function() {
var n = u.createElement("input")
, t = u.createElement("select")
, i = t.appendChild(u.createElement("option"));
n.type = "checkbox";
f.checkOn = "" !== n.value;
f.optSelected = i.selected;
t.disabled = !0;
f.optDisabled = !i.disabled;
n = u.createElement("input");
n.value = "t";
n.type = "radio";
f.radioValue = "t" === n.value
}();
g = i.expr.attrHandle;
i.fn.extend({
attr: function(n, t) {
return l(this, i.attr, n, t, arguments.length > 1)
},
removeAttr: function(n) {
return this.each(function() {
i.removeAttr(this, n)
})
}
});
i.extend({
attr: function(n, t, r) {
var u, f, e = n.nodeType;
if (n && 3 !== e && 8 !== e && 2 !== e)
return typeof n.getAttribute === b ? i.prop(n, t, r) : (1 === e && i.isXMLDoc(n) || (t = t.toLowerCase(),
u = i.attrHooks[t] || (i.expr.match.bool.test(t) ? su : oe)),
void 0 === r ? u && "get"in u && null !== (f = u.get(n, t)) ? f : (f = i.find.attr(n, t),
null == f ? void 0 : f) : null !== r ? u && "set"in u && void 0 !== (f = u.set(n, r, t)) ? f : (n.setAttribute(t, r + ""),
r) : void i.removeAttr(n, t))
},
removeAttr: function(n, t) {
var r, u, e = 0, f = t && t.match(c);
if (f && 1 === n.nodeType)
while (r = f[e++])
u = i.propFix[r] || r,
i.expr.match.bool.test(r) && (n[u] = !1),
n.removeAttribute(r)
},
attrHooks: {
type: {
set: function(n, t) {
if (!f.radioValue && "radio" === t && i.nodeName(n, "input")) {
var r = n.value;
return n.setAttribute("type", t),
r && (n.value = r),
t
}
}
}
}
});
su = {
set: function(n, t, r) {
return t === !1 ? i.removeAttr(n, r) : n.setAttribute(r, r),
r
}
};
i.each(i.expr.match.bool.source.match(/\w+/g), function(n, t) {
var r = g[t] || i.find.attr;
g[t] = function(n, t, i) {
var u, f;
return i || (f = g[t],
g[t] = u,
u = null != r(n, t, i) ? t.toLowerCase() : null,
g[t] = f),
u
}
});
hu = /^(?:input|select|textarea|button)$/i;
i.fn.extend({
prop: function(n, t) {
return l(this, i.prop, n, t, arguments.length > 1)
},
removeProp: function(n) {
return this.each(function() {
delete this[i.propFix[n] || n]
})
}
});
i.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function(n, t, r) {
var f, u, o, e = n.nodeType;
if (n && 3 !== e && 8 !== e && 2 !== e)
return o = 1 !== e || !i.isXMLDoc(n),
o && (t = i.propFix[t] || t,
u = i.propHooks[t]),
void 0 !== r ? u && "set"in u && void 0 !== (f = u.set(n, r, t)) ? f : n[t] = r : u && "get"in u && null !== (f = u.get(n, t)) ? f : n[t]
},
propHooks: {
tabIndex: {
get: function(n) {
return n.hasAttribute("tabindex") || hu.test(n.nodeName) || n.href ? n.tabIndex : -1
}
}
}
});
f.optSelected || (i.propHooks.selected = {
get: function(n) {
var t = n.parentNode;
return t && t.parentNode && t.parentNode.selectedIndex,
null
}
});
i.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function() {
i.propFix[this.toLowerCase()] = this
});
bt = /[\t\r\n\f]/g;
i.fn.extend({
addClass: function(n) {
var o, t, r, u, s, f, h = "string" == typeof n && n, e = 0, l = this.length;
if (i.isFunction(n))
return this.each(function(t) {
i(this).addClass(n.call(this, t, this.className))
});
if (h)
for (o = (n || "").match(c) || []; l > e; e++)
if (t = this[e],
r = 1 === t.nodeType && (t.className ? (" " + t.className + " ").replace(bt, " ") : " ")) {
for (s = 0; u = o[s++]; )
r.indexOf(" " + u + " ") < 0 && (r += u + " ");
f = i.trim(r);
t.className !== f && (t.className = f)
}
return this
},
removeClass: function(n) {
var o, t, r, u, s, f, h = 0 === arguments.length || "string" == typeof n && n, e = 0, l = this.length;
if (i.isFunction(n))
return this.each(function(t) {
i(this).removeClass(n.call(this, t, this.className))
});
if (h)
for (o = (n || "").match(c) || []; l > e; e++)
if (t = this[e],
r = 1 === t.nodeType && (t.className ? (" " + t.className + " ").replace(bt, " ") : "")) {
for (s = 0; u = o[s++]; )
while (r.indexOf(" " + u + " ") >= 0)
r = r.replace(" " + u + " ", " ");
f = n ? i.trim(r) : "";
t.className !== f && (t.className = f)
}
return this
},
toggleClass: function(n, t) {
var u = typeof n;
return "boolean" == typeof t && "string" === u ? t ? this.addClass(n) : this.removeClass(n) : this.each(i.isFunction(n) ? function(r) {
i(this).toggleClass(n.call(this, r, this.className, t), t)
}
: function() {
if ("string" === u)
for (var t, e = 0, f = i(this), o = n.match(c) || []; t = o[e++]; )
f.hasClass(t) ? f.removeClass(t) : f.addClass(t);
else
(u === b || "boolean" === u) && (this.className && r.set(this, "__className__", this.className),
this.className = this.className || n === !1 ? "" : r.get(this, "__className__") || "")
}
)
},
hasClass: function(n) {
for (var i = " " + n + " ", t = 0, r = this.length; r > t; t++)
if (1 === this[t].nodeType && (" " + this[t].className + " ").replace(bt, " ").indexOf(i) >= 0)
return !0;
return !1
}
});
cu = /\r/g;
i.fn.extend({
val: function(n) {
var t, r, f, u = this[0];
return arguments.length ? (f = i.isFunction(n),
this.each(function(r) {
var u;
1 === this.nodeType && (u = f ? n.call(this, r, i(this).val()) : n,
null == u ? u = "" : "number" == typeof u ? u += "" : i.isArray(u) && (u = i.map(u, function(n) {
return null == n ? "" : n + ""
})),
t = i.valHooks[this.type] || i.valHooks[this.nodeName.toLowerCase()],
t && "set"in t && void 0 !== t.set(this, u, "value") || (this.value = u))
})) : u ? (t = i.valHooks[u.type] || i.valHooks[u.nodeName.toLowerCase()],
t && "get"in t && void 0 !== (r = t.get(u, "value")) ? r : (r = u.value,
"string" == typeof r ? r.replace(cu, "") : null == r ? "" : r)) : void 0
}
});
i.extend({
valHooks: {
option: {
get: function(n) {
var t = i.find.attr(n, "value");
return null != t ? t : i.trim(i.text(n))
}
},
select: {
get: function(n) {
for (var o, t, s = n.options, r = n.selectedIndex, u = "select-one" === n.type || 0 > r, h = u ? null : [], c = u ? r + 1 : s.length, e = 0 > r ? c : u ? r : 0; c > e; e++)
if (t = s[e],
!(!t.selected && e !== r || (f.optDisabled ? t.disabled : null !== t.getAttribute("disabled")) || t.parentNode.disabled && i.nodeName(t.parentNode, "optgroup"))) {
if (o = i(t).val(),
u)
return o;
h.push(o)
}
return h
},
set: function(n, t) {
for (var u, r, f = n.options, e = i.makeArray(t), o = f.length; o--; )
r = f[o],
(r.selected = i.inArray(r.value, e) >= 0) && (u = !0);
return u || (n.selectedIndex = -1),
e
}
}
}
});
i.each(["radio", "checkbox"], function() {
i.valHooks[this] = {
set: function(n, t) {
if (i.isArray(t))
return n.checked = i.inArray(i(n).val(), t) >= 0
}
};
f.checkOn || (i.valHooks[this].get = function(n) {
return null === n.getAttribute("value") ? "on" : n.value
}
)
});
i.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(n, t) {
i.fn[t] = function(n, i) {
return arguments.length > 0 ? this.on(t, null, n, i) : this.trigger(t)
}
});
i.fn.extend({
hover: function(n, t) {
return this.mouseenter(n).mouseleave(t || n)
},
bind: function(n, t, i) {
return this.on(n, null, t, i)
},
unbind: function(n, t) {
return this.off(n, null, t)
},
delegate: function(n, t, i, r) {
return this.on(t, n, i, r)
},
undelegate: function(n, t, i) {
return 1 === arguments.length ? this.off(n, "**") : this.off(t, n || "**", i)
}
});
kt = i.now();
dt = /\?/;
i.parseJSON = function(n) {
return JSON.parse(n + "")
}
;
i.parseXML = function(n) {
var t, r;
if (!n || "string" != typeof n)
return null;
try {
r = new DOMParser;
t = r.parseFromString(n, "text/xml")
} catch (u) {
t = void 0
}
return (!t || t.getElementsByTagName("parsererror").length) && i.error("Invalid XML: " + n),
t
}
;
var se = /#.*$/
, lu = /([?&])_=[^&]*/
, he = /^(.*?):[ \t]*([^\r\n]*)$/gm
, ce = /^(?:GET|HEAD)$/
, le = /^\/\//
, au = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/
, vu = {}
, ci = {}
, yu = "*/".concat("*")
, li = n.location.href
, nt = au.exec(li.toLowerCase()) || [];
i.extend({
active: 0,
lastModified: {},
etag: {},
ajaxSettings: {
url: li,
type: "GET",
isLocal: /^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(nt[1]),
global: !0,
processData: !0,
async: !0,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
accepts: {
"*": yu,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
converters: {
"* text": String,
"text html": !0,
"text json": i.parseJSON,
"text xml": i.parseXML
},
flatOptions: {
url: !0,
context: !0
}
},
ajaxSetup: function(n, t) {
return t ? ai(ai(n, i.ajaxSettings), t) : ai(i.ajaxSettings, n)
},
ajaxPrefilter: pu(vu),
ajaxTransport: pu(ci),
ajax: function(n, t) {
function p(n, t, s, h) {
var v, it, tt, p, nt, c = t;
2 !== e && (e = 2,
b && clearTimeout(b),
l = void 0,
w = h || "",
u.readyState = n > 0 ? 4 : 0,
v = n >= 200 && 300 > n || 304 === n,
s && (p = ae(r, u, s)),
p = ve(r, p, u, v),
v ? (r.ifModified && (nt = u.getResponseHeader("Last-Modified"),
nt && (i.lastModified[f] = nt),
nt = u.getResponseHeader("etag"),
nt && (i.etag[f] = nt)),
204 === n || "HEAD" === r.type ? c = "nocontent" : 304 === n ? c = "notmodified" : (c = p.state,
it = p.data,
tt = p.error,
v = !tt)) : (tt = c,
(n || !c) && (c = "error",
0 > n && (n = 0))),
u.status = n,
u.statusText = (t || c) + "",
v ? d.resolveWith(o, [it, c, u]) : d.rejectWith(o, [u, c, tt]),
u.statusCode(y),
y = void 0,
a && k.trigger(v ? "ajaxSuccess" : "ajaxError", [u, r, v ? it : tt]),
g.fireWith(o, [u, c]),
a && (k.trigger("ajaxComplete", [u, r]),
--i.active || i.event.trigger("ajaxStop")))
}
"object" == typeof n && (t = n,
n = void 0);
t = t || {};
var l, f, w, v, b, s, a, h, r = i.ajaxSetup({}, t), o = r.context || r, k = r.context && (o.nodeType || o.jquery) ? i(o) : i.event, d = i.Deferred(), g = i.Callbacks("once memory"), y = r.statusCode || {}, tt = {}, it = {}, e = 0, rt = "canceled", u = {
readyState: 0,
getResponseHeader: function(n) {
var t;
if (2 === e) {
if (!v)
for (v = {}; t = he.exec(w); )
v[t[1].toLowerCase()] = t[2];
t = v[n.toLowerCase()]
}
return null == t ? null : t
},
getAllResponseHeaders: function() {
return 2 === e ? w : null
},
setRequestHeader: function(n, t) {
var i = n.toLowerCase();
return e || (n = it[i] = it[i] || n,
tt[n] = t),
this
},
overrideMimeType: function(n) {
return e || (r.mimeType = n),
this
},
statusCode: function(n) {
var t;
if (n)
if (2 > e)
for (t in n)
y[t] = [y[t], n[t]];
else
u.always(n[u.status]);
return this
},
abort: function(n) {
var t = n || rt;
return l && l.abort(t),
p(0, t),
this
}
};
if (d.promise(u).complete = g.add,
u.success = u.done,
u.error = u.fail,
r.url = ((n || r.url || li) + "").replace(se, "").replace(le, nt[1] + "//"),
r.type = t.method || t.type || r.method || r.type,
r.dataTypes = i.trim(r.dataType || "*").toLowerCase().match(c) || [""],
null == r.crossDomain && (s = au.exec(r.url.toLowerCase()),
r.crossDomain = !(!s || s[1] === nt[1] && s[2] === nt[2] && (s[3] || ("http:" === s[1] ? "80" : "443")) === (nt[3] || ("http:" === nt[1] ? "80" : "443")))),
r.data && r.processData && "string" != typeof r.data && (r.data = i.param(r.data, r.traditional)),
wu(vu, r, t, u),
2 === e)
return u;
a = i.event && r.global;
a && 0 == i.active++ && i.event.trigger("ajaxStart");
r.type = r.type.toUpperCase();
r.hasContent = !ce.test(r.type);
f = r.url;
r.hasContent || (r.data && (f = r.url += (dt.test(f) ? "&" : "?") + r.data,
delete r.data),
r.cache === !1 && (r.url = lu.test(f) ? f.replace(lu, "$1_=" + kt++) : f + (dt.test(f) ? "&" : "?") + "_=" + kt++));
r.ifModified && (i.lastModified[f] && u.setRequestHeader("If-Modified-Since", i.lastModified[f]),
i.etag[f] && u.setRequestHeader("If-None-Match", i.etag[f]));
(r.data && r.hasContent && r.contentType !== !1 || t.contentType) && u.setRequestHeader("Content-Type", r.contentType);
u.setRequestHeader("Accept", r.dataTypes[0] && r.accepts[r.dataTypes[0]] ? r.accepts[r.dataTypes[0]] + ("*" !== r.dataTypes[0] ? ", " + yu + "; q=0.01" : "") : r.accepts["*"]);
for (h in r.headers)
u.setRequestHeader(h, r.headers[h]);
if (r.beforeSend && (r.beforeSend.call(o, u, r) === !1 || 2 === e))
return u.abort();
rt = "abort";
for (h in {
success: 1,
error: 1,
complete: 1
})
u[h](r[h]);
if (l = wu(ci, r, t, u)) {
u.readyState = 1;
a && k.trigger("ajaxSend", [u, r]);
r.async && r.timeout > 0 && (b = setTimeout(function() {
u.abort("timeout")
}, r.timeout));
try {
e = 1;
l.send(tt, p)
} catch (ut) {
if (!(2 > e))
throw ut;
p(-1, ut)
}
} else
p(-1, "No Transport");
return u
},
getJSON: function(n, t, r) {
return i.get(n, t, r, "json")
},
getScript: function(n, t) {
return i.get(n, void 0, t, "script")
}
});
i.each(["get", "post"], function(n, t) {
i[t] = function(n, r, u, f) {
return i.isFunction(r) && (f = f || u,
u = r,
r = void 0),
i.ajax({
url: n,
type: t,
dataType: f,
data: r,
success: u
})
}
});
i._evalUrl = function(n) {
return i.ajax({
url: n,
type: "GET",
dataType: "script",
async: !1,
global: !1,
throws: !0
})
}
;
i.fn.extend({
wrapAll: function(n) {
var t;
return i.isFunction(n) ? this.each(function(t) {
i(this).wrapAll(n.call(this, t))
}) : (this[0] && (t = i(n, this[0].ownerDocument).eq(0).clone(!0),
this[0].parentNode && t.insertBefore(this[0]),
t.map(function() {
for (var n = this; n.firstElementChild; )
n = n.firstElementChild;
return n
}).append(this)),
this)
},
wrapInner: function(n) {
return this.each(i.isFunction(n) ? function(t) {
i(this).wrapInner(n.call(this, t))
}
: function() {
var t = i(this)
, r = t.contents();
r.length ? r.wrapAll(n) : t.append(n)
}
)
},
wrap: function(n) {
var t = i.isFunction(n);
return this.each(function(r) {
i(this).wrapAll(t ? n.call(this, r) : n)
})
},
unwrap: function() {
return this.parent().each(function() {
i.nodeName(this, "body") || i(this).replaceWith(this.childNodes)
}).end()
}
});
i.expr.filters.hidden = function(n) {
return n.offsetWidth <= 0 && n.offsetHeight <= 0
}
;
i.expr.filters.visible = function(n) {
return !i.expr.filters.hidden(n)
}
;
var ye = /%20/g
, pe = /\[\]$/
, bu = /\r?\n/g
, we = /^(?:submit|button|image|reset|file)$/i
, be = /^(?:input|select|textarea|keygen)/i;
i.param = function(n, t) {
var r, u = [], f = function(n, t) {
t = i.isFunction(t) ? t() : null == t ? "" : t;
u[u.length] = encodeURIComponent(n) + "=" + encodeURIComponent(t)
};
if (void 0 === t && (t = i.ajaxSettings && i.ajaxSettings.traditional),
i.isArray(n) || n.jquery && !i.isPlainObject(n))
i.each(n, function() {
f(this.name, this.value)
});
else
for (r in n)
vi(r, n[r], t, f);
return u.join("&").replace(ye, "+")
}
;
i.fn.extend({
serialize: function() {
return i.param(this.serializeArray())
},
serializeArray: function() {
return this.map(function() {
var n = i.prop(this, "elements");
return n ? i.makeArray(n) : this
}).filter(function() {
var n = this.type;
return this.name && !i(this).is(":disabled") && be.test(this.nodeName) && !we.test(n) && (this.checked || !er.test(n))
}).map(function(n, t) {
var r = i(this).val();
return null == r ? null : i.isArray(r) ? i.map(r, function(n) {
return {
name: t.name,
value: n.replace(bu, "\r\n")
}
}) : {
name: t.name,
value: r.replace(bu, "\r\n")
}
}).get()
}
});
i.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest
} catch (n) {}
}
;
var ke = 0
, gt = {}
, de = {
0: 200,
1223: 204
}
, ut = i.ajaxSettings.xhr();
return n.attachEvent && n.attachEvent("onunload", function() {
for (var n in gt)
gt[n]()
}),
f.cors = !!ut && "withCredentials"in ut,
f.ajax = ut = !!ut,
i.ajaxTransport(function(n) {
var t;
if (f.cors || ut && !n.crossDomain)
return {
send: function(i, r) {
var f, u = n.xhr(), e = ++ke;
if (u.open(n.type, n.url, n.async, n.username, n.password),
n.xhrFields)
for (f in n.xhrFields)
u[f] = n.xhrFields[f];
n.mimeType && u.overrideMimeType && u.overrideMimeType(n.mimeType);
n.crossDomain || i["X-Requested-With"] || (i["X-Requested-With"] = "XMLHttpRequest");
for (f in i)
u.setRequestHeader(f, i[f]);
t = function(n) {
return function() {
t && (delete gt[e],
t = u.onload = u.onerror = null,
"abort" === n ? u.abort() : "error" === n ? r(u.status, u.statusText) : r(de[u.status] || u.status, u.statusText, "string" == typeof u.responseText ? {
text: u.responseText
} : void 0, u.getAllResponseHeaders()))
}
}
;
u.onload = t();
u.onerror = t("error");
t = gt[e] = t("abort");
try {
u.send(n.hasContent && n.data || null)
} catch (o) {
if (t)
throw o;
}
},
abort: function() {
t && t()
}
}
}),
i.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function(n) {
return i.globalEval(n),
n
}
}
}),
i.ajaxPrefilter("script", function(n) {
void 0 === n.cache && (n.cache = !1);
n.crossDomain && (n.type = "GET")
}),
i.ajaxTransport("script", function(n) {
if (n.crossDomain) {
var r, t;
return {
send: function(f, e) {
r = i("<script>").prop({
async: !0,
charset: n.scriptCharset,
src: n.url
}).on("load error", t = function(n) {
r.remove();
t = null;
n && e("error" === n.type ? 404 : 200, n.type)
}
);
u.head.appendChild(r[0])
},
abort: function() {
t && t()
}
}
}
}),
yi = [],
ni = /(=)\?(?=&|$)|\?\?/,
i.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var n = yi.pop() || i.expando + "_" + kt++;
return this[n] = !0,
n
}
}),
i.ajaxPrefilter("json jsonp", function(t, r, u) {
var f, o, e, s = t.jsonp !== !1 && (ni.test(t.url) ? "url" : "string" == typeof t.data && !(t.contentType || "").indexOf("application/x-www-form-urlencoded") && ni.test(t.data) && "data");
if (s || "jsonp" === t.dataTypes[0])
return (f = t.jsonpCallback = i.isFunction(t.jsonpCallback) ? t.jsonpCallback() : t.jsonpCallback,
s ? t[s] = t[s].replace(ni, "$1" + f) : t.jsonp !== !1 && (t.url += (dt.test(t.url) ? "&" : "?") + t.jsonp + "=" + f),
t.converters["script json"] = function() {
return e || i.error(f + " was not called"),
e[0]
}
,
t.dataTypes[0] = "json",
o = n[f],
n[f] = function() {
e = arguments
}
,
u.always(function() {
n[f] = o;
t[f] && (t.jsonpCallback = r.jsonpCallback,
yi.push(f));
e && i.isFunction(o) && o(e[0]);
e = o = void 0
}),
"script")
}),
i.parseHTML = function(n, t, r) {
if (!n || "string" != typeof n)
return null;
"boolean" == typeof t && (r = t,
t = !1);
t = t || u;
var f = gi.exec(n)
, e = !r && [];
return f ? [t.createElement(f[1])] : (f = i.buildFragment([n], t, e),
e && e.length && i(e).remove(),
i.merge([], f.childNodes))
}
,
pi = i.fn.load,
i.fn.load = function(n, t, r) {
if ("string" != typeof n && pi)
return pi.apply(this, arguments);
var u, o, s, f = this, e = n.indexOf(" ");
return e >= 0 && (u = i.trim(n.slice(e)),
n = n.slice(0, e)),
i.isFunction(t) ? (r = t,
t = void 0) : t && "object" == typeof t && (o = "POST"),
f.length > 0 && i.ajax({
url: n,
type: o,
dataType: "html",
data: t
}).done(function(n) {
s = arguments;
f.html(u ? i("<div>").append(i.parseHTML(n)).find(u) : n)
}).complete(r && function(n, t) {
f.each(r, s || [n.responseText, t, n])
}
),
this
}
,
i.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(n, t) {
i.fn[t] = function(n) {
return this.on(t, n)
}
}),
i.expr.filters.animated = function(n) {
return i.grep(i.timers, function(t) {
return n === t.elem
}).length
}
,
wi = n.document.documentElement,
i.offset = {
setOffset: function(n, t, r) {
var e, o, s, h, u, c, v, l = i.css(n, "position"), a = i(n), f = {};
"static" === l && (n.style.position = "relative");
u = a.offset();
s = i.css(n, "top");
c = i.css(n, "left");
v = ("absolute" === l || "fixed" === l) && (s + c).indexOf("auto") > -1;
v ? (e = a.position(),
h = e.top,
o = e.left) : (h = parseFloat(s) || 0,
o = parseFloat(c) || 0);
i.isFunction(t) && (t = t.call(n, r, u));
null != t.top && (f.top = t.top - u.top + h);
null != t.left && (f.left = t.left - u.left + o);
"using"in t ? t.using.call(n, f) : a.css(f)
}
},
i.fn.extend({
offset: function(n) {
if (arguments.length)
return void 0 === n ? this : this.each(function(t) {
i.offset.setOffset(this, n, t)
});
var r, f, t = this[0], u = {
top: 0,
left: 0
}, e = t && t.ownerDocument;
if (e)
return r = e.documentElement,
i.contains(r, t) ? (typeof t.getBoundingClientRect !== b && (u = t.getBoundingClientRect()),
f = ku(e),
{
top: u.top + f.pageYOffset - r.clientTop,
left: u.left + f.pageXOffset - r.clientLeft
}) : u
},
position: function() {
if (this[0]) {
var n, r, u = this[0], t = {
top: 0,
left: 0
};
return "fixed" === i.css(u, "position") ? r = u.getBoundingClientRect() : (n = this.offsetParent(),
r = this.offset(),
i.nodeName(n[0], "html") || (t = n.offset()),
t.top += i.css(n[0], "borderTopWidth", !0),
t.left += i.css(n[0], "borderLeftWidth", !0)),
{
top: r.top - t.top - i.css(u, "marginTop", !0),
left: r.left - t.left - i.css(u, "marginLeft", !0)
}
}
},
offsetParent: function() {
return this.map(function() {
for (var n = this.offsetParent || wi; n && !i.nodeName(n, "html") && "static" === i.css(n, "position"); )
n = n.offsetParent;
return n || wi
})
}
}),
i.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(t, r) {
var u = "pageYOffset" === r;
i.fn[t] = function(i) {
return l(this, function(t, i, f) {
var e = ku(t);
return void 0 === f ? e ? e[r] : t[i] : void (e ? e.scrollTo(u ? n.pageXOffset : f, u ? f : n.pageYOffset) : t[i] = f)
}, t, i, arguments.length, null)
}
}),
i.each(["top", "left"], function(n, t) {
i.cssHooks[t] = br(f.pixelPosition, function(n, r) {
if (r)
return (r = it(n, t),
hi.test(r) ? i(n).position()[t] + "px" : r)
})
}),
i.each({
Height: "height",
Width: "width"
}, function(n, t) {
i.each({
padding: "inner" + n,
content: t,
"": "outer" + n
}, function(r, u) {
i.fn[u] = function(u, f) {
var e = arguments.length && (r || "boolean" != typeof u)
, o = r || (u === !0 || f === !0 ? "margin" : "border");
return l(this, function(t, r, u) {
var f;
return i.isWindow(t) ? t.document.documentElement["client" + n] : 9 === t.nodeType ? (f = t.documentElement,
Math.max(t.body["scroll" + n], f["scroll" + n], t.body["offset" + n], f["offset" + n], f["client" + n])) : void 0 === u ? i.css(t, r, o) : i.style(t, r, u, o)
}, t, e ? u : void 0, e, null)
}
})
}),
i.fn.size = function() {
return this.length
}
,
i.fn.andSelf = i.fn.addBack,
"function" == typeof define && define.amd && define("jquery", [], function() {
return i
}),
du = n.jQuery,
gu = n.$,
i.noConflict = function(t) {
return n.$ === i && (n.$ = gu),
t && n.jQuery === i && (n.jQuery = du),
i
}
,
typeof t === b && (n.jQuery = n.$ = i),
i
})
|
python ./multiproc.py --nproc_per_node 16 ./main.py --raport-file raport.json -j5 -p 100 --lr 4.096 --optimizer-batch-size 4096 --warmup 16 --arch resnet50 -c fanin --label-smoothing 0.1 --data-backend pytorch --lr-schedule cosine --mom 0.875 --wd 3.0517578125e-05 --workspace $1 -b 128 --epochs 90 /data/imagenet
|
<filename>test/__fixtures__/double-access/code.js
function App() {
let state = 1;
function handleAdd() {
state = state + 1;
}
function handleRemove() {
state = state - 1;
}
return (
<>
{state}
<div onClick={handleAdd}></div>
<div onClick={handleRemove}></div>
</>
);
}
|
/**
* Retrieve and display daily expenses
*
* @param string $day The date for which expenses need to be retrieved (format: 'Y-m-d')
* @return \Illuminate\View\View The view containing the expenses for the given day
*/
function displayDailyExpenses($day) {
// Assuming the 'EndExpense' model is properly defined and mapped to the 'end_expenses' table
// Fetch expenses for the given day using Laravel's Eloquent ORM
$expenses = EndExpense::whereDate('created_at', $day)->get();
// Pass the fetched expenses to the view and set the view title
return view('admin.expenses.expensesInDay', compact('expenses'))->withTitle('Expenses');
}
|
<gh_stars>0
import { ICommandProps } from ".";
import cheerio from 'cheerio'
import { getLeaderBoard } from "../utils";
import { client } from "..";
const findUserInLeaderboard = (html: string): [string, string, string, number] | null => {
const $ = cheerio.load(html)
let result: [string, string, string, number] | null = null
const rows = $('tr').toArray()
rows.forEach((item, index) => {
if (result === null) {
let userFound = false
$(item)
.find('td')
.each(function () {
if ($(this).text() === 'MatsDoesGaming') {
userFound = true
}
})
if (userFound) {
result = $(item)
.find('td')
.toArray()
.map(value => $(value).text()) as [string, string, string, number]
if (index === 0) {
result[3] = 0
} else {
const nextKills = $($(rows[index - 1]).find('td').toArray()[2]).text()
result[3] = Number(nextKills) - Number(result[2])
}
}
}
})
return result
}
export default async ({ channel }: ICommandProps) => {
const html = await getLeaderBoard()
const result = findUserInLeaderboard(html)
if (result === null) {
client.say(channel, 'It looks like Mats isn\'t in the top hundred. What a noob am i right!!! Kappa')
}
const [position, name, kills, nextKills] = result
client.say(channel, `${name} is currently in position ${position} with ${kills} kills! He needs ${nextKills} more kills to rank up! If you wan't to look at the rankings, you can find them here: https://tinyurl.com/4ayvakk3`)
}
|
<reponame>rvkhakhkhar/spring-petclinic-graphql
export { default } from "./AddOwnerPage";
|
#include "nrs.hpp"
#include "meshSetup.hpp"
#include "nekInterfaceAdapter.hpp"
#include "udf.hpp"
#include "filter.hpp"
#include "bcMap.hpp"
static dfloat *scratch;
static occa::memory o_scratch;
cds_t *cdsSetup(ins_t *ins, mesh_t *mesh, setupAide &options, occa::properties &kernelInfoH);
ins_t *insSetup(MPI_Comm comm, setupAide &options, int buildOnly)
{
ins_t *ins = new ins_t();
ins->options = options;
ins->kernelInfo = new occa::properties();
occa::properties& kernelInfo = *ins->kernelInfo;
kernelInfo["defines"].asObject();
kernelInfo["includes"].asArray();
kernelInfo["header"].asArray();
kernelInfo["flags"].asObject();
kernelInfo["include_paths"].asArray();
int N;
string install_dir;
options.getArgs("POLYNOMIAL DEGREE", N);
options.getArgs("NUMBER OF SCALARS", ins->Nscalar);
install_dir.assign(getenv("NEKRS_INSTALL_DIR"));
options.getArgs("MESH DIMENSION", ins->dim);
options.getArgs("ELEMENT TYPE", ins->elementType);
ins->cht = 0;
if (nekData.nelv != nekData.nelt && ins->Nscalar) ins->cht = 1;
if (buildOnly) {
ins->meshT = createMeshDummy(comm, N, options, kernelInfo);
ins->mesh = ins->meshT;
} else {
ins->meshT = createMeshT(comm, N, ins->cht, options, kernelInfo);
ins->mesh = ins->meshT;
if (ins->cht) ins->mesh = createMeshV(comm, N, ins->meshT, options, kernelInfo);
}
mesh_t *mesh = ins->mesh;
occa::properties kernelInfoV = kernelInfo;
occa::properties kernelInfoP = kernelInfo;
occa::properties kernelInfoS = kernelInfo;
ins->NVfields = (ins->dim==3) ? 3:2; // Total Number of Velocity Fields
ins->NTfields = (ins->dim==3) ? 4:3; // Total Velocity + Pressure
ins->SNrk = 0;
options.getArgs("SUBCYCLING TIME STAGE NUMBER", ins->SNrk);
mesh->Nfields = 1;
ins->g0 = 1.0;
ins->extbdfA = (dfloat*) calloc(3, sizeof(dfloat));
ins->extbdfB = (dfloat*) calloc(3, sizeof(dfloat));
ins->extbdfC = (dfloat*) calloc(3, sizeof(dfloat));
ins->extC = (dfloat*) calloc(3, sizeof(dfloat));
if (options.compareArgs("TIME INTEGRATOR", "TOMBO1")) {
ins->Nstages = 1;
ins->temporalOrder = 1;
ins->g0 = 1.0;
} else if (options.compareArgs("TIME INTEGRATOR", "TOMBO2")) {
ins->Nstages = 2;
ins->temporalOrder = 2;
ins->g0 = 1.5;
} else if (options.compareArgs("TIME INTEGRATOR", "TOMBO3")) {
ins->Nstages = 3;
ins->temporalOrder = 3;
ins->g0 = 11.f/6.f;
}
ins->readRestartFile = 0;
options.getArgs("RESTART FROM FILE", ins->readRestartFile);
ins->writeRestartFile = 0;
options.getArgs("WRITE RESTART FILE", ins->writeRestartFile);
dfloat mue = 1;
dfloat rho = 1;
options.getArgs("VISCOSITY", mue);
options.getArgs("DENSITY", rho);
options.getArgs("SUBCYCLING STEPS",ins->Nsubsteps);
dfloat dt;
options.getArgs("DT", dt);
ins->dt = dt;
options.getArgs("FINAL TIME", ins->finalTime);
options.getArgs("START TIME", ins->startTime);
if(ins->startTime > 0.0) {
int numSteps;
if(options.getArgs("NUMBER TIMESTEPS", numSteps))
ins->finalTime += ins->startTime;
}
ins->NtimeSteps = ceil((ins->finalTime-ins->startTime)/ins->dt);
options.setArgs("NUMBER TIMESTEPS", std::to_string(ins->NtimeSteps));
if(ins->Nsubsteps) ins->sdt = ins->dt/ins->Nsubsteps;
// Hold some inverses for kernels
ins->idt = 1.0/ins->dt;
options.getArgs("TSTEPS FOR SOLUTION OUTPUT", ins->outputStep);
const dlong Nlocal = mesh->Np*mesh->Nelements;
const dlong Ntotal = mesh->Np*(mesh->Nelements+mesh->totalHaloPairs);
ins->Nlocal = Nlocal;
ins->Ntotal = Ntotal;
{ // ensure that offset is large enough for v and t mesh and is properly aligned
const dlong NtotalT = ins->meshT->Np*(ins->meshT->Nelements+ins->meshT->totalHaloPairs);
ins->fieldOffset = mymax(Ntotal, NtotalT);
int PAGESIZE = 4096; // default is 4kB
char *tmp;
tmp = getenv("NEKRS_PAGE_SIZE");
if (tmp != NULL) PAGESIZE = std::stoi(tmp);
const int pageW = PAGESIZE/sizeof(dfloat);
if (ins->fieldOffset%pageW) ins->fieldOffset = (ins->fieldOffset/pageW + 1)*pageW;
}
ins->Nblock = (Nlocal+blockSize-1)/blockSize;
ins->U = (dfloat*) calloc(ins->NVfields*ins->Nstages*ins->fieldOffset,sizeof(dfloat));
ins->Ue = (dfloat*) calloc(ins->NVfields*ins->fieldOffset,sizeof(dfloat));
ins->P = (dfloat*) calloc(ins->fieldOffset,sizeof(dfloat));
ins->PI = (dfloat*) calloc(ins->fieldOffset,sizeof(dfloat));
ins->BF = (dfloat*) calloc(ins->NVfields*ins->fieldOffset,sizeof(dfloat));
ins->FU = (dfloat*) calloc(ins->NVfields*(ins->Nstages+1)*ins->fieldOffset,sizeof(dfloat));
if(ins->Nsubsteps){
int Sorder;
options.getArgs("SUBCYCLING TIME ORDER", Sorder);
if(Sorder==2 && ins->SNrk==2){
dfloat rka[2] = {0.0, 1.0 };
dfloat rkb[2] = {0.5, 0.5 };
dfloat rkc[2] = {0.0, 1.0 };
ins->Srka = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkb = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkc = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
memcpy(ins->Srka, rka, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkb, rkb, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkc, rkc, ins->SNrk*sizeof(dfloat));
}else if(Sorder ==3 && ins->SNrk==3){
// Using Williamson 3rd order scheme converted to low storage since the better truncation
dfloat rka[3] = {0.0, -5.0/9.0, -153.0/128.0};
dfloat rkb[3] = {1.0/3.0, 15.0/16.0, 8.0/15.0 };
dfloat rkc[3] = {0.0, 1.0/3.0, 3.0/4.0 };
ins->Srka = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkb = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkc = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
memcpy(ins->Srka, rka, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkb, rkb, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkc, rkc, ins->SNrk*sizeof(dfloat));
}else if(Sorder==4 && ins->SNrk==4){ // ERK(4,4)
dfloat rka[4] = {0.0, 1.0/2.0, 1.0/2.0, 1.0};
dfloat rkb[4] = {1.0/6.0, 1.0/3.0, 1.0/3.0, 1.0/6.0};
dfloat rkc[4] = {0.0, 1.0/2.0, 1.0/2.0, 1.0};
ins->Srka = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkb = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
ins->Srkc = (dfloat*) calloc(ins->SNrk, sizeof(dfloat));
memcpy(ins->Srka, rka, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkb, rkb, ins->SNrk*sizeof(dfloat));
memcpy(ins->Srkc, rkc, ins->SNrk*sizeof(dfloat));
}else{
if(mesh->rank==0) cout << "Unsupported subcycling scheme!\n";
MPI_Finalize();
exit(1);
}
ins->o_Srka = mesh->device.malloc(ins->SNrk*sizeof(dfloat), ins->Srka);
ins->o_Srkb = mesh->device.malloc(ins->SNrk*sizeof(dfloat), ins->Srkb);
}
// setup scratch space
const int wrkNflds = 9;
const int ellipticWrkNflds = 9;
ins->ellipticWrkOffset = wrkNflds*ins->fieldOffset;
const int scratchNflds = wrkNflds+ellipticWrkNflds;
scratch = (dfloat*) calloc(scratchNflds*ins->fieldOffset,sizeof(dfloat));
o_scratch = mesh->device.malloc(scratchNflds*ins->fieldOffset*sizeof(dfloat), scratch);
ins->o_wrk0 = o_scratch.slice( 0*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk1 = o_scratch.slice( 1*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk2 = o_scratch.slice( 2*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk3 = o_scratch.slice( 3*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk4 = o_scratch.slice( 4*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk5 = o_scratch.slice( 5*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk6 = o_scratch.slice( 6*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk9 = o_scratch.slice( 9*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk12 = o_scratch.slice(12*ins->fieldOffset*sizeof(dfloat));
ins->o_wrk15 = o_scratch.slice(15*ins->fieldOffset*sizeof(dfloat));
// dummy decleration for user work space
ins->usrwrk = (dfloat*) calloc(1, sizeof(dfloat));
ins->o_usrwrk = mesh->device.malloc(1*sizeof(dfloat), ins->usrwrk);
ins->o_U = mesh->device.malloc(ins->NVfields*ins->Nstages*ins->fieldOffset*sizeof(dfloat), ins->U);
ins->o_Ue = mesh->device.malloc(ins->NVfields*ins->fieldOffset*sizeof(dfloat), ins->Ue);
ins->o_P = mesh->device.malloc(ins->fieldOffset*sizeof(dfloat), ins->P);
ins->o_PI = mesh->device.malloc(ins->fieldOffset*sizeof(dfloat), ins->PI);
ins->o_FU = mesh->device.malloc(ins->NVfields*(ins->Nstages+1)*ins->fieldOffset*sizeof(dfloat), ins->FU);
ins->o_BF = mesh->device.malloc(ins->NVfields*ins->fieldOffset*sizeof(dfloat), ins->BF);
ins->var_coeff = 1; // use always var coeff elliptic
ins->ellipticCoeff = (dfloat*) calloc(2*ins->fieldOffset,sizeof(dfloat));
for (int i=0;i<2*ins->fieldOffset;i++) // just to avoid devision by 0 in Jacobi setup
ins->ellipticCoeff[i] = 1;
ins->o_ellipticCoeff = mesh->device.malloc(2*ins->fieldOffset*sizeof(dfloat), ins->ellipticCoeff);
ins->prop = (dfloat*) calloc(2*ins->fieldOffset,sizeof(dfloat));
for (int e=0;e<mesh->Nelements;e++) {
for (int n=0;n<mesh->Np;n++) {
ins->prop[0*ins->fieldOffset + e*mesh->Np + n] = mue;
ins->prop[1*ins->fieldOffset + e*mesh->Np + n] = rho;
}
}
ins->o_prop = mesh->device.malloc(2*ins->fieldOffset*sizeof(dfloat), ins->prop);
ins->o_mue = ins->o_prop.slice(0*ins->fieldOffset*sizeof(dfloat));
ins->o_rho = ins->o_prop.slice(1*ins->fieldOffset*sizeof(dfloat));
ins->lowMach = 0;
if(ins->options.compareArgs("LOWMACH", "TRUE")) ins->lowMach = 1;
ins->qtl = (dfloat*) calloc(ins->fieldOffset,sizeof(dfloat));
ins->o_qtl = mesh->device.malloc(ins->fieldOffset*sizeof(dfloat), ins->qtl);
ins->elementInfo = (dlong*) calloc(ins->meshT->Nelements,sizeof(dlong));
for (int e=0;e<ins->meshT->Nelements;e++) ins->elementInfo[e] = mesh->elementInfo[e];
ins->o_elementInfo = mesh->device.malloc(ins->meshT->Nelements*sizeof(dlong), ins->elementInfo);
dfloat rkC[4] = {1.0, 0.0, -1.0, -2.0};
ins->o_rkC = mesh->device.malloc(4*sizeof(dfloat),rkC);
ins->o_extbdfA = mesh->device.malloc(3*sizeof(dfloat));
ins->o_extbdfB = mesh->device.malloc(3*sizeof(dfloat));
ins->o_extbdfC = mesh->device.malloc(3*sizeof(dfloat));
ins->o_extC = mesh->device.malloc(3*sizeof(dfloat));
ins->o_prkA = ins->o_extbdfC;
ins->o_prkB = ins->o_extbdfC;
kernelInfo["defines/" "p_NTfields"]= ins->NTfields;
kernelInfo["defines/" "p_NVfields"]= ins->NVfields;
kernelInfo["defines/" "p_NfacesNfp"]= mesh->Nfaces*mesh->Nfp;
kernelInfo["defines/" "p_Nstages"]= ins->Nstages;
if(ins->Nsubsteps)
kernelInfo["defines/" "p_SUBCYCLING"]= 1;
else
kernelInfo["defines/" "p_SUBCYCLING"]= 0;
kernelInfo["defines/" "p_blockSize"]= blockSize;
//kernelInfo["parser/" "automate-add-barriers"] = "disabled";
int maxNodes = mymax(mesh->Np, (mesh->Nfp*mesh->Nfaces));
kernelInfo["defines/" "p_maxNodes"]= maxNodes;
int NblockV = mymax(1,256/mesh->Np); // works for CUDA
kernelInfo["defines/" "p_NblockV"]= NblockV;
int NblockS = mymax(1,256/maxNodes); // works for CUDA
kernelInfo["defines/" "p_NblockS"]= NblockS;
int maxNodesVolumeCub = mymax(mesh->cubNp,mesh->Np);
kernelInfo["defines/" "p_maxNodesVolumeCub"]= maxNodesVolumeCub;
int cubNblockV = mymax(1,256/maxNodesVolumeCub);
int maxNodesSurfaceCub = mymax(mesh->Np, mymax(mesh->Nfaces*mesh->Nfp,
mesh->Nfaces*mesh->intNfp));
kernelInfo["defines/" "p_maxNodesSurfaceCub"]=maxNodesSurfaceCub;
int cubNblockS = mymax(256/maxNodesSurfaceCub,1); // works for CUDA
kernelInfo["defines/" "p_cubNblockV"]=cubNblockV;
kernelInfo["defines/" "p_cubNblockS"]=cubNblockS;
// jit compile udf kernels
if (udf.loadKernels) {
if (mesh->rank == 0) cout << "building udf kernels ...";
udf.loadKernels(ins);
if (mesh->rank == 0) cout << " done" << endl;
}
occa::properties kernelInfoBC = kernelInfo;
const string bcDataFile = install_dir + "/include/insBcData.h";
kernelInfoBC["includes"] += bcDataFile.c_str();
string boundaryHeaderFileName;
options.getArgs("DATA FILE", boundaryHeaderFileName);
kernelInfoBC["includes"] += realpath(boundaryHeaderFileName.c_str(), NULL);
if(ins->options.compareArgs("FILTER STABILIZATION", "RELAXATION"))
filterSetup(ins);
if (mesh->rank==0) printf("==================VELOCITY SETUP=========================\n");
//make option objects for elliptc solvers
ins->vOptions = options;
ins->vOptions.setArgs("KRYLOV SOLVER", options.getArgs("VELOCITY KRYLOV SOLVER"));
ins->vOptions.setArgs("SOLVER TOLERANCE", options.getArgs("VELOCITY SOLVER TOLERANCE"));
ins->vOptions.setArgs("DISCRETIZATION", options.getArgs("VELOCITY DISCRETIZATION"));
ins->vOptions.setArgs("BASIS", options.getArgs("VELOCITY BASIS"));
ins->vOptions.setArgs("PRECONDITIONER", options.getArgs("VELOCITY PRECONDITIONER"));
ins->vOptions.setArgs("MULTIGRID COARSENING", options.getArgs("VELOCITY MULTIGRID COARSENING"));
ins->vOptions.setArgs("MULTIGRID SMOOTHER", options.getArgs("VELOCITY MULTIGRID SMOOTHER"));
ins->vOptions.setArgs("MULTIGRID CHEBYSHEV DEGREE", options.getArgs("VELOCITY MULTIGRID CHEBYSHEV DEGREE"));
ins->vOptions.setArgs("PARALMOND CYCLE", options.getArgs("VELOCITY PARALMOND CYCLE"));
ins->vOptions.setArgs("PARALMOND SMOOTHER", options.getArgs("VELOCITY PARALMOND SMOOTHER"));
ins->vOptions.setArgs("PARALMOND PARTITION", options.getArgs("VELOCITY PARALMOND PARTITION"));
ins->vOptions.setArgs("PARALMOND CHEBYSHEV DEGREE", options.getArgs("VELOCITY PARALMOND CHEBYSHEV DEGREE"));
ins->vOptions.setArgs("PARALMOND AGGREGATION STRATEGY", options.getArgs("VELOCITY PARALMOND AGGREGATION STRATEGY"));
ins->vOptions.setArgs("DEBUG ENABLE OGS", "1");
ins->vOptions.setArgs("DEBUG ENABLE REDUCTIONS", "1");
const int nbrBIDs = bcMap::size();
int *uBCType = (int*) calloc(nbrBIDs+1, sizeof(int));
int *vBCType = (int*) calloc(nbrBIDs+1, sizeof(int));
int *wBCType = (int*) calloc(nbrBIDs+1, sizeof(int));
int *pBCType = (int*) calloc(nbrBIDs+1, sizeof(int));
for (int bID=1; bID <= nbrBIDs; bID++) {
string bcTypeText(bcMap::text(bID, "velocity"));
if(mesh->rank == 0) printf("bID %d -> bcType %s\n", bID, bcTypeText.c_str());
uBCType[bID] = bcMap::type(bID, "x-velocity");
vBCType[bID] = bcMap::type(bID, "y-velocity");
wBCType[bID] = bcMap::type(bID, "z-velocity");
pBCType[bID] = bcMap::type(bID, "pressure");
}
//default solver tolerances
ins->presTOL = 1E-4;
ins->velTOL = 1E-6;
ins->uSolver = new elliptic_t();
ins->uSolver->wrkOffset = ins->fieldOffset;
ins->uSolver->wrk = scratch + ins->ellipticWrkOffset;
ins->uSolver->o_wrk = o_scratch.slice(ins->ellipticWrkOffset*sizeof(dfloat));
ins->uSolver->mesh = mesh;
ins->uSolver->options = ins->vOptions;
ins->uSolver->dim = ins->dim;
ins->uSolver->elementType = ins->elementType;
ins->uSolver->BCType = (int*) calloc(nbrBIDs+1,sizeof(int));
memcpy(ins->uSolver->BCType,uBCType,(nbrBIDs+1)*sizeof(int));
ins->uSolver->var_coeff = ins->var_coeff;
ins->uSolver->coeff = ins->ellipticCoeff;
ins->uSolver->o_coeff = ins->o_ellipticCoeff;
const dfloat lambda = 1; // not used if var_coeff
ellipticSolveSetup(ins->uSolver, lambda, kernelInfoV);
ins->vSolver = new elliptic_t();
ins->vSolver->wrkOffset = ins->fieldOffset;
ins->vSolver->wrk = scratch + ins->ellipticWrkOffset;
ins->vSolver->o_wrk = o_scratch.slice(ins->ellipticWrkOffset*sizeof(dfloat));
ins->vSolver->mesh = mesh;
ins->vSolver->options = ins->vOptions;
ins->vSolver->dim = ins->dim;
ins->vSolver->elementType = ins->elementType;
ins->vSolver->BCType = (int*) calloc(nbrBIDs+1,sizeof(int));
memcpy(ins->vSolver->BCType,vBCType,(nbrBIDs+1)*sizeof(int));
ins->vSolver->var_coeff = ins->var_coeff;
ins->vSolver->coeff = ins->ellipticCoeff;
ins->vSolver->o_coeff = ins->o_ellipticCoeff;
ellipticSolveSetup(ins->vSolver, lambda, kernelInfoV); //!!!!!
if (ins->dim==3) {
ins->wSolver = new elliptic_t();
ins->wSolver->wrkOffset = ins->fieldOffset;
ins->wSolver->wrk = scratch + ins->ellipticWrkOffset;
ins->wSolver->o_wrk = o_scratch.slice(ins->ellipticWrkOffset*sizeof(dfloat));
ins->wSolver->mesh = mesh;
ins->wSolver->options = ins->vOptions;
ins->wSolver->dim = ins->dim;
ins->wSolver->elementType = ins->elementType;
ins->wSolver->BCType = (int*) calloc(nbrBIDs+1,sizeof(int));
memcpy(ins->wSolver->BCType,wBCType,(nbrBIDs+1)*sizeof(int));
ins->wSolver->var_coeff = ins->var_coeff;
ins->wSolver->coeff = ins->ellipticCoeff;
ins->wSolver->o_coeff = ins->o_ellipticCoeff;
ellipticSolveSetup(ins->wSolver, lambda, kernelInfoV); //!!!!!
}
if (mesh->rank==0) printf("==================PRESSURE SETUP=========================\n");
ins->pSolver = new elliptic_t();
ins->pSolver->wrkOffset = ins->fieldOffset;
ins->pSolver->wrk = scratch + ins->ellipticWrkOffset;
ins->pSolver->o_wrk = o_scratch.slice(ins->ellipticWrkOffset*sizeof(dfloat));
ins->pSolver->mesh = mesh;
ins->pOptions = options;
ins->pOptions.setArgs("KRYLOV SOLVER", options.getArgs("PRESSURE KRYLOV SOLVER"));
ins->pOptions.setArgs("SOLVER TOLERANCE", options.getArgs("PRESSURE SOLVER TOLERANCE"));
ins->pOptions.setArgs("DISCRETIZATION", options.getArgs("PRESSURE DISCRETIZATION"));
ins->pOptions.setArgs("BASIS", options.getArgs("PRESSURE BASIS"));
ins->pOptions.setArgs("PRECONDITIONER", options.getArgs("PRESSURE PRECONDITIONER"));
ins->pOptions.setArgs("MULTIGRID COARSENING", options.getArgs("PRESSURE MULTIGRID COARSENING"));
ins->pOptions.setArgs("MULTIGRID SMOOTHER", options.getArgs("PRESSURE MULTIGRID SMOOTHER"));
ins->pOptions.setArgs("MULTIGRID CHEBYSHEV DEGREE", options.getArgs("PRESSURE MULTIGRID CHEBYSHEV DEGREE"));
ins->pOptions.setArgs("PARALMOND CYCLE", options.getArgs("PRESSURE PARALMOND CYCLE"));
ins->pOptions.setArgs("PARALMOND SMOOTHER", options.getArgs("PRESSURE PARALMOND SMOOTHER"));
ins->pOptions.setArgs("PARALMOND PARTITION", options.getArgs("PRESSURE PARALMOND PARTITION"));
ins->pOptions.setArgs("PARALMOND CHEBYSHEV DEGREE", options.getArgs("PRESSURE PARALMOND CHEBYSHEV DEGREE"));
ins->pOptions.setArgs("PARALMOND AGGREGATION STRATEGY", options.getArgs("PRESSURE PARALMOND AGGREGATION STRATEGY"));
ins->pOptions.setArgs("DEBUG ENABLE OGS", "1");
ins->pOptions.setArgs("DEBUG ENABLE REDUCTIONS", "1");
ins->pOptions.setArgs("MULTIGRID VARIABLE COEFFICIENT", "FALSE");
ins->pSolver->options = ins->pOptions;
ins->pSolver->dim = ins->dim;
ins->pSolver->elementType = ins->elementType;
ins->pSolver->BCType = (int*) calloc(nbrBIDs+1,sizeof(int));
memcpy(ins->pSolver->BCType,pBCType,(nbrBIDs+1)*sizeof(int));
ins->pSolver->var_coeff = 1;
ins->pSolver->coeff = ins->ellipticCoeff;
ins->pSolver->o_coeff = ins->o_ellipticCoeff;
ellipticSolveSetup(ins->pSolver, 0.0, kernelInfoP); //!!!!
// setup boundary mapping
dfloat largeNumber = 1<<20;
ins->VmapB = (int *) calloc(mesh->Nelements*mesh->Np,sizeof(int));
for (int e=0;e<mesh->Nelements;e++) {
for (int n=0;n<mesh->Np;n++) ins->VmapB[n+e*mesh->Np] = largeNumber;
}
ins->EToB = (int*) calloc(mesh->Nelements*mesh->Nfaces, sizeof(int));
int cnt = 0;
for (int e=0;e<mesh->Nelements;e++) {
for (int f=0;f<mesh->Nfaces;f++) {
int bc = bcMap::id(mesh->EToB[f+e*mesh->Nfaces], "velocity");
ins->EToB[cnt] = bc;
if (bc>0) {
for (int n=0;n<mesh->Nfp;n++) {
int fid = mesh->faceNodes[n+f*mesh->Nfp];
ins->VmapB[fid+e*mesh->Np] = mymin(bc,ins->VmapB[fid+e*mesh->Np]); // Dirichlet wins
}
}
cnt++;
}
}
ogsGatherScatter(ins->VmapB, ogsInt, ogsMin, mesh->ogs);
for (int n=0;n<mesh->Nelements*mesh->Np;n++) {
if (ins->VmapB[n] == largeNumber) ins->VmapB[n] = 0;
}
ins->o_EToB = mesh->device.malloc(mesh->Nelements*mesh->Nfaces*sizeof(int),ins->EToB);
ins->o_VmapB = mesh->device.malloc(mesh->Nelements*mesh->Np*sizeof(int), ins->VmapB);
// build inverse mass matrix
dfloat *lumpedMassMatrix = (dfloat*) calloc(mesh->Nelements*mesh->Np, sizeof(dfloat));
for(hlong e=0;e<mesh->Nelements;++e)
for(int n=0;n<mesh->Np;++n)
lumpedMassMatrix[e*mesh->Np+n] = mesh->vgeo[e*mesh->Np*mesh->Nvgeo+JWID*mesh->Np+n];
ogsGatherScatter(lumpedMassMatrix, ogsDfloat, ogsAdd, mesh->ogs);
for(int n=0;n<mesh->Np*mesh->Nelements;++n)
lumpedMassMatrix[n] = 1./lumpedMassMatrix[n];
ins->o_InvM =
mesh->device.malloc(mesh->Nelements*mesh->Np*sizeof(dfloat), lumpedMassMatrix);
// build kernels
string fileName, kernelName ;
const string suffix = "Hex3D";
const string oklpath = install_dir + "/okl/";
for (int r=0;r<2;r++){
if ((r==0 && mesh->rank==0) || (r==1 && mesh->rank>0)) {
fileName = oklpath + "insAdvection" + suffix + ".okl";
kernelName = "insStrongAdvectionVolume" + suffix;
ins->advectionStrongVolumeKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
kernelName = "insStrongAdvectionCubatureVolume" + suffix;
ins->advectionStrongCubatureVolumeKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insAx" + suffix + ".okl";
kernelName = "insAx" + suffix;
ins->AxKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = oklpath + "insCurl" + suffix + ".okl";
kernelName = "insCurl" + suffix;
ins->curlKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insMassMatrix" + ".okl";
kernelName = "insMassMatrix" + suffix;
ins->massMatrixKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
kernelName = "insInvMassMatrix" + suffix;
ins->invMassMatrixKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insGradient" + suffix + ".okl";
kernelName = "insGradientVolume" + suffix;
ins->gradientVolumeKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = oklpath + "insSumMakef" + suffix + ".okl";
kernelName = "insSumMakef" + suffix;
ins->sumMakefKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insDivergence" + suffix + ".okl";
kernelName = "insDivergenceVolumeTOMBO" + suffix;
ins->divergenceVolumeKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfoBC);
kernelName = "insDivergenceSurfaceTOMBO" + suffix;
ins->divergenceSurfaceKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfoBC);
fileName = oklpath + "insPressureRhs" + suffix + ".okl";
kernelName = "insPressureRhsTOMBO" + suffix;
ins->pressureRhsKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insPressureBC" + suffix + ".okl";
kernelName = "insPressureAddBCTOMBO" + suffix;
ins->pressureAddBCKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfoBC);
fileName = oklpath + "insPressureUpdate" + ".okl";
kernelName = "insPressureUpdateTOMBO";
ins->pressureUpdateKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = oklpath + "insVelocityRhs" + suffix + ".okl";
kernelName = "insVelocityRhsTOMBO" + suffix;
ins->velocityRhsKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insVelocityBC" + suffix + ".okl";
kernelName = "insVelocityBC" + suffix;
ins->velocityRhsBCKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfoBC);
kernelName = "insVelocityAddBC" + suffix;
ins->velocityAddBCKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfoBC);
fileName = oklpath + "insSubCycle" + suffix + ".okl";
kernelName = "insSubCycleStrongCubatureVolume" + suffix;
ins->subCycleStrongCubatureVolumeKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
kernelName = "insSubCycleStrongVolume" + suffix;
ins->subCycleStrongVolumeKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insSubCycleRKUpdate" + ".okl";
kernelName = "insSubCycleLSERKUpdate";
if(ins->SNrk==4) kernelName = "insSubCycleERKUpdate";
ins->subCycleRKUpdateKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insVelocityExt" + ".okl";
kernelName = "insVelocityExt";
ins->velocityExtKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
// ===========================================================================
fileName = install_dir + "/libparanumal/okl/scaledAdd.okl";
kernelName = "scaledAddwOffset";
ins->scaledAddKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = install_dir + "/libparanumal/okl/addScalar.okl";
kernelName = "setScalar";
ins->setScalarKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "math" + ".okl";
kernelName = "max";
ins->maxKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
// ===========================================================================
fileName = oklpath + "insFilterRT" + suffix + ".okl";
kernelName = "insFilterRT" + suffix;
ins->filterRTKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insCfl" + suffix + ".okl";
kernelName = "insCfl" + suffix;
ins->cflKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insQtl" + suffix + ".okl";
kernelName = "insQtl" + suffix;
ins->qtlKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "insPressureAddQtl" + ".okl";
kernelName = "insPressureAddQtl";
ins->pressureAddQtlKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = oklpath + "setEllipticCoeff.okl";
kernelName = "setEllipticCoeff";
ins->setEllipticCoeffKernel =
mesh->device.buildKernel(fileName, kernelName, kernelInfo);
kernelName = "setEllipticCoeffPressure";
ins->setEllipticCoeffPressureKernel =
mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = oklpath + "insPQ.okl";
kernelName = "insPQ";
ins->pqKernel =
mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = oklpath + "insNC.okl";
kernelName = "insNC";
ins->ncKernel =
mesh->device.buildKernel(fileName, kernelName, kernelInfo);
}
MPI_Barrier(mesh->comm);
}
// setup scalar solver
if(ins->Nscalar) {
mesh_t *msh;
(ins->cht) ? msh = ins->meshT : msh = ins->mesh;
ins->cds = cdsSetup(ins, msh, options, kernelInfoS);
}
return ins;
}
cds_t *cdsSetup(ins_t *ins, mesh_t *mesh, setupAide &options, occa::properties &kernelInfoH)
{
cds_t *cds = new cds_t();
cds->mesh = mesh;
if (mesh->rank==0)
cout << "==================SCALAR SETUP===========================\n";
string install_dir;
install_dir.assign(getenv("NEKRS_INSTALL_DIR"));
// set mesh, options
cds->meshV = ins->mesh;
cds->elementType = ins->elementType;
cds->dim = ins->dim;
cds->NVfields = ins->NVfields;
cds->NSfields = ins->Nscalar;
cds->extbdfA = ins->extbdfA;
cds->extbdfB = ins->extbdfB;
cds->extbdfC = ins->extbdfC;
cds->extC = ins->extC;
cds->Nstages = ins->Nstages;
cds->temporalOrder = ins->temporalOrder;
cds->g0 = ins->g0;
cds->o_usrwrk = ins->o_usrwrk;
dlong Nlocal = mesh->Np*mesh->Nelements;
dlong Ntotal = mesh->Np*(mesh->Nelements+mesh->totalHaloPairs);
cds->Nlocal = Nlocal;
cds->Ntotal = Ntotal;
cds->vFieldOffset = ins->fieldOffset;
cds->fieldOffset = ins->fieldOffset;
cds->Nblock = (Nlocal+blockSize-1)/blockSize;
cds->o_wrk0 = ins->o_wrk0;
cds->o_wrk1 = ins->o_wrk1;
cds->o_wrk2 = ins->o_wrk2;
cds->o_wrk3 = ins->o_wrk3;
cds->o_wrk4 = ins->o_wrk4;
cds->o_wrk5 = ins->o_wrk5;
cds->o_wrk6 = ins->o_wrk6;
// Solution storage at interpolation nodes
cds->U = ins->U; // Point to INS side Velocity
cds->S = (dfloat*) calloc(cds->NSfields*(cds->Nstages+0)*cds->fieldOffset,sizeof(dfloat));
cds->BF = (dfloat*) calloc(cds->NSfields*cds->fieldOffset,sizeof(dfloat));
cds->FS = (dfloat*) calloc(cds->NSfields*(cds->Nstages+1)*cds->fieldOffset,sizeof(dfloat));
// Use Nsubsteps if INS does to prevent stability issues
cds->Nsubsteps = ins->Nsubsteps;
if(cds->Nsubsteps){
cds->SNrk = ins->SNrk;
cds->Srka = ins->Srka;
cds->Srkb = ins->Srkb;
cds->Srkc = ins->Srkc;
cds->o_Srka = ins->o_Srka;
cds->o_Srkb = ins->o_Srkb;
}
cds->startTime =ins->startTime;
cds->dt = ins->dt;
cds->idt = 1.0/cds->dt;
cds->sdt = ins->sdt;
cds->NtimeSteps = ins->NtimeSteps;
cds->prop = (dfloat*) calloc(cds->NSfields*2*cds->fieldOffset,sizeof(dfloat));
for(int is=0; is<cds->NSfields; is++) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << is;
string sid = ss.str();
if(options.compareArgs("SCALAR" + sid + " SOLVER", "NONE")) continue;
dfloat diff = 1;
dfloat rho = 1;
options.getArgs("SCALAR" + sid + " DIFFUSIVITY", diff);
options.getArgs("SCALAR" + sid + " DENSITY", rho);
const dlong off = cds->NSfields*cds->fieldOffset;
for (int e=0;e<mesh->Nelements;e++) {
for (int n=0;n<mesh->Np;n++) {
cds->prop[0*off + is*cds->fieldOffset + e*mesh->Np + n] = diff;
cds->prop[1*off + is*cds->fieldOffset + e*mesh->Np + n] = rho;
}
}
}
cds->o_prop = mesh->device.malloc(cds->NSfields*2*cds->fieldOffset*sizeof(dfloat), cds->prop);
cds->o_diff = cds->o_prop.slice(0*cds->NSfields*cds->fieldOffset*sizeof(dfloat));
cds->o_rho = cds->o_prop.slice(1*cds->NSfields*cds->fieldOffset*sizeof(dfloat));
cds->var_coeff = 1; // use always var coeff elliptic
cds->ellipticCoeff = ins->ellipticCoeff;
cds->o_ellipticCoeff = ins->o_ellipticCoeff;
cds->o_U = ins->o_U;
cds->o_Ue = ins->o_Ue;
cds->o_S = mesh->device.malloc(cds->NSfields*(cds->Nstages+0)*cds->fieldOffset*sizeof(dfloat), cds->S);
cds->o_BF = mesh->device.malloc(cds->NSfields*cds->fieldOffset*sizeof(dfloat), cds->BF);
cds->o_FS = mesh->device.malloc(cds->NSfields*(cds->Nstages+1)*cds->fieldOffset*sizeof(dfloat), cds->FS);
//make option objects for elliptc solvers
cds->options = options;
cds->options.setArgs("KRYLOV SOLVER", options.getArgs("SCALAR SOLVER"));
cds->options.setArgs("DISCRETIZATION", options.getArgs("SCALAR DISCRETIZATION"));
cds->options.setArgs("BASIS", options.getArgs("SCALAR BASIS"));
/*
cds->options.setArgs("MULTIGRID COARSENING", options.getArgs("SCALAR MULTIGRID COARSENING"));
cds->options.setArgs("MULTIGRID SMOOTHER", options.getArgs("SCALAR MULTIGRID SMOOTHER"));
cds->options.setArgs("MULTIGRID CHEBYSHEV DEGREE", options.getArgs("SCALAR MULTIGRID CHEBYSHEV DEGREE"));
cds->options.setArgs("PARALMOND CYCLE", options.getArgs("SCALAR PARALMOND CYCLE"));
cds->options.setArgs("PARALMOND SMOOTHER", options.getArgs("SCALAR PARALMOND SMOOTHER"));
cds->options.setArgs("PARALMOND PARTITION", options.getArgs("SCALAR PARALMOND PARTITION"));
cds->options.setArgs("PARALMOND CHEBYSHEV DEGREE", options.getArgs("SCALAR PARALMOND CHEBYSHEV DEGREE"));
cds->options.setArgs("PARALMOND AGGREGATION STRATEGY", options.getArgs("SCALAR PARALMOND AGGREGATION STRATEGY"));
*/
cds->options.setArgs("DEBUG ENABLE OGS", "1");
cds->options.setArgs("DEBUG ENABLE REDUCTIONS", "1");
const int nbrBIDs = bcMap::size();
int *sBCType = (int*) calloc(nbrBIDs+1, sizeof(int));
cds->TOL = 1e-6;
for (int is=0; is<cds->NSfields; is++) {
mesh_t *mesh;
(is) ? mesh = cds->meshV : mesh = cds->mesh; // only first scalar can be a CHT mesh
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << is;
string sid = ss.str();
cds->compute[is] = 1;
if (options.compareArgs("SCALAR" + sid + " SOLVER", "NONE")) {
cds->compute[is] = 0;
continue;
}
for (int bID=1; bID <= nbrBIDs; bID++) {
string bcTypeText(bcMap::text(bID, "scalar" + sid));
if(mesh->rank == 0) printf("bID %d -> bcType %s\n", bID, bcTypeText.c_str());
sBCType[bID] = bcMap::type(bID, "scalar" + sid);
}
cds->options.setArgs("PRECONDITIONER", options.getArgs("SCALAR" + sid + " PRECONDITIONER"));
cds->options.setArgs("SOLVER TOLERANCE", options.getArgs("SCALAR" + sid + " SOLVER TOLERANCE"));
cds->solver[is] = new elliptic_t();
cds->solver[is]->wrkOffset = ins->fieldOffset;
cds->solver[is]->wrk = scratch + ins->ellipticWrkOffset;
cds->solver[is]->o_wrk = o_scratch.slice(ins->ellipticWrkOffset*sizeof(dfloat));
cds->solver[is]->mesh = mesh;
cds->solver[is]->options = cds->options;
cds->solver[is]->dim = cds->dim;
cds->solver[is]->elementType = cds->elementType;
cds->solver[is]->BCType = (int*) calloc(nbrBIDs+1,sizeof(int));
memcpy(cds->solver[is]->BCType,sBCType,(nbrBIDs+1)*sizeof(int));
cds->solver[is]->var_coeff = cds->var_coeff;
cds->solver[is]->coeff = cds->ellipticCoeff;
cds->solver[is]->o_coeff = cds->o_ellipticCoeff;
const dfloat lambda = 1; // not used if var_coeff
ellipticSolveSetup(cds->solver[is], lambda, kernelInfoH);
// setup boundary mapping
dfloat largeNumber = 1<<20;
cds->mapB[is] = (int *) calloc(mesh->Nelements*mesh->Np,sizeof(int));
int *mapB = cds->mapB[is];
for (int e=0;e<mesh->Nelements;e++) {
for (int n=0;n<mesh->Np;n++) mapB[n+e*mesh->Np] = largeNumber;
}
cds->EToB[is] = (int*) calloc(mesh->Nelements*mesh->Nfaces, sizeof(int));
int *EToB = cds->EToB[is];
int cnt = 0;
for (int e=0;e<mesh->Nelements;e++) {
for (int f=0;f<mesh->Nfaces;f++) {
int bc = bcMap::id(mesh->EToB[f+e*mesh->Nfaces], "scalar" + sid);
EToB[cnt] = bc;
if (bc>0) {
for (int n=0;n<mesh->Nfp;n++) {
int fid = mesh->faceNodes[n+f*mesh->Nfp];
if(bc != 1 && mapB[fid+e*mesh->Np] != 1)
mapB[fid+e*mesh->Np] = mapB[fid+e*mesh->Np]; // for Neumann BCs do nothing
else
mapB[fid+e*mesh->Np] = mymin(bc,mapB[fid+e*mesh->Np]); // Dirichlet wins
}
}
cnt++;
}
}
ogsGatherScatter(mapB, ogsInt, ogsMin, mesh->ogs);
for (int n=0;n<mesh->Nelements*mesh->Np;n++) {
if (mapB[n] == largeNumber) mapB[n] = 0;
}
cds->o_EToB[is] = mesh->device.malloc(mesh->Nelements*mesh->Nfaces*sizeof(int), EToB);
cds->o_mapB[is] = mesh->device.malloc(mesh->Nelements*mesh->Np*sizeof(int), mapB);
}
// build inverse mass matrix
dfloat *lumpedMassMatrix = (dfloat*) calloc(mesh->Nelements*mesh->Np, sizeof(dfloat));
for(hlong e=0;e<mesh->Nelements;++e){
for(int n=0;n<mesh->Np;++n){
lumpedMassMatrix[e*mesh->Np+n] = mesh->vgeo[e*mesh->Np*mesh->Nvgeo+JWID*mesh->Np+n];
}
}
ogsGatherScatter(lumpedMassMatrix, ogsDfloat, ogsAdd, mesh->ogs);
for(int n=0;n<mesh->Np*mesh->Nelements;++n)
lumpedMassMatrix[n] = 1./lumpedMassMatrix[n];
cds->o_InvM =
mesh->device.malloc(mesh->Nelements*mesh->Np*sizeof(dfloat), lumpedMassMatrix);
cds->o_InvMV = ins->o_InvM;
free(lumpedMassMatrix);
// time stepper
dfloat rkC[4] = {1.0, 0.0, -1.0, -2.0};
cds->o_rkC = ins->o_rkC;
cds->o_extbdfA = ins->o_extbdfA;
cds->o_extbdfB = ins->o_extbdfB;
cds->o_extbdfC = ins->o_extbdfC;
cds->o_extC = ins->o_extC;
cds->o_prkA = ins->o_extbdfC;
cds->o_prkB = ins->o_extbdfC;
// build kernels
occa::properties kernelInfo = *ins->kernelInfo;
occa::properties kernelInfoBC = kernelInfo;
//kernelInfo["defines/" "p_NSfields"] = cds->NSfields;
const string bcDataFile = install_dir + "/include/insBcData.h";
kernelInfoBC["includes"] += bcDataFile.c_str();
string boundaryHeaderFileName;
options.getArgs("DATA FILE", boundaryHeaderFileName);
kernelInfoBC["includes"] += realpath(boundaryHeaderFileName.c_str(), NULL);
string fileName, kernelName;
const string suffix = "Hex3D";
for (int r=0;r<2;r++){
if ((r==0 && mesh->rank==0) || (r==1 && mesh->rank>0)) {
fileName = install_dir + "/okl/cdsAdvection" + suffix + ".okl";
kernelName = "cdsStrongAdvectionVolume" + suffix;
cds->advectionStrongVolumeKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
kernelName = "cdsStrongAdvectionCubatureVolume" + suffix;
cds->advectionStrongCubatureVolumeKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
// ===========================================================================
fileName = install_dir + "/libparanumal/okl/addScalar.okl";
kernelName = "setScalar";
cds->setScalarKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = install_dir + "/okl/cdsSumMakef" + suffix + ".okl";
kernelName = "cdsSumMakef" + suffix;
cds->sumMakefKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = install_dir + "/okl/cdsHelmholtzBC" + suffix + ".okl";
kernelName = "cdsHelmholtzBC" + suffix;
cds->helmholtzRhsBCKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfoBC);
kernelName = "cdsHelmholtzAddBC" + suffix;
cds->helmholtzAddBCKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfoBC);
fileName = install_dir + "/okl/setEllipticCoeff.okl";
kernelName = "setEllipticCoeff";
cds->setEllipticCoeffKernel =
mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = install_dir + "/okl/cdsMassMatrix.okl";
kernelName = "cdsMassMatrix" + suffix;
cds->massMatrixKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
kernelName = "cdsInvMassMatrix" + suffix;
cds->invMassMatrixKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = install_dir + "/okl/cdsFilterRT" + suffix + ".okl";
kernelName = "cdsFilterRT" + suffix;
cds->filterRTKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
if(cds->Nsubsteps){
fileName = install_dir + "/libparanumal/okl/scaledAdd.okl";
kernelName = "scaledAddwOffset";
cds->scaledAddKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
fileName = install_dir + "/okl/cdsSubCycle" + suffix + ".okl";
kernelName = "cdsSubCycleStrongCubatureVolume" + suffix;
cds->subCycleStrongCubatureVolumeKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
kernelName = "cdsSubCycleStrongVolume" + suffix;
cds->subCycleStrongVolumeKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
fileName = install_dir + "/okl/cdsSubCycleRKUpdate.okl";
kernelName = "cdsSubCycleLSERKUpdate";
if(cds->SNrk==4) kernelName = "cdsSubCycleERKUpdate";
cds->subCycleRKUpdateKernel = mesh->device.buildKernel(fileName, kernelName, kernelInfo);
}
fileName = install_dir + "/okl/insVelocityExt" + ".okl";
kernelName = "insVelocityExt";
cds->velocityExtKernel =
mesh->device.buildKernel(fileName.c_str(), kernelName.c_str(), kernelInfo);
}
MPI_Barrier(mesh->comm);
}
return cds;
}
|
<filename>maven2.demo/src/main/java/service/LojasService.java
package service;
import dao.LojasDAO;
import model.Lojas;
import spark.Request;
import spark.Response;
public class LojasService {
private LojasDAO LojasDAO;
public LojasService() {
LojasDAO = new LojasDAO();
LojasDAO.conectar();
}
public Object add(Request request, Response response) {
String nome = request.queryParams("descricao");
String notaConsumidor = (request.queryParams("preco"));
String NumReclamacoes = (request.queryParams("quantidade"));
String NumReclamacoesResp = (request.queryParams("dataFabricacao"));
String porcProblemasResol = (request.queryParams("dataValidade"));
Lojas loja = new Lojas(nome, notaConsumidor, NumReclamacoes, NumReclamacoesResp, porcProblemasResol);
LojasDAO.inserirLoja(loja);
response.status(201); // 201 Created
return nome;
}
/*public Object get(Request request, Response response) {
String nome = request.params(":nome");
Lojas loja = (Lojas) LojasDAO.getLoja(nome);
if (loja != null) {
response.header("Content-Type", "application/xml");
response.header("Content-Encoding", "UTF-8");
return "<produto>\n" +
"\t<id>" + loja.getNome() + "</id>\n" +
"\t<descricao>" + loja.getNotaConsumidor() + "</descricao>\n" +
"\t<preco>" + loja.getNumReclamacoes() + "</preco>\n" +
"\t<quantidade>" + loja.getNumReclamacoesResp() + "</quantidade>\n" +
"\t<fabricacao>" + loja.getPorcProblemasResolv() + "</fabricacao>\n" +
"</produto>\n";
} else {
response.status(404); // 404 Not found
return "Produto " + nome + " não encontrado.";
}
}
public Object update(Request request, Response response) {
String nome = request.params(":nome");
Lojas produto = (Lojas) LojasDAO.get(nome);
if (produto != null) {
produto.setNome(request.queryParams("descricao"));
produto.setNotaConsumidor((request.queryParams("preco")));
produto.setNumReclamacoes((request.queryParams("quantidade")));
produto.setNumReclamacoesResp((request.queryParams("dataFabricacao")));
produto.setPorcProblemasResolv((request.queryParams("dataValidade")));
LojasDAO.atualizarLoja(produto);
return nome;
} else {
response.status(404); // 404 Not found
return "Produto não encontrado.";
}
}
public Object remove(Request request, Response response) {
String nome = request.params(":nome");
Lojas produto = (Lojas) LojasDAO.get(nome);
if (produto != null) {
LojasDAO.excluirLoja(produto.getNome());
response.status(200); // success
return nome;
} else {
response.status(404); // 404 Not found
return "Produto não encontrado.";
}
}*/
public Object getAll(Request request, Response response) {
StringBuffer returnValue = new StringBuffer("<usuarios type=\"array\">");
for (Lojas usuario : LojasDAO.getLojas()) {
returnValue.append("\n<usuario>\n" +
"\t<username>" + usuario.getNome() + "</username>\n" +
"\t<email>" + usuario.getNome() + "</email>\n" +
"\t<senha>" + usuario.getNome() + "</senha>\n" +
"</usuario>\n");
}
returnValue.append("</usuarios>");
response.header("Content-Type", "application/xml");
response.header("Content-Encoding", "UTF-8");
return returnValue.toString();
}
}
|
import random
randomNumber = random.randint(1, 5)
print(randomNumber)
|
import { ValidationErrorCause } from '../ValidationError';
import { ValueValidatorOptions } from './ValueValidatorOptions';
export function validate(opts: ValueValidatorOptions): ValidationErrorCause | undefined {
const { options, key, targetValue } = opts;
const validator = options?.validator?.validator;
if (!validator) {
return undefined;
}
const validatorOptions = options?.validator?.options;
const value = ((): unknown => {
if (validatorOptions?.asString) {
if (targetValue === undefined || targetValue === null) {
return '';
} else {
return String(targetValue);
}
}
return targetValue;
})();
let errorCause: ValidationErrorCause | undefined = undefined;
try {
const res = validator(value);
if (res === false) {
errorCause = { key, error: `${key} validation failed` };
} else if (res instanceof Error) {
errorCause = { key, error: res };
}
} catch (err) {
if (err instanceof Error || typeof err === 'string') {
errorCause = { key, error: err };
} else {
errorCause = { key, error: 'Unknown error' };
}
}
return errorCause;
}
|
def find_min(arr):
min = arr[0]
for num in arr:
if num < min:
min = num
return min
find_min([45, 12, 8, 33, 19])
|
# this will fail with _main undefined, but should work otherwise
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/clang++ -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk PullToRefreshView.m -arch armv7 -framework Foundation -framework UIKit -miphoneos-version-min=4.0 -framework QuartzCore
|
pkgname=swc
deps="wld:pixman"
pkgver=intel-tiling
fetch() {
curl -L "https://github.com/michaelforney/swc/archive/refs/heads/intel-tiling.tar.gz" -o $pkgname-$pkgver.tar.xz
tar -xf $pkgname-$pkgver.tar.xz
cp ../config.mk .
}
build() {
cd $pkgname-$pkgver
cp ../config.mk .
gmake PREFIX=/usr CC=cc
}
package() {
cd $pkgname-$pkgver
gmake install DESTDIR=$pkgdir PREFIX=/usr
}
license() {
cd $pkgname-$pkgver
cat LICENSE
}
|
<filename>lib/x12/empty.rb
module X12
# Class indicating the absense of any X12 element, be it loop, segment, or anything else like that.
class Empty < Base
# Create a new empty
def initialize
super(nil, [])
end
# Returns an empty string
# @return [String]
def to_s
return ''
end
end
end
|
def sort_list(list):
for i in range(len(list)):
for j in range(i+1, len(list)):
if list[i] > list[j]:
list[i], list[j] = list[j], list[i]
return list
my_list = [9, 3, 6, 7, 1]
my_list = sort_list(my_list)
print(my_list)
|
var searchData=
[
['placeformsection_169',['placeFormSection',['../class_application.html#a81f066df3ca1cdae16028a15a952a94b',1,'Application']]],
['placemenusection_170',['placeMenuSection',['../class_application.html#abb3ba6361b4dc0042031ea66ae6fe544',1,'Application']]]
];
|
<reponame>fire-punch/Fyp<filename>js/teat_seat.js<gh_stars>0
const container = document.querySelector('.container');
const count = document.querySelector('#count');
const total = document.querySelector('#total');
const seats = document.querySelectorAll('.rows .seat:not(occupied)');
const movieSelect = document.querySelector('#movie');
let moviePrice = +movieSelect.value;
localData();
movieSelect.addEventListener('change',e=>{
moviePrice = e.target.value;
movieData(e.target.selectedIndex,moviePrice);
updateUi();
})
function movieData(movieIndex,moviePrice){
localStorage.setItem('movieIndex',movieIndex);
localStorage.moviePrice = moviePrice;
}
// dat from local storage
function localData(){
const selectedSeats = JSON.parse(localStorage.getItem('selectedIndex'));//save in to array
if(selectedSeats !== null && selectedSeats.length > 0){
seats.forEach((seat,index)=>{
if(selectedSeats.indexOf(index)>-1){
seat.classList.add('selected');
}
})
}
if(localStorage.movieIndex !== null){
moviePrice = localStorage.moviePrice;
movieSelect.selectedIndex = localStorage.movieIndex;
}
}
function updateUi(){
const selectedSeats = document.querySelectorAll('.rows .seat.selected');
count.innerText = selectedSeats.length;
total.innerText = moviePrice * selectedSeats.length;
const selectedIndex = [...selectedSeats].map(seat=>{
return [...seats].indexOf(seat);
});
console.log(selectedIndex);
localStorage.setItem('selectedIndex', JSON.stringify(selectedIndex))
}
container.addEventListener('click',e=>{
if(e.target.classList.contains('seat') &&
!e.target.classList.contains('occupied')){
e.target.classList.toggle('selected')
updateUi();
}
})
updateUi();
|
<filename>src/parser/jobs/nin/modules/TrickAttackUsage.tsx
import {Trans, Plural} from '@lingui/react'
import {ActionLink} from 'components/ui/DbLink'
import {ActionKey} from 'data/ACTIONS'
import {Event, Events} from 'event'
import {Analyser} from 'parser/core/Analyser'
import {EventHook} from 'parser/core/Dispatcher'
import {filter} from 'parser/core/filter'
import {dependency} from 'parser/core/Injectable'
import {Data} from 'parser/core/modules/Data'
import Downtime from 'parser/core/modules/Downtime'
import Suggestions, {TieredSuggestion, SEVERITY} from 'parser/core/modules/Suggestions'
import React from 'react'
import {matchClosestHigher} from 'utilities'
const OPTIMAL_GCD_COUNT = 5 // Opener should be Suiton > AE combo > SE before Trick
const MUDRAS: ActionKey[] = [
'TEN',
'TEN_KASSATSU',
'CHI',
'CHI_KASSATSU',
'JIN',
'JIN_KASSATSU',
]
export class TrickAttackUsage extends Analyser {
static override handle = 'taUsage'
@dependency private data!: Data
@dependency private downtime!: Downtime
@dependency private suggestions!: Suggestions
private mudraActions: number[] = []
private taCasts: number[] = []
private lostTime: number = 0
private gcdCount: number = 0
private castHook?: EventHook<Events['action']>
override initialise() {
this.mudraActions = MUDRAS.map(k => this.data.actions[k].id)
const playerFilter = filter<Event>().source(this.parser.actor.id)
// Hook to track casts before the first Trick for the opener timing suggestion
this.castHook = this.addEventHook(playerFilter.type('action'), this.onCast)
this.addEventHook(playerFilter.type('action').action(this.data.actions.TRICK_ATTACK.id), this.onTrickAttack)
this.addEventHook('complete', this.onComplete)
}
private onCast(event: Events['action']) {
const action = this.data.getAction(event.action)
if (event.timestamp >= this.parser.pull.timestamp && action?.onGcd && !this.mudraActions.includes(action.id)) {
// Don't count the individual mudras as GCDs for this - they'll make the count screw if Suiton wasn't set up pre-pull
this.gcdCount++
}
}
private onTrickAttack(event: Events['action']) {
if (this.castHook != null) {
this.removeEventHook(this.castHook)
this.castHook = undefined
}
if (this.taCasts.length > 0) {
const lastCast = this.taCasts[this.taCasts.length - 1]
const taAvailable = lastCast + this.data.actions.TRICK_ATTACK.cooldown
const downtime = this.downtime.getDowntime(taAvailable, event.timestamp)
this.lostTime += Math.max((event.timestamp - taAvailable) - downtime, 0)
}
this.taCasts.push(event.timestamp)
}
private onComplete() {
if (this.taCasts.length > 0) {
const lastCast = this.taCasts[this.taCasts.length - 1]
// lostTime is only the time they were actually holding it off CD, but we want to add in the CD time of the final cast for
// calculating how many theoretical casts were lost. For example, 20s of holding + last cast 40s before the end of the fight
// would mean that they could've squeezed in an extra cast with perfect timing.
const lostCasts = Math.floor((this.lostTime + (this.parser.currentEpochTimestamp - lastCast)) / this.data.actions.TRICK_ATTACK.cooldown)
this.suggestions.add(new TieredSuggestion({
icon: this.data.actions.TRICK_ATTACK.icon,
content: <Trans id="nin.ta-usage.suggestions.missed.content">
Avoid holding <ActionLink action="TRICK_ATTACK"/> for extended periods of time. It's typically ideal to use it as close to on cooldown as possible in order to keep it aligned with all the other raid buffs and personal burst windows, as well as maximizing the number of uses per fight.
</Trans>,
value: lostCasts,
tiers: {
1: SEVERITY.MEDIUM,
2: SEVERITY.MAJOR,
},
why: <Trans id="nin.ta-usage.suggestions.missed.why">
You delayed Trick Attack for a cumulative {this.parser.formatDuration(this.lostTime)}, costing you <Plural value={lostCasts} one="# potential use" other="# potential uses"/>.
</Trans>,
}))
const distanceFromOptimal = Math.abs(OPTIMAL_GCD_COUNT - this.gcdCount)
this.suggestions.add(new TieredSuggestion({
icon: this.data.actions.TRICK_ATTACK.icon,
content: <Trans id="nin.ta-usage.suggestions.opener.content">
Avoid unconventional timings for your first <ActionLink action="TRICK_ATTACK"/> of the fight in order to line it up with all the other raid and personal buffs. In most openers, Trick Attack should be weaved in approximately 8-9 seconds into the fight.
</Trans>,
value: distanceFromOptimal,
tiers: {
1: SEVERITY.MEDIUM,
2: SEVERITY.MAJOR,
},
why: <Trans id="nin.ta-usage.suggestions.opener.why">
Your first Trick Attack was <Plural value={this.gcdCount} one="# GCD" other="# GCDs"/> into your opener.
</Trans>,
}))
}
// WHY ARE YOU EVEN PLAYING THIS JOB
this.suggestions.add(new TieredSuggestion({
icon: this.data.actions.TRICK_ATTACK.icon,
content: <Trans id="nin.ta-usage.suggestions.none.content">
<ActionLink action="TRICK_ATTACK"/> is the single most powerful raid buff in your kit and should be used on cooldown, or as close to it as possible depending on the flow of the fight.
</Trans>,
value: this.taCasts.length,
tiers: {
0: SEVERITY.MAJOR,
},
matcher: matchClosestHigher,
why: <Trans id="nin.ta-usage.suggestions.none.why">
You didn't use Trick Attack once the entire fight.
</Trans>,
}))
}
}
|
<filename>mashidcore/Mashid.UnitTest/wwwroot/app/es2015/demo_screenshot.UnitTest.Jasmine.js
describe("screenshot", function () {
it("screenshot for ALT-SHIFT-F10", function () {
// with electron ...
var element = document.getElementsByTagName("body");
console.log(element);
console.log(element[0]);
element[0].style.background = '#500';
});
});
|
<reponame>arcadium-dev/core<gh_stars>0
// Copyright 2021 arcadium.dev <<EMAIL>>
//
// 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.
package config // import "arcadium.dev/core/config"
import (
"crypto/tls"
"crypto/x509"
"os"
"arcadium.dev/core/errors"
)
// TLS contains the information necessary to create a tls.Config.
type TLS interface {
// Cert returns the file name of the PEM encoded public key.
Cert() string
// Key returns the file name of the PEM encoded private key.
Key() string
// CACert returns the file name of the PEM encoded public key of the client CA.
CACert() string
}
// NewTLS will create a *tls.Config given the config and options. This will
// return an error if there is a problem loading the required certificate files.
// If the WithMTLS option is specified, a client CA cert is required.
func NewTLS(config TLS, opts ...TLSOption) (*tls.Config, error) {
cfg := &tls.Config{}
for _, opt := range opts {
opt.apply(cfg)
}
// Load the server certificate.
cert, err := tls.LoadX509KeyPair(config.Cert(), config.Key())
if err != nil {
return nil, errors.Wrap(err, "Failed to load server certificate")
}
cfg.Certificates = append(cfg.Certificates, cert)
// If we are doing mTLS...
if cfg.ClientAuth == tls.RequireAndVerifyClientCert {
// ... and we have a CA cert
caCertCfg := config.CACert()
if caCertCfg != "" {
// ... create a CA certificate pool and add client's CA cert to it.
cfg.ClientCAs = x509.NewCertPool()
caCert, err := os.ReadFile(caCertCfg)
if err != nil {
return nil, errors.Wrap(err, "Failed to load the client CA certificate")
}
cfg.ClientCAs.AppendCertsFromPEM(caCert)
}
}
return cfg, nil
}
type (
// TLSOption provides options for configuring the creation of a tls.Config.
TLSOption interface {
apply(*tls.Config)
}
tlsOption struct {
f func(*tls.Config)
}
)
func newTLSOption(f func(*tls.Config)) tlsOption {
return tlsOption{f: f}
}
func (o tlsOption) apply(cfg *tls.Config) {
o.f(cfg)
}
// WithMTLS will setup the tls.Config to require and verify client connections.
func WithMTLS() TLSOption {
return newTLSOption(func(cfg *tls.Config) {
cfg.ClientAuth = tls.RequireAndVerifyClientCert
})
}
|
describe("bad username login", function() {
it("fails to login", function() {
cy.visit("/login")
cy.get("#login-email")
.type("<EMAIL>")
.should("have.value", "<EMAIL>")
cy.get("#login-password")
.type("<PASSWORD>")
.should("have.value", "<PASSWORD>")
cy.contains("Sign In").click()
cy.get(".notifications")
.contains("fail")
cy.url().should("include", "/login")
})
})
describe("bad password login", function() {
it("fails to login", function() {
cy.visit("/login")
cy.get("#login-email")
.type("<EMAIL>")
.should("have.value", "<EMAIL>")
cy.get("#login-password")
.type("<PASSWORD>")
.should("have.value", "<PASSWORD>")
cy.contains("Sign In").click()
cy.get(".notifications")
.contains("fail")
cy.url().should("include", "/login")
})
})
|
<filename>test/util/contract/execute.js<gh_stars>1-10
var deasync = require('deasync');
module.exports = function(web3, method, context, params, account, gas){
var error = false;
var mined = false;
var counter = 0;
params.push({from:account||web3.eth.defaultAccount, gas:gas||4000000})
var txid = method.apply(context, params);
console.log("contract invoked : ",txid);
var timer = setInterval(function(){
var tx = web3.eth.getTransaction(txid);
if(tx.blockNumber){
mined = true;
clearInterval(timer);
console.log("transaction mined : ",tx.blockHash)
}else{
counter++;
if(counter>100000){
console.log("error : timeout");
error = true;
}
}
},500);
while(!error&&!mined)
{
deasync.runLoopOnce();
}
return !error||mined;
}
|
<gh_stars>10-100
"use strict";
const Endpoints = Object.freeze({
GetFormSchema: 'ManageWebsiteContent/GetFormSchema',
GetLanguageSchema: 'ManageWebsiteContent/GetLanguageSchemaById',
AddDataForSchema: 'ManageWebsiteContent/AddDataForSchema',
UpdateDataForSchema: 'ManageWebsiteContent/UpdateDataForSchema',
GetDataForSchema: 'ManageWebsiteContent/GetDataForSchema',
GetDataFormReferenceId: 'ManageWebsiteContent/GetDataWithReferenceId',
DeleteDataForSchema: 'ManageWebsiteContent/DeleteDataForSchema',
UploadImageForSchema:
CookieHelper.isAliCloud() ?
'https://kadmin.getkitsune-alicloud.com/k-admin/ManageWebsiteContent/SaveUploadedFileV2':
'ManageWebsiteContent/SaveUploadedFile',
GetClassesByClassType: 'ManageWebsiteContent/GetClassesByClassType',
GetDataByClassName: 'ManageWebsiteContent/GetDataByClassType',
UploadFileToSystemWebaction: 'Inbox/UploadFileToSystemWebaction',
AddDataToSystemWebaction: 'Inbox/AddDataToSystemWebaction',
SendEmail: 'ManageWebsiteContent/SendEmail',
GetWebsiteUserDetails: 'Settings/GetWebsiteUserDetails',
GetDeveloperDetails: 'ManageWebsiteContent/GetDeveloperDetails',
GetClientId: 'ManageWebsiteContent/GetWebsiteDetails',
IsCallTrackerEnabled: 'ManageWebsiteContent/IsCallTrackerEnabled',
GetCustomerName: 'ManageWebsiteContent/GetCustomerName',
GetDataByProperty: 'ManageWebsiteContent/GetDataByProperty',
GetDataByPropertyBulk: 'ManageWebsiteContent/GetDataByPropertyBulk',
});
const isWebaction = false;
Vue.component("VueFormGenerator", VueFormGenerator.component);
Vue.component('KModal', KModal);
Vue.component('k-header', KHeader);
Vue.use(VueTippy);
Vue.component('KConsoleModeHeader', KConsoleModeHeader);
const InputTypeMapping = {
0: 'text',
1: 'complex',
2: 'number',
3: 'checkbox',
4: 'date',
5: 'complex',
6: 'complex'
}
const selectorsRegex = /(name)|(title)|(header)/i;
const advancedGroupName = "_advanced";
const PropertyVisibliityStatus = {
"_kid": true,
"k_referenceid": true,
"createdon": true,
"updatedon": true,
"isarchived": true,
"userid": true,
"schemaid": true,
"websiteid": true,
"rootaliasurl": true,
"_propertyName": true,
"_parentClassName": true,
"_parentClassId": true
};
const nativeMapping = {
'str': 'text',
'boolean': 'switch',
'number': 'number',
'datetime': 'date'
};
const nativeArrayTypes = ['str', 'boolean', 'number', 'datetime'];
const primitiveTypes = ['str', 'boolean', 'number', 'datetime'];
const Modal = Object.freeze({
'DELETE': 'delete',
'UPDATE': 'update',
'UPLOAD': 'upload',
'IMAGEPROCESSOR': 'imageProcessor',
'RICHTEXTEDITOR': 'showRichTextEditorModal',
'HAVINGISSUES': 'havingIssues',
'VMNUPDATE': 'vmnUpdate',
'DELETEOBJECT': 'deleteObject',
'TEXTAREA': 'showTextAreaModal'
});
const SlidingPanelLevel = Object.freeze({
"HIDDEN": 0,
"CLASSES": 1,
"PROPERTIES": 2,
"OBJECTS": 3
});
const COMPLEX_OBJECT_TYPE = 5;
const KSTRING_OBJECT_TYPE = 7;
const ARRAY_TYPE = 1;
const OBJECT_TYPES = [COMPLEX_OBJECT_TYPE, KSTRING_OBJECT_TYPE];
const systemProperties = ['_id', '_kid', '_parentClassId', '_parentClassName', '_propertyName', 'k_referenceid', 'createdon', 'isarchived', 'updatedon', 'websiteid', '_reflectionId', 'schemaid', 'userid', ];
var referenceDataObjectTemplate = Object.freeze({
data: null,
selectedClassName: null,
selectedPropertyName: null,
level: SlidingPanelLevel.HIDDEN,
requestedClassName: null,
isForReverseReference: false,
selectedForwardReferenceItem: null,
forwardReference: {
isMultipleSelect: false,
selectedItems: [],
},
reverseReference: {
relatedClassTypes: [],
selectedItems: [],
selectedPath: null,
items: [],
propertyToRefer: null,
},
isfetchingData: false,
});
var vm = new Vue({
el: "#app",
components: {
"SlidingHeader": SlidingHeader,
"SlidingBody": SlidingBody,
"SlidingFooter": SlidingFooter,
"SlidingPanel": SlidingPanel,
"ContextPopoverMenu": ContextPopoverMenu
},
data: {
hasSchema: true,
new_site: false,
model: {},
schemaName: '',
schemaData: {},
legends: [],
spath: [],
reference_id: '',
isArray: false,
isNative: false,
isArrayForRendering: false,
history: [],
currentPropertyList: [],
currentModel: '',
currentClassName: '',
isAddingNewToArray: false,
languageSchema: [],
renderedForm: { groups: [] },
schema: {},
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true,
isDataConsoleMode: false,
systemProperties: systemProperties,
propertyMaxChars: 25,
defaultPlaceholder: '-- -- --',
objectPropertyPlaceholder: '*******',
valueMaxChars: 50,
defaultImageLink: 'https://s3.ap-south-1.amazonaws.com/kitsune-buildtest-resources/kadmin/no-image-square-placeholder.svg',
},
classesProcessed: [],
configure: {
maxChars: 50,
defaultPlaceholder: '-- -- --',
propertyMaxChars: 25,
datetimePlaceholder: 'YYYY-MM-DD'
},
areFieldsEditable: false,
delete: {
that: null,
index: null,
displayIndex: null
},
nativearray: {
arr: null
},
upload: {
isImage: false,
isError: false
},
currentPropertyGroup: {
name: '',
index: -1
},
showRemainingBreadCrumbs: false,
modalShowStatus: {
delete: false,
update: false,
upload: false,
imageProcessor: false,
showRichTextEditorModal: false,
havingIssues: false,
vmnUpdate: false,
maxArrayCountForProperty: false,
deleteObject: false,
showTextAreaModal: false,
},
richText: {
elementId: 'froalaEditor',
content: '',
requestedPropertyName: '',
froala: null
},
textArea: {
content: '',
requestedPropertyName: '',
froala: null,
},
richTextEditorOptions: {
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'align': [] }],
['clean']
],
}
},
referenceData: _.cloneDeep(referenceDataObjectTemplate),
baseSelectedGroup: null,
supportEmailForm: {
subject: 'Reporting an issue for: ' + localStorage.getItem('DOMAIN'),
message: '',
image: null,
to: [],
clientId: null
},
systemWebactions: {
supportEmail: { name: 'kadminsupportemail', authId: '<PASSWORD>' }
},
customerData: null,
isCallTrackerEnabledForWebsite: null,
vmnData: {
sameVMNNumberList: []
},
arrayPropertyMaxCountModal: {
className: null,
propertyName: null,
maxLength: null,
},
isDataConsoleMode: false,
deleteObject: {
propertyName: null,
},
currentSchemaDataPath: [],
oldModel: {}, // the oldModel can be used to get the old state of model before user edits the properties,
arrayItemPagination: {
limit: 10,
},
maxNavigationItemNumber: 3,
propertyToDelete: {},
maxArraySizeForDataFetching: 10000,
arrayPropertyFilters: {
searchFilter: null,
sortFilter: null,
ascDesc: 1,
}
},
created: function () {
var self = this;
if (isConsoleMode) {
self.isDataConsoleMode = true;
self.removeSidebar();
self.formOptions.isDataConsoleMode = true;
}
self.getUserData();
self.loadLanguageSchema();
self.isCallTrackerEnabled();
self.isCallTrackerEnabled();
toastr.options = {
"positionClass": "toast-bottom-right"
};
},
computed: {
currentPropertyName() {
var currentProperty = _.last(this.history);
if (currentProperty) {
return this.formatPropertyName(currentProperty.displayName);
}
return "Home";
},
deleteElementIndex() {
return this.delete.displayIndex;
},
haskid() {
return !!this.model['_kid'];
},
kidForReportingIssue() {
var reportingId = this.model._kid;
if (!reportingId && this.currentSchemaDataPath.length > 1) {
var parentSegment = this.currentSchemaDataPath[this.currentSchemaDataPath.length - 2];
reportingId = parentSegment._meta.parentClassId;
}
return reportingId;
},
modelNameForUpdate() {
let model = this.currentModel;
return (model ? model : this.legends[0]);
},
isFileImage() {
return this.upload.isImage;
},
showButtonsForEditing() {
var self = this,
currentClassName = self.currentClassName;
var showEdit = true;
if (self.isAddingNewToArray && self.isArrayForRendering) {
showEdit = true;
} else if (self.isArrayForRendering) {
showEdit = false;
}
showEdit = (self.isDataConsoleMode && !self.model._kid) ? false : showEdit;
return showEdit;
},
isErrorInUploading() {
let self = this;
return self.upload.isError;
},
propertyGroups() {
var self = this,
className = self.currentClassName ? self.currentClassName : self.languageSchema.EntityName,
currentClassProperties = [],
uniqueGroups = [],
isCurrentElementArray = self.isRenderingComplexArray;
if (className) {
currentClassProperties = self.getPropertyListFromClass(className);
currentClassProperties.forEach(function (property) {
var groupName = property.GroupName;
if (groupName && (uniqueGroups.indexOf(groupName) == -1)) {
uniqueGroups.push(groupName);
}
});
}
uniqueGroups = uniqueGroups ? uniqueGroups.sort() : uniqueGroups;
return isCurrentElementArray ? [] : uniqueGroups;
},
currentGroupName() {
return this.currentPropertyGroup.name;
},
saveBtnShow() {
var self = this;
return (self.areFieldsEditable || self.isRenderingNativeArray);
},
isBaseClass() {
var self = this,
currentClassName = self.$data.currentClassName;
if (currentClassName == "") {
return true;
}
return false;
},
isRenderingNativeArray() {
var self = this;
var lastSegment = _.last(self.currentSchemaDataPath);
return (lastSegment && lastSegment.Type === ARRAY_TYPE && lastSegment.hasOwnProperty('NativeArrayProperty'));
},
/**
* Referencing
**/
getReferenceClassNames() {
var self = this,
data = self.referenceData.data,
groups = data ? data.GroupCount : [],
classNames = [];
if (groups && groups.length > 0) {
var groupsNameAndCount = function (group) {
return {
name: group.Name,
matchedProperties: group.Count
}
}
classNames = groups.map(groupsNameAndCount);
}
return classNames;
},
/**
* Referencing
**/
getPropertyNamesByClassName: function () {
var self = this,
data = self.referenceData.data,
groups = (data && data.GroupCount) ? data.GroupCount : [],
propertyNames = [],
className = self.referenceData.selectedClassName;
groups.map(function (group) {
if (group.Name === className) {
group.SubGroupCounts.map(function (subGroup) {
propertyNames.push({
name: subGroup.Name,
matchedProperties: subGroup.Count
});
});
}
});
return propertyNames;
},
/**
* Referencing: data in Level 3 Sliding panel
**/
getDataForClassAndProperty: function () {
var self = this,
properties = [],
className = self.referenceData.selectedClassName,
propertyName = self.referenceData.selectedPropertyName,
data = self.referenceData.data ? self.referenceData.data : {},
dataObjects = data.Data ? data.Data : [];
if (!self.referenceData.isForReverseReference) {
if (className && className.trim() && propertyName && propertyName.trim()) {
var selectedClassName = className.trim().toLowerCase();
var selectedPropertyName = propertyName.trim().toLowerCase();
var selectedData = function (obj) {
var propertyClassName = obj._parentClassName ? obj._parentClassName.toLowerCase() : "",
propertyName = obj._propertyName ? obj._propertyName.toLowerCase() : "";
return (propertyClassName === selectedClassName && selectedPropertyName === propertyName);
};
var isNotEmpty = function (item) {
var isNonEmpty = false;
Object.keys(item).map(function (property) {
if (!self.getSystemProperties.includes(property) && item[property] != null && isNonEmpty == false) {
isNonEmpty = true;
}
});
return isNonEmpty;
};
properties = dataObjects.filter(selectedData).filter(isNotEmpty);
} else {
//console.info("getDataForClassAndProperty, className or propertyName not valid : ", className, propertyName);
}
}
return properties;
},
/**
* Referencing - get the properties of the class to display in the sidebar level 3
**/
getPropertiesToDisplay: function () {
var self = this;
var className = self.referenceData.requestedClassName;
var propertiesToDisplay = [];
if (className && className.trim()) {
var propertiesList = self.getPropertyListFromClass(className);
if (propertiesList && propertiesList.length > 0) {
var selectorsProperties = self.findSelectors(propertiesList); // gets preferred properties
var basicProperties = self.containProperties(propertiesList); // properties to display excluding system properties
if (selectorsProperties && selectorsProperties.length > 0) {
propertiesToDisplay = selectorsProperties;
} else if (basicProperties && basicProperties.length > 0) {
propertiesToDisplay = basicProperties;
}
} else {
//console.error("No properties found for className : ", className);
}
} else {
//console.error("getPropertiesToDiplay : className not valid ", className);
}
return propertiesToDisplay;
},
/**
* Referencing get data from the head
**/
getReferenceHeaderText: function () {
var self = this;
var referenceData = self.referenceData;
if (referenceData.selectedPropertyName == null && referenceData.selectedClassName == null) {
return '';
} else if (referenceData.selectedPropertyName == null) {
return referenceData.selectedClassName;
} else {
return referenceData.selectedPropertyName + ' of ' + referenceData.selectedClassName;
}
},
isForReverseReference: function () {
return this.referenceData.isForReverseReference;
},
getContextMenu: function () {
var self = this;
return [{ name: 'Add to', action: self.getSimilarPropertiesToReferTo }];
},
isContextMenuVisible: function () {
return (this.isBaseClass === false &&
this.isArrayForRendering == false &&
this.model._kid && !this.isAtRootLevel);
},
getSystemProperties: function () {
return systemProperties;
},
isRenderingPhoneNumber: function () {
return this.currentClassName.trim().toLowerCase() === 'phonenumber';
},
getArrayPropertyMaxCount: function () {
var self = this;
var className = self.getParentClassName();
var propertyName = self.currentModel;
var advancedProperties = self.getAdvancedPropertyByClassAndProperty(className, propertyName);
var maxCount = null;
if (advancedProperties) {
if (advancedProperties.hasOwnProperty('ArrayMaxLength')) {
maxCount = advancedProperties.ArrayMaxLength;
if (typeof maxCount == 'string' && isNaN(parseInt(maxCount))) {
maxCount = _.get(self.schemaData, maxCount);
}
}
}
return maxCount;
},
getPropertiesForActiveGroup: function () {
var self = this;
var propertyList = [];
self.schema.groups[0].fields.map(function (field) {
if ((self.currentGroupName == '' && !PropertyVisibliityStatus[field.model]) || (field.groupName === self.currentGroupName)) {
propertyList.push(field.model);
}
});
return propertyList;
},
getPropertiesForCurrentRenderedProperty: function () {
var self = this;
if (!self.currentSchemaDataPath || !Array.isArray(self.currentSchemaDataPath) || !self.currentSchemaDataPath.length) {
return [];
}
let length = (self.currentSchemaDataPath.length - 1);
var currentPropertyDataType = self.currentSchemaDataPath[length].PropertyDataType;
return self.getPropertyListFromClass(currentPropertyDataType);
},
getCurrentRenderedPropertyDetails: function () {
var self = this;
return self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
},
isAtRootLevel: function () {
return (this.currentSchemaDataPath &&
Array.isArray(this.currentSchemaDataPath) &&
this.currentSchemaDataPath.length === 1);
},
schemaNavigationPathForRender: function () {
var self = this;
var navigationSegments = [];
self.currentSchemaDataPath.map(function (segment, index) {
if (segment.Type == ARRAY_TYPE && segment.Filter && segment.Filter.hasOwnProperty('_kid')) {
var arraySegment = _.cloneDeep(segment);
var arrayItemSegment = _.cloneDeep(segment);
var displayText = _.startCase(arraySegment.PropertyName);
arraySegment.displayText = displayText;
delete arraySegment.Filter;
navigationSegments.push(arraySegment);
displayText = _.startCase(arraySegment.PropertyDataType) + ' # ' + arraySegment._meta.ClickedIndex;
arrayItemSegment.displayText = displayText;
arrayItemSegment.isArrayItem = true;
navigationSegments.push(arrayItemSegment);
} else {
var pathSeg = _.cloneDeep(segment);
var displayText = _.startCase(segment.PropertyName);
if (index == 0) {
displayText = _.startCase('Home');
}
pathSeg.displayText = displayText;
navigationSegments.push(pathSeg);
}
});
return navigationSegments;
},
getPopoverSchemaNavigationItems: function () {
var self = this;
return self.schemaNavigationPathForRender.slice(0, (self.schemaNavigationPathForRender.length - self.maxNavigationItemNumber));
},
getSchemaNavigationItemsWihoutPopover: function () {
var self = this;
var offset = self.schemaNavigationPathForRender.length - self.maxNavigationItemNumber > 0 ? self.schemaNavigationPathForRender.length - self.maxNavigationItemNumber : 0
return self.schemaNavigationPathForRender.slice(offset);
},
showSaveEditBtns: function () {
var self = this;
return _.isEmpty(self.model._kid);
},
isAddingNewToComplexArray: function () {
var self = this;
var isAdding = false;
var lastSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
if (lastSegment.Type === 1 && !lastSegment.hasOwnProperty('Filter') && !self.isNative) {
isAdding = true;
}
return isAdding;
},
isRenderingComplexArray: function () {
var self = this;
var isRendering = false;
var lastSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
if (lastSegment && lastSegment.Type === 1 && !lastSegment.hasOwnProperty('Filter') && lastSegment.hasOwnProperty('Index')
&& lastSegment.hasOwnProperty('Length') && lastSegment.hasOwnProperty('Limit')) {
isRendering = true;
}
return isRendering;
},
getPaginationDataForCurrentArray: function () {
var self = this;
var lastSegment = _.last(self.currentSchemaDataPath);
if (lastSegment.Type === ARRAY_TYPE && !lastSegment.hasOwnProperty('Filter')) {
return {
length: lastSegment.Length,
index: lastSegment.Index,
pageSize: lastSegment.Limit
};
}
return null;
},
getArrayPropertySortProps: function () {
var self = this;
var propertyClass = _.find(self.languageSchema.Classes, { Name: self.currentClassName });
if (!propertyClass) {
return null;
}
var requiredProps = [];
propertyClass.PropertyList.map(function (prop) {
if (!systemProperties.includes(prop.Name) && ((prop.DataType.Name.toLowerCase() === 'str') || prop.DataType.Name.toLowerCase() === 'number')) {
requiredProps.push(prop.Name);
}
});
if (requiredProps.length > 0) {
return requiredProps;
} else {
return null;
}
},
},
methods: {
loadLanguageSchema: function () {
var self = this;
self.getLanguageSchema(function (data) {
self.showLoader(false);
self.languageSchema = data;
self.schemaName = data.EntityName;
self.processAllClasses();
self.getBaseClassProperties();
let schema = self.getProcessedClass(data.EntityName);
self.currentSchemaDataPath.push({ PropertyName: data.EntityName, PropertyDataType: data.EntityName, Type: 5 });
self.getSchemaForActiveProperty();
self.resetCurrentGroup();
self.showLoader(true);
self.getBaseClassIdForWebsite(function (response) {
self.new_site = false;
self.getSchemaDataForActiveProperty();
toastr.success('Load successful');
}, function (err) {
self.new_site = true;
self.showLoader(false);
});
}, function (err) {
self.showLoader(false);
});
},
getUserData: function () {
var self = this;
axios.get(Endpoints.GetWebsiteUserDetails, { responseType: 'json' })
.then(function (response) {
self.customerData = response.data;
self.supportEmailForm.to.push(self.customerData.contact.email);
self.getDeveloperDetails(self.customerData.developerId, function (email) {
self.supportEmailForm.to.push(email);
});
myDropzone.options.headers = Object.assign({}, myDropzone.options.headers,
{ WebsiteId: self.customerData.websiteId, DeveloperId: self.customerData.developerId });
});
},
getLanguageSchema: function (successCallback, errorCallback) {
this.showLoader(true);
axios({
method: 'post',
url: Endpoints.GetLanguageSchema
}).then(function (response) {
successCallback(response.data);
}).catch(function (err) {
errorCallback(err);
});
},
isCallTrackerEnabled: function () {
var self = this;
axios({
method: 'post',
url: Endpoints.IsCallTrackerEnabled
}).then(function (response) {
if (response.data && response.data.hasOwnProperty('isActive')) {
self.isCallTrackerEnabledForWebsite = response.data.isActive;
} else {
self.isCallTrackerEnabledForWebsite = false;
}
}).catch(function () {
self.isCallTrackerEnabledForWebsite = false;
});
},
// toggling schema loader
showLoader: function (show) {
var schemaConatiner = document.getElementById('app');
if (show) {
showLoader(schemaConatiner);
} else {
removeLoader(null, true);
}
},
// preprocess all classes received from schema
processAllClasses: function () {
let self = this;
_.forEach(self.languageSchema.Classes, (cls) => {
if (cls.ClassType != 3 && cls.Name != 'kstring' && cls.Name != 'phonenumber') {
self.getSchemaFromClass(cls);
} else if (cls.Name == 'kstring') {
let name = cls.Name;
let kstringProcessedClass = self.getKstringObject(name);
self.classesProcessed.push({ Class: kstringProcessedClass, Name: name });
} else if (cls.Name == 'phonenumber') {
let name = cls.Name;
let phoneNumberProcessedClass = self.getPhoneNumberFormField(name);
self.classesProcessed.push({ Class: phoneNumberProcessedClass, Name: name });
} else {
let name = cls.Name;
let obj = self.getNativeClassObject(name);
self.classesProcessed.push({ Class: obj, Name: name });
}
});
},
getProcessedClass: function (name, field) {
let self = this;
Vue.set(self, 'isNative', self.isClassNativeClass(name));
let clas = _.find(self.classesProcessed, (cls) => {
return cls.Name.trim().toLowerCase() === name.trim().toLowerCase();
});
if (name.trim().toLowerCase() == 'kstring' && field && field.isRichTextEnabled) {
return (Object.assign({}, self.getKstringObject("kstring", true)));
}
return Object.assign({}, clas.Class);
},
formatPropertyName: function (propertyName) {
if (propertyName) {
return _.startCase(propertyName);
}
return propertyName;
},
isClassNativeClass: function (name) {
let self = this;
name = name.trim().toLowerCase();
if (name == 'kstring' || name == 'phonenumber') {
return false;
}
let classes = self.languageSchema.Classes;
let clas = _.find(classes, function (cls) {
return cls.Name.trim().toLowerCase() == name.trim().toLowerCase();
});
return (clas.ClassType == 3);
},
setCurrentGroup: function (groupName, index) {
var self = this,
currentPropertyGroup = self.currentPropertyGroup,
areFieldsEditable = self.areFieldsEditable;
if (areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
if (self.isBaseClass) {
Vue.set(self, 'baseSelectedGroup', {
index: index,
groupName: groupName
});
}
self.resetArrayPropertyFilter();
Vue.set(currentPropertyGroup, 'index', index);
Vue.set(currentPropertyGroup, 'name', groupName);
var activeGroupObj = {
index: index,
name: groupName,
};
self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1].CurrentGroupName = activeGroupObj;
self.updateCurrentPointHistory(groupName);
},
resetCurrentGroup: function (groupName) {
var self = this,
currentPropertyGroup = self.currentPropertyGroup,
propertyGroups = self.propertyGroups,
index = 0;
var firstGroupName = _.first(propertyGroups);
groupName = (groupName !== undefined && groupName !== null) ? groupName : "";
index = _.indexOf(propertyGroups, groupName);
/*
* if groupName is passed set that group
* else set first groupName found
* else set Advanced
*/
if (groupName && index >= 0) {
self.setCurrentGroup(groupName, index);
} else if (groupName == advancedGroupName) {
self.setCurrentGroup(advancedGroupName, -1);
} else if (firstGroupName) {
self.setCurrentGroup(firstGroupName, 0);
} else {
self.setCurrentGroup(advancedGroupName, -1);
}
},
getDataForSchemaSlim: function (callback) {
$.ajax({
type: 'POST',
url: Endpoints.GetDataForSchema,
success: function (data) {
if (callback && typeof callback == 'function') {
callback(data);
}
}
});
},
isCurrentGroup: function (groupName) {
var self = this;
return (groupName == this.currentGroupName);
},
// ---- Upload ----
startUploadFile: function () {
let self = this;
self.showLoader(true);
myDropzone.processQueue();
},
// get the link for image and update the current object
updateLinkOfImgaeObject: function (link) {
var self = this;
var model = {
url: link
};
Vue.set(self, 'model', model);
self.updateDataForSchema();
self.showLoader(false);
},
setIsImageForUploading: function (isImage) {
let self = this;
Vue.set(self.upload, 'isImage', isImage);
},
setIsErrorInUploading: function (isError) {
let self = this;
Vue.set(self.upload, 'isError', isError);
},
closeUploadModal: function () {
Vue.set(Modal.UPLOAD, false);
},
// ---- Upload End ----
// makes all properties editable or uneditable
editAllButton: function () {
let self = this;
let fields = self.schema.groups[0].fields;
let btn = null;
if (!self.areFieldsEditable) {
if (self.isNative && self.isArrayForRendering) {
let data = self.model[self.currentModel];
_.forEach(data, function (ele) {
ele.readonly = false;
})
} else {
_.forEach(fields, function (field) {
if (field.readonly && field.visible && !self.isKeywordPropertyInKstring(field.model)) {
if (!field.advancedProperties ||
(field.advancedProperties.hasOwnProperty('ReadOnly') && !field.advancedProperties.ReadOnly)) {
field.readonly = !field.readonly;
}
}
});
}
self.toggleFieldsEditable(true);
} else {
if (self.isNative && self.isArrayForRendering) {
let data = self.model[self.currentModel];
_.forEach(data, function (ele) {
ele.readonly = true;
})
} else {
_.forEach(fields, function (field) {
if (!field.readonly && field.visible && !self.isKeywordPropertyInKstring(field.model)) {
field.readonly = !field.readonly;
}
});
}
self.toggleFieldsEditable(false);
}
},
isKeywordPropertyInKstring(modelName) {
var self = this,
currentClassName = self.currentClassName,
currentClassName = _.lowerCase(currentClassName);
modelName = _.lowerCase(modelName);
if (currentClassName == 'kstring' && modelName == 'keywords') {
return true;
}
return false;
},
getDeveloperDetails: function (developerId, callback) {
axios({
method: 'post',
url: Endpoints.GetDeveloperDetails,
data: { developerId: developerId }
}).then(function (response) {
callback(response.data);
});
},
getSchemaFromClass: function (klass, modelName) {
let self = this;
let klassObj = self.getClassObject(), // to get the class template
{ Name } = klass;
klassObj.model = modelName ? modelName : Name.toLowerCase();
klassObj.schema.groups[0].legend = Name.toLowerCase();
klass.PropertyList = _.sortBy(klass.PropertyList, ['Type']); // sorts properties for displaying in ui
_.forEach(klass.PropertyList, function (property) {
let { Type, Name, DataType, Description, GroupName, _AdvanceProperties } = property;
let className = DataType.Name;
let prop = null;
let isUrlPropertyInImage = false;
var isStringRichText = (Type == 0 || className.toLowerCase() == 'kstring') ? self.isRichTextEnabled(property) : false;
var isTextArea = self.isTextAreaEnabled(property);
var isStringDropdown = self.isStringDropdownEnabled(property);
var maxCharacterLimit = self.getMaxCharacterLimit(property);
var isPhoneNumberType = (Type == 8 && DataType.Name === 'PHONENUMBER');
// if not object, array or kstring or not phonenumber
if (Type != 1 && Type != 5 && Type != 7 && !isStringRichText && !isPhoneNumberType && !isTextArea && !isStringDropdown) {
// checks if property is url in image class need upload button
if (klass.Name == 'image' && Name == 'url') {
isUrlPropertyInImage = true;
}
prop = self.getPropertyObject(Name, Type, Description, isUrlPropertyInImage, GroupName, DataType, maxCharacterLimit);
// url in image class doesnot need inputtype
if (!isUrlPropertyInImage) {
prop.inputType = InputTypeMapping[Type];
if (self.isDataConsoleMode) {
prop.advancedProperties = Object.assign({}, { ReadOnly: true });
}
}
} else if (Type == 5 || Type == 1 || Type == 7 || isStringRichText || isPhoneNumberType || isStringDropdown || isTextArea) {
var config = {
isArray: Type == 1,
propertyName: Name,
groupName: GroupName,
type: Type,
isStringRichText: isStringRichText,
propertyDataType: className,
propertyType: property.Type,
placeholder: Description,
isStringDropdown: isStringDropdown,
isTextArea: isTextArea,
};
prop = self.getObjectSchema(config);
prop.model = Name;
prop.schema.groups[0].legend = Name;
prop.className = klass.Name;
}
if (prop) {
if (_AdvanceProperties) {
prop.advancedProperties = _AdvanceProperties;
if (self.isDataConsoleMode) {
if (prop.advancedProperties.hasOwnProperty('ReadOnly')) {
prop.advancedProperties.ReadOnly = false;
}
}
}
klassObj.schema.groups[0].fields.push(prop);
}
})
self.classesProcessed.push({ Class: klassObj, Name: klass.Name });
},
getClassObject: function () {
let classObj = {
type: 'object',
model: '',
schema: {
groups: [{
legend: '',
fields: []
}]
}
}
return Object.assign({}, classObj);
},
isRichTextEnabled: function (property) {
var isRichText = false;
var advanceProperties = property._AdvanceProperties;
isRichText = advanceProperties ? advanceProperties.RichText : false;
return isRichText ? true : false;
},
isStringDropdownEnabled: function (property) {
var isStringDropdown = false;
var advanceProperties = property._AdvanceProperties;
isStringDropdown = advanceProperties ? advanceProperties.StringDropdown : false;
return isStringDropdown;
},
getMaxCharacterLimit: function (property) {
var charMaxLength = null;
var advanceProperties = property._AdvanceProperties;
charMaxLength = advanceProperties && advanceProperties.hasOwnProperty('CharMaxLength') ? advanceProperties.CharMaxLength : false;
return charMaxLength;
},
isTextAreaEnabled: function (property) {
var isTextArea = false;
var advanceProperties = property._AdvanceProperties;
isTextArea = advanceProperties ? advanceProperties.TextArea : false;
return isTextArea;
},
getPropertyObject: function (propertyName, propertyType, description, isUrlInImageClass, groupName, dataType, charLimit) {
let self = this;
let propertyObj = {
type: 'input',
inputType: '',
label: propertyName,
model: propertyName,
groupName: groupName,
visible: !self.getPropertyVisibilityStatus(propertyName),
placeholder: description ? description : self.configure.defaultPlaceholder,
readonly: true,
};
if (charLimit) {
propertyObj.maxlength = charLimit;
}
let switchObj = {
type: "switch",
label: propertyName,
model: propertyName,
groupName: groupName,
textOn: "True",
textOff: "False",
visible: !self.getPropertyVisibilityStatus(propertyName),
readonly: true,
onChanged: function () {
var then = self;
if (!self.areFieldsEditable) {
Vue.set(then, 'areFieldsEditable', true);
}
}
};
let urlPropertyInImageClass = {
type: 'label',
label: propertyName,
model: propertyName,
visible: !self.getPropertyVisibilityStatus(propertyName),
placeholder: description ? description : self.configure.defaultPlaceholder,
readonly: true,
buttons: [
{
classes: "kitsune-btn-primary upload-btn",
label: "upload",
isUpload: true,
onclick: function (model, field) {
cancelUpload();
let btn = document.getElementById('uploadFileInit');
btn.click();
}
}
]
};
let dateTimeClass = {
type: 'datetime',
label: propertyName,
model: propertyName,
groupName: groupName,
visible: !self.getPropertyVisibilityStatus(propertyName),
placeholder: description,
format: 'YYYY-MM-DD',
readonly: true,
fieldClasses: 'form-control col-md-6'
};
let phoneNumberClass = {
type: 'phonenumber',
label: propertyName,
model: propertyName,
groupName: groupName,
visible: !self.getPropertyVisibilityStatus(propertyName),
placeholder: description ? description : self.configure.defaultPlaceholder,
readonly: true
};
if (self.isDataConsoleMode) {
urlPropertyInImageClass.buttons = [];
}
// upload button for image class
if (isUrlInImageClass) {
return Object.assign({}, urlPropertyInImageClass);
}
if (dataType.Name === 'DATE') {
return Object.assign({}, dateTimeClass);
}
return Object.assign({}, (propertyType == 3 ? switchObj : propertyObj));
},
getPropertyVisibilityStatus: function (propertyName) {
propertyName = propertyName.trim().toLowerCase();
return PropertyVisibliityStatus[propertyName];
},
getObjectSchema: function (config) {
var self = this;
var fieldType = (config.type == 0) ? 'richtext' : (config.isArray ? 'arrobj' : 'obj');
if (config.isTextArea) {
fieldType = 'textMultiLine';
} else if (config.isStringDropdown) {
fieldType = 'select';
}
var classObj = {
visible: !self.getPropertyVisibilityStatus(config.propertyName),
type: fieldType,
model: '',
className: '',
groupName: config.groupName,
isRichTextEnabled: config.isStringRichText,
isTextArea: config.isTextArea,
schema: {
groups: [{
legend: '',
fields: []
}]
},
propertyDataType: config.propertyDataType,
propertyType: config.propertyType,
placeholder: config.placeholder || null,
};
if (fieldType === 'arrobj') {
Object.assign(classObj, {
addNewItemToArray: self.onClickAddToArrayProperty,
showArrayItems: self.onClickShowArrayItems,
nativeArrayTypes: nativeArrayTypes,
});
} else if (fieldType === 'obj') {
Object.assign(classObj, {
showPropertyDetail: self.onClickShowObjectProperty,
initializeCurrentObj: self.saveCurrentObj,
deleteImage: self.confirmDeleteProperty,
selectFromExisting: self.selectFromExisting,
});
} else if (fieldType === 'select') {
Object.assign(classObj, {
label: config.propertyName,
values: JSON.parse(config.isStringDropdown),
selectOptions: {
name: 'displayText',
value: 'value'
},
disabled: self.isDataConsoleMode,
onChanged: function () {
if (!self.areFieldsEditable) {
Vue.set(self, 'areFieldsEditable', true);
}
}
});
}
return Object.assign({}, classObj);
},
getNativeClassObject: function (className) {
let obj = {
model: className,
schema: {
groups: [
{
fields: [
{
readonly: false,
inputType: nativeMapping[className],
label: className,
model: "val",
type: "input",
visible: true
},
{
readonly: false,
inputType: "text",
label: "_kid",
model: "_kid",
type: "input",
visible: false
},
{
readonly: false,
inputType: "text",
label: "k_referenceid",
model: "k_referenceid",
type: "input",
visible: false
},
{
readonly: false,
inputType: "text",
label: "_propertyName",
model: "_propertyName",
type: "input",
visible: false
},
{
readonly: false,
inputType: "text",
label: "_parentClassName",
model: "_parentClassName",
type: "input",
visible: false
},
{
readonly: false,
inputType: "text",
label: "_parentClassId",
model: "_parentClassId",
type: "input",
visible: false
},
{
readonly: false,
inputType: "text",
label: "isarchived",
model: "isarchived",
type: "checkbox ",
visible: false
}
],
legend: className
}
]
},
type: 'object'
}
if (className.toLowerCase() == 'boolean') {
obj.schema.groups[0].fields[0] = {
type: "switch",
label: className,
model: "val",
textOn: "True",
textOff: "False"
}
}
if (className.toLowerCase() == 'datetime') {
obj.schema.groups[0].fields[0] = {
type: 'datetime',
label: className,
format: 'YYYY-MM-DD',
model: "val",
readonly: false,
//styleClasses: 'col-md-6 col-xs-12'
};
}
return Object.assign({}, obj);
},
getNativeClassObjectForArray: function (val) {
let self = this;
let nativeObj = {
val: null,
isarchived: false,
readonly: true
}
let local = Object.assign({}, nativeObj);
if (val && self.currentClassName == 'datetime') {
val = moment(new Date(val)).format('YYYY-MM-DD');
local.val = val;
} else if (val) {
local.val = val;
}
return local;
},
getKstringObject: function (propertyName, isRichText) {
var self = this;
var KstringRichTextEditor = {
visible: true,
type: 'richtext',
model: 'text',
schema: {
groups: [{
legend: '',
fields: []
}]
}
};
var KstringPlainText = {
type: 'input',
inputType: 'text',
label: "text",
model: 'text',
readonly: true,
visible: true,
placeholder: self.configure.defaultPlaceholder,
advancedProperties: self.isDataConsoleMode ? Object.assign({}, { ReadOnly: true }) : null,
}
let kstring =
{
type: 'object',
model: propertyName,
schema:
{
groups: [{
legend: propertyName,
fields: [
isRichText ? KstringRichTextEditor : KstringPlainText,
{
type: 'input',
inputType: 'select',
label: "keywords",
model: 'keywords',
readonly: true,
visible: true,
placeholder: self.configure.defaultPlaceholder
},
{
type: 'input',
inputType: 'string',
label: "_kid",
model: '_kid',
readonly: true,
visible: false,
}
]
}]
}
}
return Object.assign({}, kstring);
},
getPhoneNumberFormField: function (propertyName) {
var self = this;
var InputField = {
type: 'input',
inputType: 'number',
label: 'text',
model: 'text',
visible: true,
readonly: true,
advancedProperties: self.isDataConsoleMode ? Object.assign({}, { ReadOnly: true }) : null,
placeholder: self.configure.defaultPlaceholder
};
var countryCodeField = Object.assign({}, InputField, {
label: 'Country Code',
model: 'countrycode',
inputType: 'tel',
onChanged: function () {
if (this.value != '+91' || this.value != '91') {
self.model.isactive = false;
Vue.set(self, 'areFieldsEditable', true);
}
},
});
var contactNumberField = Object.assign({}, InputField, { label: 'Contact Number', model: 'contactnumber' });
var callTrackerNumberField = Object.assign({}, InputField, {
type: 'label',
label: 'Call Tracker Number',
model: 'calltrackernumber',
get: function (model) {
return model.calltrackernumber || self.configure.defaultPlaceholder;
},
visible: function () { return self.isCallTrackerEnabledForWebsite }
});
var isCallTrackerActive = {
type: 'switch',
label: self.model.isactive == true ? 'Deactivate Call Tracker' : 'Activate Call Tracker',
model: 'isactive',
textOn: "True",
textOff: "False",
visible: function () {
return (this.model.countrycode == '+91' || this.model.countrycode == '91')
&& self.isCallTrackerEnabledForWebsite;
},
readonly: false,
validator: function () {
return true;
},
onValidated: function (model, errors, field) {
if (model.isactive == true) {
field.label = 'Deactivate Call Tracker';
} else {
field.label = 'Activate Call Tracker';
}
return true;
},
onChanged: function (model, newVal, oldVal, field) {
var then = self;
if (!self.areFieldsEditable) {
Vue.set(then, 'areFieldsEditable', true);
}
if (model.isactive === true) {
field.label = 'Deactivate Call Tracker';
} else {
field.label = 'Activate Call Tracker';
}
}
};
var phoneNumberObject = {
type: 'object',
model: propertyName,
schema: {
groups: [{
legend: propertyName,
fields: [countryCodeField, contactNumberField, callTrackerNumberField, isCallTrackerActive]
}]
}
};
return Object.assign({}, phoneNumberObject);
},
getArrayListFieldSchema: function (schema, arrProperty) {
var self = this;
let arraySchema = {
groups: [
{
fields: [
{
model: arrProperty.PropertyName,
schema: {
fields: []
},
type: 'arrayList',
propertyDataType: arrProperty.PropertyDataType,
propertyName: arrProperty.PropertyName,
primitiveTypes: primitiveTypes,
getNextItemsForArrayProperty: self.getNextItemsForArrayProperty,
getPreviousItemsForArrayProperty: self.getPreviousItemsForArrayProperty,
getArrayItem: self.getArrayItemWithId,
getCurrentPageIndex: function () {
self.getCurrentRenderedPropertyDetails.Index
},
addNewItemToArray: self.onClickAddToArrayProperty,
removeArrayItem: self.confirmDeleteProperty,
isNativeArray: self.isNative,
getPaginationData: function () {
return self.getPaginationDataForCurrentArray
},
addExistingItemsToArray: self.addExistingItemsToArray,
onSearch: self.onArrayPropertySearch,
onSortPropertyChanged: self.onArrayPropertySortPropertyChanged,
onSortOrderChanged: self.onArrayPropertySortOrderChanged,
filterProperties: self.arrayPropertyFilters,
sortProperties: self.getArrayPropertySortProps,
}
],
legend: null
}
]
};
let fields = schema.schema.groups[0].fields;
let legend = schema.schema.groups[0].legend;
arraySchema.groups[0].fields[0].schema.fields = fields;
arraySchema.groups[0].legend = arrProperty.PropertyName;
return arraySchema;
},
getBaseClassProperties: function () {
let self = this;
let baseClass = _.find(self.languageSchema.Classes, { ClassType: 1 });
let properties = baseClass.PropertyList;
let className = baseClass.Name;
let exists = _.find(self.legends, function (legend) { return (legend == className) });
if (!exists) {
self.legends.push(className);
}
self.currentPropertyList = properties;
},
getPropertyListFromClass: function (className) {
if (!className) {
return null;
}
let self = this;
let classes = this.languageSchema.Classes;
let currentClass = _.find(classes, function (cls) {
return cls.Name.trim().toLowerCase() == className.trim().toLowerCase();
});
if (!_.isEmpty(currentClass)) {
return currentClass.PropertyList;
}
return null;
},
updateCurrentPointHistory: function (groupName) {
var self = this,
history = self.history,
last = _.last(history);
if (last &&
groupName !== undefined &&
groupName !== null) {
Vue.set(last, 'groupName', groupName);
}
},
getBulkPropertyPathRequest: function (currentSchemaDataPath) {
var self = this;
var requiredKeysForRequest = ['PropertyName', 'PropertyDataType', 'Type', 'Index', 'Limit', 'ObjectKeys', 'Filter'];
var lastPointInPath = currentSchemaDataPath[currentSchemaDataPath.length - 1];
if (!lastPointInPath || !lastPointInPath.PropertyDataType) {
return null;
}
var currentPropertyDataType = lastPointInPath.PropertyDataType;
if (lastPointInPath.Type === KSTRING_OBJECT_TYPE) {
currentPropertyDataType = currentPropertyDataType.toLowerCase();
}
var isArrayProperty = (lastPointInPath.Type === ARRAY_TYPE);
var isObjectProperty = (COMPLEX_OBJECT_TYPE === lastPointInPath.Type);
var isArrayItem = (lastPointInPath.Filter && lastPointInPath.Filter._kid != undefined);
var isKstringType = (KSTRING_OBJECT_TYPE == lastPointInPath.Type);
var isNativeArray = (ARRAY_TYPE === lastPointInPath.Type && lastPointInPath.hasOwnProperty('NativeArrayProperty'));
if (currentPropertyDataType === 'LINK') {
currentPropertyDataType = currentPropertyDataType.toLowerCase();
}
var propertyDataTypeObj = _.find(self.languageSchema.Classes, { Name: currentPropertyDataType });
if (!propertyDataTypeObj || !propertyDataTypeObj.PropertyList) {
return null;
}
var bulkRequestObject = { BulkPropertySegments: [] };
if (isNativeArray) {
var bulkPropertySegments = getPropertiesForNativeArray(currentSchemaDataPath);
bulkRequestObject.BulkPropertySegments.push(bulkPropertySegments);
return bulkRequestObject;
} else if (isObjectProperty || isArrayItem) {
var bulkPropertySegments = getPropertiesToRenderForObject(currentSchemaDataPath);
bulkRequestObject.BulkPropertySegments = bulkPropertySegments;
return bulkRequestObject;
} else if (isKstringType) {
var bulkPropertySegments = getPropertiesToForKstring(currentSchemaDataPath);
bulkRequestObject.BulkPropertySegments = bulkPropertySegments;
return bulkRequestObject;
} else if (isArrayProperty) {
var arrayItemsPreviewRequest = [];
var objectKeys = getPropertiesNamesToRenderForObject(propertyDataTypeObj.PropertyList);
arrayItemsPreviewRequest = _.map(currentSchemaDataPath,
function (segment) {
return _.pick(segment, requiredKeysForRequest);
});
var size = (arrayItemsPreviewRequest.length - 1);
arrayItemsPreviewRequest[size].ObjectKeys = {};
objectKeys.map(function (key) {
arrayItemsPreviewRequest[size].ObjectKeys[key] = true;
});
var arrayFilterConfig = getArrayPropertySearchConfig();
if (arrayFilterConfig) {
arrayItemsPreviewRequest[size].Filter = arrayFilterConfig;
}
var arraySortConfig = getArrayPropertySortConfig();
if (arraySortConfig) {
arrayItemsPreviewRequest[size].Sort = arraySortConfig;
}
bulkRequestObject.BulkPropertySegments.push(arrayItemsPreviewRequest);
return bulkRequestObject;
}
function getArrayPropertySearchConfig() {
var stringProperties = [];
var propertyClass = _.find(self.languageSchema.Classes, { Name: self.currentClassName });
if (!self.arrayPropertyFilters.searchFilter) {
return;
}
propertyClass.PropertyList.map(function (property) {
if (!systemProperties.includes(property.Name) && property.DataType.Name.toLowerCase() === 'str') {
stringProperties.push(property.Name);
}
});
if (stringProperties.length < 1) {
return;
}
var config = { '$or': [] };
stringProperties.map(function (prop) {
config.$or.push({ [prop]: { $regex: self.arrayPropertyFilters.searchFilter , $options: "i" } });
});
return config;
}
function getArrayPropertySortConfig() {
if (!self.getArrayPropertySortProps || !self.arrayPropertyFilters.sortFilter) {
return null;
}
return { [self.arrayPropertyFilters.sortFilter]: self.arrayPropertyFilters.ascDesc };
}
function getPropertiesForNativeArray(schemaPathSegments) {
var bulkPropertySegments = [];
var currentSegments = _.cloneDeep(schemaPathSegments.slice(0, schemaPathSegments.length - 1));
var baseSegments = [];
var lastSegment = schemaPathSegments[schemaPathSegments.length - 1];
var nativeArrayProperty = _.last(schemaPathSegments).NativeArrayProperty;
var segmentSize = currentSegments.length;
currentSegments.map(function (segment, index) {
Object.keys(segment).map(function (key) {
if (!requiredKeysForRequest.includes(key)) {
delete segment[key];
}
if (index == segmentSize - 1) {
segment.ObjectKeys = { [nativeArrayProperty]: true, _kid: true };
}
});
bulkPropertySegments.push(segment);
});
return bulkPropertySegments;
}
// to render a preview of object for item in array list
function getPropertiesNamesToRenderForObject(propertyList, includeArrayProperties) {
var stringProperties = [];
var imageProperties = [];
var propertiesToRender = [];
var propertyNamesToRender = [];
propertyList.map(function (property) {
if (property.DataType.Name == 'STR' || property.DataType.Name == 'NUMBER' && PropertyVisibliityStatus[property.DataType.Name] == undefined) {
stringProperties.push(property);
} else if (property.DataType.Name == 'image' && property.Type === COMPLEX_OBJECT_TYPE) {
imageProperties.push(property);
} else if (property.DataType.Name.toLowerCase() === 'str' &&
property.Type != ARRAY_TYPE && property.Type != COMPLEX_OBJECT_TYPE) {
propertiesToRender.push(property);
}
});
if (imageProperties.length > 0) {
propertiesToRender.push(imageProperties[0]);
}
stringProperties.map(function (stringProperty) {
var isValid = selectorsRegex.test(stringProperty.Name);
if (isValid && propertiesToRender.length < 3) {
propertiesToRender.push(stringProperty);
}
});
if (propertiesToRender.length < 3) {
stringProperties.map(function (stringProperty) {
if (!selectorsRegex.test(stringProperty.Name) && propertiesToRender.length < 3) {
propertiesToRender.push(stringProperty);
}
});
}
propertyNamesToRender = _.map(propertiesToRender, 'Name');
propertyNamesToRender.unshift('_kid');
return propertyNamesToRender;
}
// - for the root schema object
// - when clickcking an item in an array,
// - other object properties
function getPropertiesToRenderForObject(schemaPathSegments) {
var bulkPropertySegments = [];
var lastSegment = schemaPathSegments[schemaPathSegments.length - 1];
var classType = lastSegment.PropertyDataType;
if (lastSegment.Type === KSTRING_OBJECT_TYPE) {
classType = classType.toLowerCase();
} else if (classType === 'LINK') {
classType = classType.toLowerCase();
}
var propertyClass = _.find(self.languageSchema.Classes, { Name: classType });
if (!propertyClass) {
console.error('propertyClass not found');
return;
}
var arrayProperties = [];
var objectProperties = [];
var simpleTypeProperties = [];
var kStringProperties = [];
var basePathSegment = _.cloneDeep(schemaPathSegments);
propertyClass.PropertyList.map(function (property) {
if (COMPLEX_OBJECT_TYPE === property.Type && PropertyVisibliityStatus[property.Name] == undefined) {
objectProperties.push(property);
} else if (KSTRING_OBJECT_TYPE === property.Type && PropertyVisibliityStatus[property.Name] == undefined) {
kStringProperties.push(property);
} else if (property.Type == ARRAY_TYPE && classType === 'kstring' && property.Name === 'keywords') {
simpleTypeProperties.push(property);
} else if (property.Type == ARRAY_TYPE && PropertyVisibliityStatus[property.Name] == undefined) {
arrayProperties.push(property);
} else if (property.Type != COMPLEX_OBJECT_TYPE && property.Type != ARRAY_TYPE) {
simpleTypeProperties.push(property);
}
});
if (simpleTypeProperties.length > 0) {
var simpleTypePropertyNames = _.map(simpleTypeProperties, 'Name');
var plainPropertiesSegment = _.cloneDeep(_.last(basePathSegment));
var bulkRequestItem = [];
plainPropertiesSegment.ObjectKeys = {};
simpleTypePropertyNames.map(function (name) {
plainPropertiesSegment.ObjectKeys[name] = true;
});
basePathSegment.map(function (segment, index) {
if (index < basePathSegment.length - 1) {
bulkRequestItem.push(segment);
}
});
bulkRequestItem.push(plainPropertiesSegment);
bulkPropertySegments.push(bulkRequestItem);
}
arrayProperties.map(function (property) {
var bulkRequestItem = [];
var arrPropertySegment = {
PropertyName: property.Name,
PropertyDataType: property.DataType.Name,
Type: ARRAY_TYPE,
};
var lengthPropertySegment = {
PropertyName: 'length',
PropertyDataType: 'function',
Type: 6,
};
basePathSegment.map(function (segment) {
bulkRequestItem.push(segment);
});
bulkRequestItem.push(arrPropertySegment);
bulkRequestItem.push(lengthPropertySegment);
bulkPropertySegments.push(bulkRequestItem);
});
kStringProperties.map(function (property) {
var bulkRequestItem = [];
var kstringPropertySegment = {
PropertyName: property.Name,
PropertyDataType: property.DataType.Name,
Type: KSTRING_OBJECT_TYPE,
};
basePathSegment.map(function (segment) {
bulkRequestItem.push(segment);
});
bulkRequestItem.push(kstringPropertySegment);
bulkPropertySegments.push(bulkRequestItem);
});
objectProperties.map(function (property) {
var objectPropertySegment = {};
var bulkRequestItem = [];
if (property.DataType.Name === 'image') {
objectPropertySegment = {
PropertyName: property.Name,
PropertyDataType: property.DataType.Name,
Type: COMPLEX_OBJECT_TYPE,
};
} else if (property.DataType.Name === 'phonenumber') {
objectPropertySegment = {
PropertyName: property.Name,
PropertyDataType: property.DataType.Name,
Type: COMPLEX_OBJECT_TYPE,
};
} else {
var propertyName = property.DataType.Name;
if (property.Type === KSTRING_OBJECT_TYPE) {
propertyName = propertyName.toLowerCase();
} else if (propertyName === 'LINK') {
propertyName = propertyName.toLowerCase();
}
var dataTypeObj = _.find(self.languageSchema.Classes, { Name: propertyName });
var stringPropertyList = dataTypeObj.PropertyList.filter(function (type) {
return type.DataType.Name === 'STR'
});
var imagePropertyList = dataTypeObj.PropertyList.filter(function (type) {
return type.DataType.Name === 'image';
});
var booleanPropertyList = dataTypeObj.PropertyList.filter(function (type) {
return type.DataType.Name === 'BOOLEAN';
});
var propertiesToRender = [];
if (imagePropertyList.length > 0) {
propertiesToRender = stringPropertyList.slice(0, 2);
propertiesToRender.unshift(imagePropertyList[0]);
} else {
propertiesToRender = stringPropertyList.slice(0, 3);
}
if (propertiesToRender.length < 3 && booleanPropertyList.length > 0) {
booleanPropertyList.map(function (property) {
if (propertiesToRender.length < 3) {
propertiesToRender.push(property);
}
});
}
var objectKeys = { _kid: true };
propertiesToRender.map(function (property) {
objectKeys[property.Name] = true;
});
if (!_.isEmpty(objectKeys)) {
objectPropertySegment = {
PropertyName: property.Name,
PropertyDataType: property.DataType.Name,
Type: 5,
ObjectKeys: objectKeys,
};
}
}
if (!_.isEmpty(objectPropertySegment)) {
//bulkRequestItem.push(basePathSegment);
basePathSegment.map(function (segment) {
bulkRequestItem.push(segment);
});
bulkRequestItem.push(objectPropertySegment);
bulkPropertySegments.push(bulkRequestItem);
}
});
return bulkPropertySegments;
}
function getPropertiesToForKstring(schemaPathSegments) {
var bulkPropertySegments = [];
var lastSegment = _.last(schemaPathSegments);
var basePathSegment = _.cloneDeep(schemaPathSegments);
var classType = lastSegment.PropertyDataType.toLowerCase();
var propertyClass = _.find(self.languageSchema.Classes, { Name: classType });
if (propertyClass && propertyClass.PropertyList && propertyClass.PropertyList.length) {
var kStringPropertyNames = _.map(propertyClass.PropertyList, 'Name');
var propertySegment = _.cloneDeep(_.last(basePathSegment));
var bulkRequestItem = [];
propertySegment.ObjectKeys = {};
kStringPropertyNames.map(function (name) {
propertySegment.ObjectKeys[name] = true;
});
basePathSegment.map(function (segment, index) {
if (index < basePathSegment.length - 1) {
bulkRequestItem.push(segment);
}
});
bulkRequestItem.push(propertySegment);
bulkPropertySegments.push(bulkRequestItem);
}
return bulkPropertySegments;
}
},
getSchemaDataForActiveProperty: function () {
var self = this;
self.showLoader(true);
var bulkDataRequest = self.getBulkPropertyPathRequest(_.cloneDeep(self.currentSchemaDataPath));
if (_.isEmpty(bulkDataRequest)) {
self.showLoader(false);
return;
}
self.getDataByPropertyPathBulk(bulkDataRequest, function (response) {
self.onFetchBulkSchemaDataSuccess(bulkDataRequest, response);
self.showLoader(false);
}, function (err) {
toastr.error('error fetching data.');
self.showLoader(false);
});
},
/**
* Update this.model with the schema data
**/
onFetchBulkSchemaDataSuccess: function (bulkDataRequest, data) {
var model = {};
var self = this;
if (!bulkDataRequest || !data || _.isEmpty(data) || _.isEmpty(bulkDataRequest)) {
return;
}
bulkDataRequest.BulkPropertySegments.map(function (propertySegments, index) {
var propertyKey = getPropertyKey(propertySegments);
var propertyValue = _.cloneDeep(data[index].Data);
var valueKeysLength = propertyValue ? Object.keys(propertyValue).length : false;
if (self.isNative && isPropertyOfTypeNativeArray(self.currentSchemaDataPath)) {
if (Array.isArray(propertyValue)) {
Object.assign(model, propertyValue[0]);
} else {
Object.assign(model, propertyValue);
}
} else if (isPropertyTypeOfArray(propertySegments) && !Array.isArray(propertyValue)) {
propertyValue = [];
propertyValue.length = data[index].Data;
_.assign(model, { [propertyKey]: propertyValue });
} else if (isPropertyTypeOfArray(propertySegments) && isArrayItem(propertySegments)) {
_.assign(model, data[index].Data[0]);
} else if (isPropertyTypeOfArray(propertySegments)) {
_.assign(model, { [propertyKey]: propertyValue });
} else if (isObjectProperty(propertySegments)) {
var currentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
var isParentProperty = currentSegment.PropertyName === propertyKey;
if (isParentProperty) {
Object.assign(model, propertyValue);
} else {
_.assign(model, { [propertyKey]: propertyValue });
}
} else if (isKStringProperty(propertySegments)) {
if (isRederingInParentObject(model)) {
_.assign(model, { [propertyKey]: propertyValue });
} else {
Object.assign(model, propertyValue);
}
}
});
Vue.set(self, 'model', model);
var lastPropertySegment = self.currentSchemaDataPath.slice(self.currentSchemaDataPath.length - 1)[0];
if (lastPropertySegment.Type == COMPLEX_OBJECT_TYPE) { // check if is object
var updatedPath = _.cloneDeep(self.currentSchemaDataPath);
var parentSegment = updatedPath[updatedPath.length - 2];
updatedPath[updatedPath.length - 1]._meta = {};
updatedPath[updatedPath.length - 1]._meta.parentClassId = self.model._kid;
if (parentSegment) {
updatedPath[updatedPath.length - 1]._meta.parentClassName = parentSegment.PropertyDataType;
}
Vue.set(self, 'currentSchemaDataPath', updatedPath);
}
self.showLoader(false);
function getPropertyKey(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return lastPropertySegment.PropertyName;
}
function isPropertyOfTypeNativeArray(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return (lastPropertySegment.Type === ARRAY_TYPE && lastPropertySegment.hasOwnProperty('NativeArrayProperty'));
}
function isPropertyTypeOfArray(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return (lastPropertySegment.Type === ARRAY_TYPE);
}
function isObjectProperty(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return (lastPropertySegment.Type === COMPLEX_OBJECT_TYPE);
}
function isKStringProperty(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return (lastPropertySegment.Type === KSTRING_OBJECT_TYPE);
}
function isArrayItem(propertySegments) {
var lastPropertySegment = getPropertySegmentFromSegmentsArray(propertySegments);
return (lastPropertySegment.Filter != undefined && lastPropertySegment.Filter._kid != undefined);
}
function getPropertySegmentFromSegmentsArray(propertySegments) {
var lastPropertySegment = propertySegments[propertySegments.length - 1];
if (lastPropertySegment && lastPropertySegment.Type == 6) {
lastPropertySegment = propertySegments[propertySegments.length - 2];
}
return lastPropertySegment;
}
function isRederingInParentObject(model) {
return !!model._kid;
}
},
// show list of array items with preview
onClickShowArrayItems: function (fieldObj) {
var self = this;
self.resetArrayPropertyFilter();
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
if (self.new_site) {
self.addDataForSchema(function () {
self.onClickShowArrayItems(fieldObj);
});
return;
}
if (!self.model._kid) {
self.saveCurrentObj(function () {
self.onClickAddToArrayProperty(fieldObj);
});
return;
}
var isNativeArray = nativeArrayTypes.includes(fieldObj.propertyDataType);
if (isNativeArray) {
var currentSchemaDataPath = _.cloneDeep(self.currentSchemaDataPath);
var lastSegment = currentSchemaDataPath[currentSchemaDataPath.length - 1];
lastSegment.nativeArrayProperty = fieldObj.model;
self.resetCurrentGroup(advancedGroupName);
var arrPathSegment = {
PropertyDataType: fieldObj.propertyDataType,
PropertyName: fieldObj.model,
Type: fieldObj.propertyType,
Index: 0,
Limit: self.arrayItemPagination.limit,
Length: (self.model[fieldObj.model] && Array.isArray(self.model[fieldObj.model])) ? self.model[fieldObj.model].length : 0,
NativeArrayProperty: fieldObj.model
};
self.currentClassName = fieldObj.propertyDataType;
self.resetCurrentGroup(advancedGroupName);
self.currentSchemaDataPath.push(arrPathSegment);
} else {
var arrPathSegment = {
PropertyDataType: fieldObj.propertyDataType,
PropertyName: fieldObj.model,
Type: fieldObj.propertyType,
Index: 0,
Limit: self.arrayItemPagination.limit,
Length: (self.model[fieldObj.model] && Array.isArray(self.model[fieldObj.model])) ? self.model[fieldObj.model].length : 0,
};
self.currentClassName = fieldObj.propertyDataType;
self.currentSchemaDataPath.push(arrPathSegment);
self.resetCurrentGroup(advancedGroupName);
}
self.showLoader(true);
self.getSchemaForActiveProperty();
self.getSchemaDataForActiveProperty();
},
// to add new item to array (complex obj array)
onClickAddToArrayProperty: function (fieldObj) {
var self = this;
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
if (self.new_site) {
self.addDataForSchema(function () {
self.onClickAddToArrayProperty(fieldObj);
});
return;
}
var arrPathSegment = {
PropertyDataType: fieldObj.propertyDataType,
PropertyName: fieldObj.model,
Type: fieldObj.propertyType,
IsAddNew: true,
_meta: {
Limit: self.arrayItemPagination.limit,
Length: (self.model[fieldObj.model] && Array.isArray(self.model[fieldObj.model])) ? self.model[fieldObj.model].length : 0,
Index: (self.model[fieldObj.model] && Array.isArray(self.model[fieldObj.model])) ? self.model[fieldObj.model].length : 0,
}
};
if (fieldObj.type !== 'arrayList') {
self.currentClassName = fieldObj.propertyDataType;
self.currentSchemaDataPath.push(arrPathSegment);
self.resetCurrentGroup();
} else {
var currentPathSegments = _.cloneDeep(self.currentSchemaDataPath);
var lastSegment = currentPathSegments[currentPathSegments.length - 1];
var meta = {};
Object.keys(lastSegment).map(function (key) {
if (key != 'PropertyDataType' && key != 'PropertyName' && key != 'Type') {
meta[key] = lastSegment[key]
delete lastSegment[key];
}
});
lastSegment._meta = meta;
lastSegment.IsAddNew = true;
Vue.set(self, 'currentSchemaDataPath', currentPathSegments);
}
var objectField = self.getProcessedClass(fieldObj.propertyDataType);
Vue.set(self, 'schema', objectField.schema);
Vue.set(self, 'model', {});
},
onClickShowObjectProperty: function (fieldObj) {
var self = this;
self.resetArrayPropertyFilter();
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
if (!self.model._kid) {
self.saveCurrentObj(function () {
self.onClickShowObjectProperty(fieldObj);
});
return;
}
var objectSegment = {
PropertyDataType: fieldObj.propertyDataType,
PropertyName: fieldObj.propertyName,
Type: fieldObj.type,
};
self.currentClassName = fieldObj.propertyDataType;
self.currentSchemaDataPath.push(objectSegment);
self.resetCurrentGroup();
self.showLoader(true);
self.getSchemaForActiveProperty(fieldObj);
self.getSchemaDataForActiveProperty();
},
// show array item with kid
getArrayItemWithId: function (kid, propertyObj) {
var self = this;
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
var pathSegments = _.cloneDeep(self.currentSchemaDataPath);
var lastSegment = pathSegments[pathSegments.length - 1];
var requiredKeys = ['PropertyDataType', 'PropertyName', 'Type'];
Object.keys(lastSegment).map(function (key) {
if (!requiredKeys.includes(key)) {
lastSegment._meta = _.isEmpty(lastSegment._meta) ? {} : lastSegment._meta;
lastSegment._meta[key] = lastSegment[key];
delete lastSegment[key];
}
});
lastSegment.Filter = { _kid: kid };
lastSegment.Index = 0;
Object.assign(lastSegment._meta, { ClickedIndex: propertyObj.clickedIndex });
Vue.set(self, 'currentSchemaDataPath', pathSegments);
self.currentClassName = propertyObj.propertyDataType;
self.resetCurrentGroup();
self.showLoader(true);
self.getSchemaForActiveProperty();
self.getSchemaDataForActiveProperty();
},
// when clicking configure new or select from existing
// from within an empty object / without _kid
// case when add new in array and configure an object
// property in array
saveCurrentObj: function (callback) {
var self = this;
self.showLoader(true);
self.updateDataForSchema(function () {
if (callback && typeof callback === 'function') {
callback();
}
self.showLoader(false);
});
},
getNextItemsForArrayProperty: function () {
var self = this;
var currentPropertyPath = _.cloneDeep(self.currentSchemaDataPath);
var depth = currentPropertyPath.length - 1;
var currentSegment = currentPropertyPath[depth];
if (currentSegment.Index + self.arrayItemPagination.limit < currentSegment.Length) {
currentSegment.Index = (currentSegment.Index + self.arrayItemPagination.limit);
}
Vue.set(self, 'currentSchemaDataPath', currentPropertyPath);
self.showLoader(true);
self.getSchemaDataForActiveProperty();
},
getPreviousItemsForArrayProperty: function () {
var self = this;
var currentPropertyPath = _.cloneDeep(self.currentSchemaDataPath);
var depth = currentPropertyPath.length - 1;
currentPropertyPath[depth].Index = (currentPropertyPath[depth].Index - self.arrayItemPagination.limit);
currentPropertyPath[depth].Index = (currentPropertyPath[depth].Index < 0) ? 0 : currentPropertyPath[depth].Index;
Vue.set(self, 'currentSchemaDataPath', currentPropertyPath);
self.showLoader(true);
self.getSchemaDataForActiveProperty();
},
onArrayPropertySearch: function () {
var self = this;
var propertyClass = _.find(self.languageSchema.Classes, { Name: self.currentClassName });
if (!propertyClass) {
return;
}
self.showLoader(true);
var bulkRequestObject = { BulkPropertySegments: [] };
var currentSchemaDataPath = _.cloneDeep(self.currentSchemaDataPath);
bulkRequestObject.BulkPropertySegments = getArrayPropertySearchItemsLength(currentSchemaDataPath.slice(0, currentSchemaDataPath.length - 1));
self.getDataByPropertyPathBulk(bulkRequestObject, function (response) {
if (!Array.isArray(response) || !response[0].hasOwnProperty('Data') || !Number.isInteger(response[0].Data)) {
self.showLoader(false);
self.getSchemaDataForActiveProperty();
return;
}
var updatedSchemaDataPath = _.cloneDeep(self.currentSchemaDataPath);
updatedSchemaDataPath[updatedSchemaDataPath.length - 1].Length = response[0].Data;
Vue.set(self, 'currentSchemaDataPath', updatedSchemaDataPath);
self.getSchemaDataForActiveProperty();
self.showLoader(false);
}, function (err) {
self.showLoader(false);
self.getSchemaDataForActiveProperty();
});
function getArrayPropertySearchItemsLength(schemaPathSegments) {
var bulkPropertySegments = [];
var lastSegment = schemaPathSegments[schemaPathSegments.length - 1];
var classType = lastSegment.PropertyDataType;
if (lastSegment.Type === KSTRING_OBJECT_TYPE) {
classType = classType.toLowerCase();
} else if (classType === 'LINK') {
classType = classType.toLowerCase();
}
var basePathSegment = _.cloneDeep(schemaPathSegments);
var bulkRequestItem = [];
var arrPropertySegment = {
PropertyName: _.last(self.currentSchemaDataPath).PropertyName,
PropertyDataType: self.currentClassName,
Type: ARRAY_TYPE,
};
var searchConfig = getArrayPropertySearchConfig();
if (searchConfig) {
arrPropertySegment.Filter = searchConfig;
}
var lengthPropertySegment = {
PropertyName: 'length',
PropertyDataType: 'function',
Type: 6,
};
basePathSegment.map(function (segment) {
bulkRequestItem.push(segment);
});
bulkRequestItem.push(arrPropertySegment);
bulkRequestItem.push(lengthPropertySegment);
bulkPropertySegments.push(bulkRequestItem);
return bulkPropertySegments;
}
function getArrayPropertySearchConfig() {
var stringProperties = [];
var propertyClass = _.find(self.languageSchema.Classes, { Name: self.currentClassName });
if (!self.arrayPropertyFilters.searchFilter) {
return;
}
propertyClass.PropertyList.map(function (property) {
if (!systemProperties.includes(property.Name) && property.DataType.Name.toLowerCase() === 'str') {
stringProperties.push(property.Name);
}
});
if (stringProperties.length < 1) {
return;
}
var config = { '$or': [] };
stringProperties.map(function (prop) {
config.$or.push({ [prop]: { $regex: self.arrayPropertyFilters.searchFilter, $options: "i" } });
});
return config;
}
},
onArrayPropertySortPropertyChanged: function () {
var self = this;
if (self.arrayPropertyFilters.sortFilter) {
self.getSchemaDataForActiveProperty();
}
},
onArrayPropertySortOrderChanged: function () {
var self = this;
if (self.arrayPropertyFilters.ascDesc === 1) {
self.arrayPropertyFilters.ascDesc = -1;
} else {
self.arrayPropertyFilters.ascDesc = 1;
}
if (self.arrayPropertyFilters.sortFilter) {
self.getSchemaDataForActiveProperty();
}
},
resetArrayPropertyFilter: function () {
var self = this;
self.arrayPropertyFilters.searchFilter = null;
self.arrayPropertyFilters.sortFilter = null;
self.arrayPropertyFilters.ascDesc = 1;
},
getDataByPropertyPathBulk: function (request, successCallback, errorCallback) {
axios({
method: 'post',
url: Endpoints.GetDataByPropertyBulk,
data: request,
}).then(function (response) {
if (successCallback && typeof successCallback === 'function') {
successCallback(response.data);
}
}).catch(function (err) {
if (errorCallback && typeof errorCallback === 'function') {
errorCallback(err);
}
});
},
getNonSystemPropertiesFromPropertyList: function (properties) {
return properties.filter(function (property) {
return (PropertyVisibliityStatus[property] == undefined);
});
},
// Find properties to render in fieldObj and fieldDynamic (rendering array of objects)
//
findPropertiesToRenderForFieldObject: function (propertyList, count) {
var selectedProperties = [];
propertyList.map(function (property) {
var propertyName = property.Name;
var isOfRequiredType = (property.Type !== 6 && property.Type !== 1 && property.Type !== 5);
var isNotSystemProperty = !!PropertyVisibliityStatus[propertyName];
var valid = (selectorsRegex.test(name) && (selectedProperties.length <= 3) && isNotSystemProperty && isOfRequiredType);
if (valid) {
selectedProperties.push(property);
}
});
return selectedProperties;
},
goToPathInDataNavigation: function (index, isAddOffset) {
var self = this;
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
var actualPath = _.cloneDeep(self.currentSchemaDataPath);
var renderedPath = _.cloneDeep(self.schemaNavigationPathForRender);
if (isAddOffset) {
index += (renderedPath.length - self.maxNavigationItemNumber);
}
var popsToMake = renderedPath.length - (index + 1);
var newRenderedSegment = renderedPath.slice(0, index);
popsToMake = (popsToMake < 0) ? 0 : popsToMake;
var isUpdateNeeded = (popsToMake > 0);
while (popsToMake > 0 && actualPath.length > 1) {
var lastSegment = _.last(actualPath);
if (lastSegment.Type === ARRAY_TYPE && lastSegment.hasOwnProperty('Filter')) {
delete lastSegment.Filter;
if (lastSegment.hasOwnProperty('_meta')) {
Object.keys(lastSegment._meta).map(function (key) {
lastSegment[key] = lastSegment._meta[key];
});
delete lastSegment._meta;
}
} else {
actualPath.pop();
}
popsToMake--;
}
if (isUpdateNeeded) {
Vue.set(self, 'currentSchemaDataPath', actualPath);
self.getSchemaForActiveProperty();
self.getSchemaDataForActiveProperty();
if (_.last(actualPath).hasOwnProperty('CurrentGroupName')) {
self.resetCurrentGroup(_.last(actualPath).CurrentGroupName.name);
} else {
self.resetCurrentGroup();
}
}
},
getSchemaForActiveProperty: function (fieldObj) {
var self = this;
var lastSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
if (OBJECT_TYPES.includes(lastSegment.Type)) { // for object property
var objectField = self.getProcessedClass(lastSegment.PropertyDataType, fieldObj);
Vue.set(self, 'schema', objectField.schema);
self.currentClassName = lastSegment.PropertyDataType;
} else if (lastSegment.Type === 1 && !lastSegment.hasOwnProperty('Filter')) { // for array list
var objectField = self.getProcessedClass(lastSegment.PropertyDataType /*fieldObj*/);
var arrayListFieldSchema = self.getArrayListFieldSchema(objectField, lastSegment);
Vue.set(self, 'schema', arrayListFieldSchema);
} else if (lastSegment.Type === 1) { // for array item
var objectField = self.getProcessedClass(lastSegment.PropertyDataType);
Vue.set(self, 'schema', objectField.schema);
} else {
console.error('getSchemaForActiveProperty no schema');
}
},
updateDataForSchema: function (callback, ignoreVMNcheck) {
var self = this;
var propertiesForUpdate = [];
var fields = _.cloneDeep(self.schema.groups[0]).fields;
self.showLoader(true);
if (self.new_site) {
self.addDataForSchema(function () {
self.updateDataForSchema(callback);
});
return;
}
if (self.isRenderingPhoneNumber && !ignoreVMNcheck && self.isCallTrackerEnabledForWebsite) {
self.updateDataForVMN();
return;
}
if (!self.isRenderingNativeArray) {
// label for image url, switch for boolean
fields.map(function (field) {
if (field.type === 'input' || field.type === 'label'
|| field.type === 'textMultiLine' || field.type === 'select'
|| field.type === 'switch' || field.type === 'richtext' || field.type === 'datetime'
&& !systemProperties.includes(field.model)) {
propertiesForUpdate.push(field.model);
}
});
} else {
propertiesForUpdate.push(fields[0].model);
}
var updateObject = {};
propertiesForUpdate.map(function (property) {
updateObject[property] = self.model[property];
});
var updateRequest = { BulkUpdates: [], Query: null, UpdateValue: null };
var updateItem = {};
/*if (self.isRenderingNativeArray) {
updateItem.Query = { _kid: self.model._kid };
} else */
if (self.currentSchemaDataPath.length == 1) {
updateItem.Query = { _kid: self.model._kid, _parentClassId: self.model._kid, _parentClassName: self.schemaName, _propertyName: self.schemaName };
} else if (self.isAddingNewToComplexArray) {
updateItem.Query = { _parentClassId: getParentClassId(), _parentClassName: getParentClassName(), _propertyName: getPropertyName() };
} else if (!self.model._kid) { //adding new object property
updateItem.Query = { _parentClassId: getParentClassId(), _parentClassName: getParentClassName(), _propertyName: getPropertyName() };
} else if (self.isNative) {
var parent = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
var grandParent = self.currentSchemaDataPath.length > 2 ? self.currentSchemaDataPath[self.currentSchemaDataPath.length - 3] : null;
updateItem.Query = {
_kid: self.model._kid,
_parentClassId: (parent && parent.Type === ARRAY_TYPE) ? ((grandParent && grandParent._meta) ? grandParent._meta.parentClassId : null) : parent._meta.parentClassId,
_parentClassName: (parent && parent.Type === ARRAY_TYPE) ? grandParent.PropertyDataType : ((parent.hasOwnProperty('_meta')) ? parent._meta.parentClassName : null),
_propertyName: parent.PropertyName,
};
if (updateItem.Query._parentClassId == null) {
delete updateItem.Query._parentClassId;
}
if (updateItem.Query._parentClassName == null) {
delete updateItem.Query._parentClassName;
}
if (updateItem.Query._propertyName == null) {
delete updateItem.Query._propertyName;
}
} else {
updateItem.Query = { _kid: self.model._kid, _parentClassId: getParentClassId(), _parentClassName: getParentClassName(), _propertyName: getPropertyName() };
}
updateItem.UpdateValue = updateObject;
updateRequest.BulkUpdates.push(updateItem);
axios({
method: 'post',
url: Endpoints.UpdateDataForSchema,
data: updateRequest,
}).then(function (response) {
if (response.data && Array.isArray(response.data) && response.data.length) {
if (!self.model._kid) { // for newly created obj
var newKid = response.data[0].Kid;
self.model._kid = newKid;
var currentSchemaDataPath = _.cloneDeep(self.currentSchemaDataPath);
var lastSchemaDataPath = currentSchemaDataPath[currentSchemaDataPath.length - 1];
if (lastSchemaDataPath.Type === ARRAY_TYPE && !lastSchemaDataPath.hasOwnProperty('Filter')) { // when adding new item to complex array
lastSchemaDataPath.Filter = { _kid: newKid };
var newLength = Number(lastSchemaDataPath._meta.Length) ? (lastSchemaDataPath._meta.Length + 1) : 1;
Object.assign(lastSchemaDataPath._meta, { ClickedIndex: newLength, Length: newLength });
lastSchemaDataPath.IsAddNew ? delete lastSchemaDataPath.IsAddNew : null;
Vue.set(self, 'currentSchemaDataPath', currentSchemaDataPath);
}
}
}
self.toggleFieldsEditable(false);
self.resetFieldsToNonEditable();
toastr.success('Save successful');
if (self.isRenderingPhoneNumber) {
self.getSchemaDataForActiveProperty();
} else {
self.showLoader(false);
}
if (callback && typeof callback === 'function') {
callback();
}
}).catch(function (response) {
self.showLoader(false);
self.toggleFieldsEditable(false);
toastr.error('Error');
console.error('err', response);
});
function getParentClassId() {
var parentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
if (parentSegment.Type === COMPLEX_OBJECT_TYPE) {
return parentSegment._meta.parentClassId;
} else {
return parentSegment.Filter._kid;
}
}
function getParentClassName() {
var currentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
return currentSegment.PropertyDataType;
}
function getPropertyName() {
var currentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
return currentSegment.PropertyName;
}
},
updateDataForVMN: function () {
var self = this;
self.showLoader(true);
self.showPhoneNumberUpdateModel();
},
addDataForSchema: function (callback) {
var self = this;
var requestObj = {
WebsiteId: null,
Data: {},
};
axios({
method: 'post',
url: Endpoints.AddDataForSchema,
data: requestObj,
}).then(function (response) {
Vue.set(self.model, '_kid', response.data);
Vue.set(self, 'new_site', false);
var schemaNavigationPath = _.cloneDeep(self.currentSchemaDataPath);
var baseSegment = schemaNavigationPath[0];
baseSegment._meta = { parentClassId: response.data };
Vue.set(self, 'currentSchemaDataPath', schemaNavigationPath);
if (callback && typeof callback === 'function') {
callback();
}
}).catch(function (err) {
toastr.error("Error", "Error");
})
},
toggleFieldsEditable: function (toggle) {
var self = this;
self.areFieldsEditable = toggle;
},
// reset input fields to non editable
resetFieldsToNonEditable: function () {
let self = this;
let fields = self.schema.groups[0].fields;
let activebtns = _.filter(fields, function (field) {
if (!field.readonly && field.visible) {
return true;
}
});
_.forEach(activebtns, function (field) {
Vue.set(field, 'readonly', !field.readonly);
});
self.areFieldsEditable = false;
},
setIsImageForUploading: function (isImage) {
let self = this;
Vue.set(self.upload, 'isImage', isImage);
},
// delete array item or image
deleteProperty: function () {
var self = this;
var item = self.propertyToDelete;
var requestObj = { BulkDelete: [] };
var deleteItem = {
_kid: item._kid,
_parentClassId: item._parentClassId,
_parentClassName: item._parentClassName,
_propertyName: item._propertyName
};
requestObj.BulkDelete.push(deleteItem);
self.showLoader(true);
axios({
method: 'post',
url: Endpoints.DeleteDataForSchema,
data: requestObj
}).then(function (response) {
self.showLoader(false);
toastr.success('Delete Successful');
self.cancelPropertyDelete();
if (self.isRenderingComplexArray) {
var currentPath = _.cloneDeep(self.currentSchemaDataPath);
var lastSegment = currentPath[currentPath.length - 1];
lastSegment.Length--;
Vue.set(self, 'currentSchemaDataPath', currentPath);
}
self.getSchemaDataForActiveProperty();
}).catch(function (response) {
self.showLoader(false);
self.cancelPropertyDelete();
toastr.error("Error", "Error");
self.getSchemaDataForActiveProperty();
});
},
confirmDeleteProperty: function (item) {
var self = this;
var lastPathSegment = _.last(self.currentSchemaDataPath);
if (lastPathSegment.Type === 1 && !lastPathSegment.Filter) { // is deleting from array
var parentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
item._parentClassId = parentSegment._meta.parentClassId;
item._propertyName = lastPathSegment.PropertyName;
item._parentClassName = parentSegment.PropertyDataType;
item.displayText = lastPathSegment.PropertyDataType;
}
Vue.set(self, 'propertyToDelete', item);
self.showDeleteObjModal();
},
cancelPropertyDelete: function () {
var self = this;
Vue.set(self, 'propertyToDelete', {});
self.hideAllModals();
},
deleteConfirm: function () {
var self = this;
if (self.isNative) {
var newArray = _.cloneDeep(self.model[self.currentModel]);
newArray.splice(self.delete.index, 1);
Vue.set(self.model, self.currentModel, newArray);
self.updateDataForSchema(function () {
Vue.set(self, 'delete', {
displayIndex: null,
index: null,
that: null
});
});
self.hideAllModals();
}
},
/**
* Just receives the update object and calls the api and sends the response as callback
**/
updateDataForSchemaSlim: function (updateObj, callback, errorCallback) {
if (!updateObj) {
return;
}
let self = this;
self.showLoader(true);
if (self.new_site) {
self.addDataForSchema(function () {
self.updateDataForSchemaSlim(updateObj, callback);
});
return;
}
axios({
method: 'post',
url: Endpoints.UpdateDataForSchema,
data: updateObj
}).then(function (response) {
self.showLoader(false);
toastr.success('Save successful');
if (callback && typeof callback === 'function') {
callback(response.data);
}
}).catch(function (response) {
self.showLoader(false);
if (errorCallback && errorCallback === 'function') {
errorCallback(response);
}
toastr.error("", "Error");
});
},
getDataByPropertySlim: function (requestObj, successCb, errorCb) {
var self = this;
axios({
method: 'POST',
url: Endpoints.GetDataByProperty,
data: requestObj,
}).then(function (response) {
if (successCb && typeof successCb === 'function') {
successCb(response.data);
}
}).catch(function (error) {
if (errorCb && typeof errorCb === 'function') {
errorCb(error.response.data);
}
});
},
getBaseClassIdForWebsite: function (successCb, errorCb) {
var self = this;
var requestObj = {
PropertySegments: [
{
PropertyName: self.schemaName,
PropertyDataType: self.schemaName,
Type: 5
}
]
};
self.getDataByPropertySlim(requestObj, function (response) {
if (successCb && typeof successCb === 'function') {
successCb(response);
}
}, function (err) {
if (errorCb && typeof errorCb === 'function') {
errorCb(err);
}
});
},
// VMN/CallTracker - START
isCallTrackerEnabled: function () {
var self = this;
axios({
method: 'post',
url: Endpoints.IsCallTrackerEnabled
}).then(function (response) {
if (response.data && response.data.hasOwnProperty('isActive')) {
self.isCallTrackerEnabledForWebsite = response.data.isActive;
} else {
self.isCallTrackerEnabledForWebsite = false;
}
}).catch(function () {
self.isCallTrackerEnabledForWebsite = false;
});
},
showPhoneNumberUpdateModel: function () {
var self = this;
var classType = 'phonenumber';
self.getDataForClassByClassType(classType, function (classData) {
var otherOccourances = self.isMultipleOccouranceOfVMNPresent(self.oldModel, classData);
if (otherOccourances && otherOccourances.length > 1) {
self.vmnData.sameVMNNumberList = otherOccourances;
self.modalShowStatus.vmnUpdate = true;
} else {
self.updateDataForSchema(null, true);
}
});
},
isMultipleOccouranceOfVMNPresent: function (phoneNumberObj, classData) {
var otherOccourances = [];
if (!classData || !classData.Data || !Array.isArray(classData.Data)) {
return otherOccourances;
}
classData.Data.map(function (item) {
if (phoneNumberObj.contactnumber == item.contactnumber && item.isactive == true) {
otherOccourances.push(item);
}
});
return otherOccourances;
},
updateAllVMN: function () {
var self = this;
var updateObj = self.getVMNBulkUpdateObj();
self.updateDataForSchemaSlim(updateObj, function (successResponse) {
self.resetFieldsToNonEditable();
self.getSchemaDataForActiveProperty();
self.showHideModal(Modal.VMNUPDATE, false);
self.vmnData.sameVMNNumberList = [];
}, function () {
self.resetFieldsToNonEditable();
});
},
getVMNBulkUpdateObj: function () {
var self = this;
var updateObj = {
BulkUpdates: [],
Query: null,
UpdateValue: null
};
if (self.vmnData.sameVMNNumberList.length < 1) {
return updateObj;
}
var newValueToUpdate = Object.assign({}, _.pick(self.model, [
'calltrackernumber',
'contactnumber',
'countrycode',
'isactive',
'websiteid'
]));
self.vmnData.sameVMNNumberList.map(function (phonenumber) {
var updateItem = {
Query: _.pick(phonenumber, ['_parentClassId', '_parentClassName', '_propertyName', '_kid']),
UpdateValue: newValueToUpdate
};
updateObj.BulkUpdates.push(updateItem);
});
return updateObj;
},
// update this phone number and get the new calltracker number
updateThisVMNAndGetNewCallTracker: function () {
var self = this;
var updateObj = {
BulkUpdates: [],
Query: {},
UpdateValue: null
};
var nonActiveNumber = Object.assign({}, getVMNUpdateObj(self, false));
var activeNumber = Object.assign({}, getVMNUpdateObj(self, true));
updateObj.BulkUpdates.splice(0, 0, nonActiveNumber, activeNumber);
self.updateDataForSchemaSlim(updateObj, function (response) {
self.resetFieldsToNonEditable();
self.getSchemaDataForActiveProperty();
self.showHideModal(Modal.VMNUPDATE, false);
});
function getVMNUpdateObj(context, isActive) {
var valueToUpdate = {
Query: {
_parentClassId: getParentClassId(),
_parentClassName: getParentClassName(),
_propertyName: getPropertyName(),
_kid: self.model._kid,
},
UpdateValue: Object.assign({}, context.model, { 'isactive': isActive }),
};
return valueToUpdate;
}
function getParentClassId() {
var parentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
if (parentSegment.Type === COMPLEX_OBJECT_TYPE) {
return parentSegment._meta.parentClassId;
} else {
return parentSegment.Filter._kid;
}
}
function getParentClassName() {
var currentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
return currentSegment.PropertyDataType || null;
}
function getPropertyName() {
var currentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 1];
return currentSegment.PropertyName;
}
},
// VMN / CallTracker - END
// MODAL START
showHideModal: function (modalName, show) {
var modalStatus = this.modalShowStatus;
Vue.set(modalStatus, modalName, show)
},
hideAllModals: function () {
var self = this;
var modalStatus = self.modalShowStatus;
for (var key in modalStatus) {
self.showHideModal(key, false);
}
self.resetArrayPropertyMaxCountModal();
},
resetArrayPropertyMaxCountModal: function () {
var self = this;
for (var key in self.arrayPropertyMaxCountModal) {
self.arrayPropertyMaxCountModal[key] = null;
}
},
showDeleteObjModal: function () {
var self = this;
self.modalShowStatus.deleteObject = true;
},
unsavedChangesModal: function (open) {
var self = this;
self.showHideModal(Modal.UPDATE, open ? true : false);
},
// save action in Modal
saveUnsavedChanges: function () {
var self = this;
self.updateDataForSchema();
self.unsavedChangesModal(false);
},
discardUnsavedChanges: function () {
var self = this;
self.resetFieldsToNonEditable();
self.unsavedChangesModal(false);
},
showhavingIssuesModal: function () {
var self = this;
self.showHideModal(Modal.HAVINGISSUES, true);
self.supportEmailForm.message = 'Hi, \n \n' +
'I\'m facing issues while adding content to my website "' + localStorage.getItem("DOMAIN") +
'". You can reach out to me at ' +
self.customerData.contact.email + (self.customerData.contact.phoneNumber ? (' or ' + self.customerData.contact.phoneNumber) : "") +
" ." + '\n \n Debug Id : ' + self.kidForReportingIssue;
},
// MODAL END
// support email START
isSupportEmailFormValid: function () {
var self = this;
return (self.supportEmailForm.message != null && self.supportEmailForm.message.length > 0);
},
cancelSendSupportEmail: function () {
var self = this;
self.hideAllModals();
self.resetSupportEmailForm();
},
resetSupportEmailForm: function () {
var self = this;
self.supportEmailForm.subject = 'Reporting an issue for website: ' + localStorage.getItem('DOMAIN');
self.supportEmailForm.message = '';
self.supportEmailForm.image = null;
},
processUploadedFile: function (event) {
var self = this;
var files = event.target.files || event.dataTransfer.files;
if (!files.length) {
return;
}
self.supportEmailForm.image = files[0];
//to-do show image preview
},
sendSupportEmail: function (event) {
var self = this;
self.hideAllModals();
if (!self.isSupportEmailFormValid()) {
event.preventDefault();
event.stopPropagation();
return;
}
var emailRequest = {
To: self.supportEmailForm.to,
Subject: self.supportEmailForm.subject,
EmailBody: self.supportEmailForm.message,
Attachments: [],
clientId: self.supportEmailForm.clientId
};
if (self.supportEmailForm.image) {
self.uploadSupportEmailImage(self.supportEmailForm.image, function (uploadedUrl) {
emailRequest.Attachments = uploadedUrl.error ? [] : [uploadedUrl];
self.sendEmail(emailRequest);
self.logSupportEmailInWebAction(emailRequest);
self.resetSupportEmailForm();
});
} else {
self.sendEmail(emailRequest);
self.logSupportEmailInWebAction(emailRequest);
self.resetSupportEmailForm();
}
},
uploadSupportEmailImage: function (image, callback) {
var self = this;
var formData = new FormData();
formData.append('File', image);
formData.append('WebactionName', self.systemWebactions.supportEmail.name);
formData.append('AuthId', self.systemWebactions.supportEmail.authId);
formData.append('FileName', image.name);
axios({
method: 'post',
url: Endpoints.UploadFileToSystemWebaction,
config: { headers: { 'Content-Type': 'multipart/form-data' } },
data: formData
}).then(function (response) {
callback(response.data);
}).catch(function (error) {
callback({ error: 'error' });
});
},
logSupportEmailInWebAction: function (emailObj) {
var self = this;
var payload = {
webactionName: self.systemWebactions.supportEmail.name,
authId: self.systemWebactions.supportEmail.authId,
webactionData: {
ActionData: {
Subject: emailObj.Subject,
EmailBody: emailObj.EmailBody,
Attachments: emailObj.Attachments,
kid: self.kidForReportingIssue,
developerId: self.customerData.developerId || ''
},
WebsiteId: self.customerData.websiteId
},
};
axios({
method: 'post',
url: Endpoints.AddDataToSystemWebaction,
data: payload
}).catch(function (error) {
console.error('there is an error logging your webaction');
});
},
sendEmail: function (request) {
if (request.To.length < 2) {
return;
}
axios({
method: 'post',
url: Endpoints.SendEmail,
data: request
}).then(function (response) {
toastr.success("", "Successfully sent the email");
}).catch(function (error) {
toastr.error("", "Error sending support email");
});
},
showGenericHelpModal: function () {
this.showhavingIssuesModal();
},
// support email END
// Rich Text Editor -- Start
intializeFroala: function () {
var self = this;
var richText = self.richText;
richText.froala = FroalaEditor(richText.elementId);
richText.froala.initialize();
richText.froala.setContent(richText.content);
},
onRichTextModalSave: function () {
var self = this;
var richText = self.richText;
richText.content = richText.froala.getContent();
Vue.set(self.model, richText.requestedPropertyName, richText.content);
self.showHideModal(Modal.RICHTEXTEDITOR, false);
self.updateDataForSchema();
},
onRichTextModalCancel: function () {
var self = this;
Vue.set(self.richText, 'content', '');
self.showHideModal(Modal.RICHTEXTEDITOR, false);
},
// Rich Text Editor -- End
// Text Area Start
onTextAreaModalSave: function () {
var self = this;
var textArea = self.textArea;
Vue.set(self.model, textArea.requestedPropertyName, textArea.content);
self.showHideModal(Modal.TEXTAREA, false);
self.updateDataForSchema();
},
onTextAreaModalCancel: function () {
var self = this;
Vue.set(self.textArea, 'content', '');
self.showHideModal(Modal.TEXTAREA, false);
},
// Text Area End
// data console mode
removeSidebar: function () {
var $el = document.getElementById('wrapper');
$el.classList.remove('toggled');
},
// REFERENCING START ---
// managing object selectors --start
findSelectors: function (propertyList, root) {
var propertyNames = [];
for (let i = 0; i < propertyList.length; i++) {
let property = propertyList[i];
let name = property.Name;
let type = property.Type;
let isDefaultProperty = !!PropertyVisibliityStatus[name];
let valid = selectorsRegex.test(name) && (propertyNames.length <= 3) && (!isDefaultProperty);
if (valid) {
propertyNames.push(name);
}
}
return propertyNames;
},
containProperties: function (propertyList, root) {
var propertyNames = [],
length = propertyList.length >= 3 ? 3 : propertyList.length, // 3 -> minimum number of properties to show
i = 0;
while (propertyNames.length < length && i < propertyList.length) {
let name = propertyList[i].Name;
let isDefaultProperty = !!PropertyVisibliityStatus[name];
if (!isDefaultProperty) {
propertyNames.push(name);
}
i++;
}
return propertyNames;
},
/**
* Referencing Forward
**/
setSelectedclassNameInReferenceData: function (item) {
var self = this,
className = item ? item.name : null;
if (className && className.trim()) {
self.referenceData.selectedClassName = className;
self.setSlidingPanelLevel(SlidingPanelLevel.PROPERTIES);
} else {
console.error("setSelectedclassNameInReferenceData: className can't be empty or null : ", className);
}
},
/**
* Referencing Forward
**/
setSelectedPropertyNameInReferenceData: function (item) {
var self = this,
propertyName = item ? item.name : null;
if (propertyName && propertyName.trim()) {
self.referenceData.selectedPropertyName = propertyName;
self.setSlidingPanelLevel(SlidingPanelLevel.OBJECTS);
} else {
console.error("setSelectedPropertyInReferenceData: propertyName can't be null or empty : ", propertyName);
}
},
// Referencing - get reverse referencing classes
getSimilarPropertiesToReferTo: function () {
var self = this;
self.getClassesByClassType(self.currentClassName, function (referenceProperties) {
if (referenceProperties && referenceProperties.length) {
referenceProperties = referenceProperties.filter(function (item) {
return self.isSelfReferencing(item) != true;
});
Vue.set(self.referenceData.reverseReference, 'relatedClassTypes', referenceProperties);
self.processReverseReferenceData(referenceProperties);
self.openReferenceSideBar(true);
} else if (referenceProperties && referenceProperties.length === 0) {
toastr.error("something went wrong");
}
});
},
isSelfReferencing: function (item) {
var self = this;
var splitItems = item.split(':');
var isSelfRefer = false;
var dataPath = '';
var lastSegment = _.last(self.currentSchemaDataPath);
var lastSplitItem = _.last(splitItems);
return (lastSegment.PropertyName === lastSplitItem.split('.')[1] && splitItems.length == self.currentSchemaDataPath.length - 1);
},
/**
* Referencing reverse - process the reverse reference data and set props for Sliding Panel
**/
processReverseReferenceData: function (refData) {
var self = this;
var referencePanelList = [];
var data = {
Data: [],
GroupCount: []
};
refData.map(parseResponse);
Vue.set(self.referenceData, 'data', data);
function parseResponse(item) {
var listItemText = '';
var splitItems = item.split(':');
splitItems = splitItems.reverse();
var obj = {
Count: 0,
Name: '',
SubGroupCounts: []
};
if (splitItems.length == 1) {
var path = splitItems[0].split('.')[1];
obj.Name += path;
} else {
splitItems.map(function (splitItem, index) {
var path = splitItem.split('.');
if (path[0] == self.schemaName) {
obj.Name += ' of ' + path[1];
} else {
if (index == 0) {
//obj.Name += ' ' + splitItem.split('.')[1] + ' of ' + splitItem.split('.')[0];
obj.Name += ' ' + splitItem.split('.')[1];
} else if (index != splitItems.length - 1) {
obj.Name += ' of ' + splitItem.split('.')[1];
}
}
});
}
data.GroupCount.push(obj);
}
},
// Reverse Referencing - get data by property
getDataByPropertyName: function (propertyPath, callback) {
if (!propertyPath || typeof propertyPath !== 'string' || !propertyPath.length) {
if (callback && typeof callback == 'function') {
callback();
}
return;
}
var self = this;
var requestObj = {
PropertySegments: []
};
var segments = propertyPath.split(':');
var propertySegmentItem = {};
var classType = segments[segments.length - 1].split('.')[0];
var propertyName = segments[segments.length - 1].split('.')[1];
propertySegmentItem.PropertyName = segments[0].split('.')[0];
propertySegmentItem.PropertyDataType = segments[0].split('.')[0];
propertySegmentItem.Type = 5;
requestObj.PropertySegments.push(propertySegmentItem);
if (segments.length > 1) {
segments.map(function (segment, index) {
if ((index + 1) < segments.length) {
var classType = _.find(self.languageSchema.Classes, { Name: segments[index + 1].split('.')[0] });
var requiredProps = [];
classType.PropertyList.map(function (prop) {
if (prop.Type !== COMPLEX_OBJECT_TYPE && prop.Type !== ARRAY_TYPE) {
requiredProps.push(prop.Name);
} else if (prop.Type === COMPLEX_OBJECT_TYPE && prop.DataType.Name === 'image') {
requiredProps.push(prop.Name);
}
});
propertySegmentItem = {};
propertySegmentItem.PropertyName = segment.split('.')[1];
propertySegmentItem.PropertyDataType = segments[index + 1].split('.')[0];
propertySegmentItem.Type = self.isPropertyAnArray(segment.split('.')[1], segment.split('.')[0]) ? 1 : 5;
propertySegmentItem.Limit = (propertySegmentItem.Type === ARRAY_TYPE) ? self.maxArraySizeForDataFetching : 0;
propertySegmentItem.ObjectKeys = {};
requiredProps.map(function (key) {
propertySegmentItem.ObjectKeys[key] = true;
});
requestObj.PropertySegments.push(propertySegmentItem);
}
});
} else {
if (!self.schemaData[propertyName] || !Array.isArray(self.schemaData[propertyName])) {
return;
}
var data = {
Data: Object.assign({}, {
'_parentClassName': segments[0].split('.')[0],
'_propertyName': segments[0].split('.')[1],
'_parentClassId': self.schemaData._kid,
'_kid': self.schemaData._kid,
}),
};
data.Data[propertyName] = self.schemaData[propertyName];
return callback(data, classType, propertyName);
}
self.showLoader(true);
axios({
method: 'post',
url: Endpoints.GetDataByProperty,
data: requestObj,
}).then(function (response) {
self.showLoader(false);
callback(response.data, classType, propertyName);
}).catch(function (error) {
self.showLoader(false);
callback(null, classType, propertyName);
});
},
// checks if the given property for the given class is an array or not
// from the language
isPropertyAnArray: function (propertyName, parentClassName) {
var self = this;
var isArray = false;
var parentClass = _.find(self.languageSchema.Classes, { Name: parentClassName });
if (parentClass) {
parentClass = Array.isArray(parentClass) ? parentClass[0] : parentClass;
if (parentClass.hasOwnProperty('Name')) {
var propertyObj = _.find(parentClass.PropertyList, { Name: propertyName });
if (propertyObj) {
propertyObj = Array.isArray(propertyObj) ? propertyObj[0] : propertyObj;
if (propertyObj.hasOwnProperty('Type') && propertyObj.Type === 1) {
isArray = true;
}
}
}
}
return isArray;
},
/**
* Referencing Reverse - to get related classes by class type
**/
getClassesByClassType: function (classType, callback) {
var self = this;
var referenceData = self.referenceData;
if (classType != null) {
referenceData.isfetchingData = true;
}
referenceData.isfetchingData = true;
axios({
method: 'POST',
url: Endpoints.GetClassesByClassType,
data: { classType: classType },
}).then(function (response) {
referenceData.isfetchingData = false;
callback(response.data);
}).catch(function (err) {
referenceData.isfetchingData = false;
toastr.error("error while getting classes for reverse referencing.", "Error");
});
},
removePropertyRecursivelyFromObject: function (propertyList, object) {
if (!propertyList || !Array.isArray(propertyList) || !propertyList.length) {
return object;
}
propertyList.map(function (property) {
recursivelyRemoveProperty(property, object);
});
return object;
function recursivelyRemoveProperty(property, object) {
for (var key in object) {
if (typeof object[key] === 'object') {
recursivelyRemoveProperty(property, object[key]);
} else if (!_.isEmpty(object[key]) && key === property) {
delete object[key];
}
}
}
},
selectFromExisting: function (fieldObj) {
var self = this;
if (self.areFieldsEditable) {
self.unsavedChangesModal(true);
return;
}
if (!self.model._kid) {
self.saveCurrentObj(function () {
self.selectFromExisting(fieldObj);
});
}
var objectSegment = {
PropertyDataType: fieldObj.propertyDataType,
PropertyName: fieldObj.propertyName,
Type: fieldObj.type,
};
self.currentClassName = fieldObj.propertyDataType;
self.currentSchemaDataPath.push(objectSegment);
self.resetCurrentGroup();
self.getSchemaForActiveProperty(fieldObj);
self.openReferenceSideBar();
},
openReferenceSideBar: function (isForReverseReference) {
var self = this;
var referenceData = self.referenceData;
Vue.set(referenceData, "requestedClassName", self.currentClassName);
if (isForReverseReference !== true) {
self.setSlidingPanelLevel(SlidingPanelLevel.CLASSES);
Vue.set(referenceData, 'isForReverseReference', false);
} else if (isForReverseReference === true && referenceData.data.GroupCount.length > 0) {
self.setSlidingPanelLevel(SlidingPanelLevel.CLASSES);
Vue.set(referenceData, 'isForReverseReference', true);
}
if (isForReverseReference === true && referenceData.data.GroupCount.length === 0) {
toastr.error("something went wrong");
}
},
referenceSaveAction: function () {
var self = this;
var referenceData = self.referenceData;
if (!self.isForReverseReference) {
if (referenceData.forwardReference.isMultipleSelect) {
self.addSelectedReferenceItemToArray();
} else {
var dataToUpdate = Object.assign({}, referenceData.selectedForwardReferenceItem);
dataToUpdate = _.cloneDeep(self.removePropertyRecursivelyFromObject(['_kid', '_id'], dataToUpdate));
Vue.set(self, 'model', dataToUpdate);
self.resetReferenceData();
var requestObj = {
BulkUpdates: [],
Query: null,
UpdateValue: null,
};
var lastSegment = _.last(self.currentSchemaDataPath);
var parentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
var _parentClassId = null;
if (parentSegment._meta && parentSegment._meta.parentClassId) {
_parentClassId = parentSegment._meta.parentClassId
} else if (parentSegment.Filter && parentSegment.Filter._kid) {
_parentClassId = parentSegment.Filter._kid;
}
var updateItem = {
Query: {
_parentClassId: _parentClassId,
_parentClassName: parentSegment.PropertyDataType,
_propertyName: lastSegment.PropertyName,
},
UpdateValue: self.removeExtraPropertiesFromObjectForReference(dataToUpdate),
};
requestObj.BulkUpdates.push(updateItem);
self.resetReferenceData();
self.updateDataForSchemaSlim(requestObj, function (response) {
self.getSchemaDataForActiveProperty();
});
}
} else {
self.referenceData.level = 0;
var requestObj = {
BulkUpdates: [],
Query: null,
UpdateValue: null
};
requestObj.BulkUpdates = self.getReverseReferenceUpdateObject();
self.resetReferenceData();
self.updateDataForSchemaSlim(requestObj, function (response) {
toastr.success('Save successful');
});
}
},
getReverseReferenceUpdateObject: function () {
var self = this;
var referenceData = self.referenceData;
var bulkUpdateArr = [];
_.map(referenceData.reverseReference.selectedItems, function (item) {
var bulkUpdateItem = {};
bulkUpdateItem.Query = {
_parentClassId: item._kid,
_parentClassName: referenceData.requestedClassName,
_propertyName: referenceData.reverseReference.propertyToRefer,
};
bulkUpdateItem.UpdateValue = self.removePropertyRecursivelyFromObject(['_kid'], Object.assign({}, self.model));
bulkUpdateArr.push(bulkUpdateItem);
});
return bulkUpdateArr;
},
resetReferenceData: function () {
var self = this;
var referenceData = self.referenceData;
Vue.set(self, 'referenceData', Object.assign({}, _.cloneDeep(referenceDataObjectTemplate)));
},
/**
* Referencing - set the current model to the selected reference object
**/
updateCurrentPropertyWithSelectedReferencedObject: function (obj) {
var self = this;
if (obj) {
var processedObject = self.removeExtraPropertiesFromObjectForReference(obj);
var currentObjectProperties = self.model;
var currentModel = Object.assign({}, self.model);
var originalProperties = Object.keys(self.removeExtraPropertiesFromObjectForReference(currentModel));
var replaceProperties = Object.keys(processedObject);
var differenceProperties = _.differenceWith(originalProperties, replaceProperties);
differenceProperties.map(setEmptyProperties);
function setEmptyProperties(property) {
delete self.model[property];
}
var updateProperties = function (propertyName) {
Vue.set(self.model, propertyName, processedObject[propertyName]);
}
if (processedObject && Object.keys(processedObject)) {
Object.keys(processedObject).forEach(updateProperties);
}
} else {
console.error("updateCurrentPRopertyForSelectedReferncedObject obj cant be null or empty", obj);
}
},
/**
* Referencing forward - select multiple
**/
addExistingItemsToArray: function () {
var self = this;
self.currentClassName = _.last(self.currentSchemaDataPath).PropertyDataType;
self.referenceData.forwardReference.isMultipleSelect = true;
self.openReferenceSideBar();
},
/**
* Referencing - forward reference - add multiple items to the array
**/
addSelectedReferenceItemToArray: function () {
var self = this;
var selectedItems = self.referenceData.forwardReference.selectedItems.slice();
if (selectedItems.length < 1) {
return;
}
selectedItems.forEach(function (item) {
self.removePropertyRecursivelyFromObject(['_kid'], item);
});
var requestObj = {
BulkUpdates: [],
Query: null,
UpdateValue: null,
};
var lastSegment = _.last(self.currentSchemaDataPath);
var parentSegment = self.currentSchemaDataPath[self.currentSchemaDataPath.length - 2];
var _parentClassId = null;
if (parentSegment._meta && parentSegment._meta.parentClassId) {
_parentClassId = parentSegment._meta.parentClassId
} else if (parentSegment.Filter && parentSegment.Filter._kid) {
_parentClassId = parentSegment.Filter._kid;
}
selectedItems.map(function (item) {
var updateItem = {
Query: {
_parentClassId: _parentClassId,
_parentClassName: parentSegment.PropertyDataType,
_propertyName: lastSegment.PropertyName,
},
UpdateValue: self.removeExtraPropertiesFromObjectForReference(item),
};
requestObj.BulkUpdates.push(updateItem);
});
self.resetReferenceData();
self.updateDataForSchemaSlim(requestObj, function (response) {
if (!response || !Array.isArray(response)) {
return;
}
var newlyAddedCount = response.length;
var currentPath = _.cloneDeep(self.currentSchemaDataPath);
var lastSegment = currentPath[currentPath.length - 1];
lastSegment.Length = Number(lastSegment.Length) ? (lastSegment.Length + newlyAddedCount) : newlyAddedCount;
Vue.set(self, 'currentSchemaDataPath', currentPath);
self.getSchemaDataForActiveProperty();
});
},
/**
* Referencing
**/
removeExtraPropertiesFromObjectForReference: function (obj) {
const propertiesToRemove = [
"_kid",
"_id",
"k_referenceid",
"createdon",
"updatedon",
//"isarchived",
"userid",
"schemaid",
"rootaliasurl",
"_propertyName",
"_parentClassName",
"_parentClassId"
];
if (obj) {
if (!obj.hasOwnProperty('_reflectionId')) {
obj['_reflectionId'] = obj["_kid"]
}
var removeProperty = function (propertyName) {
if (obj.hasOwnProperty(propertyName)) {
delete obj[propertyName];
}
};
_.forEach(propertiesToRemove, removeProperty);
}
return obj;
},
resetToastrPosition: function () {
toastr.options = {
"positionClass": "toast-top-right",
};
},
/**
* Referencing - Forward and VMN feature
* to get the data for the className (for referencing)
**/
getDataForClassByClassType: function (className, callback) {
var self = this,
classType = self.referenceData.requestedClassName || className;
if (classType != null) {
self.referenceData.isfetchingData = true;
}
if (classType && classType.trim()) {
$.ajax({
type: 'POST',
url: Endpoints.GetDataByClassName,
data: JSON.stringify({ classType: classType }),
contentType: "application/json",
success: function (data) {
if (data && self.referenceData.requestedClassName) {
Vue.set(self.referenceData, 'data', data);
} else if (callback) {
callback(data);
} else {
toastr.error("something went wrong.", "Error");
}
},
error: function (err) {
toastr.error("error while getting classes.", "Error");
},
complete: function () {
self.referenceData.isfetchingData = false;
}
});
} else {
//console.error("getDataForClassByClassType, classType not valid. classType : ", classType);
}
},
/**
* Referencing
**/
itemActions: function (item, index) {
var self = this,
level = self.referenceData.level;
if (item) {
switch (level) {
case SlidingPanelLevel.CLASSES:
if (self.referenceData.isForReverseReference) {
var propertyPathWithSegments = self.referenceData.reverseReference.relatedClassTypes[index];
self.getDataByPropertyName(propertyPathWithSegments, function (data, classType, propertyName) {
self.referenceData.requestedClassName = classType;
self.referenceData.reverseReference.propertyToRefer = propertyName;
if (data && data.Data) {
if (Array.isArray(data.Data)) {
self.referenceData.reverseReference.items = data.Data.slice(0);
} else {
self.referenceData.reverseReference.items.push(data.Data);
}
}
self.setSlidingPanelLevel(SlidingPanelLevel.PROPERTIES);
});
} else {
self.setSelectedclassNameInReferenceData(item);
}
break;
case SlidingPanelLevel.PROPERTIES:
if (self.referenceData.isForReverseReference) {
} else {
self.setSelectedPropertyNameInReferenceData(item);
}
break;
case SlidingPanelLevel.OBJECTS:
self.referenceData.selectedForwardReferenceItem = item;
break;
default:
console.error("Stage Not Valid :", level, item);
break;
}
} else {
console.error("error item not valid in itemActions", item);
}
},
/**
* Referencing
**/
setSlidingPanelLevel: function (val) {
var self = this;
if (val) {
self.referenceData.level = val;
}
},
/**
* Referencing
**/
referenceCancelAction: function () {
var self = this,
level = self.referenceData.level;
if (level == SlidingPanelLevel.CLASSES) {
self.referenceData.level -= 1;
self.resetReferenceData();
} else if (level == SlidingPanelLevel.PROPERTIES) {
if (self.referenceData.isForReverseReference === true) {
self.referenceData.reverseReference.items = [];
self.referenceData.reverseReference.selectedItems = [];
self.referenceData.reverseReference.selectedPath = null;
self.referenceData.reverseReference.propertyToRefer = null;
}
self.referenceData.level -= 1;
} else if (level == SlidingPanelLevel.OBJECTS) {
if (!self.referenceData.isForReverseReference) {
self.referenceData.selectedForwardReferenceItem = null;
self.referenceData.forwardReference.selectedItems = [];
}
self.referenceData.level -= 1;
}
},
},
watch: {
'referenceData.level': function (val, oldVal) {
if (val === SlidingPanelLevel.HIDDEN) {
this.resetToastrPosition();
}
if (val === SlidingPanelLevel.CLASSES) {
this.referenceData.selectedClassName = null;
this.referenceData.selectedPropertyName = null;
}
if (oldVal === SlidingPanelLevel.OBJECTS && val === SlidingPanelLevel.PROPERTIES) {
this.referenceData.selectedPropertyName = null;
}
},
// the oldModel can be used to get the old state of model before user edits the properties
'model': function (val, oldVal) {
var self = this;
if (val && val.hasOwnProperty('_kid') && self.oldModel['_kid'] !== val['_kid']) {
self.oldModel = Object.assign({}, val);
}
}
}
});
function showHavingIssueModal() {
vm.showhavingIssuesModal();
}
|
$:<< File.expand_path(File.dirname(__FILE__) + '/../..')
require 'test_helper.rb'
class ResponseTest < ActionDispatch::IntegrationTest
WARN_RESPONSE = {
:response => QBWC_CUSTOMER_QUERY_RESPONSE_WARN,
:code => '500',
:severity => 'Warn',
:message => QBWC_CUSTOMER_QUERY_STATUS_MESSAGE_WARN,
}
ERROR_RESPONSE = {
:response => QBWC_CUSTOMER_QUERY_RESPONSE_ERROR,
:code => '3120',
:severity => 'Error',
:message => QBWC_CUSTOMER_QUERY_STATUS_MESSAGE_ERROR,
}
def setup
ResponseTest.app = Rails.application
QBWC.on_error = :stop
QBWC.clear_jobs
$HANDLE_RESPONSE_EXECUTED = false
$HANDLE_RESPONSE_DATA = nil
$HANDLE_RESPONSE_IS_PASSED_DATA = false
end
def _receive_responses(*responses)
# Simulate controller authenticate
ticket_string = QBWC::ActiveRecord::Session.new(QBWC_USERNAME, COMPANY).ticket
assert_not_nil(ticket_string)
session = QBWC::Session.new(nil, COMPANY)
responses.each do |resp|
expect_error = "QBWC #{resp[:severity].upcase}: #{resp[:code]} - #{resp[:message]}"
# Simulate controller receive_response
$HANDLE_RESPONSE_EXECUTED = false
session.response = resp[:response]
assert_equal resp[:progress], session.progress unless resp[:progress].nil?
assert_equal resp[:code], session.status_code
assert_equal resp[:severity], session.status_severity
assert_equal expect_error, session.error
assert $HANDLE_RESPONSE_EXECUTED
# Simulate controller send_request
if session.progress == 100
assert_nil(session.next_request)
return
end
assert_not_nil(session.next_request)
end
end
def _test_warning_then_error(expected_progress1 = 50)
warn = WARN_RESPONSE.merge(:progress => expected_progress1)
error = ERROR_RESPONSE.merge(:progress => 100)
_receive_responses(warn, error)
end
def _test_error_then_warning(expected_progress1 = 50)
error = ERROR_RESPONSE.merge(:progress => expected_progress1)
warn = WARN_RESPONSE.merge(:progress => 100)
_receive_responses(error, warn)
end
def _test_error_then_warning_that_stops
_test_error_then_warning(100)
end
class HandleResponseWithDataWorker < QBWC::Worker
def requests(job, session, data)
{:customer_query_rq => {:full_name => '<NAME>'}}
end
def handle_response(response, session, job, request, data)
$HANDLE_RESPONSE_EXECUTED = true
$HANDLE_RESPONSE_IS_PASSED_DATA = (data == $HANDLE_RESPONSE_DATA)
end
end
test "handle_response is passed data" do
$HANDLE_RESPONSE_DATA = {:first => {:second => 2, :third => '3'} }
$HANDLE_RESPONSE_IS_PASSED_DATA = false
QBWC.add_job(:integration_test, true, '', HandleResponseWithDataWorker, nil, $HANDLE_RESPONSE_DATA)
session = QBWC::Session.new('foo', '')
assert_not_nil session.next_request
simulate_response(session, QBWC_CUSTOMER_ADD_RESPONSE_LONG)
assert_nil session.next_request
assert $HANDLE_RESPONSE_IS_PASSED_DATA
end
class HandleResponseRaisesExceptionWorker < QBWC::Worker
def requests(job, session, data)
{:customer_query_rq => {:full_name => '<NAME>'}}
end
def handle_response(response, session, job, request, data)
raise "Exception in handle_response"
end
end
test "handle_response raises exception" do
QBWC.add_job(:integration_test, true, '', HandleResponseRaisesExceptionWorker)
session = QBWC::Session.new('foo', '')
assert_not_nil session.next_request
simulate_response(session)
assert_nil session.next_request
assert_equal "Exception in handle_response", session.error
end
class HandleResponseOmitsJobWorker < QBWC::Worker
def requests(job, session, data)
{:customer_query_rq => {:full_name => '<NAME>'}}
end
def handle_response(*response)
$HANDLE_RESPONSE_EXECUTED = true
end
end
test "handle_response must use splat operator when omitting remaining arguments" do
QBWC.add_job(:integration_test, true, '', HandleResponseOmitsJobWorker)
session = QBWC::Session.new('foo', '')
assert_not_nil session.next_request
simulate_response(session)
assert_nil session.next_request
assert $HANDLE_RESPONSE_EXECUTED
end
class QueryAndDeleteWorker < QBWC::Worker
def requests(job, session, data)
{:name => 'mrjoecustomer'}
end
def handle_response(resp, session, job, request, data)
QBWC.delete_job(job.name)
end
end
test "processes warning responses and deletes the job" do
QBWC.on_error = :stop
# Add a job
QBWC.add_job(:query_joe_customer, true, COMPANY, QueryAndDeleteWorker)
# Simulate controller authenticate
ticket_string = QBWC::ActiveRecord::Session.new(QBWC_USERNAME, COMPANY).ticket
session = QBWC::Session.new(nil, COMPANY)
# Simulate controller receive_response
session.response = QBWC_CUSTOMER_QUERY_RESPONSE_WARN
assert_equal 100, session.progress
# Simulate controller send_request
assert_nil session.next_request
# Simulate arbitrary controller action
session = QBWC::ActiveRecord::Session.get(ticket_string) # simulated get_session
session.save # simulated save_session
end
test "processes error responses and deletes the job" do
QBWC.on_error = :stop
# Add a job
QBWC.add_job(:query_joe_customer, true, COMPANY, QueryAndDeleteWorker)
# Simulate controller authenticate
ticket_string = QBWC::ActiveRecord::Session.new(QBWC_USERNAME, COMPANY).ticket
session = QBWC::Session.new(nil, COMPANY)
# Simulate controller receive_response
session.response = QBWC_CUSTOMER_QUERY_RESPONSE_ERROR
assert_equal 100, session.progress
# Simulate controller send_request
assert_nil session.next_request
# Simulate controller get_last_error
session = QBWC::ActiveRecord::Session.get(ticket_string) # simulated get_session
session.save # simulated save_session
end
test "processes warning response stop" do
QBWC.on_error = :stop
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
_receive_responses(WARN_RESPONSE.merge(:progress => 100))
end
test "processes warning response continue" do
QBWC.on_error = :continue
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
_receive_responses(WARN_RESPONSE.merge(:progress => 100))
end
test "processes error response stop" do
QBWC.on_error = :stop
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
_receive_responses(ERROR_RESPONSE.merge(:progress => 100))
end
test "processes error response continue" do
QBWC.on_error = :continue
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
_receive_responses(ERROR_RESPONSE.merge(:progress => 100))
end
class MultiRequestWorker < QBWC::Worker
def requests(job, session, data)
[
{:customer_query_rq => {:full_name => 'First Request'}},
{:customer_query_rq => {:full_name => 'Second Request'}},
]
end
def handle_response(resp, session, job, request, data)
$HANDLE_RESPONSE_EXECUTED = true
end
end
test "processes warning then error stop 2jobs" do
QBWC.on_error = :stop
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
QBWC.add_job(:query_joe_customer_again, true, COMPANY, HandleResponseWithDataWorker)
_test_warning_then_error
end
test "processes warning then error continue 2jobs" do
QBWC.on_error = :continue
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
QBWC.add_job(:query_joe_customer_again, true, COMPANY, HandleResponseWithDataWorker)
_test_warning_then_error
end
test "processes warning then error stop 2requests byworker" do
QBWC.on_error = :stop
QBWC.add_job(:multiple_request_job, true, COMPANY, MultiRequestWorker)
_test_warning_then_error(0)
end
test "processes warning then error continue 2requests byworker" do
QBWC.on_error = :continue
QBWC.add_job(:multiple_request_job, true, COMPANY, MultiRequestWorker)
_test_warning_then_error(0)
end
test "processes warning then error stop 2requests byargument" do
QBWC.on_error = :stop
QBWC.add_job(:multiple_request_job, true, COMPANY, HandleResponseWithDataWorker, [QBWC_CUSTOMER_QUERY_RQ, QBWC_CUSTOMER_QUERY_RQ])
_test_warning_then_error(0)
end
test "processes warning then error continue 2requests byargument" do
QBWC.on_error = :continue
QBWC.add_job(:multiple_request_job, true, COMPANY, HandleResponseWithDataWorker, [QBWC_CUSTOMER_QUERY_RQ, QBWC_CUSTOMER_QUERY_RQ])
_test_warning_then_error(0)
end
test "processes error then warning stop 2jobs" do
QBWC.on_error = :stop
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
QBWC.add_job(:query_joe_customer_again, true, COMPANY, HandleResponseWithDataWorker)
_test_error_then_warning_that_stops
end
test "processes error then warning continue 2jobs" do
QBWC.on_error = :continue
QBWC.add_job(:query_joe_customer, true, COMPANY, HandleResponseWithDataWorker)
QBWC.add_job(:query_joe_customer_again, true, COMPANY, HandleResponseWithDataWorker)
_test_error_then_warning
end
test "processes error then warning stop 2requests byworker" do
QBWC.on_error = :stop
QBWC.add_job(:multiple_request_job, true, COMPANY, MultiRequestWorker)
_test_error_then_warning_that_stops
end
test "processes error then warning continue 2requests byworker" do
QBWC.on_error = :continue
QBWC.add_job(:multiple_request_job, true, COMPANY, MultiRequestWorker)
_test_error_then_warning(0)
end
test "processes error then warning stop 2requests byargument" do
QBWC.on_error = :stop
QBWC.add_job(:multiple_request_job, true, COMPANY, HandleResponseWithDataWorker, [QBWC_CUSTOMER_QUERY_RQ, QBWC_CUSTOMER_QUERY_RQ])
_test_error_then_warning_that_stops
end
test "processes error then warning continue 2requests byargument" do
QBWC.on_error = :continue
QBWC.add_job(:multiple_request_job, true, COMPANY, HandleResponseWithDataWorker, [QBWC_CUSTOMER_QUERY_RQ, QBWC_CUSTOMER_QUERY_RQ])
_test_error_then_warning(0)
end
end
|
#!/bin/bash
dieharder -d 207 -g 29 -S 2374669537
|
#!/bin/sh
### BEGIN INIT INFO
# Provides: ledplay_s
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start:
# Default-Stop:
# Short-Description: Enables/Disables each LED once at boot
### END INIT INFO
. @LIBEXEC@/ledctrl
led_test_s
exit 0
|
package migrations
const (
// recent changes to the pyup updater were made.
// since pyup updates their sec-db slowly, this
// bumps out any existing fingerprint associated
// with the pyup sec-db and forces a re-fetch
// and re-download by the updater code.
migration3 = `
UPDATE update_operation SET fingerprint = '' WHERE updater = 'pyupio';
`
)
|
class CloudStorageAccount:
service_name = 'Dropbox'
def __init__(self, username):
self.username = username
def get_username(self):
return self.username
|
#!/bin/sh
${TEST_RUNNER} sub
|
<gh_stars>10-100
package io.opensphere.geopackage.mantle;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.opensphere.core.Toolbox;
import io.opensphere.core.data.DataRegistry;
import io.opensphere.core.data.DataRegistryListenerAdapter;
import io.opensphere.core.data.util.DataModelCategory;
import io.opensphere.core.data.util.SimpleQuery;
import io.opensphere.core.preferences.Preferences;
import io.opensphere.core.preferences.PreferencesRegistry;
import io.opensphere.core.util.collections.New;
import io.opensphere.geopackage.model.GeoPackageLayer;
import io.opensphere.geopackage.model.GeoPackagePropertyDescriptors;
import io.opensphere.mantle.MantleToolbox;
import io.opensphere.mantle.controller.DataGroupController;
import io.opensphere.mantle.data.DataGroupInfo;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.mantle.data.impl.DefaultDataGroupInfo;
import io.opensphere.mantle.util.MantleToolboxUtils;
/**
* Creates data groups that represent the layers within a geopackage file. Given
* the root geopackage data group, this class will create a datagroup for the
* geopackage file and then create subsequent groups for each layer in a
* geopackage file. The creation will happen at startup if there are any saved
* geopackages, as well as on import.
*/
public class GeoPackageDataGroupController extends DataRegistryListenerAdapter<GeoPackageLayer>
{
/**
* The key to the list of imported klv files.
*/
protected static final String ourImportsKey = "imports";
/**
* The data model category to use for getting {@link GeoPackageLayer}.
*/
private static final DataModelCategory ourCategory = new DataModelCategory(null, null, GeoPackageLayer.class.getName());
/**
* The id of the root group.
*/
private static final String ourRootGroupId = "GeoPackage";
/**
* Used to add the geopackage root data group to the layers tree.
*/
private final DataGroupController myDataGroupController;
/**
* Creates the groups and data types for the layers within a geo package
* file.
*/
private final DataGroupBuilder myGroupBuilder;
/**
* The mantle toolbox.
*/
private final MantleToolbox myMantleToolbox;
/**
* Used to save which files have been imported.
*/
private final PreferencesRegistry myPrefsRegistry;
/**
* Contains the GeoPackage file data.
*/
private final DataRegistry myRegistry;
/**
* The root GeoPackage group.
*/
private final DataGroupInfo myRootGroup;
/**
* The system toolbox.
*/
private final Toolbox myToolbox;
/**
* Constructs a new DataGroupCreator.
*
* @param toolbox The system toolbox.
* @param tileListener The listener wanting notification of geopackage tile
* layer activations.
*/
public GeoPackageDataGroupController(Toolbox toolbox, LayerActivationListener tileListener)
{
myToolbox = toolbox;
myMantleToolbox = MantleToolboxUtils.getMantleToolbox(myToolbox);
myDataGroupController = myMantleToolbox.getDataGroupController();
myRegistry = toolbox.getDataRegistry();
myPrefsRegistry = toolbox.getPreferencesRegistry();
myRootGroup = new DefaultDataGroupInfo(true, myToolbox, ourRootGroupId, ourRootGroupId, "GPKG Files");
myDataGroupController.addRootDataGroupInfo(myRootGroup, this);
myGroupBuilder = new DataGroupBuilder(myToolbox, tileListener);
myRegistry.addChangeListener(this, ourCategory, GeoPackagePropertyDescriptors.GEOPACKAGE_LAYER_PROPERTY_DESCRIPTOR);
loadExisting();
}
/**
* Stops this object from listening for new imports.
*/
public void close()
{
myDataGroupController.removeDataGroupInfo(myRootGroup, this);
myRegistry.removeChangeListener(this);
myGroupBuilder.close();
}
/**
* Gets a set of all files that have been imported into the system.
*
* @return The set of files that are currently in the system.
*/
public Set<String> getImports()
{
Preferences prefs = myPrefsRegistry.getPreferences(GeoPackageDataGroupController.class);
return prefs.getStringSet(ourImportsKey, New.set());
}
@Override
public boolean isIdArrayNeeded()
{
return false;
}
@Override
public void valuesAdded(DataModelCategory dataModelCategory, long[] ids, Iterable<? extends GeoPackageLayer> newValues,
Object source)
{
List<GeoPackageLayer> layers = New.list();
for (GeoPackageLayer layer : newValues)
{
layers.add(layer);
}
createDataGroups(layers);
}
/**
* Gets the {@link DataGroupController}.
*
* @return The {@link DataGroupController}.
*/
protected DataGroupBuilder getDataGroupBuilder()
{
return myGroupBuilder;
}
/**
* Creates {@link DataGroupInfo} and {@link DataTypeInfo} for the passed in
* layers. These groups and types are then added to the rootGroup passed
* into the constructor.
*
* @param layers The layers to create groups and types for.
*/
private void createDataGroups(List<GeoPackageLayer> layers)
{
Map<String, DataGroupInfo> dataGroups = New.map();
Map<String, DataGroupInfo> layerGroups = New.map();
Map<String, String> layersToPackage = New.map();
for (GeoPackageLayer layer : layers)
{
String packageLayerId = layer.getPackageFile();
String layerId = layer.getPackageFile() + layer.getName();
layersToPackage.put(layerId, packageLayerId);
if (!dataGroups.containsKey(packageLayerId))
{
if (!getImports().contains(packageLayerId))
{
saveToPrefs(packageLayerId);
}
DataGroupInfo dataGroup = myGroupBuilder.createPackageGroup(layer, packageLayerId,
new GeoPackageDeleter(myMantleToolbox, myRegistry, () -> removeFromPrefs(packageLayerId)));
myRootGroup.addChild(dataGroup, this);
dataGroups.put(packageLayerId, dataGroup);
}
if (!layerGroups.containsKey(layerId))
{
DataGroupInfo dataGroup = myGroupBuilder.createLayerGroup(layer, layerId);
layerGroups.put(layerId, dataGroup);
}
DataGroupInfo layerGroup = layerGroups.get(layerId);
DataTypeInfo dataType = myGroupBuilder.createDataType(layer, layerId);
layerGroup.addMember(dataType, this);
}
for (DataGroupInfo dataGroup : layerGroups.values())
{
String packageId = layersToPackage.get(dataGroup.getId());
DataGroupInfo packageGroup = dataGroups.get(packageId);
packageGroup.addChild(dataGroup, this);
}
}
/**
* Loads existing imported geopackage files.
*/
private void loadExisting()
{
SimpleQuery<GeoPackageLayer> query = new SimpleQuery<>(ourCategory,
GeoPackagePropertyDescriptors.GEOPACKAGE_LAYER_PROPERTY_DESCRIPTOR);
myRegistry.performLocalQuery(query);
if (query.getResults() != null && !query.getResults().isEmpty())
{
createDataGroups(query.getResults());
}
}
/**
* Removes the feed from the saved list of imported files.
*
* @param geoPackagePath The file path to the geopackage file that has been
* removed from the system.
*/
private void removeFromPrefs(String geoPackagePath)
{
Preferences prefs = myPrefsRegistry.getPreferences(GeoPackageDataGroupController.class);
prefs.removeElementFromSet(ourImportsKey, geoPackagePath, this);
}
/**
* Adds the feed the the saved list of imported feeds.
*
* @param geoPackagePath The file path to the newly imported geo package
* file.
*/
private void saveToPrefs(String geoPackagePath)
{
Preferences prefs = myPrefsRegistry.getPreferences(GeoPackageDataGroupController.class);
prefs.addElementToSet(ourImportsKey, geoPackagePath, this);
}
}
|
<filename>z2clib/BaseCompiler.h
#ifndef _z2clib_BaseCompiler_h_
#define _z2clib_BaseCompiler_h_
#include "Assembly.h"
#include "Source.h"
class BaseCompiler {
public:
enum PlatformType {
WINDOWS32,
POSIX,
};
BaseCompiler(Assembly& aAss): ass(aAss) {
#ifdef PLATFORM_WIN32
Platform = WINDOWS32;
#endif
#ifdef PLATFORM_POSIX
Platform = POSIX;
#endif
}
VectorMap<String, String> LookUp;
PlatformType Platform;
int LookUpClass(ZSource& source, const String& className);
int LookUpClassInReferences(ZSource& source, const String& className);
int LookUpQualifiedClass(const String& className);
ZSource& LoadSource(ZSource& source);
ZSource* FindSource(const String& aSourcePath);
Assembly& GetAssembly() {
return ass;
}
protected:
Assembly& ass;
ArrayMap<String, ZPackage> packages;
int filesOpened = 0;
};
#endif
|
#!/usr/bin/env bash
# Copyright 2016 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.
# ==============================================================================
# Build a whl and container with Intel(R) MKL support
# Usage: build-dev-container.sh
DEBUG=1
DOCKER_BINARY="docker"
TMP_DIR=$(pwd)
# Helper function to traverse directories up until given file is found.
function upsearch () {
test / == "$PWD" && return || \
test -e "$1" && echo "$PWD" && return || \
cd .. && upsearch "$1"
}
function debug()
{
if [[ ${DEBUG} == 1 ]] ; then
echo $1
fi
}
function die()
{
echo $1
exit 1
}
# Set up WORKSPACE.
WORKSPACE="${WORKSPACE:-$(upsearch WORKSPACE)}"
ROOT_CONTAINER=${ROOT_CONTAINER:-tensorflow/tensorflow}
TF_ROOT_CONTAINER_TAG=${ROOT_CONTAINER_TAG:-devel}
# TF_BUILD_VERSION can be either a tag, branch, commit ID or PR number.
# For a PR, set TF_BUILD_VERSION_IS_PR="yes"
TF_BUILD_VERSION=${TF_DOCKER_BUILD_DEVEL_BRANCH:-master}
TF_BUILD_VERSION_IS_PR=${TF_DOCKER_BUILD_DEVEL_BRANCH_IS_PR:-no}
TF_REPO=${TF_REPO:-https://github.com/tensorflow/tensorflow}
FINAL_IMAGE_NAME=${TF_DOCKER_BUILD_IMAGE_NAME:-intel-mkl/tensorflow}
TF_DOCKER_BUILD_VERSION=${TF_DOCKER_BUILD_VERSION:-nightly}
BUILD_AVX_CONTAINERS=${BUILD_AVX_CONTAINERS:-no}
BUILD_AVX2_CONTAINERS=${BUILD_AVX2_CONTAINERS:-no}
BUILD_SKX_CONTAINERS=${BUILD_SKX_CONTAINERS:-no}
BUILD_CLX_CONTAINERS=${BUILD_CLX_CONTAINERS:-no}
CONTAINER_PORT=${TF_DOCKER_BUILD_PORT:-8888}
BUILD_TF_V2_CONTAINERS=${BUILD_TF_V2_CONTAINERS:-no}
ENABLE_SECURE_BUILD=${ENABLE_SECURE_BUILD:-no}
debug "ROOT_CONTAINER=${ROOT_CONTAINER}"
debug "TF_ROOT_CONTAINER_TAG=${TF_ROOT_CONTAINER_TAG}"
debug "TF_BUILD_VERSION=${TF_BUILD_VERSION}"
debug "TF_BUILD_VERSION_IS_PR=${TF_BUILD_VERSION_IS_PR}"
debug "FINAL_IMAGE_NAME=${FINAL_IMAGE_NAME}"
debug "TF_DOCKER_BUILD_VERSION=${TF_DOCKER_BUILD_VERSION}"
debug "BUILD_AVX_CONTAINERS=${BUILD_AVX_CONTAINERS}"
debug "BUILD_AVX2_CONTAINERS=${BUILD_AVX2_CONTAINERS}"
debug "BUILD_SKX_CONTAINERS=${BUILD_SKX_CONTAINERS}"
debug "BUILD_CLX_CONTAINERS=${BUILD_CLX_CONTAINERS}"
debug "BUILD_TF_V2_CONTAINERS=${BUILD_TF_V2_CONTAINERS}"
debug "ENABLE_SECURE_BUILD=${ENABLE_SECURE_BUILD}"
debug "TMP_DIR=${TMP_DIR}"
function build_container()
{
if [[ $# -lt 2 ]]; then
die "Usage: build_container <TEMP_IMAGE_NAME> <TF_DOCKER_BUILD_ARGS>."
fi
TEMP_IMAGE_NAME=${1}
debug "TEMP_IMAGE_NAME=${TEMP_IMAGE_NAME}"
shift
TF_DOCKER_BUILD_ARGS=("${@}")
# Add the proxy info build args
TF_DOCKER_BUILD_ARGS+=("--build-arg http_proxy=${http_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg https_proxy=${https_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg socks_proxy=${socks_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg no_proxy=${no_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg HTTP_PROXY=${http_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg SOCKS_PROXY=${socks_proxy}")
TF_DOCKER_BUILD_ARGS+=("--build-arg NO_PROXY=${no_proxy}")
#Add --config=v2 build arg for TF v2
if [[ ${BUILD_TF_V2_CONTAINERS} == "no" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg CONFIG_V2_DISABLE=--disable-v2")
fi
#Add build arg for Secure Build
if [[ ${ENABLE_SECURE_BUILD} == "yes" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg ENABLE_SECURE_BUILD=--secure-build")
fi
# Perform docker build
debug "Building docker image with image name and tag: ${TEMP_IMAGE_NAME}"
CMD="${DOCKER_BINARY} build ${TF_DOCKER_BUILD_ARGS[@]} --no-cache --pull -t ${TEMP_IMAGE_NAME} -f Dockerfile.devel-mkl ."
debug "CMD=${CMD}"
${CMD}
if [[ $? == "0" ]]; then
debug "${DOCKER_BINARY} build of ${TEMP_IMAGE_NAME} succeeded"
else
die "FAIL: ${DOCKER_BINARY} build of ${TEMP_IMAGE_NAME} failed"
fi
}
function test_container()
{
if [[ "$#" != "1" ]]; then
die "Usage: ${FUNCNAME} <TEMP_IMAGE_NAME>"
fi
TEMP_IMAGE_NAME=${1}
# Make sure that there is no other containers of the same image running
if "${DOCKER_BINARY}" ps | grep -q "${TEMP_IMAGE_NAME}"; then
die "ERROR: It appears that there are docker containers of the image "\
"${TEMP_IMAGE_NAME} running. Please stop them before proceeding"
fi
# Start a docker container from the newly-built docker image
DOCKER_RUN_LOG="${TMP_DIR}/docker_run.log"
debug " Log file is at: ${DOCKER_RUN_LOG}"
debug "Running docker container from image ${TEMP_IMAGE_NAME}..."
RUN_CMD="${DOCKER_BINARY} run --rm -d -p ${CONTAINER_PORT}:${CONTAINER_PORT} ${TEMP_IMAGE_NAME} tail -f /dev/null 2>&1 > ${DOCKER_RUN_LOG}"
debug "RUN_CMD=${RUN_CMD}"
${RUN_CMD}
# Get the container ID
CONTAINER_ID=""
while [[ -z ${CONTAINER_ID} ]]; do
sleep 1
debug "Polling for container ID..."
CONTAINER_ID=$("${DOCKER_BINARY}" ps | grep "${TEMP_IMAGE_NAME}" | awk '{print $1}')
done
debug "ID of the running docker container: ${CONTAINER_ID}"
debug "Performing basic sanity checks on the running container..."
TEST_CMD=$(${DOCKER_BINARY} exec ${CONTAINER_ID} bash -c "${PYTHON} -c 'from tensorflow.python import pywrap_tensorflow; print(pywrap_tensorflow.IsMklEnabled())'")
debug "Running test command: ${TEST_CMD}"
if [ "${TEST_CMD}" = "True" ] ; then
echo "PASS: MKL enabled test in ${TEMP_IMAGE_NAME}"
else
die "FAIL: MKL enabled test in ${TEMP_IMAGE_NAME}"
fi
# Stop the running docker container
sleep 1
"${DOCKER_BINARY}" stop --time=0 ${CONTAINER_ID}
}
function checkout_tensorflow()
{
if [[ "$#" != "3" ]]; then
die "Usage: ${FUNCNAME} <REPO_URL> <BRANCH/TAG/COMMIT-ID/PR-ID> <TF_BUILD_VERSION_IS_PR>"
fi
TF_REPO="${1}"
TF_BUILD_VERSION="${2}"
TF_BUILD_VERSION_IS_PR="${3}"
TENSORFLOW_DIR="tensorflow"
debug "Checking out ${TF_REPO}:${TF_BUILD_VERSION} into ${TENSORFLOW_DIR}"
# Clean any existing tensorflow sources
rm -rf "${TENSORFLOW_DIR}"
git clone ${TF_REPO} ${TENSORFLOW_DIR}
cd ${TENSORFLOW_DIR}
if [[ "${TF_BUILD_VERSION_IS_PR}" == "yes" ]]; then
# If TF_BUILD_VERSION is a PR number, then fetch first
git fetch origin pull/${TF_BUILD_VERSION}/head:pr-${TF_BUILD_VERSION}
git checkout pr-${TF_BUILD_VERSION}
else
git checkout ${TF_BUILD_VERSION}
fi
if [ $? -ne 0 ]; then
die "Unable to find ${TF_BUILD_VERSION} on ${TF_REPO}"
fi
cd ..
}
function tag_container()
{
# Apply the final image name and tag
TEMP_IMAGE_NAME="${1}"
FINAL_IMG="${2}"
DOCKER_VER=$("${DOCKER_BINARY}" version | grep Version | head -1 | awk '{print $NF}')
if [[ -z "${DOCKER_VER}" ]]; then
die "ERROR: Failed to determine ${DOCKER_BINARY} version"
fi
DOCKER_MAJOR_VER=$(echo "${DOCKER_VER}" | cut -d. -f 1)
DOCKER_MINOR_VER=$(echo "${DOCKER_VER}" | cut -d. -f 2)
FORCE_TAG=""
if [[ "${DOCKER_MAJOR_VER}" -le 1 ]] && \
[[ "${DOCKER_MINOR_VER}" -le 9 ]]; then
FORCE_TAG="--force"
fi
"${DOCKER_BINARY}" tag ${FORCE_TAG} "${TEMP_IMAGE_NAME}" "${FINAL_IMG}" || \
die "Failed to tag intermediate docker image ${TEMP_IMAGE_NAME} as ${FINAL_IMG}"
debug "Successfully tagged docker image: ${FINAL_IMG}"
}
PYTHON_VERSIONS=("python" "python3")
PLATFORMS=()
if [[ ${BUILD_AVX_CONTAINERS} == "yes" ]]; then
PLATFORMS+=("sandybridge")
fi
if [[ ${BUILD_AVX2_CONTAINERS} == "yes" ]]; then
PLATFORMS+=("haswell")
fi
if [[ ${BUILD_SKX_CONTAINERS} == "yes" ]]; then
PLATFORMS+=("skylake")
fi
if [[ ${BUILD_CLX_CONTAINERS} == "yes" ]]; then
PLATFORMS+=("icelake")
fi
# Checking out sources needs to be done only once
checkout_tensorflow "${TF_REPO}" "${TF_BUILD_VERSION}" "${TF_BUILD_VERSION_IS_PR}"
for PLATFORM in "${PLATFORMS[@]}"
do
for PYTHON in "${PYTHON_VERSIONS[@]}"
do
# Clear the build args array
TF_DOCKER_BUILD_ARGS=("--build-arg TARGET_PLATFORM=${PLATFORM}")
TF_DOCKER_BUILD_ARGS+=("--build-arg ROOT_CONTAINER=${ROOT_CONTAINER}")
FINAL_TAG="${TF_DOCKER_BUILD_VERSION}"
ROOT_CONTAINER_TAG="${TF_ROOT_CONTAINER_TAG}"
if [[ ${PLATFORM} == "haswell" ]]; then
FINAL_TAG="${FINAL_TAG}-avx2"
fi
if [[ ${PLATFORM} == "skylake" ]]; then
FINAL_TAG="${FINAL_TAG}-avx512"
fi
if [[ ${PLATFORM} == "icelake" ]]; then
FINAL_TAG="${FINAL_TAG}-avx512-VNNI"
fi
# Add -devel-mkl to the image tag
FINAL_TAG="${FINAL_TAG}-devel-mkl"
if [[ "${PYTHON}" == "python3" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg WHL_DIR=/tmp/pip3")
TF_DOCKER_BUILD_ARGS+=("--build-arg PIP=pip3")
FINAL_TAG="${FINAL_TAG}-py3"
ROOT_CONTAINER_TAG="${ROOT_CONTAINER_TAG}-py3"
fi
TF_DOCKER_BUILD_ARGS+=("--build-arg PYTHON=${PYTHON}")
TF_DOCKER_BUILD_ARGS+=("--build-arg ROOT_CONTAINER_TAG=${ROOT_CONTAINER_TAG}")
# Intermediate image name with tag
TEMP_IMAGE_NAME="${USER}/tensorflow:${FINAL_TAG}"
build_container "${TEMP_IMAGE_NAME}" "${TF_DOCKER_BUILD_ARGS[@]}"
test_container "${TEMP_IMAGE_NAME}"
tag_container "${TEMP_IMAGE_NAME}" "${FINAL_IMAGE_NAME}:${FINAL_TAG}"
done
done
|
// Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.kududb.client;
import org.kududb.WireProtocol;
import org.kududb.annotations.InterfaceAudience;
import org.kududb.annotations.InterfaceStability;
import org.kududb.tserver.Tserver;
/**
* Wrapper class for a single row error.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class RowError {
private final String status;
private final String message;
private final Operation operation;
private final String tsUUID;
private RowError(String errorStatus, String errorMessage, Operation operation, String tsUUID) {
this.status = errorStatus;
this.message = errorMessage;
this.operation = operation;
this.tsUUID = tsUUID;
}
/**
* Get the string-representation of the error code that the tablet server returned.
* @return A short string representation of the error.
*/
public String getStatus() {
return status;
}
/**
* Get the error message the tablet server sent.
* @return The error message.
*/
public String getMessage() {
return message;
}
/**
* Get the Operation that failed.
* @return The same Operation instance that failed.
*/
public Operation getOperation() {
return operation;
}
/**
* Get the identifier of the tablet server that sent the error.
* @return A string containing a UUID.
*/
public String getTsUUID() {
return tsUUID;
}
@Override
public String toString() {
return "Row error for primary key=" + Bytes.pretty(operation.getRow().encodePrimaryKey()) +
", tablet=" + operation.getTablet().getTabletIdAsString() +
", server=" + tsUUID +
", status=" + status +
", message=" + message;
}
/**
* Converts a PerRowErrorPB into a RowError.
* @param errorPB a row error in its pb format
* @param operation the original operation
* @param tsUUID a string containing the originating TS's UUID
* @return a row error
*/
static RowError fromRowErrorPb(Tserver.WriteResponsePB.PerRowErrorPB errorPB,
Operation operation, String tsUUID) {
WireProtocol.AppStatusPB statusPB = errorPB.getError();
return new RowError(statusPB.getCode().toString(),
statusPB.getMessage(), operation, tsUUID);
}
}
|
#!/bin/bash
go-callvis \
-focus gitlab.tocraw.com/root/toc_trader/pkg/modules/tradebot \
-skipbrowser \
-file=./assets/callvis \
./cmd || exit 1
|
import './App.css';
import 'react-toastify/dist/ReactToastify.css';
import Location from './Location';
//container
import React, { useEffect, useState } from 'react';
import Weather from './Weather';
function App() {
const [location, setLocation] = useState('')
return <React.Fragment>
<div className="header">
<span>Weather React/NodeJs Application</span>
</div>
<div className="container" >
<Location submitLocation={(location) => setLocation(location)}/>
<hr></hr>
<Weather location={location} />
</div>
</React.Fragment>
}
export default App;
|
def query_db(db):
try:
result = db.query("SELECT * FROM users")
except Exception as e:
print("An error occurred while querying the database: " + str(e))
return None
return result
|
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("t")
public class class17 extends class14 {
@ObfuscatedName("f")
boolean field136;
@ObfuscatedName("o")
byte field133;
@ObfuscatedName("u")
byte field134;
@ObfuscatedName("p")
byte field132;
@ObfuscatedName("b")
byte field135;
// $FF: synthetic field
@ObfuscatedSignature(
descriptor = "Lu;"
)
final class2 this$0;
@ObfuscatedSignature(
descriptor = "(Lu;)V"
)
class17(class2 var1) {
this.this$0 = var1; // L: 248
}
@ObfuscatedName("f")
@ObfuscatedSignature(
descriptor = "(Lnu;I)V",
garbageValue = "-1383981708"
)
void vmethod371(Buffer var1) {
this.field136 = var1.readUnsignedByte() == 1; // L: 251
this.field133 = var1.readByte(); // L: 252
this.field134 = var1.readByte(); // L: 253
this.field132 = var1.readByte(); // L: 254
this.field135 = var1.readByte(); // L: 255
} // L: 256
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "(Lm;I)V",
garbageValue = "-1475503816"
)
void vmethod376(class11 var1) {
var1.field90 = this.field136; // L: 259
var1.field84 = this.field133; // L: 260
var1.field83 = this.field134; // L: 261
var1.field86 = this.field132; // L: 262
var1.field87 = this.field135; // L: 263
} // L: 264
}
|
def is_leap(year):
if (year % 400 == 0) :
return True
if (year % 100 == 0) :
return False
if (year % 4 == 0):
return True
else:
return False
|
class Person:
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_country(self):
return self.country
|
<reponame>m-wrona/hevicado
'use strict';
describe('calendar-renderer-spec:', function () {
//prepare module for testing
beforeEach(angular.mock.module('chronos'));
describe('CalendarRenderer-spec:', function () {
var renderer;
beforeEach(inject(function ($injector) {
renderer = $injector.get('CalendarRenderer');
expect(renderer).toBeDefined();
}));
it('should create time line for event', function () {
//given no events are attached yet
//and quarter length
var quarterLength = 15;
//when attaching first event
var event = {
start: Date.today().set({
hour: 8,
minute: 0
})
};
renderer.attach(event, quarterLength);
//then event is attach to new time line
expect(event.timeline).toBe(0);
expect(event.overlap.value).toBe(1);
});
it('should attach overlapping event to next time line', function () {
//given quarter length
var quarterLength = 15;
//and first event takes one hour
var event1 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 0
}),
duration: 60
};
renderer.attach(event1, quarterLength);
expect(event1.timeline).toBe(0);
expect(event1.overlap.value).toBe(1);
expect(event1.quarter).toBe(4);
//when attaching new event that's overlapping previous event
var event2 = {
start: Date.today().set({
hour: 8,
minute: 15
}),
end: Date.today().set({
hour: 8,
minute: 45
}),
duration: 30
};
renderer.attach(event2, quarterLength);
//then event is attached to new time line
expect(event2.timeline).toBe(1);
expect(event2.quarter).toBe(2);
//and overlapping index is updated
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
//and time line of previous event is not changed
expect(event1.timeline).toBe(0);
});
it('should attach overlapping event to existing time line', function () {
//given quarter length
var quarterLength = 15;
// and first starts at 8 and end at 9
var event1 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 0
})
};
renderer.attach(event1, quarterLength);
expect(event1.timeline).toBe(0);
expect(event1.overlap.value).toBe(1);
//and next event that starts 8 but ends 8:30
var event2 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 8,
minute: 30
})
};
renderer.attach(event2, quarterLength);
expect(event2.timeline).toBe(1);
expect(event2.overlap.value).toBe(2);
//when attaching new event that starts after 8:30
var event3 = {
start: Date.today().set({
hour: 8,
minute: 45
}),
end: Date.today().set({
hour: 9,
minute: 15
})
};
renderer.attach(event3, quarterLength);
//then event is attached to second time line
expect(event3.timeline).toBe(1);
//and overlapping index is updated
expect(event3.overlap.value).toBe(2);
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
//and time lines of previous events are not changed
expect(event1.timeline).toBe(0);
expect(event2.timeline).toBe(1);
});
it('should dispatch events to keep time lines even', function () {
//given quarter length
var quarterLength = 15;
//and first starts at 8 and end at 9
var event1 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 0
})
};
renderer.attach(event1, quarterLength);
expect(event1.timeline).toBe(0);
expect(event1.overlap.value).toBe(1);
//and next event that starts 8 but ends 8:30
var event2 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 8,
minute: 30
})
};
renderer.attach(event2, quarterLength);
expect(event2.timeline).toBe(1);
expect(event2.overlap.value).toBe(2);
//and next event that starts at 8:45 and ends 9:15
var event3 = {
start: Date.today().set({
hour: 8,
minute: 45
}),
end: Date.today().set({
hour: 9,
minute: 15
})
};
renderer.attach(event3, quarterLength);
expect(event3.timeline).toBe(1);
expect(event3.overlap.value).toBe(2);
//when attaching new event that starts at 9 and ends 9:15
var event4 = {
start: Date.today().set({
hour: 9,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 15
})
};
renderer.attach(event4, quarterLength);
//then event is attached to first time line
//in order to keep them even
expect(event4.timeline).toBe(0);
//and overlapping index is updated
expect(event4.overlap.value).toBe(2);
expect(event3.overlap.value).toBe(2);
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
//and time lines of previous events are not changed
expect(event1.timeline).toBe(0);
expect(event2.timeline).toBe(1);
expect(event3.timeline).toBe(1);
});
it('should clear time lines when new event starts after attached events', function () {
//given quarter length
var quarterLength = 15;
//and first starts at 8 and end at 9
var event1 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 0
})
};
renderer.attach(event1, quarterLength);
expect(event1.timeline).toBe(0);
expect(event1.overlap.value).toBe(1);
//and next event that starts 8 but ends 8:30
var event2 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 8,
minute: 30
})
};
renderer.attach(event2, quarterLength);
expect(event2.timeline).toBe(1);
expect(event2.overlap.value).toBe(2);
//and next event that starts at 8:45 and ends 9:15
var event3 = {
start: Date.today().set({
hour: 8,
minute: 45
}),
end: Date.today().set({
hour: 9,
minute: 15
})
};
renderer.attach(event3, quarterLength);
expect(event3.timeline).toBe(1);
expect(event3.overlap.value).toBe(2);
//when attaching new event that starts after all attached events
var event4 = {
start: Date.today().set({
hour: 9,
minute: 15
}),
end: Date.today().set({
hour: 9,
minute: 30
})
};
renderer.attach(event4, quarterLength);
//then event is attached to first time line
expect(event4.timeline).toBe(0);
//and overlapping index of new event is cleared
expect(event4.overlap.value).toBe(1);
//and old overlapping indexes remain untouched
expect(event3.overlap.value).toBe(2);
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
//and time lines of previous events are not changed
expect(event1.timeline).toBe(0);
expect(event2.timeline).toBe(1);
expect(event3.timeline).toBe(1);
});
it('should attach all events in proper order', function () {
//given first starts at 8 and end at 9
var event1 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 9,
minute: 0
})
};
//and next event that starts 8 but ends 8:30
var event2 = {
start: Date.today().set({
hour: 8,
minute: 0
}),
end: Date.today().set({
hour: 8,
minute: 30
})
};
//and next event that starts at 8:45 and ends 9:15
var event3 = {
start: Date.today().set({
hour: 8,
minute: 45
}),
end: Date.today().set({
hour: 9,
minute: 15
})
};
//and next event that starts after all attached events
var event4 = {
start: Date.today().set({
hour: 9,
minute: 15
}),
end: Date.today().set({
hour: 9,
minute: 30
})
};
//and quarter length
var quarterLength = 15;
//when attaching all events in random order
renderer.attachAll([event4, event3, event2, event1], quarterLength);
//then events are sorted and attached to proper time lines
expect(event1.timeline).toBe(0);
expect(event2.timeline).toBe(1);
expect(event3.timeline).toBe(1);
expect(event4.timeline).toBe(0);
//and proper overlapping indexes are set
expect(event4.overlap.value).toBe(1);
expect(event3.overlap.value).toBe(2);
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
});
it('should attach to proper quarter for non-standard quarter length', function () {
//given non-standard quarter length
var quarterLength = 30;
//and first event takes one hour
var event1 = {
start: Date.today().set({
hour: 8,
minute: 45
}),
end: Date.today().set({
hour: 9,
minute: 0
}),
duration: 60
};
renderer.attach(event1, quarterLength);
expect(event1.timeline).toBe(0);
expect(event1.overlap.value).toBe(1);
expect(event1.quarter).toBe(2);
//when attaching new event that's overlapping previous event
var event2 = {
start: Date.today().set({
hour: 8,
minute: 15
}),
end: Date.today().set({
hour: 8,
minute: 45
}),
duration: 30
};
renderer.attach(event2, quarterLength);
//then event is attached to new time line
expect(event2.timeline).toBe(1);
expect(event2.quarter).toBe(1);
//and overlapping index is updated
expect(event2.overlap.value).toBe(2);
expect(event1.overlap.value).toBe(2);
//and time line of previous event is not changed
expect(event1.timeline).toBe(0);
});
});
});
|
#!/bin/bash
set -e
cd "$(dirname "$(readlink -f "$BASH_SOURCE")")"
declare -A aliases=(
#[suite]='tag1 tag2 ...'
)
aliases[$(< latest)]+=' latest'
aliases[$(< rolling)]+=' rolling' # https://github.com/docker-library/official-images/issues/2323#issuecomment-284409446
declare -A noVersion=(
#[suite]=1
)
develSuite="$(
wget -qO- http://archive.ubuntu.com/ubuntu/dists/devel/Release \
| awk -F ': ' '$1 == "Codename" { print $2; exit }' \
|| true
)"
if [ "$develSuite" ]; then
aliases[$develSuite]+=' devel'
fi
archMaps=( $(
git ls-remote --heads https://github.com/tianon/docker-brew-ubuntu-core.git \
| awk -F '[\t/]' '$4 ~ /^dist-/ { gsub(/^dist-/, "", $4); print $4 "=" $1 }' \
| sort
) )
arches=()
declare -A archCommits=()
for archMap in "${archMaps[@]}"; do
arch="${archMap%%=*}"
commit="${archMap#${arch}=}"
arches+=( "$arch" )
archCommits[$arch]="$commit"
done
versions=( */ )
versions=( "${versions[@]%/}" )
cat <<-EOH
# Maintained by Tianon as proxy for upstream's official builds.
# see https://partner-images.canonical.com/core/
# see also https://wiki.ubuntu.com/Releases#Current
Maintainers: Tianon Gravi <tianon@debian.org> (@tianon)
GitRepo: https://github.com/tianon/docker-brew-ubuntu-core.git
GitCommit: $(git log --format='format:%H' -1)
EOH
for arch in "${arches[@]}"; do
cat <<-EOA
# https://github.com/tianon/docker-brew-ubuntu-core/tree/dist-${arch}
${arch}-GitFetch: refs/heads/dist-${arch}
${arch}-GitCommit: ${archCommits[$arch]}
EOA
done
# prints "$2$1$3$1...$N"
join() {
local sep="$1"; shift
local out; printf -v out "${sep//%/%%}%s" "$@"
echo "${out#$sep}"
}
for version in "${versions[@]}"; do
versionArches=()
versionSerial=
for arch in "${arches[@]}"; do
if buildInfo="$(wget -qO- "https://raw.githubusercontent.com/tianon/docker-brew-ubuntu-core/${archCommits[$arch]}/${version}/build-info.txt")"; then
versionArches+=( "$arch" )
archSerial="$(echo "$buildInfo" | awk -F '=' '$1 == "SERIAL" { print $2; exit }')"
if [ ! -z "$versionSerial" ] && [ "$versionSerial" != "$archSerial" ]; then
echo >&2 "error: inconsistent serials for '$version'! ('$versionSerial' vs '$archSerial' in '$arch')"
exit 1
fi
versionSerial="$archSerial"
fi
done
versionAliases=()
[ -s "$version/alias" ] && versionAliases+=( $(< "$version/alias") )
versionAliases+=( $version-$versionSerial )
versionAliases+=(
$version
${aliases[$version]}
)
# assert some amount of sanity
[ "${#versionArches[@]}" -gt 0 ]
echo
cat <<-EOE
# $versionSerial ($version)
Tags: $(join ', ' "${versionAliases[@]}")
Architectures: $(join ', ' "${versionArches[@]}")
Directory: $version
EOE
done
|
<gh_stars>100-1000
#coding:utf-8
import os, sys
import os.path as osp
import numpy as np
import torch
from torch import nn
from torch.optim import Optimizer
from functools import reduce
from torch.optim import AdamW
class MultiOptimizer:
def __init__(self, optimizers={}):
self.optimizers = optimizers
self.keys = list(optimizers.keys())
self.param_groups = reduce(lambda x,y: x+y, [v.param_groups for v in self.optimizers.values()])
def state_dict(self):
state_dicts = [(key, self.optimizers[key].state_dict())\
for key in self.keys]
return state_dicts
def load_state_dict(self, state_dict):
for key, val in state_dict:
try:
self.optimizers[key].load_state_dict(val)
except:
print("Unloaded %s" % key)
def step(self, key=None, scaler=None):
keys = [key] if key is not None else self.keys
_ = [self._step(key, scaler) for key in keys]
def _step(self, key, scaler=None):
if scaler is not None:
scaler.step(self.optimizers[key])
scaler.update()
else:
self.optimizers[key].step()
def zero_grad(self, key=None):
if key is not None:
self.optimizers[key].zero_grad()
else:
_ = [self.optimizers[key].zero_grad() for key in self.keys]
|
/*
* Copyright 2021 HM Revenue & Customs
*
* 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.
*/
package models.fe.tcsp
import models.des.DesConstants
import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
class ComplexCorpStructureCreationSpec extends PlaySpec with MustMatchers {
"The ComplexCorpStructureCreation model" when {
"given a valid model" must {
"return the form values" when {
"for json" when {
"complexCorpStructureCreation is 'yes'" in {
val model = ComplexCorpStructureCreationYes
val result = ComplexCorpStructureCreation.jsonWrite.writes(model).toString()
val expected = "{\"complexCorpStructureCreation\":true}"
result mustBe expected
}
"complexCorpStructureCreation is 'no'" in {
val model = ComplexCorpStructureCreationNo
val result = ComplexCorpStructureCreation.jsonWrite.writes(model).toString()
val expected = "{\"complexCorpStructureCreation\":false}"
result mustBe expected
}
}
}
"converting the des subscription model must yield a frontend TCSP model" in {
ComplexCorpStructureCreation.conv(DesConstants.SubscriptionViewModel) must
be(Some(ComplexCorpStructureCreationYes))
}
"converting the des subscription model with no formation agent must yield a frontend TCSP model" in {
ComplexCorpStructureCreation.conv(DesConstants.SubscriptionViewModelNoFormationAgent) must
be(Some(ComplexCorpStructureCreationNo))
}
"converting the des subscription model with no formation agent service offered must yield a frontend TCSP model" in {
ComplexCorpStructureCreation.conv(DesConstants.SubscriptionViewModelNoFormationAgentSvc) must
be(None)
}
"converting the des subscription model with no tcsp services must yield a frontend TCSP model" in {
ComplexCorpStructureCreation.conv(DesConstants.SubscriptionViewModelNoFormationAgentNoTcspServices) must
be(None)
}
}
}
}
|
#!/bin/bash
#
# ADMIN UTILITY
#
# This script is only used during the development process and aids to recreated
# the protobug related python files which correspond to the RPC's server defined .proto files.
# You DO NOT need to invoke this script manually.
# This is only needed id the proto files on avatica-core-${VERSION}-POLYPHENY have changed
# Copyright 2019-2021 The Polypheny Project
AUTHOR="Marc Hennemann"
set -e
# Retrieve latest version
AVATICA_VER="v1.17.2"
# Cleanup old environment
rm -rf polypheny-avatica-tmp
# Recreate new environemnt
mkdir polypheny-avatica-tmp
cd polypheny-avatica-tmp
# Get latest version of polypheny-avatica
wget -O polypheny-avatica.tar.gz https://github.com/polypheny/Avatica/archive/refs/tags/${AVATICA_VER}.tar.gz
tar -x --strip-components=1 -f polypheny-avatica.tar.gz
rm -f ../polypheny/avatica/protobuf/*_pb2.py
protoc --proto_path=polypheny-avatica-tmp/core/src/main/protobuf/ --python_out=polypheny/avatica/protobuf polypheny-avatica-tmp/core/src/main/protobuf/*.proto
protoc --proto_path=polypheny-avatica-tmp/ --python_out=polypheny/avatica/protobuf polypheny-avatica-tmp/*.proto
sed -i 's/import common_pb2/from . import common_pb2/' ../polypheny/avatica/protobuf/*_pb2.py
rm -rf polypheny-avatica-tmp
|
#include <iostream>
#include <cstdint>
namespace duckdb {
const uint64_t VERSION_NUMBER = 31;
uint64_t incrementVersion(uint64_t currentVersion) {
return currentVersion + 1;
}
}
int main() {
uint64_t currentVersion = duckdb::VERSION_NUMBER;
uint64_t updatedVersion = duckdb::incrementVersion(currentVersion);
std::cout << "Updated version number: " << updatedVersion << std::endl;
return 0;
}
|
import random
names = ["John", "Mary", "Paul", "Gerry"]
print("The randomly chosen name is", random.choice(names))
|
<reponame>LaudateCorpus1/hermes-5<filename>src/examples/cf_example.py<gh_stars>100-1000
#!/usr/bin/env python
import click
import itertools
import json
import os
import sys
from pyspark import SparkConf
from pyspark.mllib.recommendation import ALS
from pyspark.sql.types import StructType
from pyspark.mllib.util import MLUtils
from pyspark.mllib.classification import LogisticRegressionWithLBFGS
from pyspark.mllib.evaluation import MulticlassMetrics
from sklearn import datasets, svm
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import StratifiedShuffleSplit
sys.path.append("../algorithms")
import performance_metrics as pm
import content_based as cb
from singleton import SCSingleton
from timer import Timer
"""
This entire file is to provide a basic understanding of collaborative filtering
and its performance metrics.
* test_simple_rmse() tests RMSE with ALS model and a small dataset using sklearn (meaning it uses array).
* test_rmse() tests RMSE with ALS model and a large dataset using pyspark (meaning it uses RDD).
* test_simple_prfs() tests precision and recall with SVD model and a small dataset using sklearn (meaning it uses array).
* test_prfs() tests precision and recall with LogisticRegressionWithLBFGS model and a large dataset using pyspark (meaning it uses RDD).
This example assumes that you have installed
* pyspark
* psutil
* scala
* spark
* hadoop
"""
def test_simple_rmse():
""" Test RMSE as follows:
(1) train the ALS model with a subset of 15 values
(2) predict a subset of 15 values using the trained model
(3) calculate RMSE or how accurately the prediction is
in comparison to the known values
Values used to train the ALS model are based on a fictitious world where
5 users rate 4 items whether they like or dislike an item. If the user liked
the item, he will provide a rating of 1; otherwise, if the user disliked the
item, he will provide a rating of -1. No rating means that the user has not
rated the item. This data will be formatted in an RDD of [(userId, itemId, rating)].
Splitting these 15 values into training, validation, and test dataset is
randomly selected.
0 1 2 3 = itemID
userId = 0 1 -1 1 1
1 1 -1 -1
2 1 1 -1
3 -1 1
4 1 1 -1
0: (0, 0, 1)
1: (0, 1, -1)
2: (0, 2, 1)
3: (0, 3, 1)
4: (1, 1, 1)
5: (1, 2, -1)
6: (1, 3, -1)
7: (2, 0, 1)
8: (2, 1, 1)
9: (2, 1, -1)
10: (3, 0, -1)
11: (3, 2, 1)
12: (4, 0, 1)
13: (4, 1, 1)
14: (4, 3, -1)
"""
# load the data, an RDD of [(userId, itemId, rating)]
# split data into train (60%), validation (20%), test(20%)
# training (8): data to train the model
# validation (3): best performing approach using the validation data
# test (3): estimate accuracy of the selected approach
# TODO: possible split using sklearn's train_test_split?
trainingArray = [(4, 3, -1), (1, 1, 1), (3, 0, -1),
(4, 0, 1), (1, 2, -1), (0, 0, 1),
(2, 1, -1), (0, 2, 1), (1, 3, -1)]
validationArray = [(4, 1, 1), (3, 2, 1), (2, 1, 1)]
testArray = [(2, 0, 1), (0, 1, -1), (0, 3, 1)]
trainingRDD = scsingleton.sc.parallelize(trainingArray)
validationRDD = scsingleton.sc.parallelize(validationArray)
testRDD = scsingleton.sc.parallelize(testArray)
# run training algorithm to build the model
isExplicit = True
ranks = [3, 5, 7]
#numIters = [5] # default value
#lmbdas = [0.01] # default value
#blocks = -1 # default value
#nonnegative = False # default value
#seed = None # default value
#alpha = [0.01] # default value
model = None
bestModel = None
bestValidationRmse = float("inf")
bestRank = 0
# with validation
#for rank, numIter, lmbda in itertools.product(ranks, numIters, lmbdas):
for rank in ranks:
if isExplicit:
model = ALS.train(trainingRDD, rank)
else:
# TODO: figure out why trainImplicit crash
model = ALS.trainImplicit(trainingRDD, rank, iterations=5, alpha=0.01)
validationPredRDD = model.predictAll( validationRDD.map( lambda x: (x[0], x[1]) ) )
validationRmse = pm.calculate_rmse_using_rdd(validationRDD, validationPredRDD)
if (validationRmse < bestValidationRmse):
bestModel = model
bestValidationRmse = validationRmse
bestRank = rank
# make a prediction
testPredRDD = bestModel.predictAll( testRDD.map( lambda x: (x[0], x[1]) ) ).cache()
"""
# without validation
model = ALS.train(trainingRDD, rank=3)
testPredRDD = model.predictAll( testRDD.map( lambda x: (x[0], x[1]) ) )
"""
# calculate RMSE
testRmse = pm.calculate_rmse_using_rdd(testRDD, testPredRDD)
print "testRmse using RDD = ", testRmse
return
def test_rmse():
# TODO: revised so that it will take user's inputs instead of hardcoded values
movies_schema = None
ratings_schema = None
# load the schemas
with open("movielens_20m_movies_schema.json", "r") as json_schema_file:
movies_schema = StructType.fromJson(json.load(json_schema_file))
with open("movielens_20m_ratings_schema.json", "r") as json_schema_file:
ratings_schema = StructType.fromJson(json.load(json_schema_file))
# create a hdfs directory
os.system("hdfs dfs -mkdir datasets")
# load the json file into the hdfs directory
os.system("hdfs dfs -put movielens_10m_ratings.json.gz datasets/movielens_10m_ratings.json.gz")
# create a DataFrame based on the content of the json file
ratingsDF = scsingleton.sqlCtx.read.json("hdfs://localhost:9000/datasets/movielens_10m_ratings.json.gz", schema=ratings_schema)
# explicitly repartition RDD after loading so that more tasks can run on it in parallel
# by default, defaultMinPartitions == defaultParallelism == estimated # of cores across all of the machines in your cluster
ratingsDF = ratingsDF.repartition(scsingleton.sc.defaultParallelism * 3)
# parse ratings DataFrame into an RDD of [(userId, itemId, rating)]
ratingsRDD = ratingsDF.map(lambda row: (row.user_id, row.movie_id, row.rating))
ratingsRDD.cache()
# split data into train (60%), test (40%)
# TODO: add validation in the future? train (60%), validation (20%), test(20%)?
trainingRDD, testRDD = ratingsRDD.randomSplit([0.6, 0.4])
trainingRDD.cache()
testRDD.cache()
# run training algorithm to build the model
# without validation
with Timer() as t:
model = ALS.train(trainingRDD, rank=3)
print "ALS.train(trainingRDD, rank=3): %s seconds" % t.secs
# make a prediction
with Timer() as t:
testPredRDD = model.predictAll( testRDD.map( lambda x: (x[0], x[1]) ) ).cache()
print "testPredRDD: %s seconds" % t.secs
# calculate RMSE
with Timer() as t:
testRmse = pm.calculate_rmse_using_rdd(testRDD, testPredRDD)
print "testRmse: %s seconds" % t.secs
print "testRmse", testRmse
return
def test_simple_prfs():
""" Test Precision and Recall at N (as well as F1-score and Support) as follows:
(1) train the SVC model with a subset of sklearn's digits dataset
(2) predict what the number is using
the trained model and a subset of sklearn's digits dataset
(3) calculate "Precision and Recall at N" or how accurately it classifies the
digit in comparison to the known values
"""
# load the data
digits = datasets.load_digits()
data = digits.data
labels = digits.target
#print "data\n", data[0]
#print "labels\n", labels
print "numData = ", len(digits.data)
print "numTarget = ", len(digits.target)
# split data into train (60%), test(40%)
# TODO: add validation in the future? train (60%), validation (20%), test(20%)?
trainingData, testData, trainingLabel, testLabel = train_test_split(data, labels, test_size=0.4)
print "numTrainingData = ", len(trainingData)
print "numTestData = ", len(testData)
print "numTrainingLabel = ", len(trainingLabel)
print "numTestLabel == ", len(testLabel)
# train the model
model = svm.SVC(gamma=0.001, C=100)
model.fit(trainingData, trainingLabel)
# make a prediction
testPredLabel = model.predict(testData)
# calculate PRFS
print "testLabel"
print testLabel
print "testPredictedLabel"
print testPredLabel
p, r, f, s = pm.calculate_prfs_using_array(testLabel, testPredLabel)
print "precision =\n", p
print "recall =\n", r
print "fscore =\n", f
print "support =\n", s
return
def test_prfs():
# TODO: revised so that it will take user's inputs instead of hardcoded values
"""
Test Precision, Recall, Fscore, and Support on multiclass classification data
Input data: https://github.com/apache/spark/blob/master/data/mllib/sample_multiclass_classification_data.txt.
"""
# load the schemas (if existed)
# create a hdfs directory
#os.system("hdfs dfs -mkdir datasets")
# load the data file into the hdfs directory
os.system("hdfs dfs -put sample_multiclass_classification_data.txt datasets/sample_multiclass_classification_data.txt")
data = MLUtils.loadLibSVMFile(scsingleton.sc, "hdfs://localhost:9000/datasets/sample_multiclass_classification_data.txt")
# print data.take(1)
# ie. [LabeledPoint(1.0, (4,[0,1,2,3],[-0.222222,0.5,-0.762712,-0.833333]))]
# [ ( finalClassification, (numLabels, [label0, label1, label2, ..., labelN], [prob0, prob1, prob2, ..., probN]) ) ]
# split data into train (60%), test (40%)
trainingRDD, testRDD = data.randomSplit([0.6, 0.4])
trainingRDD.cache()
testRDD.cache()
with Timer() as t:
numTest = testRDD.count()
print "testRDD.count(): %s seconds" % t.secs
# run training algorithm to build the model
# without validation
with Timer() as t:
model = LogisticRegressionWithLBFGS.train(trainingRDD, numClasses=3)
print "LogisticRegressionWithLBFGS.train(trainingRDD, numClasses=3): %s seconds" % t.secs
# make a prediction
with Timer() as t:
testPredAndLabel = testRDD.map(lambda lp: (float(model.predict(lp.features)), lp.label))
print "testPredAndLabel: %s seconds" % t.secs
# calculate Precision, Recall, F1-score
metrics = MulticlassMetrics(testPredAndLabel)
print( "precision = %s" % metrics.precision() )
print( "recall = %s" % metrics.recall() )
print( "f1-score = %s" % metrics.fMeasure() )
# statistics by class
labels = data.map(lambda lp: lp.label).distinct().collect()
for label in sorted(labels):
print( "Class %s precision = %s" % (label, metrics.precision(label)) )
print( "Class %s recall = %s" % (label, metrics.recall(label)) )
print( "Class %s f1-score = %s" % (label, metrics.fMeasure(label, beta=1.0)) )
# weighted stats
print( "Weighted precision = %s" % metrics.weightedPrecision )
print( "Weighted recall = %s" % metrics.weightedRecall )
print( "Weighted f1-score = %s" % metrics.weightedFMeasure() )
print( "Weighted f(0.5)-score = %s" % metrics.weightedFMeasure(beta=0.5) )
print( "Weighted false positive rate = %s" % metrics.weightedFalsePositiveRate )
return
if __name__ == "__main__":
# set up spark environment
conf = SparkConf().setAppName("test_precision_metrics").set("spark.executor.memory", "5g")
scsingleton = SCSingleton(conf)
test_simple_rmse()
test_rmse()
test_simple_prfs()
test_prfs()
|
<gh_stars>1-10
// 20 june 2016
// kept in a separate file for now
typedef struct uiImage uiImage;
// TODO use const void * for const correctness
_UI_EXTERN uiImage *uiNewImage(double width, double height);
_UI_EXTERN void uiFreeImage(uiImage *i);
_UI_EXTERN void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int pixelStride);
typedef struct uiTableValue uiTableValue;
_UI_EXTERN void uiFreeTableValue(uiTableValue *v);
// TODO actually validate these
_UI_ENUM(uiTableValueType) {
uiTableValueTypeString,
uiTableValueTypeImage,
uiTableValueTypeInt,
uiTableValueTypeColor,
};
// TODO I don't like this name
_UI_EXTERN uiTableValueType uiTableValueGetType(const uiTableValue *v);
_UI_EXTERN uiTableValue *uiNewTableValueString(const char *str);
_UI_EXTERN const char *uiTableValueString(const uiTableValue *v);
_UI_EXTERN uiTableValue *uiNewTableValueImage(uiImage *img);
_UI_EXTERN uiImage *uiTableValueImage(const uiTableValue *v);
_UI_EXTERN uiTableValue *uiNewTableValueInt(int i);
_UI_EXTERN int uiTableValueInt(const uiTableValue *v);
_UI_EXTERN uiTableValue *uiNewTableValueColor(double r, double g, double b, double a);
_UI_EXTERN void uiTableValueColor(const uiTableValue *v, double *r, double *g, double *b, double *a);
typedef struct uiTableModel uiTableModel;
typedef struct uiTableModelHandler uiTableModelHandler;
// TODO validate ranges; validate types on each getter/setter call (? table columns only?)
struct uiTableModelHandler {
int (*NumColumns)(uiTableModelHandler *, uiTableModel *);
uiTableValueType (*ColumnType)(uiTableModelHandler *, uiTableModel *, int);
int (*NumRows)(uiTableModelHandler *, uiTableModel *);
uiTableValue *(*CellValue)(uiTableModelHandler *, uiTableModel *, int, int);
void (*SetCellValue)(uiTableModelHandler *, uiTableModel *, int, int, const uiTableValue *);
};
_UI_EXTERN uiTableModel *uiNewTableModel(uiTableModelHandler *mh);
_UI_EXTERN void uiFreeTableModel(uiTableModel *m);
_UI_EXTERN void uiTableModelRowInserted(uiTableModel *m, int newIndex);
_UI_EXTERN void uiTableModelRowChanged(uiTableModel *m, int index);
_UI_EXTERN void uiTableModelRowDeleted(uiTableModel *m, int oldIndex);
// TODO reordering/moving
#define uiTableModelColumnNeverEditable (-1)
#define uiTableModelColumnAlwaysEditable (-2)
typedef struct uiTableTextColumnOptionalParams uiTableTextColumnOptionalParams;
typedef struct uiTableParams uiTableParams;
struct uiTableTextColumnOptionalParams {
int ColorModelColumn;
};
struct uiTableParams {
uiTableModel *Model;
int RowBackgroundColorModelColumn;
};
typedef struct uiTable uiTable;
#define uiTable(this) ((uiTable *) (this))
_UI_EXTERN void uiTableAppendTextColumn(uiTable *t,
const char *name,
int textModelColumn,
int textEditableModelColumn,
uiTableTextColumnOptionalParams *textParams);
_UI_EXTERN void uiTableAppendImageColumn(uiTable *t,
const char *name,
int imageModelColumn);
_UI_EXTERN void uiTableAppendImageTextColumn(uiTable *t,
const char *name,
int imageModelColumn,
int textModelColumn,
int textEditableModelColumn,
uiTableTextColumnOptionalParams *textParams);
_UI_EXTERN void uiTableAppendCheckboxColumn(uiTable *t,
const char *name,
int checkboxModelColumn,
int checkboxEditableModelColumn);
_UI_EXTERN void uiTableAppendCheckboxTextColumn(uiTable *t,
const char *name,
int checkboxModelColumn,
int checkboxEditableModelColumn,
int textModelColumn,
int textEditableModelColumn,
uiTableTextColumnOptionalParams *textParams);
_UI_EXTERN void uiTableAppendProgressBarColumn(uiTable *t,
const char *name,
int progressModelColumn);
_UI_EXTERN void uiTableAppendButtonColumn(uiTable *t,
const char *name,
int buttonModelColumn,
int buttonClickableModelColumn);
_UI_EXTERN uiTable *uiNewTable(uiTableParams *params);
|
#!/usr/bin/env bash
cd features/fixtures/sampler
function launch_app() {
react-native run-ios \
--configuration=Release \
--simulator "iPhone SE" \
--no-packager
}
echo "{\"name\": \"$EVENT_TYPE\"}" > scenario.json
launch_app
sleep 2s
echo "{\"name\": \"none\"}" > scenario.json
launch_app
sleep 2s
|
<filename>hotspots.py
from prettytable import PrettyTable
import click
import datetime
import iso8601
import math
import os
import requests
GITHUB_TOKEN = os.environ['GITHUB_TOKEN']
BASE_URL = 'https://api.github.com'
client = requests.Session()
client.auth = ('token', GITHUB_TOKEN)
def get_all_pages(url, params=None):
all_results = []
first_page = client.get(BASE_URL + url, params=params)
all_results += first_page.json()
if 'next' in first_page.links:
url = first_page.links['next']['url']
while True:
page = client.get(url)
all_results += page.json()
if 'next' not in page.links:
break
url = page.links['next']['url']
return all_results
def filter_bugfixes(prs):
title_words = lambda pr: set(pr['title'].lower().split())
bugfix_words = set(['bugfix', 'fix', 'bug', 'fixes', 'fixing'])
is_bugfix = lambda pr: len(title_words(pr).intersection(bugfix_words)) > 0
return [pr for pr in prs if is_bugfix(pr)]
def get_files(repo, pr):
files_url = '/repos/' + repo + '/pulls/' + str(pr['number']) + '/files'
results = get_all_pages(files_url)
return results
def get_repository_creation_timestamp(repo):
url = '/repos/' + repo
response = client.get(BASE_URL + url)
return iso8601.parse_date(response.json()['created_at'])
@click.command()
@click.argument('repo')
@click.option('--verbose', is_flag=True, default=False)
def main(repo, verbose):
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
repository_created_at = get_repository_creation_timestamp(repo)
repository_age_in_seconds = (now - repository_created_at).total_seconds()
all_prs = get_all_pages('/repos/' + repo + '/pulls', params={'state': 'all', 'base': 'master'})
bugfixes = filter_bugfixes(all_prs)
click.echo("Found {} bugfix PRs\n".format(len(bugfixes)))
scores = {}
for bugfix in bugfixes:
if verbose:
click.echo("{} - {}".format(bugfix['created_at'], bugfix['title']))
files = get_files(repo, bugfix)
bugfix_created_at = iso8601.parse_date(bugfix['created_at'])
bugfix_age_in_seconds = (now - bugfix_created_at).total_seconds()
bugfix_age_as_a_proportion_of_repository_age = 1 - (bugfix_age_in_seconds / repository_age_in_seconds)
# https://google-engtools.blogspot.co.uk/2011/12/bug-prediction-at-google.html
score = 1 / (1 + math.exp((-12 * bugfix_age_as_a_proportion_of_repository_age) + 12))
filenames = [f['filename'] for f in files if 'test' not in f['filename'] and 'migration' not in f['filename']]
for filename in filenames:
if filename not in scores:
scores[filename] = 0
scores[filename] += score
top_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)[:10]
table = PrettyTable()
table.field_names = ['file', 'score']
table.align = 'r'
for name, score in top_scores:
table.add_row([name, "{:.2f}".format(score)])
click.echo(table.get_string())
if __name__ == "__main__":
main()
|
#ifndef __DOMAIN_UPDATE_H__
#define __DOMAIN_UPDATE_H__
#include "db_update.h"
#define DNS_STATUS_INIT "init"
#define DNS_STATUS_RUN "running"
void domian_info_exchange_run(uint16_t web_port, int ssl_enable, char *key_pem_file, char *cert_pem_file);
int domain_list_del_zones(char *del_zones);
void domain_info_master_init(void);
#endif
|
<gh_stars>10-100
package com.peony.core.control.job;
import com.peony.core.control.annotation.Service;
import com.peony.core.data.DataService;
import com.peony.core.data.tx.AbListDataTxLifeDepend;
import com.peony.core.data.tx.Tx;
import com.peony.core.data.tx.TxCacheService;
import com.peony.common.exception.MMException;
import com.peony.core.server.IdService;
import com.peony.core.server.Server;
import com.peony.core.control.BeanHelper;
import com.peony.common.tool.thread.ThreadPoolHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.*;
/**
* Job服务。Job指过一段时间后执行某个方法。
* <p>
* Job使用的是{@code ScheduledThreadPoolExecutor}实现。同时Job会保存在数据库中,确保
* Job不会因为服务器关闭而被清除。
* <p>
* TODO 目前先用ScheduledThreadPoolExecutor实现,后面可以考虑使用quartz实现
*
* @author zhengyuzhen
* @see Job
* @since 1.0
*/
@Service(init = "init",initPriority = 4)
public class JobService {
private static final Logger log = LoggerFactory.getLogger(JobService.class);
// 执行job的调度器
private ScheduledThreadPoolExecutor executor = ThreadPoolHelper.newScheduledThreadPoolExecutor("Job",16);
// 未执行的job
private ConcurrentHashMap<Long,JobExecutor> jobExecutorMap = new ConcurrentHashMap<>();
// 事务依赖处理器
private JobTxLifeDepend<Job> jobTxLifeDepend = new JobTxLifeDepend<>();
private DataService dataService;
private IdService idService;
private TxCacheService txCacheService;
public void init(){
// 系统初始化时,从数据库中取出之前的Job,并启动
List<Job> jobList = dataService.selectList(Job.class,"serverId=?",Server.getServerId());
for (Job job : jobList){
startJob(job,false);
}
// 注册事务依赖处理器
txCacheService.registerTxLifeDepend(jobTxLifeDepend);
}
/**
* 启动一个Job
*
* @param delay 延时时间
* @param service Service类,必须是@Service
* @param method 方法名
* @param params 方法的参数
* @return Job的id
*/
@Tx
public long startJob(int delay,Class<?> service, String method,Object... params){
Job job = new Job();
job.setId(idService.acquireLong(Job.class));
job.setServerId(Server.getServerId());
job.setStartDate(new Timestamp(System.currentTimeMillis()+delay));
job.setMethod(method);
job.setServiceClass(service.getName());
job.setParamsObjectArray(params);
startJob(job);
return job.getId();
}
private void startJob(Job job){
// 如果在事务中,先放入事务
if(jobTxLifeDepend.checkAndPut(job)){
return;
}
startJob(job,true);
}
private void startJob(Job job,boolean isDb){
JobExecutor jobExecutor = createJobExecutor(job);
synchronized (jobExecutor){
// 本地验证唯一性
JobExecutor oldJ = jobExecutorMap.putIfAbsent(job.getId(), jobExecutor);
if (oldJ != null) { // 已经存在了
log.error("job id error!");
throw new MMException("job has exist! id = " + job.getId());
}
// 存储
if(isDb){
dataService.insert(job);
}
// 实际运行
RunnableScheduledFuture<?> future = (RunnableScheduledFuture) executor.schedule(jobExecutor,
jobExecutor.delay, TimeUnit.MILLISECONDS); // 这里delay<0是处理的了
//
jobExecutor.future = future;
}
}
/**
* 事务依赖器,事务提交时才启动事务
*
* @param <T>
*/
class JobTxLifeDepend<T> extends AbListDataTxLifeDepend<T> {
@Override
protected void executeTxCommit(T object) {
startJob((Job) object);
}
public boolean checkAndDelete(long id){
if(txCacheService.isInTx()){
List<T> jobList = jobThreadLocal.get();
if(jobList != null){
for(T t : jobList){
Job job = (Job)t;
if(job.getId() == id){
jobList.remove(t);
return true;
}
}
}
}
return false;
}
}
/**
* 删除一个Job
*
* @param id job的id
*/
@Tx
public void deleteJob(long id){
// 如果在事务中,先尝试从事务中删除
if(jobTxLifeDepend.checkAndDelete(id)){
return;
}
deleteJob(id,false);
}
private void deleteJob(long id,boolean jobFinish){
// 清除自身的保存
JobExecutor jobExecutor = jobExecutorMap.remove(id);
if(jobExecutor != null){
synchronized (jobExecutor) {
if(!jobFinish) {
jobExecutor.future.cancel(true);
}
dataService.delete(Job.class,"id=?",id);
}
}
}
/**
* 创建Job执行器
*
* @param job
* @return
*/
private JobExecutor createJobExecutor(Job job){
JobExecutor jobExecutor = new JobExecutor();
jobExecutor.id = job.getId();
long delay = job.getStartDate().getTime() - System.currentTimeMillis();
jobExecutor.delay = delay>0?delay:0;
Object bean = BeanHelper.getServiceBean(job.getServiceClass());
if(bean == null){
throw new MMException("job set error: service is not exist:"+job.getServiceClass());
}
Method method = null;
Method[] methods = bean.getClass().getMethods();
for(int i = 0;i<methods.length;i++){
if(methods[i].getName().equals(job.getMethod())){
Class<?>[] classes = methods[i].getParameterTypes(); // 它是可能是父类
if((job.getParamsObjectArray() == null || job.getParamsObjectArray().length == 0)
&&(classes == null || classes.length == 0)){ // 都没有
method = methods[i];
break;
}
if((job.getParamsObjectArray() == null || job.getParamsObjectArray().length == 0)
||(classes == null || classes.length == 0)){ // 其中一个没有
continue;
}
if(classes.length != job.getParamsObjectArray().length){//
continue;
}
// 比较参数
Class<?>[] paraClasses = new Class[job.getParamsObjectArray().length];
for(int p=0;p<paraClasses.length;p++){
paraClasses[p] = job.getParamsObjectArray()[p].getClass();
}
boolean success = true;
for(int k = 0;k<classes.length;k++){
if(!classes[k].isAssignableFrom(paraClasses[k])){
success = false;
break;
}
}
if(success) {
method = methods[i];
break;
}
}
}
if(method == null){
throw new MMException("can't find method with such para: "+job.getMethod());
}
jobExecutor.method = method;
jobExecutor.para = job.getParamsObjectArray();
jobExecutor.object = bean;
return jobExecutor;
}
private class JobExecutor implements Runnable{
private long id;
//
private long delay; // 第一次执行时间,
private Method method;
private Object object;
private Object[] para;
private RunnableScheduledFuture<?> future;
@Override
public void run() {
try {
method.invoke(object,para);
} catch (IllegalAccessException e) {
log.error("job execute error!",e);
} catch (InvocationTargetException e) {
log.error("job execute error!",e);
}finally {
deleteJob(id,true);
}
}
}
}
|
<gh_stars>1-10
const obs = require('../obs')
module.exports = {
getScenes: async (request, response) => {
if (!obs.getConnectionStatus()) {
return response.json({ error: 'Não conectadado' })
}
const cenas = await obs.getScenes()
return response.json(cenas)
},
swithScene: async (request, response) => {
const { scene } = request.query
if (!obs.getConnectionStatus()) {
return response.json({ error: 'Não conectadado' })
}
const cenas = await obs.getScenes()
if (cenas.includes(scene)) await obs.swithScene(scene)
else return response.json({ error: 'Cena não encontrada' })
return response.send()
},
record: async (request, response) => {
const { command } = request.query
if (!obs.getConnectionStatus()) {
return response.json({ error: 'Não conectadado' })
}
await obs.record(command)
return response.send()
},
stream: async (request, response) => {
if (!obs.getConnectionStatus()) {
return response.json({ error: 'Não conectadado' })
}
await obs.stream()
return response.send()
}
}
|
<?hh // strict
namespace Waffle\Http\Server\__Private;
use type Waffle\Contract\Http\Message\ResponseInterface;
use type Waffle\Contract\Http\Message\ServerRequestInterface;
use type Waffle\Contract\Http\Server\RequestHandlerInterface;
use type Waffle\Contract\Http\Server\MiddlewareInterface;
use type SplPriorityQueue;
class NextMiddlewareProcessor implements RequestHandlerInterface
{
private SplPriorityQueue<MiddlewareInterface> $queue;
public function __construct(SplPriorityQueue<MiddlewareInterface> $queue, private RequestHandlerInterface $handler)
{
$this->queue = clone $queue;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
if (0 === $this->queue->count()) {
return $this->handler->handle($request);
}
$middleware = $this->queue->extract();
return $middleware->process($request, $this);
}
}
|
#!/bin/bash
DEPS=("websocat" "curl" "jq" "cut" "twitchpipe")
API_URL="https://gql.twitch.tv/gql"
WEBSOCKET_URL="wss://pubsub-edge.twitch.tv/v1"
CLIENT_ID="kimne78kx3ncx6brgo4mv6wki5h1ko"
PRINT_FILENAME=0
GROUP="chunked"
FILENAME_COMMAND=$'date -u \'+%Y_%m_%d_%H_%M_%S_(%Z)\''
errf(){ >&2 printf "${@}"; }
safe_name() {
echo -n "${1//[[:cntrl:]<>:\/\\|?*]/_}"
}
get_ids () {
USERNAMES="$(printf "%s\n" "${@}")"
USERNAMES_ARRAY="$(jq -R . <<< "${USERNAMES}" | jq -s -c .)"
QUERY_STRING="$(printf "{users(logins:%s){id}}" "${USERNAMES_ARRAY}")"
DATA="$(jq -c -R '{"query":.}' <<< "${QUERY_STRING}")"
IDS="$(curl --silent --fail -H "Client-ID: ${CLIENT_ID}" "${API_URL}" --data-raw "${DATA}" | jq -r ".data.users[].id | .//-1")"
echo -n "${IDS}"
}
print_usage() {
errf "Usage: record [OPTIONS...] <USERNAMES...>\n"
errf "\n"
errf "Options:\n"
errf " -h\t\t\tPrints this help text\n"
errf " -p\t\t\tPrint filenames to standard output once stream ends\n"
errf " -g <GROUP>\t\tSelect playlist group to record (default '%s')\n" "${GROUP}"
errf " -f <COMMAND>\t\tCommand that will be evaluated to get output filename (default '%s')\n" "${FILENAME_COMMAND}"
errf " \t\tFilename will be read from the command's standard output\n"
errf " \t\tBash variables are expanded in the command, the following variables may be useful:\n"
errf $" \t\t\t\$username: \tThe streamer's Twitch username\n"
errf $" \t\t\t\$id: \t\tThe streamer's numerical Twitch ID\n"
errf " \t\tNote that filenames are sanitized prior to use, so the final filename may not match exactly what this command returns\n"
errf " \t\tAlong with sanitization, the file extension '.ts' will be appended to the final result\n"
}
check_deps() {
for i in "${DEPS[@]}"
do
if ! [ -x "$(command -v ${i})" ]
then
errf $'missing dependency \'%s\'\n' "${i}"
exit 1
fi
done
}
invalid_input() {
errf "%s\n" "${1}"
errf $'try \'record -h\' for usage information'
exit 1
}
check_deps
while getopts ":phg:f:" opt
do
case "${opt}" in
p )
PRINT_FILENAME=1
;;
h )
print_usage
exit 0
;;
g )
if [ -z "${OPTARG}"]
then
invalid_input "option '-g' cannot be empty"
exit 1
fi
GROUP="${OPTARG}"
;;
f )
if [ -z "${OPTARG}" ]
then
invalid_input "option '-f' cannot be empty"
fi
FILENAME_COMMAND="${OPTARG}"
;;
\? )
invalid_input "$(printf $'unknown option \'-%s\'' "${OPTARG}")"
;;
esac
done
shift $((OPTIND -1))
USERNAMES=("${@,,}")
if [ "${#USERNAMES[@]}" -lt 1 ]; then
invalid_input 'no username(s) supplied'
fi
errf 'fetching user IDs...\n'
IDS="$(get_ids "${USERNAMES[@]}" | tr -d '\r')"
declare -A id_username
i=0
while read -r ID
do
USERNAME="${USERNAMES[${i}]}"
if [[ "${ID}" -eq "-1" ]]
then
errf 'ERROR! could not get ID for "%s"' "${USERNAME}"
exit 1
fi
id_username["${ID}"]="${USERNAME}"
((i++))
done <<< "${IDS}"
(
trap exit SIGINT SIGTERM
while :
do
errf 'connecting to websocket...\n'
(
(
while :
do
echo '{"type":"PING"}'
sleep 150
done
) &
for k in "${!id_username[@]}"
do
printf '{"type":"LISTEN","data":{"topics":["video-playback-by-id.%d"]}}\n' "${k}"
done
) | websocat "${WEBSOCKET_URL}"
errf 'disconnected, re'
done
) | (
errf 'monitoring streams...\n'
while read -r line;
do
#errf ">%s\n" "${line}"
type="$(echo "${line}" | jq -r .type)"
case "${type}" in
MESSAGE)
id="$(echo "${line}" | jq -r .data.topic | cut -d . -f 2)"
message="$(echo "${line}" | jq -r .data.message)"
message_type="$(echo "${message}" | jq -r .type)"
if [ "${message_type}" == "stream-up" ];
then
(
username="${id_username[${id}]}"
errf '[%s] stream started\a\n' "${username}"
while :
do
mkdir -p "${username}"
filename="$(printf "%s/%s.ts" "${username}" "$(safe_name "$(eval "${FILENAME_COMMAND}")")")"
errf '[%s] recording to %s\n' "${username}" "${filename}"
(twitchpipe --archive --group "${GROUP}" "${username}" >> "${filename}") 2>&1 | (
while read -r line;
do
errf '[%s] %s\n' "${username}" "${line}"
done
)
EXIT_STATUS="${PIPESTATUS[0]}"
if [ -s "${filename}" ]
then
if [ "${PRINT_FILENAME}" == "1" ];
then
printf '%s\n' "${filename}"
fi
else
errf '[%s] output file %s was empty, removing...\n' "${username}" "${filename}"
rm "${filename}"
fi
if [ "${EXIT_STATUS}" == "2" ];
then
errf '[%s] stream ended with error, restarting...\n' "${username}"
continue
fi
break
done
) &
fi
;;
PONG)
;;
RESPONSE)
;;
*)
errf '>%s\n' "${line}"
;;
esac
done
)
|
Phaser.Plugin.JSON2Game = function(game, parent, settings) {
Phaser.Plugin.call(this, game, parent);
DOM_Wrapper.install(game); // hay que ver como hacer esto más prolijo
var def = (typeof $ == "function" && typeof $.Deferred == "function") ?
$.Deferred :
(typeof jwk == "object" && typeof jwk.Deferred == "function") ?
jwk.Deferred :
settings.Deferred;
this._default = {
defferred:def
};
this._settings = this._default;
this._parse_JSON2Game = function (JSON2Game) {
this._data = JSON2Game;
if (typeof this._data == "string") {
try {
this._data = JSON.parse(this._data);
} catch(e) {
console.error("ERROR: JSON2Game must be a plane map object or a valid json string. ", JSON2Game);
return false;
}
}
return true;
}
this._create_scenes = function() {
for (var name in this._data.scenes) {
console.log(name, this._data.scenes[name]);
var spec = this._data.scenes[name];
spec.instance_name = name;
var state = new Phaser.Plugin.JSON2Game.Scene(game, spec);
game.state.add(name, state, spec.autostart);
if (spec.autostart) {
game.state.clearCurrentState();
game.state.setCurrentState(name);
}
// this.scenes[name] = state;
}
}
this._create = function (JSON2Game) {
if (this._parse_JSON2Game(JSON2Game)) {
console.assert(this._data, "ERROR: this._data not set");
this._create_scenes();
} else {
console.warn("WARNING: this._data not set properly");
};
};
this._resize = function () {
var current = this.game.state.getCurrentState();
// console.log("onResize() current state: ", current);
current.resize();
};
this.preUpdate = null;
this.update = null;
this.postUpdate = null;
this.render = null;
this.postRender = null;
};
Phaser.Plugin.JSON2Game.utils = {
hexToRgb: function (hex) {
// http://stackoverflow.com/a/5624139
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
}
Phaser.Plugin.JSON2Game.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.JSON2Game.prototype.constructor = Phaser.Plugin.JSON2Game;
Phaser.Plugin.JSON2Game.prototype.setup = function (obj) {
this._settings = Phaser.Utils.extend(false, {}, this._default, obj);
};
Phaser.Plugin.JSON2Game.prototype.create = function(gamejson) {
var def = this._settings.defferred();
var self = this;
for (var name in gamejson.preload) {
this.game.load.image(name, gamejson.preload[name]);
}
this.game.load.onLoadComplete.add(function () {
self._create.call(self, gamejson);
/*
self.game.state.getCurrentState().onCreate(function () {
def.resolve();
});*/
}, this);
this.game.load.start();
return def.promise();;
};
Phaser.Plugin.JSON2Game.prototype.resize = function() {
return this._resize.apply(this, arguments);
};
// --------------------------------------------------------------------------------------
Phaser.Plugin.JSON2Game.Base = function (game, spec) {
this.game = game;
this.spec = spec;
this.instance_name = spec.instance_name;
this.createChildren();
this.sortChildren();
}
Phaser.Plugin.JSON2Game.Base.prototype = {
constructor: Phaser.Plugin.JSON2Game.Base,
getDependencies: function () {
var result = [];
if (this.spec.position) {
result.push(this.spec.position.of);
}
if (this.spec.anchors) {
for (var i in this.spec.anchors) {
result.push(this.spec.anchors[i].of);
}
}
return result;
},
sortChildren: function () {
console.assert(this.children, "ERROR: this.children does't exist");
var index = 0;
var list = this.children.map(function (n) { return n; }); // copia limpia
var ready = {};
var new_order = [];
var counter = 100;
while (list.length > 0) {
if (counter--<0) {
console.error("ERROR: infinite dependency loop");
break;
}
var child = list.shift();
var deps = child.getDependencies();
console.assert(typeof child.spec.instance_name == "string", "ERROR: child.spec.instance_name is not a string", child);
ready[child.spec.instance_name] = true;
for (var i=0; i<deps.length; i++) {
if (deps[i] == "parent") continue;
index = deps[i].indexOf("parent.");
if (index == 0) {
var dep = deps[i].substr(7);
if (!(dep in ready)) {
ready[child.spec.instance_name] = false;
list.push(child);
}
}
}
if (ready[child.spec.instance_name]) new_order.push(child);
}
console.assert(this.children.length == new_order.length, "ERROR: some child lost in the sorting proccess");
this.children = new_order;
},
createChildren: function () {
console.assert(this.spec, "ERROR: this.spec does't exist");
this.children = [];
for (var name in this.spec.children) {
var child_spec = this.spec.children[name];
var child = null;
var constructor = Phaser.Plugin.JSON2Game[child_spec.type];
console.assert(constructor, "ERROR: type not found: ", child_spec.type, [child_spec]);
child_spec.instance_name = name;
child = new constructor(this.game, child_spec);
child.parent = this;
this.children.push(child);
}
},
childrenDoCreate: function() {
console.assert(this.children, "ERROR: this.children does't exist");
for (var i=0; i<this.children.length; i++) {
this.children[i].create();
// this.children[i].childrenDoCreate();
}
},
getChild: function(name) {
for (var i=0; i<this.children.length; i++) {
if (this.children[i].instance_name == name) {
return this.children[i];
}
}
console.error("ERROR: no child with name '"+name+"' was found", this.children);
},
translateToCoords: function (str) {
var x, y, ox, oy;
console.assert(typeof str == "string", "ERROR: str must be a string. got: ", typeof str);
var parts = str.split(" ");
console.assert(parts.length == 2, "ERROR: str MUST have two expresions separated by one space. got: ", str);
switch (parts[0]) {
case "top": oy = 0; break;
case "middle": oy = 0.5; break;
case "bottom": oy = 1; break;
default:
if (parts[0].indexOf("%") != -1) {
oy = parseInt(parts[0].substr(0, parts[0].indexOf("%"))) * 0.01;
} else {
oy = parts[0] / this.height;
}
}
switch (parts[1]) {
case "left": ox = 0; break;
case "center": ox = 0.5; break;
case "right": ox = 1; break;
default:
if (parts[1].indexOf("%") != -1) {
ox = parseInt(parts[1].substr(0, parts[1].indexOf("%"))) * 0.01;
} else {
ox = parts[1] / this.width;
}
}
x = this.phaserObj.x + this.phaserObj.width * ox;
y = this.phaserObj.y + this.phaserObj.height * oy;
return {x:x, y:y, ox:ox, oy:oy};
},
setDeployment: function (dep) {
console.error("ERROR");
},
updateDeployment: function () {
this.computeDeployment(true);
return this;
},
computeRelativeValue: function (val, porp) {
if (typeof val == "string" && val.indexOf("%") != -1) {
var percent = parseFloat(val.substr(0, val.indexOf("%")));
return percent * this.parent.phaserObj[porp] / 100;
} else {
return parseInt(val);
}
},
computeDeployment: function (apply) {
var result = {width: 12, height: 34},
before = {},
max, min;
if (this.spec.width) {
result.width = this.computeRelativeValue(this.spec.width, "width");
if (this.spec.maxWidth) {
max = this.computeRelativeValue(this.spec.maxWidth, "width");
result.width = Math.min(max, result.width);
}
if (this.spec.minWidth) {
min = this.computeRelativeValue(this.spec.minWidth, "width");
result.width = Math.max(min, result.width);
}
}
if (this.spec.height) {
result.height = this.computeRelativeValue(this.spec.height, "height");
if (this.spec.maxHeight) {
max = this.computeRelativeValue(this.spec.maxHeight, "height");
result.height = Math.min(max, result.height);
}
if (this.spec.minHeight) {
min = this.computeRelativeValue(this.spec.minHeight, "height");
result.height = Math.max(min, result.height);
}
}
if (apply) {
this.setSize(result);
} else {
before = {
x: this.phaserObj.x,
y: this.phaserObj.y
}
}
if (this.spec.position) {
console.assert(typeof this.spec.position.of == "string", "ERROR: position MUST have a 'of' attribute referencing a valid object");
console.assert(typeof this.spec.position.at == "string", "ERROR: position MUST have a 'at' attribute referencing a valid object");
var refobj = this.parent;
var index = this.spec.position.of.indexOf("parent.");
if (index != -1) {
refobj = this.parent.getChild(this.spec.position.of.substr("parent.".length));
}
this.phaserObj.y = this.phaserObj.x = 0;
var my_coords = this.translateToCoords(this.spec.position.my);
var at_coords = refobj.translateToCoords(this.spec.position.at);
result.x = at_coords.x - my_coords.x;
result.y = at_coords.y - my_coords.y;
}
if (this.spec.anchors) {
console.assert(this.spec.anchors.length == 2, "ERROR: anchors MUST be an array-like object width 2 objects containing {my, at, of} map each");
var refobj = [this.parent,this.parent],
index = [],
my_coords=[],
at_coords=[];
this.phaserObj.y = this.phaserObj.x = 0;
for (var i=0;i<2;i++) {
index[i] = this.spec.anchors[i].of.indexOf("parent.");
if (index[i] != -1) {
refobj[i] = this.parent.getChild(this.spec.anchors[i].of.substr("parent.".length));
}
my_coords[i] = this.translateToCoords(this.spec.anchors[i].my);
at_coords[i] = refobj[i].translateToCoords(this.spec.anchors[i].at);
}
/*
// Despeje
result.x + result.width * my_coords[0].ox = at_coords[0].x;
result.x + result.width * my_coords[1].ox = at_coords[1].x;
result.x + result.width * my_coords[0].ox - (result.x + result.width * my_coords[1].ox)= at_coords[0].x - (at_coords[1].x);
result.x + result.width * my_coords[0].ox - result.x - result.width * my_coords[1].ox = at_coords[0].x - at_coords[1].x;
result.width * my_coords[0].ox - result.width * my_coords[1].ox = at_coords[0].x - at_coords[1].x;
result.width * (my_coords[0].ox - my_coords[1].ox) = at_coords[0].x - at_coords[1].x;
result.width = (at_coords[0].x - at_coords[1].x) / (my_coords[0].ox - my_coords[1].ox); <<--- (width)
result.x = at_coords[0].x - result.width * my_coords[0].ox; <<--- (x)
*/
result.width = Math.abs((at_coords[0].x - at_coords[1].x));
result.x = at_coords[0].x - result.width * my_coords[0].ox;
result.height = Math.abs((at_coords[0].y - at_coords[1].y));
result.y = at_coords[0].y - result.width * my_coords[0].ox;
if (apply) {
this.setSize(result);
}
}
if (apply) {
this.setPosition(result);
} else {
this.setPosition(before);
}
return result;
},
setSize: function (size) {
this.phaserObj.width = size.width;
this.phaserObj.height = size.height;
},
setPosition: function (pos) {
this.phaserObj.x = pos.x;
this.phaserObj.y = pos.y;
},
resize: function () {
// console.log("Phaser.Plugin.JSON2Game.base.prototype.resize");
this.updateDeployment();
for (var i in this.children) {
this.children[i].resize();
}
// console.log(this);
//alert("resize: " + this.instance_name);
}
}
// --------------------------------------------------------------------------------------
Phaser.Plugin.JSON2Game.Scene = function (game, spec) {
this.phaserObj = game.world;
this.width = game.world.width;
this.height = game.world.height;
Phaser.Plugin.JSON2Game.Base.call(this, game, spec);
}
Phaser.Plugin.JSON2Game.Scene.prototype = Object.create(Phaser.Plugin.JSON2Game.Base.prototype);
Phaser.Plugin.JSON2Game.Scene.prototype.constructor = Phaser.Plugin.JSON2Game.Scene;
Phaser.Plugin.JSON2Game.Scene.prototype.resize = function () {
this.width = this.game.world.width;
this.height = this.game.world.height;
// console.log(this.game.world.width);
for (var i in this.children) {
this.children[i].resize();
}
}
Phaser.Plugin.JSON2Game.Scene.prototype.create = function () {
this.childrenDoCreate();
this.resize();
if (typeof this.onCreateCallback == "function") this.onCreateCallback();
}
Phaser.Plugin.JSON2Game.Scene.prototype.render = function () {
if (typeof this.onRenderCallback == "function") this.onRenderCallback();
}
Phaser.Plugin.JSON2Game.Scene.prototype.update = function () {
if (typeof this.onUpdateCallback == "function") this.onUpdateCallback();
}
Phaser.Plugin.JSON2Game.Scene.prototype.onCreate = function (callback) {
this.onCreateCallback = callback;
}
Phaser.Plugin.JSON2Game.Scene.prototype.onRender = function (callback) {
this.onRenderCallback = callback;
}
Phaser.Plugin.JSON2Game.Scene.prototype.onUpdate = function (callback) {
this.onUpdateCallback = callback;
}
// --------------------------------------------------------------------------------------
CroppedSprite = function (game, x, y, texture) {
Phaser.Sprite.call(this, game, x, y, texture);
};
CroppedSprite.prototype = Object.create(Phaser.Sprite.prototype);
CroppedSprite.prototype.constructor = CroppedSprite;
CroppedSprite.prototype.update = function() {
console.log("this.updateCrop();");
this.updateCrop();
};
MaskedSprite = function (game, x, y, texture) {
Phaser.Sprite.call(this, game, x, y, texture);
};
MaskedSprite.prototype = Object.create(Phaser.Sprite.prototype);
MaskedSprite.prototype.constructor = MaskedSprite;
MaskedSprite.prototype.update = function() {
};
// ---------------------------------
Phaser.Plugin.JSON2Game.Sprite = function (game, spec) {
Phaser.Plugin.JSON2Game.Base.call(this, game, spec);
}
Phaser.Plugin.JSON2Game.Sprite.prototype = Object.create(Phaser.Plugin.JSON2Game.Base.prototype);
Phaser.Plugin.JSON2Game.Sprite.prototype.constructor = Phaser.Plugin.JSON2Game.Sprite;
Phaser.Plugin.JSON2Game.Sprite.prototype.create = function () {
// this.phaserObj = new CroppedSprite(game, 0, 0, this.spec.texture); // game.add.sprite(0, 0, this.spec.texture);
this.phaserObj = this.game.add.sprite(0, 0, this.spec.texture);
console.log("Phaser.Plugin.JSON2Game.Sprite.prototype.create() this.phaserObj: ",[ this.phaserObj]);
this.game.add.existing(this.phaserObj);
this.cropRect = new Phaser.Rectangle(0, 0, this.phaserObj.texture.width, this.phaserObj.texture.height);
this.mask = this.game.add.graphics(0, 0);
// Shapes drawn to the Graphics object must be filled.
this.mask.beginFill(0xff0000);
this.mask.drawRect(0, 0, this.phaserObj.texture.width, this.phaserObj.texture.height);
this.phaserObj.mask = this.mask;
this.texture = {h:this.phaserObj.texture.height, w: this.phaserObj.texture.width};
this.aspectRatio = this.texture.w / this.texture.h;
//this.phaserObj.crop(this.cropRect);
this.childrenDoCreate();
this.phaserObj.worldTransform = new PIXI.Matrix();
console.log("this.phaserObj.worldTransform = new PIXI.Matrix();", [this.phaserObj.getBounds()]);
}
Phaser.Plugin.JSON2Game.Sprite.prototype.setDeployment = function (dep) {
Phaser.Plugin.JSON2Game.Base.prototype.setDeployment.call(this, dep);
if (dep.crop) {
if (dep.crop.x) this.cropRect.x = dep.crop.x;
if (dep.crop.y) this.cropRect.y = dep.crop.y;
if (dep.crop.width) this.cropRect.width = dep.crop.width;
if (dep.crop.height) this.cropRect.height = dep.crop.height;
}
if (dep.mask) {
this.mask.clear();
this.mask.beginFill(0xff0000);
this.mask.drawRect(dep.mask.x, dep.mask.y, dep.mask.width, dep.mask.height);
this.phaserObj._bounds = new Phaser.Rectangle(dep.mask.x, dep.mask.y, dep.mask.width, dep.mask.height);
}
}
Phaser.Plugin.JSON2Game.Sprite.prototype.computeDeployment = function (apply) {
var dep = Phaser.Plugin.JSON2Game.Base.prototype.computeDeployment.call(this, false);
var temp, percent;
this.phaserObj.scale.x = 1;
this.phaserObj.scale.y = 1;
var size = this.spec["texture-size"];
switch (size) {
case "cover":
dep.mask = {x:dep.x,y:dep.y,width:dep.width,height:dep.height};
if (this.aspectRatio <= dep.width / dep.height) {
temp = dep.width / this.aspectRatio;
percent = 0.5 * (temp-dep.height)/temp;
// dep.crop = {height:Math.floor(this.texture.h*(1-percent*2))+1};
// console.log(dep.crop.height, percent, temp, dep.height);
// dep.crop = {height:dep.height};
// dep.crop = {y:percent*this.texture.h, height:(1-percent*2) * this.texture.h};
dep.y -= 0.5 * (temp-dep.height);
dep.height = temp;
} else {
temp = dep.height * this.aspectRatio;
//percent = 0.5 * (temp-dep.width)/temp;
//dep.crop = { x:percent*this.texture.w, width:(1-percent*2) * this.texture.w};
dep.x -= 0.5 * (temp-dep.width);
dep.width = temp;
}
break;
case "contain":
if (this.aspectRatio <= dep.width / dep.height) {
temp = dep.height * this.aspectRatio;
dep.x += 0.5 * (temp-dep.width);
dep.width = temp;
} else {
temp = dep.width / this.aspectRatio;
dep.y += 0.5 * (temp-dep.height);
dep.height = temp;
}
break;
default:
}
if (apply) {
this.setDeployment(dep);
}
return dep;
}
// --------------------------------------------------------------------------------------
Phaser.Plugin.JSON2Game.BitmapData = function (game, spec) {
Phaser.Plugin.JSON2Game.Base.call(this, game, spec);
}
Phaser.Plugin.JSON2Game.BitmapData.prototype = Object.create(Phaser.Plugin.JSON2Game.Base.prototype);
Phaser.Plugin.JSON2Game.BitmapData.prototype.constructor = Phaser.Plugin.JSON2Game.BitmapData;
Phaser.Plugin.JSON2Game.BitmapData.prototype.create = function () {
var pos, color = Phaser.Plugin.JSON2Game.utils.hexToRgb(this.spec.fillStyle);
var layout = {x:22,y:33,width:200,height:200};
this.bmd = this.game.make.bitmapData(layout.width,layout.height);
this.bmd.fill(color.r, color.g, color.b);
this.img = this.bmd.addToWorld(layout.x,layout.y);
this.phaserObj = this.img;
this.childrenDoCreate();
}
Phaser.Plugin.JSON2Game.BitmapData.prototype.setDeployment = function (dep) {
this.bmd.width = dep.width;
this.bmd.height = dep.height;
Phaser.Plugin.JSON2Game.Base.prototype.setDeployment.call(this, size);
}
Phaser.Plugin.JSON2Game.BitmapData.prototype.setSize = function (size) {
this.bmd.width = size.width;
this.bmd.height = size.height;
Phaser.Plugin.JSON2Game.Base.prototype.setSize.call(this, size);
}
// --------------------------------------------------------------------------------------
Phaser.Plugin.JSON2Game.DOM_Wrapper = function (game, spec) {
Phaser.Plugin.JSON2Game.Base.call(this, game, spec);
}
Phaser.Plugin.JSON2Game.DOM_Wrapper.prototype = Object.create(Phaser.Plugin.JSON2Game.Base.prototype);
Phaser.Plugin.JSON2Game.DOM_Wrapper.prototype.constructor = Phaser.Plugin.JSON2Game.Sprite;
Phaser.Plugin.JSON2Game.DOM_Wrapper.prototype.create = function () {
var x=0,y=0,w=200,h=150; // provisorio
this.phaserObj = this.game.add.domWrapper(game,spec.html,x,y,w,h);
this.childrenDoCreate();
}
// --------------------------------------------------------------------------------------
Phaser.Plugin.JSON2Game.YoutubeVideo = function (game, spec) {
Phaser.Plugin.JSON2Game.Base.call(this, game, spec);
}
Phaser.Plugin.JSON2Game.YoutubeVideo.prototype = Object.create(Phaser.Plugin.JSON2Game.Base.prototype);
Phaser.Plugin.JSON2Game.YoutubeVideo.prototype.constructor = Phaser.Plugin.JSON2Game.Sprite;
Phaser.Plugin.JSON2Game.YoutubeVideo.prototype.create = function () {
var x=0,y=0,w=200,h=150; // provisorio
var autoplay = "autoplay=" + (this.spec.autoplay ? "1" : "0");
var fullscreen = "allowfullscreen='" + (this.spec.allowfullscreen ? "true" : "false") + "'";
var part_1 ="<iframe frameborder='0' "+fullscreen+" style='height:100%; width:100%'src='https://www.youtube.com/embed/",
part_2 = "?feature=oembed&"+autoplay+"&wmode=opaque&rel=0&showinfo=0&modestbranding=0&fs=1'></iframe>";
var html = part_1 + this.spec.videoid + part_2;
this.phaserObj = this.game.add.domWrapper(html,x,y,w,h);
this.childrenDoCreate();
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.tdb.store.tupletable;
import org.apache.jena.atlas.lib.ColumnMap ;
import org.apache.jena.tdb.base.file.FileSet ;
import org.apache.jena.tdb.base.record.RecordFactory ;
import org.apache.jena.tdb.index.IndexFactory ;
import org.apache.jena.tdb.index.IndexParams ;
import org.apache.jena.tdb.index.RangeIndex ;
import org.apache.jena.tdb.setup.StoreParams ;
import org.apache.jena.tdb.store.tupletable.TupleIndexRecord ;
import org.apache.jena.tdb.sys.SystemTDB ;
public class TestTupleIndexRecord extends AbstractTestTupleIndex
{
static RecordFactory factory = new RecordFactory(3*SystemTDB.SizeOfNodeId, 0) ;
@Override
protected TupleIndexRecord create(String description)
{
IndexParams indexParams = StoreParams.getDftStoreParams() ;
RangeIndex rIdx = IndexFactory.buildRangeIndex(FileSet.mem(), factory, indexParams) ;
ColumnMap cmap = new ColumnMap("SPO", description) ;
TupleIndexRecord index = new TupleIndexRecord(3, cmap, description, factory, rIdx) ;
return index ;
}
}
|
package org.para.distributed.util;
import java.util.Comparator;
import org.apache.log4j.Logger;
import org.para.distributed.dto.WorkerNode;
/**
* 按照资源总值排序
*
*
* 按照公式:CPU剩余率*100*CPU权重+内存剩余率*100*(1-CPU权重)=负载Value,进行从大到小的排序。(
* 硬件的性能指数还可以在细化:CPU工作频率、内存工作频率、硬盘转数、网络吞吐量)
*
* @author liuyan
* @Email:<EMAIL>
* @version 0.1
* @Date: 2013-11-16 下午3:41:22
* @Copyright: 2013 story All rights reserved.
*
*/
public class SortCPUAndMemroyComparator implements Comparator<WorkerNode> {
private static Logger logger = Logger
.getLogger(SortCPUAndMemroyComparator.class);
/**
* 实体互相进行比较
*/
public int compare(WorkerNode workerNode1, WorkerNode workerNode2) {
if (null == workerNode1 || null == workerNode2) {
logger.info("error, nodeInfo1 or nodeInfo2 is null!");
return 0;
}
float node1PowerValue = getNodeValue(workerNode1);
float node2PowerValue = getNodeValue(workerNode2);
// 综合值进行对比
if (node1PowerValue < node2PowerValue) {
return 1;
} else if (node1PowerValue == node2PowerValue) {
return 0;
} else {
return -1;
}
}
/**
* 获取结点机器的负载值
*
* @param nodeInfo
* @return
*/
public float getNodeValue(WorkerNode workerNode) {
// node1-CPU剩余率
float node1CpuFreeRate = workerNode.getCpufreerate();
// node1-内存剩余率
float node1MemroyFreeRate = workerNode.getFreememroy();
// node1-的综合值
// TODO:此处算法的权重需要可配置,客户端可以根据自己的场景需求进行权重配置
float node1PowerValue = node1CpuFreeRate * 0.5F * 100.0F
+ node1MemroyFreeRate * (1 - 0.5f) * 100;
return node1PowerValue;
}
}
|
/*
Copyright © 2020 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.
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.
*/
package controller
import (
"errors"
"fmt"
"os"
"strings"
"github.com/awslabs/clencli/cobra/aid"
"github.com/awslabs/clencli/cobra/dao"
"github.com/awslabs/clencli/cobra/model"
"github.com/awslabs/clencli/helper"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var renderValidArgs = []string{"template"}
// RenderCmd command to render templates
func RenderCmd() *cobra.Command {
man, err := helper.GetManual("render")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
cmd := &cobra.Command{
Use: man.Use,
Short: man.Short,
Long: man.Long,
ValidArgs: renderValidArgs,
Args: cobra.OnlyValidArgs,
PreRunE: renderPreRun,
RunE: renderRun,
}
cmd.Flags().StringP("name", "n", "readme", "Database file name of the template to be rendered (it must be under clencli/ directory.")
return cmd
}
func renderPreRun(cmd *cobra.Command, args []string) error {
logrus.Traceln("start: command render pre-run")
if err := helper.ValidateCmdArgs(cmd, args, "render"); err != nil {
return err
}
if err := helper.ValidateCmdArgAndFlag(cmd, args, "render", "template", "name"); err != nil {
return err
}
name, err := cmd.Flags().GetString("name")
if err != nil {
logrus.Errorf("error: unable to access flag name\n%v", err)
return fmt.Errorf("unable to access flag name\n%v", err)
}
path := "clencli/" + name + ".yaml"
if !helper.FileExists(path) {
logrus.Errorf("missing database " + path)
return errors.New("missing database " + path)
}
path = "clencli/" + name + ".tmpl"
if !helper.FileExists(path) {
logrus.Errorf("missing template " + path)
return errors.New("missing template " + path)
}
logrus.Traceln("end: command render pre-run")
return nil
}
func renderRun(cmd *cobra.Command, args []string) error {
logrus.Traceln("start: command render run")
name, err := cmd.Flags().GetString("name")
if err != nil {
logrus.Errorf("error: unable to render template "+name+"\n%v", err)
return fmt.Errorf("unable to render template "+name+"\n%v", err)
}
// TODO: fix this, causing issues on Windows
// remove any trailing whitespaces
// path := "./clencli/" + name + ".yaml"
// if err := helper.TrimRightFile(path, true); err != nil {
// logrus.Errorf("unexpected err: %v", err)
// return fmt.Errorf("unable to remove white spaces from %s.yaml\n%v", name, err)
// }
if err := updateLogo(profile); err != nil {
logrus.Errorf("Unexpected error: %v", err)
return fmt.Errorf("unable to update logo url\n%v", err)
}
if err := aid.BuildTemplate(name); err != nil {
logrus.Errorf("Unexpected error: %v", err)
return fmt.Errorf("unable to render template "+name+"\n%v", err)
}
cmd.Println("Template " + name + ".tmpl rendered as " + strings.ToUpper(name) + ".md.")
logrus.Traceln("end: command render run")
return nil
}
func updateLogo(profile string) error {
if !updateLogoFromUnsplashFile() {
return updateLogoFromConfigurations(profile)
}
return nil
}
func updateLogoFromUnsplashFile() bool {
if helper.FileExists("unsplash.yaml") {
configPath, _ := os.Getwd()
configName := "unsplash"
configType := "yaml"
var response model.UnsplashRandomPhotoResponse
v, err := aid.ReadConfigAsViper(configPath, configName, configType)
if err != nil {
logrus.Errorf("unable to read unsplash.yaml as viper object\n%v", err)
return false
}
err = v.Unmarshal(&response)
if err != nil {
logrus.Errorf("unable to unmarshall unsplash.yaml as unsplash response\n%v", err)
return false
}
err = helper.DownloadFile(response.Urls.Regular, "clencli", "logo.jpeg")
if err != nil {
logrus.Errorf("unable to download photo\n%v", err)
return false
}
response.Urls.Regular = "clencli/logo.jpeg"
readMe, err := dao.GetReadMe()
if err != nil {
logrus.Errorf("Unable to get local readme config\n%v", err)
return false
}
err = aid.UpdateReadMeLogoURL(readMe, response)
if err != nil {
logrus.Errorf("unable to update logo URL\n%s", err)
return false
}
return true
}
return false
}
func updateLogoFromConfigurations(profile string) error {
if aid.ConfigurationsDirectoryExist() {
if aid.CredentialsFileExist() && aid.ConfigurationsFileExist() {
// ignore error, as credentials doesn't exist
cred, err := dao.GetCredentialByProvider(profile, "unsplash")
if err != nil {
logrus.Warnf("no unsplash credential found\n%v", err)
return nil
}
if cred.AccessKey != "" && cred.SecretKey != "" {
readMe, err := dao.GetReadMe()
if err != nil {
return fmt.Errorf("Unable to get local readme config\n%v", err)
}
params := dao.GetUnsplashRandomPhotoParameters(profile)
if (model.UnsplashRandomPhotoParameters{}) == params {
logrus.Warnf("no unsplash random photo parameters configuration found or enabled\n%v", err)
return nil
}
response, err := aid.RequestRandomPhoto(params, cred)
if err != nil {
logrus.Warnf("unable to fetch response from unsplash during render command\n%v", err)
return err
}
err = aid.UpdateReadMeLogoURL(readMe, response)
if err != nil {
return fmt.Errorf("unable to update logo URL\n%s", err)
}
}
}
}
return nil
}
|
def web_scrape(url):
response = req.get(url)
soup = bs4.BeautifulSoup(response.text, 'html.parser')
data = []
# Find all elements with the required class
elems = soup.find_all('div', {'class': 'sample_class'})
# Extract the data
for elem in elems:
data.append(elem.text)
return data
|
<reponame>justcrossheaven/platform
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as Mongoose from 'mongoose';
import { Model } from 'mongoose';
import { Bill, BillDocument, BillModel } from './bill.schema';
@Injectable()
export class BillStoreService {
constructor(
@InjectModel(Bill.name)
private readonly BillModel: Model<BillDocument>,
) {
Mongoose.set('sanitizeFilter', true);
}
async create(createdBillModel: BillModel): Promise<BillDocument> {
return this.BillModel.create(createdBillModel);
}
async findOne(id: string | Mongoose.Types.ObjectId): Promise<BillDocument> {
return this.BillModel.findOne({ _id: id }).exec();
}
async findAll(): Promise<BillDocument[]> {
return this.BillModel.find().exec();
}
async findAllForHouse(id: Mongoose.Types.ObjectId): Promise<BillDocument[]> {
return this.BillModel.find({ house: id }).exec();
}
async update(
id: string,
updateBillModel: Partial<BillModel>,
): Promise<BillDocument> {
return this.BillModel.findOneAndUpdate({ _id: id }, updateBillModel, {
new: true,
}).exec();
}
async delete(id: string): Promise<BillDocument> {
return this.BillModel.findByIdAndRemove({
_id: id,
}).exec();
}
}
|
#!/usr/bin/env bash
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
frameworkVersion=net45
# sdk must match installed framworks under PREFIX/lib/mono/[value]
sdk=4.5.2-api
# langversion refers to C# language features. see man mcs for details.
langversion=${sdk}
nuget_cmd=nuget
# Match against our known SDK possibilities
case "${sdk}" in
4)
langversion=4
;;
4.5*)
langversion=5
;;
4.6*)
langversion=6
;;
4.7*)
langversion=7 # ignoring 7.1 for now.
;;
*)
langversion=6
;;
esac
echo "[INFO] Target framework: ${frameworkVersion}"
if ! type nuget &>/dev/null; then
echo "[INFO] Download nuget and packages"
wget -nc https://dist.nuget.org/win-x86-commandline/latest/nuget.exe;
nuget_cmd="mono nuget.exe"
fi
mozroots --import --sync
${nuget_cmd} install src/Cloudmersive.APIClient.NET.Security/packages.config -o packages;
echo "[INFO] Copy DLLs to the 'bin' folder"
mkdir -p bin;
cp packages/Newtonsoft.Json.10.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll;
cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll;
cp packages/JsonSubTypes.1.2.0/lib/net45/JsonSubTypes.dll bin/JsonSubTypes.dll
echo "[INFO] Run 'mcs' to build bin/Cloudmersive.APIClient.NET.Security.dll"
mcs -langversion:${langversion} -sdk:${sdk} -r:bin/Newtonsoft.Json.dll,bin/JsonSubTypes.dll,\
bin/RestSharp.dll,\
System.ComponentModel.DataAnnotations.dll,\
System.Runtime.Serialization.dll \
-target:library \
-out:bin/Cloudmersive.APIClient.NET.Security.dll \
-recurse:'src/Cloudmersive.APIClient.NET.Security/*.cs' \
-doc:bin/Cloudmersive.APIClient.NET.Security.xml \
-platform:anycpu
if [ $? -ne 0 ]
then
echo "[ERROR] Compilation failed with exit code $?"
exit 1
else
echo "[INFO] bin/Cloudmersive.APIClient.NET.Security.dll was created successfully"
fi
|
#!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
# Start Script for the CATALINA Server
# -----------------------------------------------------------------------------
# Better OS/400 detection: see Bugzilla 31132
os400=false
case "`uname`" in
OS400*) os400=true;;
esac
# resolve links - $0 may be a softlink
PRG="$0"
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`/"$link"
fi
done
PRGDIR=`dirname "$PRG"`
EXECUTABLE=catalina.sh
# Check that target executable exists
if $os400; then
# -x will Only work on the os400 if the files are:
# 1. owned by the user
# 2. owned by the PRIMARY group of the user
# this will not work if the user belongs in secondary groups
eval
else
if [ ! -x "$PRGDIR"/"$EXECUTABLE" ]; then
echo "Cannot find $PRGDIR/$EXECUTABLE"
echo "The file is absent or does not have execute permission"
echo "This file is needed to run this program"
exit 1
fi
fi
# cootf wangyaohui 20170620 add begin
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/
export JRE_HOME=${JAVA_HOME}/jre
export CATALINA_HOME=/home/wangyaohui/sd/android_env/tomcat
export CLASSPATH=.:${JRE_HOME}/lib/rt.jar:${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar:$JAVA_HOME/lib:$JRE_HOME/lib:$CATALINA_HOME/lib:$CLASSPATH
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$CATALINA_HOME/bin:$PATH
java -version
# cootf wangyaohui 20170620 add end
exec "$PRGDIR"/"$EXECUTABLE" start "$@"
|
#ifndef INCLUDED_RENDER_HEAD_ACTION_RENDERER_H
#define INCLUDED_RENDER_HEAD_ACTION_RENDERER_H
#include "platform/i_platform.h"
#include "render/action_renderer.h"
#include "core/actor.h"
#include "renderable_sprite.h"
#include "renderable_repo.h"
namespace render {
class HeadActionRenderer : public ActionRenderer
{
public:
HeadActionRenderer( int32_t Id );
};
} // namespace render
#endif//INCLUDED_RENDER_HEAD_ACTION_RENDERER_H
//command: "classgenerator.exe" -g "action_renderer" -c "head_action_renderer"
|
import torch
def adjust_image(image: torch.Tensor) -> torch.Tensor:
return torch.clamp(image, 0.0, 1.0)
|
#!/usr/bin/env bash
# Build soldat.smod file
# Requires zip
set -o errexit
set -o pipefail
set -o nounset
#set -o xtrace
pushd . &> /dev/null
if ! command -v zip &> /dev/null
then
echo "Error: Cannot find zip executable"
exit
fi
ROOTDIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")")
cd "${ROOTDIR}"
if [ -f "soldat.smod" ]; then
rm "soldat.smod"
fi
echo "Creating 'soldat.smod' file..."
cd "${ROOTDIR}/shared"
zip -r ../soldat.smod *
cd "${ROOTDIR}/client"
zip -ur ../soldat.smod configs
cd "${ROOTDIR}/server"
zip -ur ../soldat.smod configs
echo "Created soldat.smod"
popd &> /dev/null
|
package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Boj3004 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
System.out.println(getRes(N));
}
private static int getRes(int n) {
int num = (n / 2 + 1 + (n % 2));
return num * (num - (n % 2));
}
}
|
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
class DocumentClassifier:
def __init__(self,model_path):
self.model_path = model_path
self.vectorizer = None
self.clf = None
def fit(self,X, y):
# split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# prepare training data by transforming documents to TF-IDF vectors
self.vectorizer = TfidfVectorizer(min_df=2,max_df=0.5,ngram_range=(1,2))
X_train = self.vectorizer.fit_transform(X_train)
# train a multinomial Naive Bayes classifier
self.clf = MultinomialNB()
self.clf.fit(X_train,y_train)
def predict(self,X):
X = self.vectorizer.transform(X)
return self.clf.predict(X)
def save(self):
# save vectorizer and classifier to disk
np.save(self.model_path + 'vectorizer.npy', self.vectorizer)
np.save(self.model_path + 'clf.npy', self.clf)
|
#!/bin/bash
echo -e "Removing previous SAML metadata directory, if any, for ${SCENARIO}"
rm -Rf "${PWD}/ci/tests/puppeteer/scenarios/${SCENARIO}/saml-md"
echo -e "Creating SAML metadata directory for ${SCENARIO}"
mkdir "${PWD}/ci/tests/puppeteer/scenarios/${SCENARIO}/saml-md"
|
import os
import numpy as np
import matplotlib.pyplot as plt
GENGERATIONS = 30
POPULATION_SIZE = 50
LOG_FILE_NAME = "../../logs/evolution_18-09-29_17:15.log"
LABELS = ['Average','Best individual','Worst individual']
if __name__ == "__main__":
lines = [line.rstrip('\n') for line in open(LOG_FILE_NAME)]
lines_pure = lines[1::2]
data = np.empty((POPULATION_SIZE, GENGERATIONS))
row = 0
column = 0
for line in lines_pure:
rank = line.split(':')
data[row][column] = rank[2]
row += 1
if row == POPULATION_SIZE:
row = 0
column +=1
data *= -1
generations_avg = np.mean(data, axis=0)
generations_max = data.max(axis=0)
generations_min = data.min(axis=0)
plt.figure()
plt.plot(generations_avg, label = LABELS[0])
plt.plot(generations_min, label = LABELS[1])
plt.plot(generations_max, label = LABELS[2])
plt.xlabel('Generation')
plt.ylabel('Distance from target')
plt.grid()
plt.legend(loc=1)
plt.show()
|
#!/bin/sh
# failure validates that the correct error message
# is displayed for XOR'd args
../build/examples/test20 -ba > tmp.out 2>&1
if cmp -s tmp.out $srcdir/test76.out; then
exit 0
else
exit 1
fi
|
#!/bin/bash
#
# Copyright (c) 2020, 2021 Red Hat, IBM Corporation and others.
#
# 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.
#
##### Constants for autotuneconfig yaml tests #####
#
# get the absolute path of current directory
CURRENT_DIR="$(dirname "$(realpath "$0")")"
pushd ${CURRENT_DIR}/.. >> setup.log
# Path to the directory containing yaml files
MANIFESTS="${PWD}/autotune_test_yamls/manifests"
autotune_config_testsuite="autotune_config_yaml"
testcase_matched=0
module="da"
yaml_path="${MANIFESTS}/${module}/${autotune_config_testsuite}"
autotune_config_obj_create_msg='com.autotune.analyzer.deployment.AutotuneDeployment - Added autotuneconfig'
exception="com.autotune.analyzer.exceptions.InvalidValueException:"
invalid_bound_exception='com.autotune.analyzer.exceptions.InvalidBoundsException'
# testcases for autotune config yaml
autotune_config_tests=("layer_name"
"layer_level"
"presence"
"layer_presence_query_datasource"
"layer_presence_query"
"layer_presence_query_key"
"layer_presence_label_name"
"layer_presence_labelvalue"
"layer_presence"
"tunable_name"
"tunable_value_type"
"tunable_upper_bound"
"tunable_lower_bound"
"step"
"tunable_query"
"tunable_datasource_name"
"tunable_slo_class"
"tunables")
# tests for layer name
layer_name_testcases=("blank-layer-name"
"no-layer-name"
"no-layer-name-value"
"null-layer-name"
"numerical-layer-name"
"valid-layer-name")
# tests for layer level
layer_level_testcases=("char-layer-level"
"invalid-layer-level"
"no-layer-level"
"no-layer-level-value"
"null-layer-level"
"valid-layer-level")
# tests for presence
presence_testcases=("blank-presence"
"invalid-presence"
"no-presence"
"no-presence-value"
"null-presence"
"numerical-presence"
"valid-presence")
# tests for layer presence query datasource
layer_presence_query_datasource_testcases=("blank-layer-presence-query-datasource"
"invalid-layer-presence-query-datasource"
"no-layer-presence-query-datasource"
"no-layer-presence-query-datasource-value"
"null-layer-presence-query-datasource"
"numerical-layer-presence-query-datasource"
"valid-layer-presence-query-datasource")
# tests for layer presence query
layer_presence_query_testcases=("blank-layer-presence-query"
"invalid-layer-presence-query"
"no-layer-presence-query"
"no-layer-presence-query-value"
"null-layer-presence-query"
"numerical-layer-presence-query"
"valid-layer-presence-query")
# tests for layer presence query key
layer_presence_query_key_testcases=("blank-layer-presence-query-key"
"invalid-layer-presence-query-key"
"no-layer-presence-query-key"
"no-layer-presence-query-key-value"
"null-layer-presence-query-key"
"numerical-layer-presence-query-key"
"valid-layer-presence-query-key")
# tests for layer presence label name
layer_presence_label_name_testcases=("blank-layer-presence-label-name"
"invalid-layer-presence-label-name"
"no-layer-presence-label-name"
"no-layer-presence-label-name-value"
"null-layer-presence-label-name"
"numerical-layer-presence-label-name"
"valid-layer-presence-label-name")
# tests for layer presence label value
layer_presence_labelvalue_testcases=("blank-layer-presence-labelvalue"
"invalid-layer-presence-labelvalue"
"no-layer-presence-labelvalue"
"no-layer-presence-labelvalue-value"
"null-layer-presence-labelvalue"
"numerical-layer-presence-labelvalue"
"valid-layer-presence-labelvalue")
# tests for layer presence
layer_presence_testcases=("complete-layer-presence"
"empty-layer-presence"
"no-label-layer-presence"
"no-layer-presence"
"no-presence-layer-presence"
"no-query-layer-presence"
"only-label-layer-presence"
"only-query-layer-presence"
"valid-layer-presence")
# tests for tunable name
tunable_name_testcases=("blank-tunable-name"
"no-tunable-name-value"
"null-tunable-name"
"numerical-tunable-name"
"valid-tunable-name")
# tests for tunable value type
tunable_value_type_testcases=("blank-tunable-value-type"
"invalid-tunable-value-type"
"no-tunable-value-type"
"no-tunable-value-type-value"
"null-tunable-value-type"
"numerical-tunable-value-type"
"valid-tunable-value-type")
# tests for tunable upper bound
tunable_upper_bound_testcases=("blank-tunable-upper-bound"
"invalid-tunable-upper-bound"
"no-tunable-upper-bound"
"no-tunable-upper-bound-value"
"null-tunable-upper-bound"
"char-tunable-upper-bound"
"zero-tunable-upper-bound"
"valid-tunable-upper-bound")
# tests for tunable lower bound
tunable_lower_bound_testcases=("blank-tunable-lower-bound"
"invalid-tunable-lower-bound"
"no-tunable-lower-bound"
"no-tunable-lower-bound-value"
"null-tunable-lower-bound"
"char-tunable-lower-bound"
"zero-tunable-lower-bound"
"valid-tunable-lower-bound")
# tests for step
step_testcases=("invalid-step"
"no-step-value"
"null-step"
"char-step"
"zero-step"
"valid-step")
# tests for tunable query
tunable_query_testcases=("blank-tunable-query"
"invalid-tunable-query"
"no-tunable-query"
"no-tunable-query-value"
"null-tunable-query"
"numerical-tunable-query"
"valid-tunable-query")
# tests for tunable datasource name
tunable_datasource_name_testcases=("blank-tunable-datasource-name"
"invalid-tunable-datasource-name"
"no-tunable-datasource-name"
"no-tunable-datasource-name-value"
"null-tunable-datasource-name"
"numerical-tunable-datasource-name"
"valid-tunable-datasource-name")
# tests for tunable slo class
tunable_slo_class_testcases=("blank-tunable-slo-class"
"invalid-tunable-slo-class"
"empty-tunable-slo-class"
"no-tunable-slo-class"
"no-tunable-slo-class-value"
"null-tunable-slo-class"
"numerical-tunable-slo-class"
"valid-tunable-slo-class")
# tests for tunables
tunables_testcases=("interchanged-bound"
"no-tunables"
"no-tunables-queries"
"no-tunables-slo-class"
"valid-tunables")
# other test cases
autotuneconfig_other_testcases=("incomplete-autotuneconfig")
# Expected autotune object for layer name
declare -A layer_name_autotune_objects
layer_name_autotune_objects=([blank-layer-name]='true'
[no-layer-name]='false'
[no-layer-name-value]='false'
[null-layer-name]='false'
[numerical-layer-name]='false'
[valid-layer-name]='true')
# Expected log message for layer-name
declare -A layer_name_expected_log_msgs
layer_name_yaml_path="${yaml_path}/${autotune_config_tests[0]}"
layer_name_kubectl_error=': error validating data: ValidationError(AutotuneConfig): missing required field "layer_name" in com.recommender.v1.AutotuneConfig; if you choose to ignore these errors, turn validation off with --validate=false'
layer_name_expected_log_msgs=([blank-layer-name]=''${exception}' AutotuneConfig object name cannot be null or empty'
[no-layer-name]='error: error validating "'${layer_name_yaml_path}/no-layer-name.yaml'"'${layer_name_kubectl_error}''
[no-layer-name-value]='error: error validating "'${layer_name_yaml_path}/no-layer-name-value.yaml'"'${layer_name_kubectl_error}''
[null-layer-name]='error: error validating "'${layer_name_yaml_path}/null-layer-name.yaml'"'${layer_name_kubectl_error}''
[numerical-layer-name]='The AutotuneConfig "numerical-layer-name" is invalid: layer_name: Invalid value: "integer": layer_name in body must be of type string: "integer"'
[valid-layer-name]=''${autotune_config_obj_create_msg}' valid-layer-name')
# Expected autotune object for layer-level
declare -A layer_level_autotune_objects
layer_level_autotune_objects=([char-layer-level]='false'
[invalid-layer-level]='true'
[no-layer-level]='false'
[no-layer-level-value]='false'
[null-layer-level]='false'
[char-layer-level]='false'
[valid-layer-level]='true')
# Expected log message for layer-level
declare -A layer_level_expected_log_msgs
layer_level_yaml_path="${yaml_path}/${autotune_config_tests[1]}"
layer_level_kubectl_error=': error validating data: ValidationError(AutotuneConfig): missing required field "layer_level" in com.recommender.v1.AutotuneConfig; if you choose to ignore these errors, turn validation off with --validate=false'
layer_level_expected_log_msgs=([char-layer-level]='error: error validating "'${layer_level_yaml_path}/char-layer-level.yaml'": error validating data: ValidationError(AutotuneConfig.layer_level): invalid type for com.recommender.v1.AutotuneConfig.layer_level: got "string", expected "integer"; if you choose to ignore these errors, turn validation off with --validate=false'
[invalid-layer-level]=''${exception}' Layer level must be a non-negative integer'
[no-layer-level]='error: error validating "'${layer_level_yaml_path}/no-layer-level.yaml'"'${layer_level_kubectl_error}''
[no-layer-level-value]='error: error validating "'${layer_level_yaml_path}/no-layer-level-value.yaml'"'${layer_level_kubectl_error}''
[null-layer-level]='error: error validating "'${layer_level_yaml_path}/null-layer-level.yaml'"'${layer_level_kubectl_error}''
[valid-layer-level]=''${autotune_config_obj_create_msg}' valid-layer-level')
# Expected autotune object for presence
declare -A presence_autotune_objects
presence_autotune_objects=([blank-presence]='true'
[invalid-presence]='true'
[no-presence]='false'
[no-presence-value]='true'
[null-presence]='true'
[numerical-presence]='false'
[valid-presence]='true')
#Expected log message for presence
declare -A presence_expected_log_msgs
presence_yaml_path="${yaml_path}/${autotune_config_tests[2]}"
presence_exception='Layer presence missing! Must be indicated through a presence field, layerPresenceQuery or layerPresenceLabel'
presence_expected_log_msgs=([blank-presence]=''${exception}' '${presence_exception}''
[invalid-presence]=''${exception}' '${presence_exception}''
[no-presence]='error: error validating "'${presence_yaml_path}/no-presence.yaml'": error validating data: ValidationError(AutotuneConfig): missing required field "layerPresence" in com.recommender.v1.AutotuneConfig; if you choose to ignore these errors, turn validation off with --validate=false'
[no-presence-value]=''${exception}' '${presence_exception}''
[null-presence]=''${exception}' '${presence_exception}''
[numerical-presence]='The AutotuneConfig "numerical-presence" is invalid: layerPresence.presence: Invalid value: "integer": layerPresence.presence in body must be of type string: "integer"'
[valid-presence]=''${autotune_config_obj_create_msg}' valid-presence')
# Expected autotune object for layer preseence query
declare -A layer_presence_query_datasource_autotune_objects
layer_presence_query_datasource_autotune_objects=([blank-layer-presence-query-datasource]='true'
[invalid-layer-presence-query-datasource]='true'
[no-layer-presence-query-datasource]='false'
[no-layer-presence-query-datasource-value]='false'
[null-layer-presence-query-datasource]='false'
[numerical-layer-presence-query-datasource]='false'
[valid-layer-presence-query-datasource]='true')
#Expected log message for layer preseence query
declare -A layer_presence_query_datasource_expected_log_msgs
layer_presence_query_ds_yaml_path="${yaml_path}/${autotune_config_tests[3]}"
layer_presence_query_ds_kubectl_error=': error validating data: ValidationError(AutotuneConfig.layerPresence.query.datasource\[0\]): missing required field "name" in com.recommender.v1.AutotuneConfig.layerPresence.query.datasource; if you choose to ignore these errors, turn validation off with --validate=false'
layer_presence_query_datasource_expected_log_msgs=([blank-layer-presence-query-datasource]=''${exception}' '${presence_exception}''
[invalid-layer-presence-query-datasource]=''${exception}' '${presence_exception}''
[no-layer-presence-query-datasource]='error: error validating "'${layer_presence_query_ds_yaml_path}/no-layer-presence-query-datasource.yaml'": error validating data: ValidationError(AutotuneConfig.layerPresence.query.datasource): invalid type for com.recommender.v1.AutotuneConfig.layerPresence.query.datasource: got "map", expected "array"; if you choose to ignore these errors, turn validation off with --validate=false'
[no-layer-presence-query-datasource-value]='error: error validating "'${layer_presence_query_ds_yaml_path}/no-layer-presence-query-datasource-value.yaml'"'${layer_presence_query_ds_kubectl_error}''
[null-layer-presence-query-datasource]='error: error validating "'${layer_presence_query_ds_yaml_path}/null-layer-presence-query-datasource.yaml'"'${layer_presence_query_ds_kubectl_error}''
[numerical-layer-presence-query-datasource]='The AutotuneConfig "numerical-layer-presence-query-datasource" is invalid: layerPresence.query.datasource.name: Invalid value: "integer": layerPresence.query.datasource.name in body must be of type string: "integer"'
[valid-layer-presence-query-datasource]=''${autotune_config_obj_create_msg}' valid-layer-presence-query-datasource')
# Expected autotune object for layer presence query
declare -A layer_presence_query_autotune_objects
layer_presence_query_autotune_objects=([blank-layer-presence-query]='true'
[invalid-layer-presence-query]='true'
[no-layer-presence-query]='false'
[no-layer-presence-query-value]='false'
[null-layer-presence-query]='false'
[numerical-layer-presence-query]='false'
[valid-layer-presence-query]='true')
#Expected log message for layer presence query
declare -A layer_presence_query_expected_log_msgs
layer_presence_query_yaml_path="${yaml_path}/${autotune_config_tests[4]}"
layer_presence_query_kubectl_error=': error validating data: ValidationError(AutotuneConfig.layerPresence.query.datasource\[0\]): missing required field "query" in com.recommender.v1.AutotuneConfig.layerPresence.query.datasource; if you choose to ignore these errors, turn validation off with --validate=false'
layer_presence_query_expected_log_msgs=([blank-layer-presence-query]='com.autotune.analyzer.deployment.AutotuneDeployment - Could not get the applications for the layer blank-layer-presence-query'
[invalid-layer-presence-query]='validation from da'
[no-layer-presence-query]='error: error validating "'${layer_presence_query_yaml_path}/no-layer-presence-query.yaml'"'${layer_presence_query_kubectl_error}''
[no-layer-presence-query-value]='error: error validating "'${layer_presence_query_yaml_path}/no-layer-presence-query-value.yaml'"'${layer_presence_query_kubectl_error}''
[null-layer-presence-query]='error: error validating "'${layer_presence_query_yaml_path}/null-layer-presence-query.yaml'"'${layer_presence_query_kubectl_error}''
[numerical-layer-presence-query]='The AutotuneConfig "numerical-layer-presence-query" is invalid: layerPresence.query.datasource.query: Invalid value: "integer": layerPresence.query.datasource.query in body must be of type string: "integer"'
[valid-layer-presence-query]=''${autotune_config_obj_create_msg}' valid-layer-presence-query')
# Expected autotune object for layer presence query key
declare -A layer_presence_query_key_autotune_objects
layer_presence_query_key_autotune_objects=([blank-layer-presence-query-key]='true'
[invalid-layer-presence-query-key]='true'
[no-layer-presence-query-key]='false'
[no-layer-presence-query-key-value]='false'
[null-layer-presence-query-key]='false'
[numerical-layer-presence-query-key]='false'
[valid-layer-presence-query-key]='true')
# Expected autotune object for layer presence query key
declare -A layer_presence_query_key_expected_log_msgs
layer_presence_query_key_yaml_path="${yaml_path}/${autotune_config_tests[5]}"
layer_presence_query_key_kubectl_error=': error validating data: ValidationError(AutotuneConfig.layerPresence.query.datasource\[0\]): missing required field "key" in com.recommender.v1.AutotuneConfig.layerPresence.query.datasource; if you choose to ignore these errors, turn validation off with --validate=false'
layer_presence_query_key_expected_log_msgs=([blank-layer-presence-query-key]='validation from da'
[invalid-layer-presence-query-key]='validation from da'
[no-layer-presence-query-key]='error: error validating "'${layer_presence_query_key_yaml_path}/no-layer-presence-query-key.yaml'"'${layer_presence_query_key_kubectl_error}''
[no-layer-presence-query-key-value]='error: error validating "'${layer_presence_query_key_yaml_path}/no-layer-presence-query-key-value.yaml'"'${layer_presence_query_key_kubectl_error}''
[null-layer-presence-query-key]='error: error validating "'${layer_presence_query_key_yaml_path}/null-layer-presence-query-key.yaml'"'${layer_presence_query_key_kubectl_error}''
[numerical-layer-presence-query-key]='The AutotuneConfig "numerical-layer-presence-query-key" is invalid: layerPresence.query.datasource.key: Invalid value: "integer": layerPresence.query.datasource.key in body must be of type string: "integer"'
[valid-layer-presence-query-key]=''${autotune_config_obj_create_msg}' valid-layer-presence-query-key')
# Expected autotune object for layer presence label name
declare -A layer_presence_label_name_autotune_objects
layer_presence_label_name_autotune_objects=([blank-layer-presence-label-name]='true'
[invalid-layer-presence-label-name]='true'
[no-layer-presence-label-name]='false'
[no-layer-presence-label-name-value]='false'
[null-layer-presence-label-name]='false'
[numerical-layer-presence-label-name]='false'
[valid-layer-presence-label-name]='true')
# Expected log message for layer presence label name
declare -A layer_presence_label_name_expected_log_msgs
layer_presence_label_name_expected_log_msgs=([blank-layer-presence-label-name]='validation from da'
[invalid-layer-presence-label-name]='validation from da'
[no-layer-presence-label-name]='error: error validating "'${yaml_path}/${autotune_config_tests[6]}/no-layer-presence-label-name.yaml'": error validating data: ValidationError(AutotuneConfig.layerPresence.label): invalid type for com.recommender.v1.AutotuneConfig.layerPresence.label: got "map", expected "array"; if you choose to ignore these errors, turn validation off with --validate=false'
[no-layer-presence-label-name-value]='validation from crd'
[null-layer-presence-label-name]='validation from crd'
[numerical-layer-presence-label-name]='The AutotuneConfig "numerical-layer-presence-label-name" is invalid: layerPresence.label.name: Invalid value: "integer": layerPresence.label.name in body must be of type string: "integer"'
[valid-layer-presence-label-name]=''${autotune_config_obj_create_msg}' valid-layer-presence-label-name')
# Expected autotune object for layer-presence-labelvalue
declare -A layer_presence_labelvalue_autotune_objects
layer_presence_labelvalue_autotune_objects=([blank-layer-presence-labelvalue]='true'
[invalid-layer-presence-labelvalue]='true'
[no-layer-presence-labelvalue]='false'
[no-layer-presence-labelvalue-value]='false'
[null-layer-presence-labelvalue]='false'
[numerical-layer-presence-labelvalue]='false'
[valid-layer-presence-labelvalue]='true')
# Expected log message for layer-presence-labelvalue
declare -A layer_presence_labelvalue_expected_log_msgs
layer_presence_labelvalue_error=': layerPresence.label.value in body must be of type string:'
layer_presence_labelvalue_expected_log_msgs=([blank-layer-presence-labelvalue]='Validation from da'
[invalid-layer-presence-labelvalue]='validation from da'
[no-layer-presence-labelvalue]='validation from crd'
[no-layer-presence-labelvalue-value]='The AutotuneConfig "no-layer-presence-labelvalue-value" is invalid: layerPresence.label.value: Invalid value: "null"'${layer_presence_labelvalue_error}' "null"'
[null-layer-presence-labelvalue]='The AutotuneConfig "null-layer-presence-labelvalue" is invalid: layerPresence.label.value: Invalid value: "null"'${layer_presence_labelvalue_error}' "null"'
[numerical-layer-presence-labelvalue]='The AutotuneConfig "numerical-layer-presence-labelvalue" is invalid: layerPresence.label.value: Invalid value: "integer"'${layer_presence_labelvalue_error}' "integer"'
[valid-layer-presence-labelvalue]=''${autotune_config_obj_create_msg}' valid-layer-presence-labelvalue')
# Expected autotune object for layer presence
declare -A layer_presence_autotune_objects
layer_presence_autotune_objects=([complete-layer-presence]='true'
[empty-layer-presence]='false'
[no-label-layer-presence]='true'
[no-layer-presence]='false'
[no-presence-layer-presence]='true'
[no-query-layer-presence]='true'
[only-label-layer-presence]='true'
[only-query-layer-presence]='true'
[valid-layer-presence]='true')
# Expected log message for layer presence
declare -A layer_presence_expected_log_msgs
layer_presence_yaml_path="${yaml_path}/${autotune_config_tests[8]}"
layer_presence_kubectl_error=': error validating data: ValidationError(AutotuneConfig): missing required field "layerPresence" in com.recommender.v1.AutotuneConfig; if you choose to ignore these errors, turn validation off with --validate=false'
layer_presence_expected_log_msgs=([complete-layer-presence]=''${exception}' Both layerPresenceQuery and layerPresenceLabel cannot be set'
[empty-layer-presence]='error: error validating "'${layer_presence_yaml_path}/empty-layer-presence.yaml'"'${layer_presence_kubectl_error}''
[no-label-layer-presence]=''${autotune_config_obj_create_msg}' no-label-layer-presence'
[no-layer-presence]='error: error validating "'${layer_presence_yaml_path}/no-layer-presence.yaml'"'${layer_presence_kubectl_error}''
[no-presence-layer-presence]=''${exception}' Both layerPresenceQuery and layerPresenceLabel cannot be set'
[no-query-layer-presence]=''${autotune_config_obj_create_msg}' no-query-layer-presence'
[only-label-layer-presence]=''${autotune_config_obj_create_msg}' only-label-layer-presence'
[only-query-layer-presence]=''${autotune_config_obj_create_msg}' only-query-layer-presence'
[valid-layer-presence]=''${autotune_config_obj_create_msg}' valid-layer-presence')
# Expected autotune object for tunable-name
declare -A tunable_name_autotune_objects
tunable_name_autotune_objects=([blank-tunable-name]='true'
[no-tunable-name-value]='false'
[null-tunable-name]='false'
[numerical-tunable-name]='false'
[valid-tunable-name]='true')
# Expected log message for tunable-name
declare -A tunable_name_expected_log_msgs
tunable_name_yaml_path="${yaml_path}/${autotune_config_tests[9]}"
tunable_name_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "name" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_name_expected_log_msgs=([blank-tunable-name]=''${exception}' Tunable name cannot be empty'
[no-tunable-name-value]='error: error validating "'${tunable_name_yaml_path}/no-tunable-name-value.yaml'"'${tunable_name_kubectl_error}''
[null-tunable-name]='error: error validating "'${tunable_name_yaml_path}/null-tunable-name.yaml'"'${tunable_name_kubectl_error}''
[numerical-tunable-name]='The AutotuneConfig "numerical-tunable-name" is invalid: tunables.name: Invalid value: "integer": tunables.name in body must be of type string: "integer"'
[valid-tunable-name]=''${autotune_config_obj_create_msg}' valid-tunable-name')
# Expected autotune object for tunable-value-type
declare -A tunable_value_type_autotune_objects
tunable_value_type_autotune_objects=([blank-tunable-value-type]='true'
[invalid-tunable-value-type]='true'
[no-tunable-value-type]='false'
[no-tunable-value-type-value]='false'
[null-tunable-value-type]='false'
[numerical-tunable-value-type]='false'
[valid-tunable-value-type]='true')
# Expected log message for tunable-value-type
declare -A tunable_value_type_expected_log_msgs
tunable_value_yaml_path="${yaml_path}/${autotune_config_tests[10]}"
tunable_value_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "value_type" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_value_type_expected_log_msgs=([blank-tunable-value-type]='Validation from da'
[invalid-tunable-value-type]='validation from da'
[no-tunable-value-type]='error: error validating "'${tunable_value_yaml_path}/no-tunable-value-type.yaml'"'${tunable_value_kubectl_error}''
[no-tunable-value-type-value]='error: error validating "'${tunable_value_yaml_path}/no-tunable-value-type-value.yaml'": error validating data: \[ValidationError(AutotuneConfig.tunables\[0\]): missing required field "value_type" in com.recommender.v1.AutotuneConfig.tunables, ValidationError(AutotuneConfig): missing required field "layer_name" in com.recommender.v1.AutotuneConfig\]; if you choose to ignore these errors, turn validation off with --validate=false'
[null-tunable-value-type]='error: error validating "'${tunable_value_yaml_path}/null-tunable-value-type.yaml'"'${tunable_value_kubectl_error}''
[numerical-tunable-value-type]='The AutotuneConfig "numerical-tunable-value-type" is invalid: tunables.value_type: Invalid value: "integer": tunables.value_type in body must be of type string: "integer"'
[valid-tunable-value-type]=''${autotune_config_obj_create_msg}' valid-tunable-value-type')
# Expected autotune object for tunable upper bound
declare -A tunable_upper_bound_autotune_objects
tunable_upper_bound_autotune_objects=([blank-tunable-upper-bound]='false'
[invalid-tunable-upper-bound]='true'
[no-tunable-upper-bound]='false'
[no-tunable-upper-bound-value]='false'
[null-tunable-upper-bound]='false'
[char-tunable-upper-bound]='false'
[zero-tunable-upper-bound]='true'
[valid-tunable-upper-bound]='true')
# Expected log message for tunable-upper-bound
declare -A tunable_upper_bound_expected_log_msgs
tunable_upper_bound_yaml_path="${yaml_path}/${autotune_config_tests[11]}"
tunable_upper_bound_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "upper_bound" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
invalid_upper_bound_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\].upper_bound): invalid type for com.recommender.v1.AutotuneConfig.tunables.upper_bound: got "string", expected "number"; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_upper_bound_expected_log_msgs=([blank-tunable-upper-bound]='error: error validating "'${tunable_upper_bound_yaml_path}/blank-tunable-upper-bound.yaml'"'${invalid_upper_bound_error}''
[invalid-tunable-upper-bound]=''${invalid_bound_exception}''
[no-tunable-upper-bound]='error: error validating "'${tunable_upper_bound_yaml_path}/no-tunable-upper-bound.yaml'"'${tunable_upper_bound_kubectl_error}''
[no-tunable-upper-bound-value]='error: error validating "'${tunable_upper_bound_yaml_path}/no-tunable-upper-bound-value.yaml'"'${tunable_upper_bound_kubectl_error}''
[null-tunable-upper-bound]='error: error validating "'${tunable_upper_bound_yaml_path}/null-tunable-upper-bound.yaml'"'${tunable_upper_bound_kubectl_error}''
[char-tunable-upper-bound]='error: error validating "'${tunable_upper_bound_yaml_path}/char-tunable-upper-bound.yaml'"'${invalid_upper_bound_error}''
[zero-tunable-upper-bound]=''${invalid_bound_exception}''
[valid-tunable-upper-bound]=''${autotune_config_obj_create_msg}' valid-tunable-upper-bound')
# Expected autotune object for tunable lower bound
declare -A tunable_lower_bound_autotune_objects
tunable_lower_bound_autotune_objects=([blank-tunable-lower-bound]='false'
[invalid-tunable-lower-bound]='true'
[no-tunable-lower-bound]='false'
[no-tunable-lower-bound-value]='false'
[null-tunable-lower-bound]='false'
[char-tunable-lower-bound]='false'
[zero-tunable-lower-bound]='true'
[valid-tunable-lower-bound]='true')
# Expected log message for tunable-lower-bound
declare -A tunable_lower_bound_expected_log_msgs
tunable_lower_bound_yaml_path="${yaml_path}/${autotune_config_tests[12]}"
tunable_lower_bound_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "lower_bound" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
invalid_lower_bound_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\].lower_bound): invalid type for com.recommender.v1.AutotuneConfig.tunables.lower_bound: got "string", expected "number"; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_lower_bound_expected_log_msgs=([blank-tunable-lower-bound]='error: error validating "'${tunable_lower_bound_yaml_path}/blank-tunable-lower-bound.yaml'"'${invalid_lower_bound_error}''
[invalid-tunable-lower-bound]=''${invalid_bound_exception}''
[no-tunable-lower-bound]='error: error validating "'${tunable_lower_bound_yaml_path}/no-tunable-lower-bound.yaml'"'${tunable_lower_bound_kubectl_error}''
[no-tunable-lower-bound-value]='error: error validating "'${tunable_lower_bound_yaml_path}/no-tunable-lower-bound-value.yaml'"'${tunable_lower_bound_kubectl_error}''
[null-tunable-lower-bound]='error: error validating "'${tunable_lower_bound_yaml_path}/null-tunable-lower-bound.yaml'"'${tunable_lower_bound_kubectl_error}''
[char-tunable-lower-bound]='error: error validating "'${tunable_lower_bound_yaml_path}/char-tunable-lower-bound.yaml'"'${invalid_lower_bound_error}''
[zero-tunable-lower-bound]=''${autotune_config_obj_create_msg}' zero-tunable-lower-bound'
[valid-tunable-lower-bound]=''${autotune_config_obj_create_msg}' valid-tunable-lower-bound')
# Expected autotune object for step
declare -A step_autotune_objects
step_autotune_objects=([invalid-step]='true'
[no-step-value]='true'
[null-step]='true'
[char-step]='false'
[zero-step]='true'
[valid-step]='true')
# Expected log message for tunable-lower-bound
declare -A step_expected_log_msgs
step_yaml_path="${yaml_path}/${autotune_config_tests[13]}"
step_expected_log_msgs=([invalid-step]=''${invalid_bound_exception}''
[no-step-value]='validation from da'
[null-step]='validation from da'
[char-step]='error: error validating "'${step_yaml_path}/char-step.yaml'": error validating data: \[ValidationError(AutotuneConfig.tunables\[0\].step): invalid type for com.recommender.v1.AutotuneConfig.tunables.step: got "string", expected "number", ValidationError(AutotuneConfig.tunables\[1\].step): invalid type for com.recommender.v1.AutotuneConfig.tunables.step: got "string", expected "number"\]; if you choose to ignore these errors, turn validation off with --validate=false'
[zero-step]=''${exception}' Tunable step cannot be 0'
[valid-step]=''${autotune_config_obj_create_msg}' valid-step')
# Expected autotune object for tunable query
declare -A tunable_query_autotune_objects
tunable_query_autotune_objects=([blank-tunable-query]='true'
[invalid-tunable-query]='true'
[no-tunable-query]='false'
[no-tunable-query-value]='false'
[null-tunable-query]='false'
[numerical-tunable-query]='false'
[valid-tunable-query]='true')
# Expected log message for tunable query
declare -A tunable_query_expected_log_msgs
tunable_query_yaml_path="${yaml_path}/${autotune_config_tests[14]}"
tunable_query_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\].queries.datasource\[0\]): missing required field "query" in com.recommender.v1.AutotuneConfig.tunables.queries.datasource; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_query_expected_log_msgs=([blank-tunable-query]='validation from da'
[invalid-tunable-query]='validation from da'
[no-tunable-query]='error: error validating "'${tunable_query_yaml_path}/no-tunable-query.yaml'"'${tunable_query_kubectl_error}''
[no-tunable-query-value]='error: error validating "'${tunable_query_yaml_path}/no-tunable-query-value.yaml'"'${tunable_query_kubectl_error}''
[null-tunable-query]='error: error validating "'${tunable_query_yaml_path}/null-tunable-query.yaml'"'${tunable_query_kubectl_error}''
[numerical-tunable-query]='The AutotuneConfig "numerical-tunable-query" is invalid: tunables.queries.datasource.query: Invalid value: "integer": tunables.queries.datasource.query in body must be of type string: "integer"'
[valid-tunable-query]=''${autotune_config_obj_create_msg}' valid-tunable-query' )
# Expected autotune object for tunable datasource name
declare -A tunable_datasource_name_autotune_objects
tunable_datasource_name_autotune_objects=([blank-tunable-datasource-name]='true'
[invalid-tunable-datasource-name]='true'
[no-tunable-datasource-name]='false'
[no-tunable-datasource-name-value]='false'
[null-tunable-datasource-name]='false'
[numerical-tunable-datasource-name]='false'
[valid-tunable-datasource-name]='true')
# Expected log message for tunable datasource name
declare -A tunable_datasource_name_expected_log_msgs
tunable_datasource_name_yaml_path="${yaml_path}/${autotune_config_tests[15]}"
tunable_datasource_name_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\].queries.datasource\[0\]): missing required field "name" in com.recommender.v1.AutotuneConfig.tunables.queries.datasource; if you choose to ignore these errors, turn validation off with --validate=false'
tunable_datasource_name_expected_log_msgs=([blank-tunable-datasource-name]='validation form da'
[invalid-tunable-datasource-name]='error from da'
[no-tunable-datasource-name]='error: error validating "'${tunable_datasource_name_yaml_path}/no-tunable-datasource-name.yaml'": error validating data: ValidationError(AutotuneConfig.tunables\[0\].queries.datasource): invalid type for com.recommender.v1.AutotuneConfig.tunables.queries.datasource: got "map", expected "array"; if you choose to ignore these errors, turn validation off with --validate=false'
[no-tunable-datasource-name-value]='error: error validating "'${tunable_datasource_name_yaml_path}/no-tunable-datasource-name-value.yaml'"'${tunable_datasource_name_kubectl_error}''
[null-tunable-datasource-name]='error: error validating "'${tunable_datasource_name_yaml_path}/null-tunable-datasource-name.yaml'"'${tunable_datasource_name_kubectl_error}''
[numerical-tunable-datasource-name]='The AutotuneConfig "numerical-tunable-datasource-name" is invalid: tunables.queries.datasource.name: Invalid value: "integer": tunables.queries.datasource.name in body must be of type string: "integer"'
[valid-tunable-datasource-name]=''${autotune_config_obj_create_msg}' valid-tunable-datasource-name' )
# Expected autotune object for slo class
declare -A tunable_slo_class_autotune_objects
tunable_slo_class_autotune_objects=([blank-tunable-slo-class]='true'
[invalid-tunable-slo-class]='true'
[empty-tunable-slo-class]='false'
[no-slo-tunable-class]='false'
[no-tunable-slo-class-value]='false'
[null-tunable-slo-class]='false'
[numerical-tunable-slo-value]='false'
[valid-tunable-slo-class]='true')
# Expected log message for slo class
declare -A tunable_slo_class_expected_log_msgs
tunable_slo_class_yaml_path="${yaml_path}/${autotune_config_tests[16]}"
tunable_slo_class_kubectl_error=': error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "slo_class" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
validation_error='ValidationError(AutotuneConfig.tunables\[0\].slo_class): unknown object type "nil" in AutotuneConfig.tunables\[0\]'
tunable_slo_class_expected_log_msgs=([blank-tunable-slo-class]=''${exception}' Invalid slo_class for tunable memoryRequest'
[invalid-tunable-slo-class]=''${exception}' Invalid slo_class for tunable memoryRequest'
[empty-tunable-slo-class]='error: error validating "'${tunable_slo_class_yaml_path}/empty-tunable-slo-class.yaml'"'${tunable_slo_class_kubectl_error}''
[no-tunable-slo-class]='error: error validating "'${tunable_slo_class_yaml_path}/no-tunable-slo-class.yaml'"'${tunable_slo_class_kubectl_error}''
[no-tunable-slo-class-value]='error: error validating "'${tunable_slo_class_yaml_path}/no-tunable-slo-class-value.yaml'": error validating data: \['${validation_error}'.slo_class\[0\], '${validation_error}'.slo_class\[1\], '${validation_error}'.slo_class\[2\]\]; if you choose to ignore these errors, turn validation off with --validate=false'
[null-tunable-slo-class]='error: error validating "'${tunable_slo_class_yaml_path}/null-tunable-slo-class.yaml'": error validating data: '${validation_error}'.slo_class\[0\]; if you choose to ignore these errors, turn validation off with --validate=false'
[numerical-tunable-slo-class]='The AutotuneConfig "numerical-tunable-slo-class" is invalid: tunables.slo_class: Invalid value: "integer": tunables.slo_class in body must be of type string: "integer"'
[valid-tunable-slo-class]=''${autotune_config_obj_create_msg}' valid-tunable-slo-class')
# Expected autotune object for tunables
declare -A tunables_autotune_objects
tunables_autotune_objects=([interchanged-bound]='true'
[no-tunables]='false'
[no-tunables-queries]='true'
[no-tunables-slo-class]='false'
[valid-tunables]='true')
# Expected log message for tunables
declare -A tunables_expected_log_msgs
tunables_yaml_path="${yaml_path}/${autotune_config_tests[17]}"
tunables_expected_log_msgs=([interchanged-bound]=''${invalid_bound_exception}''
[no-tunables]='error: error validating "'${tunables_yaml_path}/no-tunables.yaml'": error validating data: ValidationError(AutotuneConfig): missing required field "tunables" in com.recommender.v1.AutotuneConfig; if you choose to ignore these errors, turn validation off with --validate=false'
[no-tunables-queries]=''${autotune_config_obj_create_msg}' no-tunables-queries'
[no-tunables-slo-class]='error: error validating "'${tunables_yaml_path}/no-tunables-slo-class.yaml'": error validating data: ValidationError(AutotuneConfig.tunables\[0\]): missing required field "slo_class" in com.recommender.v1.AutotuneConfig.tunables; if you choose to ignore these errors, turn validation off with --validate=false'
[valid-tunables]=''${autotune_config_obj_create_msg}' valid-tunables' )
# Expected autotune object for other test cases
declare -A autotuneconfig_other_autotune_objects
autotuneconfig_other_autotune_objects=([incomplete-autotuneconfig]='false')
# Expected log message for other test cases
declare -A autotuneconfig_other_expected_log_msgs
autotuneconfig_other_expected_log_msgs=([incomplete-autotuneconfig]='error: error validating "'${yaml_path}/autotuneconfig_other/incomplete-autotuneconfig.yaml'": error validating data: \[ValidationError(AutotuneConfig): missing required field "layer_name" in com.recommender.v1.AutotuneConfig, ValidationError(AutotuneConfig): missing required field "layer_level" in com.recommender.v1.AutotuneConfig, ValidationError(AutotuneConfig): missing required field "layerPresence" in com.recommender.v1.AutotuneConfig, ValidationError(AutotuneConfig): missing required field "tunables" in com.recommender.v1.AutotuneConfig\]; if you choose to ignore these errors, turn validation off with --validate=false')
|
function codeCommune() {
return '34172'
}
module.exports = {codeCommune}
|
import numpy as np
def multiply_two_matrices(x, y):
return np.matmul(x, y)
|
export class NPMErr extends Error {
public readonly type: NPMErrType;
constructor(type: NPMErrType, message: string) {
super(message);
this.type = type;
}
}
export enum NPMErrType {
Error,
Warning,
Info
}
|
<reponame>tkowalcz/rx-java-pantha-rhei
package pl.tkowalcz.twitter.mock;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import rx.Observable;
import rx.schedulers.Schedulers;
public class MockTwitterClient implements AutoCloseable {
public Observable<String> tweets() {
return Observable.<String>create(subscriber -> {
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/firehose.jsons"))) {
String line;
while ((line = reader.readLine()) != null) {
if (subscriber.isUnsubscribed()) {
return;
}
subscriber.onNext(line);
}
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}).subscribeOn(Schedulers.newThread());
}
@Override
public void close() {
}
}
|
#!/usr/bin/env bash
git archive --format zip --output taiga-collapse-us.zip master
|
<reponame>zheleznovux/beauty-saloon-server
import { Controller, Get, Param, HttpException, HttpStatus, Body, Post, Delete, Query, UseGuards, UseInterceptors, UploadedFile, Res, Patch } from '@nestjs/common';
import { ApiOperation, ApiTags, ApiOkResponse, ApiNotFoundResponse, ApiCreatedResponse, ApiQuery, ApiBearerAuth, ApiConsumes } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express'
import { StaffDto, UpdateStaffDto, CreateStaffDto } from 'src/shared/dto';
import { StaffService } from 'src/services';
import { Utils } from 'src/shared/utils';
import { JwtAuthGuard } from 'src/services/auth';
import { memoryStorage } from 'multer';
import { extname } from 'path';
@ApiTags('Staff')
@Controller('staff')
export class StaffController {
constructor(private readonly staffService: StaffService) { }
@Get()
@ApiQuery({ name: 'search', description: 'Фильтрует клиента по ФИО или номер телефона', required: false })
@ApiOperation({ summary: 'Возвращает список сотрудников' })
@ApiOkResponse({ type: [StaffDto] })
getStaff(@Query('search') search: string): StaffDto[] {
return this.staffService
.getAll()
.map(staff => new StaffDto(staff))
.filter(staff => {
const findByName = Utils.compare(staff.fullName, search);
return findByName;
});
}
@Get(':id')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Возвращает сотрудника по id' })
@ApiOkResponse({ type: StaffDto })
@ApiNotFoundResponse({ description: 'Сотрудник не найден' })
getStaffById(@Param('id') id: number): StaffDto {
const staff = this.staffService.get(+id);
if (!staff) {
throw new HttpException('Сотрудник не найден', HttpStatus.NOT_FOUND);
}
return new StaffDto(staff);
}
@Post()
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@UseInterceptors(FileInterceptor('photo', {
storage: memoryStorage(),
fileFilter: (req, file, cb) => {
if (file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
cb(null, true);
} else {
cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
}
}
}))
@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: 'Создаёт нового сотрудника' })
@ApiCreatedResponse({ description: 'Сотрудник успешно создан', type: StaffDto })
async createStaff(@Body() createStaffDto: CreateStaffDto, @UploadedFile() photo): Promise<StaffDto> {
let photoUrl = '';
try {
photoUrl = await this.staffService.uploadPhoto(photo);
} finally {
const createdstaff = this.staffService.create({
...createStaffDto,
photo: photoUrl
});
return new StaffDto(createdstaff);
}
}
@Patch(':id')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@UseInterceptors(FileInterceptor('photo', {
storage: memoryStorage(),
fileFilter: (req, file, cb) => {
if (file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
cb(null, true);
} else {
cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
}
}
}))
@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: 'Редактирует данные сотрудника' })
@ApiNotFoundResponse({ description: 'Сотрудник не найден' })
@ApiCreatedResponse({ description: 'Данные сотрудника отредактированы', type: StaffDto })
async updatetaff(
@Param('id') id: number,
@Body() updateStaffDto: UpdateStaffDto,
@UploadedFile() photo
): Promise<StaffDto> {
const staff = this.staffService.get(+id);
if (!staff) {
throw new HttpException('Сотрудник не найден', HttpStatus.NOT_FOUND);
}
let photoUrl = '';
try {
photoUrl = await this.staffService.uploadPhoto(photo);
} finally {
this.staffService.update({
...updateStaffDto,
id,
photo: photoUrl
});
return new StaffDto(this.staffService.get(+id));
}
}
@Get('photo/:fileId')
async serveAvatar(@Param('fileId') fileId, @Res() res): Promise<any> {
res.sendFile(fileId, { root: 'public' });
}
@Delete(':id')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Удаляет сотрудника' })
@ApiOkResponse({ description: 'Сотрудник успешно удалён' })
@ApiNotFoundResponse({ description: 'Сотрудник не найден' })
deleteStaff(@Param('id') id: number) {
const staff = this.staffService.get(+id);
if (staff) {
this.staffService.delete(+id);
return;
}
throw new HttpException('Сотрудник не найден', HttpStatus.NOT_FOUND);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.