code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
(function() {
'use strict';
angular
.module('application')
.directive('navbar', function($log, Github) {
return {
restrict: 'E',
templateUrl: 'components/navbar/navbar.html',
scope: {
repo: '='
},
controller: function($scope) {
$scope.repo.starsCount = '- -';
$scope.repo.forksCount = '- -';
Github.getRepo($scope.repo.name)
.success(function(data) {
$scope.repo.url = data.html_url;
$scope.repo.starsCount = data.stargazers_count;
$scope.repo.forksCount = data.forks_count;
})
.error(function(data) {
$log.warn('GitHub: ' + data.message);
});
}
};
});
})();
| shafaiatul/ginger | src/app/components/navbar/navbar.directive.js | JavaScript | mit | 782 |
import Login from './views/Login.vue'
import Register from './views/register3.vue'
import scale from './views/scale.vue'
import NotFound from './views/404.vue'
import Home from './views/Home.vue'
import barChart from './views/systemSetting/barChart.vue'
import Table from './views/systemSetting/Table.vue'
import Form from './views/systemSetting/Form.vue'
import passset from './views/systemSetting/passset.vue'
import dataDic from './views/systemSetting/dataDic.vue'
import support from './views/systemSetting/support.vue'
import helpdoc from './views/systemSetting/helpDoc.vue'
import carEquip from './views/basicInfo/carEquip.vue'
import shipEquip from './views/basicInfo/shipEquip.vue'
import harbourEquip from './views/basicInfo/harbourEquip.vue'
import Page6 from './views/statisticalAnalysis/Page6.vue'
import RoadGoods from './views/statisticalAnalysis/RoadGoods.vue'
import Index from './views/index/Index.vue'
import main from './views/Main.vue'
import busChart from './components/busChart.vue'
import taxiChart from './components/taxiChart.vue'
import allTypChart from './components/allTypChart.vue'
import engTypChgChart from './components/engTypChgChart.vue'
import traTypPreChgChart from './components/traTypPreChgChart.vue'
import relTimDatChart from './components/relTimDatChart.vue'
import OceanFreight from './views/statisticalAnalysis/OceanFreight.vue'
import TrafficEnergy from './views/statisticalAnalysis/TrafficEnergy.vue'
import CityEnergy from './views/statisticalAnalysis/CityEnergy.vue'
import analyzeReport from './components/analyzeReport.vue'
//import TotalEnergy from './views/statisticalAnalysis/TotalEnergy.vue'
import DataInMap from './views/datadetection/DataInMap.vue'
import GuestCar from './views/datadetection/GuestCar.vue'//数据监测,客运车辆
import goodsCar from './views/datadetection/GoodsCar.vue'//数据监测,货运车辆
import taxi from './views/datadetection/Taxi.vue'//数据监测,出租车
import bus from './views/datadetection/Bus.vue'//数据监测,公交车
import riverShip from './views/datadetection/RiverShip.vue'//数据监测,内河船舶
import rivTraChart from './components/rivTraChart.vue'
import OceanPgerTrans from './views/statisticalAnalysis/OceanPgerTrans.vue'
import PortProduction from './views/statisticalAnalysis/PortProduction.vue'
import EnergyStruct from './views/statisticalAnalysis/EnergyStruct.vue'
let routes = [
{
path: '/login',
component: Login,
name: '',
hidden: true
},
{
path: '/register',
component: Register,
name: '',
hidden: true
},{
path: '/scale',
component: scale,
name: '',
hidden: true
},
{
path: '/404',
component: NotFound,
name: '',
hidden: true
},
{
path: '/',
hidden: true,
redirect: { path: '/index' }
},
{
path: '/index.html',
hidden: true,
redirect: { path: '/index' }
},
{
path: '/enger/login',
hidden: true,
redirect: { path: '/login' }
},
{
path: '/enger/index.html',
hidden: true,
redirect: { path: '/index' }
},
//{ path: '/main', component: Main },
{
path: '/',
component: Home,
name: '',
iconCls: 'fa fa-home',
leaf: true,//只有一个节点
children: [
{ path: '/index', component: Index, name: '首页' }
]
},
{
path: '/',
component: Home,
name: '系统设置',
iconCls: 'fa fa-cogs',
children: [
{ path: '/userSetting', pri:['R_ADMIN'],component: Table, name: '用户管理' },
{ path: '/passSetting', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: passset, name: '密码修改' },
{ path: '/helpDoc', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: helpdoc, name: '帮助文档' },
{ path: '/dictSetting',pri:['R_ADMIN'], component: dataDic, name: '数据字典' },
{ path: '/support', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: support, name: '技术支持' }
]
},
{
path: '/',
component: Home,
name: '统计分析',
iconCls: 'fa fa-bar-chart-o',
children: [
{ path: '/roadPassengerTrans', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: barChart, name: '道路客运' },
{ path: '/roadGoodsTrans', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: RoadGoods, name: '道路货运' },
{ path: '/busTrans', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: busChart, name: '公交客运' },
{ path: '/taxiTrans', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: taxiChart, name: '出租车运输' },
{ path: '/riverTrans', pri:['R_ADMIN','R_TRA','R_WAT','R_ENT'],component: rivTraChart, name: '内河运输' },
{ path: '/oceanGoodsTran', pri:['R_ADMIN','R_TRA','R_WAT','R_ENT'],component: OceanFreight, name: '海洋货运' },
{ path: '/oceanPassTran', pri:['R_ADMIN','R_TRA','R_WAT','R_ENT'],component: OceanPgerTrans, name: '海洋客运' },
{ path: '/portProduce', pri:['R_ADMIN','R_TRA','R_WAT','R_ENT'],component: PortProduction, name: '港口生产' },
{ path: '/traTypPerYear', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: traTypPreChgChart, name: '能耗变化趋势' },
{ path: '/perDisEng', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: allTypChart, name: '单位运距能耗指标' },
{ path: '/cityTranTypEnger', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: CityEnergy, name: '地市能耗构成图' },
{ path: '/traCitTypeEng', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: TrafficEnergy, name: '交通方式能耗构成图' },
{ path: '/engTypYear', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: engTypChgChart, name: '年度数据对比' },
{ path: '/reportAll', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: analyzeReport, name: '分析报告' },
]
},
{
path: '/',
component: Home,
name: '数据监测',
iconCls: 'fa fa-eye',
children: [
//{ path: '/relTimDatChart', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: relTimDatChart, name: '数据展示' },
{ path: '/rtRoadPass', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: GuestCar, name: '道路客运' },
{ path: '/rtRoadGoods', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: goodsCar, name: '道路货运' },
{ path: '/rtTaxi', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: taxi, name: '出租车运输' },
{ path: '/rtBus', pri:['R_ADMIN','R_TRA','R_LAN','R_ENT'],component: bus, name: '公交客运' },
{ path: '/rtRiver', pri:['R_ADMIN','R_TRA','R_WAT','R_ENT'],component: riverShip, name: '内河运输' },
{ path: '/DataInMap', pri:['R_ADMIN','R_TRA','R_LAN','R_WAT','R_ENT'],component: DataInMap, name: '专题图展示'}
]
},
{
path: '*',
hidden: true,
redirect: { path: '/404' }
}
];
export default routes; | xingfeihappy/TrafficPerformance | src/routes.js | JavaScript | mit | 7,377 |
/**
* Created by ezgoing on 14/9/2014.
*/
"use strict";
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
var cropbox = function(options, el){
var el = el || $(options.imageBox),
obj =
{
state : {},
ratio : 1,
options : options,
imageBox : el,
thumbBox : el.find(options.thumbBox),
spinner : el.find(options.spinner),
image : new Image(),
getDataURL: function ()
{
var width = this.thumbBox.width(),
height = this.thumbBox.height(),
canvas = document.createElement("canvas"),
dim = el.css('background-position').split(' '),
size = el.css('background-size').split(' '),
dx = parseInt(dim[0]) - el.width()/2 + width/2,
dy = parseInt(dim[1]) - el.height()/2 + height/2,
dw = parseInt(size[0]),
dh = parseInt(size[1]),
sh = parseInt(this.image.height),
sw = parseInt(this.image.width);
if(this.image.width!=0){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
var imageData = canvas.toDataURL('image/png');
}else{
var imageData = '';
}
return imageData;
},
getBlob: function()
{
var imageData = this.getDataURL();
var b64 = imageData.replace('data:image/png;base64,','');
var binary = atob(b64);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
},
zoomIn: function ()
{
this.ratio*=1.1;
setBackground();
if(options.func!=null&&options.func!=''){
eval(options.func);
}
},
zoomOut: function ()
{
this.ratio*=0.9;
setBackground();
if(options.func!=null&&options.func!=''){
eval(options.func);
}
}
},
setBackground = function()
{
var w = parseInt(obj.image.width)*obj.ratio;
var h = parseInt(obj.image.height)*obj.ratio;
var pw = (el.width() - w) / 2;
var ph = (el.height() - h) / 2;
/*
'background-size': w/3.18 +'px ' + h/3.18 + 'px',
'background-position': pw/1.75 + 'px ' + ph/1.75 + 'px',
*/
el.css({
'background-image': 'url(' + obj.image.src + ')',
'background-size': w +'px ' + h + 'px',
'background-position': pw + 'px ' + ph + 'px',
'background-repeat': 'no-repeat'});
},
imgMouseDown = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = true;
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
},
imgMouseMove = function(e)
{
e.stopImmediatePropagation();
if (obj.state.dragable)
{
var x = e.clientX - obj.state.mouseX;
var y = e.clientY - obj.state.mouseY;
var bg = el.css('background-position').split(' ');
var bgX = x + parseInt(bg[0]);
var bgY = y + parseInt(bg[1]);
el.css('background-position', bgX +'px ' + bgY + 'px');
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
}
},
imgMouseUp = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = false;
if(options.func!=null&&options.func!=''){
eval(options.func);
}
},
zoomImage = function(e)
{
e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio*=1.1 : obj.ratio*=0.9;
setBackground();
if(options.func!=null&&options.func!=''){
eval(options.func);
}
}
obj.spinner.show();
obj.image.onload = function() {
obj.spinner.hide();
setBackground();
el.bind('mousedown', imgMouseDown);
el.bind('mousemove', imgMouseMove);
$(window).bind('mouseup', imgMouseUp);
el.bind('mousewheel DOMMouseScroll', zoomImage);
if(options.func!=null&&options.func!=''){
eval(options.func);
}
};
obj.image.src = options.imgSrc;
el.on('remove', function(){$(window).unbind('mouseup', imgMouseUp)});
return obj;
};
jQuery.fn.cropbox = function(options){
return new cropbox(options, this);
};
}));
| xygdev/XYG_QBORD | WebRoot/plugin/js/cropbox.js | JavaScript | mit | 5,998 |
const elem = document.getElementById('renderer');
const ctx = elem.getContext('2d');
ctx.fillStyle = '#000';
ctx.lineWidth = 1.5;
let clicks = 1;
let branches = 1;
const end = 7;
const degToRad = Math.PI / 180.0;
function drawLine(x1, y1, x2, y2) {
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
function drawBranch(x1, y1, angle, d, length) {
if (d !== 0) {
const l = d !== 1 ? 10.0 : length;
const ugh = clicks / 10 - (branches - d);
const x2 = x1 + (Math.cos(angle * degToRad) * ugh * l * 1.5);
const y2 = y1 + (Math.sin(angle * degToRad) * ugh * l * 1.5);
drawLine(x1, y1, x2, y2);
drawBranch(x2, y2, angle - 40, d - 1, length);
drawBranch(x2, y2, angle + 20, d - 1, length);
drawBranch(x2, y2, angle - 10, d - 1, length);
}
}
const drawTree = (depth, length) => {
ctx.clearRect(0, 0, elem.width, elem.height);
ctx.beginPath();
drawBranch(300, 500, -90, depth, length);
ctx.closePath();
ctx.stroke();
};
elem.addEventListener('click', () => {
clicks++;
if (clicks % 10 === 0) branches++;
if (!(branches >= end)) {
drawTree(branches, clicks % 10);
}
});
| Petroochio/forrest-clicker | src/app.js | JavaScript | mit | 1,120 |
import { getAndRemoveConfig } from '../utils';
import { isAbsolutePath } from '../../router/util';
export const linkCompiler = ({
renderer,
router,
linkTarget,
linkRel,
compilerClass,
}) =>
(renderer.link = (href, title = '', text) => {
let attrs = [];
const { str, config } = getAndRemoveConfig(title);
linkTarget = config.target || linkTarget;
linkRel =
linkTarget === '_blank'
? compilerClass.config.externalLinkRel || 'noopener'
: '';
title = str;
if (
!isAbsolutePath(href) &&
!compilerClass._matchNotCompileLink(href) &&
!config.ignore
) {
if (href === compilerClass.config.homepage) {
href = 'README';
}
href = router.toURL(href, null, router.getCurrentPath());
} else {
if (!isAbsolutePath(href) && href.startsWith('./')) {
href =
document.URL.replace(/\/(?!.*\/).*/, '/').replace('#/./', '') + href;
}
attrs.push(href.indexOf('mailto:') === 0 ? '' : `target="${linkTarget}"`);
attrs.push(
href.indexOf('mailto:') === 0
? ''
: linkRel !== ''
? ` rel="${linkRel}"`
: ''
);
}
// special case to check crossorigin urls
if (
config.crossorgin &&
linkTarget === '_self' &&
compilerClass.config.routerMode === 'history'
) {
if (compilerClass.config.crossOriginLinks.indexOf(href) === -1) {
compilerClass.config.crossOriginLinks.push(href);
}
}
if (config.disabled) {
attrs.push('disabled');
href = 'javascript:void(0)';
}
if (config.class) {
attrs.push(`class="${config.class}"`);
}
if (config.id) {
attrs.push(`id="${config.id}"`);
}
if (title) {
attrs.push(`title="${title}"`);
}
return `<a href="${href}" ${attrs.join(' ')}>${text}</a>`;
});
| nsina/docsify | src/core/render/compiler/link.js | JavaScript | mit | 1,888 |
(function() {
'use strict';
angular
.module('blocks.logger')
.factory('logger', logger);
logger.$inject = ['$log', 'toastr', 'moment'];
function logger($log, toastr, moment) {
var service = {
showToasts: true,
error : error,
info : info,
success : success,
warning : warning,
// straight to console; bypass toastr
log : $log.log
};
return service;
/////////////////////
function error(message, data, title) {
toastr.error(message, title);
$log.error('Error: ' + message, data);
}
function info(message, data, title) {
toastr.info(message, title);
$log.info('Info: ' + message, data);
}
function success(message, data, title) {
toastr.success(message, title);
$log.info('Success: ' + message, data);
}
function warning(message, data, title) {
toastr.warning(message, title);
$log.warn('Warning: ' + message, data);
}
}
}());
| geobourazanas/angularjs-start-smart | src/client/app/blocks/logger/logger.js | JavaScript | mit | 1,155 |
version https://git-lfs.github.com/spec/v1
oid sha256:ffd0407af5207dbb71d69a11c57df7969ebd72d98028bcbb0392d7f505c8813d
size 6762
| yogeshsaroya/new-cdnjs | ajax/libs/openlayers/2.11/lib/OpenLayers/Format/Filter/v1.min.js | JavaScript | mit | 129 |
'use scrict'
var path = require('path')
var config = require('./config.json')
module.exports = function(grunt) {
grunt.initConfig({
testfairy: {
android: {
options : {
platform: "android",
api_key: config["api_key"],
file: './test.apk',
notify: 'on',
groups: 'onlyme'
}
},
ios: {
options : {
platform: "ios",
api_key: config["api_key"],
file: './test.ipa'
}
}
}
})
grunt.loadTasks('tasks')
grunt.registerTask('default', 'testfairy');
}
| Urucas/grunt-testfairy | Gruntfile.js | JavaScript | mit | 590 |
export const DATA_TABS = [
{
label: 'Datasets',
value: 'datasets',
route: '/admin/data/datasets',
params: {},
},
{
label: 'Widgets',
value: 'widgets',
route: '/admin/data/widgets',
params: {},
},
{
label: 'Layers',
value: 'layers',
route: '/admin/data/layers',
params: {},
},
{
label: 'Explore',
value: 'explore',
route: '/admin/data/explore',
params: {},
},
];
export default { DATA_TABS };
| resource-watch/resource-watch | layout/admin/data/constants.js | JavaScript | mit | 473 |
// Many utils inlined from Underscore.js
// 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Objects
// -------
export function _assign(target, extensions, undefinedOnly) {
extensions.forEach(function(extension) {
if (!extension) {
return;
}
var keys = Object.keys(extension);
var key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (!undefinedOnly || target[key] === void 0) {
target[key] = extension[key];
}
}
});
return target;
}
export var assign = Object.assign || function(obj) {
return _assign(obj, slice.call(arguments, 1));
};
export function defaults(obj) {
return _assign(obj, slice.call(arguments, 1), true);
}
export function extend(target) {
var extensions = slice.call(arguments, 1);
extensions.forEach(function(extension) {
for (var key in extension) {
target[key] = extension[key];
}
});
return target;
}
export function objectEach(obj, fn) {
if (!obj) {
return;
}
var keys = Object.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
fn(obj[keys[i]], keys[i], obj);
}
}
// Arrays
// ------
var slice = Array.prototype.slice;
export function difference(a, b) {
return a.filter(function(value) { return b.indexOf(value) < 0; });
}
export function includes(arr, item) {
return arr.indexOf(item) >= 0;
}
export function toArray(arr) {
return slice.call(arr);
}
// Functions
// ---------
export function curry(fn) {
var values = slice.call(arguments, 1);
return function() {
var args = slice.call(arguments);
return fn.apply(this, values.concat(args));
};
}
// Checks
// ------
export function isBoolean(obj) {
return obj === true || obj === false;
}
export function isObject(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
}
export function isNumber(obj) {
return toString.call(obj) === '[object Number]';
}
export function isString(obj) {
return toString.call(obj) === '[object String]';
}
export function isUndefined(obj) {
return obj === void 0;
}
export var isFunction = function(obj) {
return toString.call(obj) === '[object Function]';
};
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
export function inherits(Child, Parent) {
Child.prototype = Object.create(Parent.prototype, {
constructor: {
value: Child,
enumerable: false,
writeable: true,
configurable: true
}
});
if (Object.setPrototypeOf) {
Object.setPrototypeOf(Child, Parent);
}
else {
Child.__proto__ = Parent; //eslint-disable-line no-proto
// __proto__ isn't supported in IE,
// use one-time copy of static properties to approximate
defaults(Child, Parent);
}
}
var utils = {
assign: assign,
defaults: defaults,
extend: extend,
objectEach: objectEach,
difference: difference,
includes: includes,
toArray: toArray,
curry: curry,
isBoolean: isBoolean,
isObject: isObject,
isNumber: isNumber,
isString: isString,
isUndefined: isUndefined,
isFunction: isFunction,
inherits: inherits
};
export default utils;
| CSNW/d3.compose | src/utils.js | JavaScript | mit | 3,264 |
export default (metricsHandler, errorHandler) => request => {
const startTime = Date.now();
const callback = request.callback;
request.callback = (error, response) => {
try {
metricsHandler({
duration: Date.now() - startTime,
error,
response,
request,
});
} catch (err) {
errorHandler(err);
}
callback.call(request, error, response);
};
return request;
};
| mefellows/express-template | src/api/superagent-timing/index.js | JavaScript | mit | 435 |
import assert from 'power-assert'
import Vue from 'vue'
import { trigger } from '../../src/util'
describe('github issues', () => {
let el, vm
beforeEach(() => {
el = document.createElement('div')
})
describe('#195', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="text" v-model="value" number>
<input type="text" v-model="value" number v-validate:value="['required']">
</form>
</validator>
`
vm = new Vue({ el: el, data: { value: 0 } })
vm.$nextTick(done)
})
it('should be validated', (done) => {
let field1 = el.getElementsByTagName('input')[0]
let field2 = el.getElementsByTagName('input')[1]
assert(field1.value === '0')
assert(field2.value === '0')
done()
})
})
describe('#208', () => {
describe('radio', () => {
beforeEach((done) => {
el.innerHTML = `
'<validator name="validator1">
<form novalidate>
<h1>Survey</h1>
<fieldset>
<legend>Which do you like fruit ?</legend>
<input id="apple" type="radio" name="fruit" initial="off" value="apple" v-validate:fruits="{
required: true
}">
<label for="apple">Apple</label>
<input id="orange" type="radio" name="fruit" value="orange" initial="off" v-validate:fruits>
<label for="orange">Orage</label>
<input id="grape" type="radio" name="fruit" value="grape" initial="off" v-validate:fruits>
<label for="grape">Grape</label>
<input id="banana" type="radio" name="fruit" value="banana" initial="off" v-validate:fruits>
<label for="banana">Banana</label>
<p v-if="$validator1.fruits.required">required fields</p>
</fieldset>
</form>
</validator>
`
vm = new Vue({ el: el })
vm.$nextTick(done)
})
it('should not validated', (done) => {
assert(vm.$validator1.fruits.valid === true)
assert(vm.$validator1.fruits.invalid === false)
assert(vm.$validator1.fruits.required === false)
assert(vm.$validator1.valid === true)
assert(vm.$validator1.invalid === false)
done()
})
})
describe('checkbox', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="checkbox" initial="off" value="foo" v-validate:field1="{ required: true, minlength: 1 }">
<input type="checkbox" initial="off" value="bar" v-validate:field1="{ required: true, minlength: 1 }">
</form>
</validator>
`
vm = new Vue({
el: el
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === false)
assert(vm.$validator1.field1.dirty === false)
done()
})
})
describe('select', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<select initial="off" v-validate:lang="{ required: true }">
<option value="en">english</option>
<option value="ja">japanese</option>
<option value="zh">chinese</option>
</select>
</form>
</validator>
`
vm = new Vue({ el: el })
vm.$nextTick(done)
})
it('should be validated', (done) => {
assert(vm.$validator1.lang.required === false)
assert(vm.$validator1.lang.valid === true)
assert(vm.$validator1.lang.touched === false)
assert(vm.$validator1.lang.dirty === false)
assert(vm.$validator1.lang.modified === false)
assert(vm.$validator1.valid === true)
assert(vm.$validator1.touched === false)
assert(vm.$validator1.dirty === false)
assert(vm.$validator1.modified === false)
done()
})
})
})
describe('#214', () => {
describe('text v-model', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="text" v-model="msg" initial="off" v-validate:field1="{ required: true, minlength: 10 }">
</form>
</validator>
`
vm = new Vue({
el: el,
data: { msg: 'hello' }
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
let field = el.getElementsByTagName('input')[0]
// default
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === false)
assert(vm.$validator1.field1.modified === false)
assert(vm.$validator1.field1.dirty === false)
assert(field.value === vm.msg)
// modify vm property
vm.msg = 'helloworld!!'
setTimeout(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === false)
assert(vm.$validator1.field1.modified === true)
assert(vm.$validator1.field1.dirty === true)
assert(field.value === vm.msg)
field.value = 'foo'
trigger(field, 'input')
trigger(field, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === true)
assert(vm.$validator1.field1.valid === false)
assert(vm.$validator1.field1.touched === true)
assert(vm.$validator1.field1.modified === true)
assert(vm.$validator1.field1.dirty === true)
done()
})
}, 10)
})
})
describe('checkbox v-model', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="checkbox" v-model="checkedNames" initial="off" value="foo" v-validate:field1="{ required: true, minlength: 2 }">
<input type="checkbox" v-model="checkedNames" initial="off" value="bar" v-validate:field1>
<input type="checkbox" v-model="checkedNames" initial="off" value="buz" v-validate:field1>
</form>
</validator>
`
vm = new Vue({
el: el,
data: { checkedNames: [] }
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
let foo = el.getElementsByTagName('input')[0]
let bar = el.getElementsByTagName('input')[1]
// default
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === false)
assert(vm.$validator1.field1.dirty === false)
assert(vm.$validator1.field1.modified === false)
// checked foo
foo.checked = true
trigger(foo, 'change')
trigger(foo, 'click')
trigger(foo, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === true)
assert(vm.$validator1.field1.valid === false)
assert(vm.$validator1.field1.touched === true)
assert(vm.$validator1.field1.dirty === true)
assert(vm.$validator1.field1.modified === true)
assert(vm.checkedNames.sort().toString() === ['foo'].sort().toString())
// checked bar
bar.checked = true
trigger(bar, 'change')
trigger(bar, 'click')
trigger(bar, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.minlength === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === true)
assert(vm.$validator1.field1.dirty === true)
assert(vm.$validator1.field1.modified === true)
assert(vm.checkedNames.sort().toString() === ['foo', 'bar'].sort().toString())
done()
})
})
})
})
describe('radio v-model', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="radio" v-model="picked" name="r1" value="foo" initial="off" v-validate:field1="{ required: true }">
<input type="radio" v-model="picked" name="r1" value="bar" initial="off" v-validate:field1>
</form>
</validator>
`
vm = new Vue({
el: el,
data: { picked: 'foo' }
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
let foo = el.getElementsByTagName('input')[0]
let bar = el.getElementsByTagName('input')[1]
// default
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === false)
assert(vm.$validator1.field1.dirty === false)
assert(vm.$validator1.field1.modified === false)
assert(vm.$validator1.valid === true)
assert(vm.$validator1.touched === false)
assert(vm.$validator1.dirty === false)
assert(vm.$validator1.modified === false)
// change bar radio
bar.checked = true
trigger(bar, 'change')
trigger(bar, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === true)
assert(vm.$validator1.field1.dirty === true)
assert(vm.$validator1.field1.modified === true)
assert(vm.$validator1.valid === true)
assert(vm.$validator1.touched === true)
assert(vm.$validator1.dirty === true)
assert(vm.$validator1.modified === true)
assert(vm.picked === 'bar')
// back to foo radio
foo.checked = true
trigger(foo, 'change')
trigger(foo, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.field1.required === false)
assert(vm.$validator1.field1.valid === true)
assert(vm.$validator1.field1.touched === true)
assert(vm.$validator1.field1.dirty === true)
assert(vm.$validator1.field1.modified === false)
assert(vm.$validator1.valid === true)
assert(vm.$validator1.touched === true)
assert(vm.$validator1.dirty === true)
assert(vm.$validator1.modified === false)
assert(vm.picked === 'foo')
done()
})
})
})
})
describe('select v-model', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<select v-model="lang" initial="off" v-validate:lang="{ required: true }">
<option value="en">english</option>
<option selected value="ja">japanese</option>
<option value="zh">chinese</option>
</select>
</form>
</validator>
`
vm = new Vue({
el: el,
data: { lang: 'ja' }
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
let select = el.getElementsByTagName('select')[0]
let en = el.getElementsByTagName('option')[0]
let zh = el.getElementsByTagName('option')[2]
// default
assert(vm.$validator1.lang.required === false)
assert(vm.$validator1.lang.valid === true)
assert(vm.$validator1.lang.touched === false)
assert(vm.$validator1.lang.dirty === false)
assert(vm.$validator1.lang.modified === false)
assert(vm.lang === 'ja')
en.selected = true
trigger(select, 'change')
vm.$nextTick(() => {
assert(vm.$validator1.lang.required === false)
assert(vm.$validator1.lang.valid === true)
assert(vm.$validator1.lang.touched === false)
assert(vm.$validator1.lang.dirty === true)
assert(vm.$validator1.lang.modified === true)
assert(vm.lang === 'en')
zh.selected = true
trigger(select, 'change')
trigger(select, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.lang.required === false)
assert(vm.$validator1.lang.valid === true)
assert(vm.$validator1.lang.touched === true)
assert(vm.$validator1.lang.dirty === true)
assert(vm.$validator1.lang.modified === true)
assert(vm.lang === 'zh')
done()
})
})
})
})
})
describe('#236', () => {
beforeEach((done) => {
el.innerHTML = `
<div v-if='show'>
<validator name="validator1">
<form novalidate>
<input type="text" v-model="name" v-validate:name="['required']">
<span v-if="!$validator1.valid">Name is required</span>
<pre>{{$validator1 | json}}</pre>
</form>
</validator>
</div>
<button @click="toogle">Toogle</button>{{ show }}
<pre>{{$validator1 | json}}</pre>
`
vm = new Vue({
el: el,
data: {
name: 'test',
show: true
},
methods: {
toogle () {
if (this.$data.show) {
this.$data.show = false
} else {
this.show = true
}
}
}
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
assert(vm.validator1 !== null)
let button = el.getElementsByTagName('button')[0]
let input = el.getElementsByTagName('input')[0]
input.value = ''
trigger(input, 'input')
trigger(input, 'blur')
trigger(button, 'click')
vm.$nextTick(() => {
assert(vm['$validator1'] === undefined)
assert(vm._validatorMaps['$validator1'] === undefined)
trigger(button, 'click')
vm.$nextTick(() => {
assert(vm.$validator1 !== null)
assert(vm.$validator1.name.invalid === true)
assert(vm.$validator1.name.required)
input = el.getElementsByTagName('input')[0]
input.value = 'test'
trigger(input, 'input')
trigger(input, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.name.invalid === false)
assert(vm.$validator1.name.required === false)
done()
})
})
})
})
})
describe('#243', () => {
beforeEach((done) => {
el.innerHTML = `
<validator name="validator1">
<form novalidate>
<input type="text" v-pickadate="'date'" v-validate:name="['required']">
</form>
</validator>
`
vm = new Vue({
el,
directives: {
pickadate: {
bind () {
const elm = document.createElement('div')
elm.innerHTML = '<p>hello world</p>'
Vue.util.after(elm, this.el)
}
}
}
})
vm.$nextTick(done)
})
it('should be validated', (done) => {
const field1 = vm.$el.querySelector('input')
field1.value = 'hello'
trigger(field1, 'input')
trigger(field1, 'blur')
vm.$nextTick(() => {
assert(vm.$validator1.name.required === false)
done()
})
})
})
})
| fire17643/Vue-resource | vue-validator-dev/test/specs/issues.js | JavaScript | mit | 16,379 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var academicCalendar = require('./routes/academiccalendar');
var contacts = require('./routes/contacts');
var events = require('./routes/events');
var libraries = require('./routes/libraries');
var maps = require('./routes/maps');
var index = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect(process.env.COMPOSE_URI || process.env.MONGOLAB_URI || 'mongodb://localhost/redevents');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
//app.use('/academiccalendar', academicCalendar);
app.use('/contacts', contacts);
app.use('/events', events);
app.use('/libraries', libraries);
app.use('/maps', maps);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| TrevorEdwards/RedEvents | app.js | JavaScript | mit | 1,916 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({widgetLabel:"\u041c\u0430\u0441\u0448\u0442\u0430\u0431\u0438\u0440\u043e\u0432\u0430\u0442\u044c",zoomIn:"\u041f\u0440\u0438\u0431\u043b\u0438\u0437\u0438\u0442\u044c",zoomOut:"\u041e\u0442\u0434\u0430\u043b\u0438\u0442\u044c"}); | ycabon/presentations | 2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/widgets/Zoom/nls/ru/Zoom.js | JavaScript | mit | 394 |
$(document).ready(function() {
$('#search-results').hide()
var songArray = [];
$('#search-box').on('keyup', function(event) {
event.preventDefault();
$('#search-results').hide()
$('#search-results').empty()
if ($('#search-box').val().length > 4) {
console.log('keyup if')
var data = $(this).serialize();
$.ajax({
url: '/spotify',
type: 'POST',
data: data
})
.done(function(response) {
songArray = []
// var titlesArray = [];
for (object in response) {
var song = new Song(response[object]);
// titlesArray.push(song.name + " - " + song.artist)
songArray.push(song)
}
var songList = new SongList(songArray)
$('#search-results').show()
$('#search-results').empty()
$('#search-results').append(songList.toHtml())
})
}
});
$('#search-form').on('submit', function(event) {
event.preventDefault();
var id = $(this).parent().attr('id')
var data;
for (object in songArray) {
if (songArray[object].name + " - " + songArray[object].artist == $('#search-box').val()) {
var newSong = songArray[object]
data = {song: newSong.id}
break;
}
}
if ( data ) {
$.ajax({
url: '/playlists/' + id,
type: 'PUT',
data: data
}).done(function(response){
$('#search-box').val('')
$('#search-results').html('')
$('#requests-remaining').text('Requests remaining: ' + response)
$('#search-results').hide()
}).error(function() {
var modal = $('#myModal').show();
})
}
});
// display the modal when the user votes on the same song
$("#myModal").on('click', function(){
$('#myModal').hide();
$('#search-box').val('')
$('#search-results').html('');
$('#search-results').hide()
$('#search-box').focus()
})
$('#search-results').on('mouseenter', 'p', function(){
$(this).css('background-color', '#EE6D94')
});
$('#search-results').on('mouseleave', 'p', function(){
$(this).css('background-color', '#181019')
});
$('#search-results').on('click', 'p', function(){
var text = $(this).text()
$('#search-box').val(text)
});
$('#song-list').on('submit', '.vote-button', function(event){
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
data: $(this).serialize()
}).done(function(response){
$('#requests-remaining').text('Requests remaining: ' + response)
})
})
});
| William-Jung/WeJ | app/assets/javascripts/spotify_search_controller.js | JavaScript | mit | 2,608 |
const expect = require('chai').expect;
const InspireTree = require('../../' + (process.env.DIST ? 'dist' : 'build') + '/inspire-tree');
describe('TreeNodes.prototype.indeterminate', function() {
let tree;
before(function() {
// Create tree
tree = new InspireTree({
selection: {
mode: 'checkbox'
},
data: [{
text: 'A',
id: 1,
children: [{
text: 'B',
id: 2
}, {
text: 'C',
id: 3
}]
}]
});
});
it('exists', function() {
expect(tree.nodes().indeterminate).to.be.a('function');
expect(tree.indeterminate).to.be.a('function');
});
it('returns indeterminate nodes', function() {
tree.node(3).select();
expect(tree.indeterminate()).to.have.length(1);
});
});
| helion3/inspire-tree | test/treenodes/indeterminate.spec.js | JavaScript | mit | 964 |
import ghUser from 'gh-user';
export default async function ghAvatar(username, {token} = {}) {
const user = await ghUser(username, {token});
return user.avatar_url;
}
| sindresorhus/gh-avatar | index.js | JavaScript | mit | 170 |
class TradeRuleAddController {
constructor (API, $state, $stateParams, $scope) {
'ngInject'
$scope.vm.content = "<h3>在这里输入内容</h3>"
$scope.froalaOptions = {
// placeholder: "Edit Me",
heightMin: 300,
language: 'zh_cn',
imageUploadURL: "upload/imgEditor"
}
this.$state = $state
this.formSubmitted = false
this.API = API
this.alerts = []
if ($stateParams.alerts) {
this.alerts.push($stateParams.alerts)
}
}
save (isValid) {
if (isValid) {
let TradeRules = this.API.service('traderules', this.API.all('informs'))
// let $state = this.$state
TradeRules.post({
'title': this.title,
'content': this.content
}).then(() => {
let alert = { type: 'success', 'title': 'Success!', msg: '成功添加了一条交易规则.' }
// $state.go($state.current, { alerts: alert})
this.alerts.push(alert);
}, (response) => {
let alert = { type: 'error', 'title': 'Error!', msg: response.data.message }
// $state.go($state.current, { alerts: alert})
this.alerts.push(alert);
})
} else {
this.formSubmitted = true
}
}
$onInit () {}
}
export const TradeRuleAddComponent = {
templateUrl: './views/app/components/trade-rule-add/trade-rule-add.component.html',
controller: TradeRuleAddController,
controllerAs: 'vm',
bindings: {}
}
| qijingyu2013/AdminCMS | angular/app/components/trade-rule-add/trade-rule-add.component.js | JavaScript | mit | 1,429 |
/**
*
*/
var fs = require('fs');
var rs = fs.createReadStream('./read.txt',{
start:0,end:5,highWaterMark:3
})
rs.setEncoding('utf8');
rs.on('open',function(){
console.log('打开文件');
});
rs.resume();
setTimeout(function(){
rs.on('data',function(data){
//setTimeout(function(){
console.log(data);
/* rs.pause();
setTimeout(function(){
rs.resume();
},3000)*/
//},5000)
});
},5000);
rs.on('end',function(){
console.log('读取完成');
});
rs.on('close',function(){
console.log('文件关闭');
});
| zhufengnodejs/node201509 | 12.stream/1.readstream.js | JavaScript | mit | 596 |
"use strict";
var render = require("../../../render");
var path = require("path");
render(
{
src: __dirname + "/../../../src/commonJS/*.js",
template: __dirname + "/template.hbs"
},
__dirname + "/readme.md"
);
| daserge/jsdoc-to-markdown | example/templating/selector helpers/module/render.js | JavaScript | mit | 240 |
/**
* Valid function with a charge of 0
* @charge 0
* @returns {string}
*/
module.exports = (callback) => {
return callback(null, 'valid charge');
};
| faaslang/faaslang | tests/files/cases/function_valid_zero_charge.js | JavaScript | mit | 154 |
import React from 'react'
import PropTypes from 'prop-types'
import {
Fab,
AddIcon,
withStyles,
List,
ListItem,
TextField,
ListItemSecondaryAction,
DeleteIconButton,
EditIconButton,
SimpleDialog
} from 'ui/admin'
import FilesContainer from 'client/containers/FilesContainer'
const styles = theme => ({
resources: {
marginBottom: '30px'
},
textfield: {
width: '80%'
},
fab: {
position: 'absolute',
bottom: '0px',
right: '0px',
margin: theme.spacing(1)
}
})
class ResourceEditor extends React.Component {
constructor(props) {
super(props)
this.state = {
resources: '',
resourcesArray: [],
editResource: false
}
}
static getDerivedStateFromProps(nextProps, prevState) {
const {resources} = nextProps
if (resources !== prevState.resources) {
try {
let resourcesArray = JSON.parse(resources)
if (!resourcesArray) resourcesArray = []
return Object.assign({}, prevState, {resources, resourcesArray})
} catch (e) {
}
}
return null
}
render() {
const {classes, ...rest} = this.props
const {resourcesArray} = this.state
return <div className={classes.resources}>
<List dense={true}>
{resourcesArray.map((item, i) => {
let src
if(item.constructor === Object){
src = item.src
item = JSON.stringify(item)
}else{
src = item
}
const isExternal = src.match(/[a-zA-Z0-9]*:\/\/[^\s]*/g) != null
return <ListItem key={'resource-' + i}>
<TextField value={item}
onChange={this.handleChange.bind(this, i)}
className={classes.textfield}
placeholder="Enter a url"/>
<ListItemSecondaryAction>
{!isExternal && <EditIconButton onClick={this.handleEditClick.bind(this, item)}/>}
<DeleteIconButton onClick={this.handleRemoveClick.bind(this, i)}/>
</ListItemSecondaryAction>
</ListItem>
})
}
</List>
<Fab
size="small"
onClick={this.handleAddClick.bind(this)}
color="secondary"
aria-label="Add"
className={classes.fab}>
<AddIcon />
</Fab>
<SimpleDialog open={!!this.state.editResource} onClose={this.handleDialogClose.bind(this)}
actions={[{
key: 'ok',
label: 'Ok',
type: 'primary'
}]}
title="Edit Resource">
<FilesContainer editOnly space="./build/" file={this.state.editResource} embedded />
</SimpleDialog>
</div>
}
handleDialogClose() {
this.setState({editResource: false})
}
handleAddClick() {
const resourcesArray = this.state.resourcesArray
resourcesArray.push('/style.css')
this.setState({resourcesArray}, this.emitChange)
}
handleEditClick(item) {
this.setState({editResource: item})
}
handleChange(i, e) {
const resourcesArray = this.state.resourcesArray
let val = e.target.value.trim()
if(val.startsWith('{')){
try {
val = JSON.parse(val)
}catch (e) {
}
}
resourcesArray[i] = val
this.setState({resourcesArray}, this.emitChange.bind(this, true))
}
handleRemoveClick(i) {
const resourcesArray = this.state.resourcesArray
resourcesArray.splice(i, 1)
this.setState({resourcesArray}, this.emitChange)
}
emitChange(delayed) {
const {onChange, resources} = this.props
if (onChange) {
clearTimeout(this.emitChangeTimeout)
console.log(this.state.resourcesArray)
const data = JSON.stringify(this.state.resourcesArray)
if (data !== resources) {
if (delayed) {
this.emitChangeTimeout = setTimeout(() => {
onChange(data)
}, 1000)
} else {
onChange(data)
}
}
}
}
}
ResourceEditor.propTypes = {
classes: PropTypes.object.isRequired,
resources: PropTypes.string,
onChange: PropTypes.func
}
export default withStyles(styles)(ResourceEditor)
| axax/lunuc | extensions/cms/components/ResourceEditor.js | JavaScript | mit | 4,960 |
var gulp = require('gulp');
var cssimport = require('gulp-cssimport');
var rollup = require('gulp-better-rollup');
var cssnano = require('cssnano');
var postcss = require('gulp-postcss');
var sucrase = require('@sucrase/gulp-plugin');
var minify = require('gulp-minify');
var rename = require('gulp-rename');
var del = require('del');
var resolve = require('rollup-plugin-node-resolve');
var commonjs = require('rollup-plugin-commonjs');
var rootImport = require('rollup-plugin-root-import');
var globals = require('rollup-plugin-node-globals');
/***
Main config options
***/
var urbitrc = require('../urbitrc');
/***
End main config options
***/
gulp.task('css-bundle', function() {
let plugins = [
cssnano()
];
return gulp
.src('src/index.css')
.pipe(cssimport())
.pipe(postcss(plugins))
.pipe(gulp.dest('../../arvo/app/debug/css'));
});
gulp.task('jsx-transform', function(cb) {
return gulp.src('src/**/*.js')
.pipe(sucrase({
transforms: ['jsx']
}))
.pipe(gulp.dest('dist'));
});
gulp.task('tile-jsx-transform', function(cb) {
return gulp.src('tile/**/*.js')
.pipe(sucrase({
transforms: ['jsx']
}))
.pipe(gulp.dest('dist'));
});
gulp.task('js-imports', function(cb) {
return gulp.src('dist/index.js')
.pipe(rollup({
plugins: [
commonjs({
namedExports: {
'node_modules/react/index.js': [ 'Component', 'createRef', 'createElement', 'useState', 'useRef', 'useEffect', 'Fragment' ],
'node_modules/react-is/index.js': [ 'isValidElementType' ],
}
}),
rootImport({
root: `${__dirname}/dist/js`,
useEntry: 'prepend',
extensions: '.js'
}),
globals(),
resolve()
]
}, 'umd'))
.on('error', function(e){
console.log(e);
cb();
})
.pipe(gulp.dest('../../arvo/app/debug/js/'))
.on('end', cb);
});
gulp.task('tile-js-imports', function(cb) {
return gulp.src('dist/tile.js')
.pipe(rollup({
plugins: [
commonjs({
namedExports: {
'node_modules/react/index.js': [ 'Component' ],
}
}),
rootImport({
root: `${__dirname}/dist/js`,
useEntry: 'prepend',
extensions: '.js'
}),
globals(),
resolve()
]
}, 'umd'))
.on('error', function(e){
console.log(e);
cb();
})
.pipe(gulp.dest('../../arvo/app/debug/js/'))
.on('end', cb);
});
gulp.task('js-minify', function () {
return gulp.src('../../arvo/app/debug/js/index.js')
.pipe(minify())
.pipe(gulp.dest('../../arvo/app/debug/js/'));
});
gulp.task('tile-js-minify', function () {
return gulp.src('../../arvo/app/debug/js/tile.js')
.pipe(minify())
.pipe(gulp.dest('../../arvo/app/debug/js/'));
});
gulp.task('rename-index-min', function() {
return gulp.src('../../arvo/app/debug/js/index-min.js')
.pipe(rename('index.js'))
.pipe(gulp.dest('../../arvo/app/debug/js/'))
});
gulp.task('rename-tile-min', function() {
return gulp.src('../../arvo/app/debug/js/tile-min.js')
.pipe(rename('tile.js'))
.pipe(gulp.dest('../../arvo/app/debug/js/'))});
gulp.task('clean-min', function() {
return del(['../../arvo/app/debug/js/index-min.js', '../../arvo/app/debug/js/tile-min.js'], {force: true})
});
gulp.task('urbit-copy', function () {
let ret = gulp.src('../../arvo/**/*');
urbitrc.URBIT_PIERS.forEach(function(pier) {
ret = ret.pipe(gulp.dest(pier));
});
return ret;
});
gulp.task('js-bundle-dev', gulp.series('jsx-transform', 'js-imports'));
gulp.task('tile-js-bundle-dev', gulp.series('tile-jsx-transform', 'tile-js-imports'));
gulp.task('js-bundle-prod', gulp.series('jsx-transform', 'js-imports', 'js-minify'))
gulp.task('tile-js-bundle-prod',
gulp.series('tile-jsx-transform', 'tile-js-imports', 'tile-js-minify'));
gulp.task('bundle-dev',
gulp.series(
gulp.parallel(
'css-bundle',
'js-bundle-dev',
'tile-js-bundle-dev'
),
'urbit-copy'
)
);
gulp.task('bundle-prod',
gulp.series(
gulp.parallel(
'css-bundle',
'js-bundle-prod',
'tile-js-bundle-prod',
),
'rename-index-min',
'rename-tile-min',
'clean-min',
'urbit-copy'
)
);
gulp.task('default', gulp.series('bundle-dev'));
gulp.task('watch', gulp.series('default', function() {
gulp.watch('tile/**/*.js', gulp.parallel('tile-js-bundle-dev'));
gulp.watch('src/**/*.js', gulp.parallel('js-bundle-dev'));
gulp.watch('src/**/*.css', gulp.parallel('css-bundle'));
gulp.watch('../../arvo/**/*', gulp.parallel('urbit-copy'));
}));
| urbit/urbit | pkg/interface/dbug/gulpfile.js | JavaScript | mit | 4,659 |
var urllib = require('url');
var querystring = require('querystring');
var sax = require('sax');
var request = require('./request');
var util = require('./util');
var sig = require('./sig');
var FORMATS = require('./formats');
var VIDEO_URL = 'https://www.youtube.com/watch?v=';
var EMBED_URL = 'https://www.youtube.com/embed/';
var VIDEO_EURL = 'https://youtube.googleapis.com/v/';
var THUMBNAIL_URL = 'https://i.ytimg.com/vi/';
var INFO_HOST = 'www.youtube.com';
var INFO_PATH = '/get_video_info';
var KEYS_TO_SPLIT = [
'keywords',
'fmt_list',
'fexp',
'watermark'
];
/**
* Gets info from a video.
*
* @param {String} link
* @param {Object} options
* @param {Function(Error, Object)} callback
*/
module.exports = function getInfo(link, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else if (!options) {
options = {};
}
if (!callback) {
return new Promise(function(resolve, reject) {
getInfo(link, options, function(err, info) {
if (err) return reject(err);
resolve(info);
});
});
}
var myrequest = options.request || request;
var id = util.getVideoID(link);
if (id instanceof Error) return callback(id);
// Try getting config from the video page first.
var url = VIDEO_URL + id;
myrequest(url, options.requestOptions, function(err, body) {
if (err) return callback(err);
// Check if there are any errors with this video page.
var unavailableMsg = util.between(body, '<div id="player-unavailable"', '>');
if (!/\bhid\b/.test(util.between(unavailableMsg, 'class="', '"'))) {
// Ignore error about age restriction.
if (body.indexOf('<div id="watch7-player-age-gate-content"') < 0) {
return callback(new Error(util.between(body,
'<h1 id="unavailable-message" class="message">', '</h1>').trim()));
}
}
// Parse out some additional informations since we already load that page.
var additional = {
// Get informations about the author/uploader.
author: util.getAuthor(body),
// Get the day the vid was published.
published: util.getPublished(body),
// Get description from #eow-description.
description: util.getVideoDescription(body),
// Get related videos.
related_videos: util.getRelatedVideos(body),
// Give the canonical link to the video.
video_url: url,
// Thumbnails.
iurlsd : THUMBNAIL_URL + id + '/sddefault.jpg',
iurlmq : THUMBNAIL_URL + id + '/mqdefault.jpg',
iurlhq : THUMBNAIL_URL + id + '/hqdefault.jpg',
iurlmaxres : THUMBNAIL_URL + id + '/maxresdefault.jpg',
};
var jsonStr = util.between(body, 'ytplayer.config = ', '</script>');
if (jsonStr) {
jsonStr = jsonStr.slice(0, jsonStr.lastIndexOf(';ytplayer.load'));
var config;
try {
config = JSON.parse(jsonStr);
} catch (err) {
return callback(new Error('Error parsing config: ' + err.message));
}
if (!config) {
return callback(new Error('Could not parse video page config'));
}
gotConfig(id, options, additional, config, callback);
} else {
// If the video page doesn't work, maybe because it has mature content.
// and requires an account logged into view, try the embed page.
url = EMBED_URL + id;
myrequest(url, options.requestOptions, function(err, body) {
if (err) return callback(err);
config = util.between(body, 't.setConfig({\'PLAYER_CONFIG\': ', '},\'');
if (!config) {
return callback(new Error('Could not find `player config`'));
}
try {
config = JSON.parse(config + '}');
} catch (err) {
return callback(new Error('Error parsing config: ' + err.message));
}
gotConfig(id, options, additional, config, callback);
});
}
});
};
/**
* @param {Object} id
* @param {Object} options
* @param {Object} additional
* @param {Object} config
* @param {Function(Error, Object)} callback
*/
function gotConfig(id, options, additional, config, callback) {
if (config.status === 'fail') {
return new Error(config.errorcode && config.reason ?
'Code ' + config.errorcode + ': ' + config.reason : 'Video not found');
}
var url = urllib.format({
protocol: 'https',
host: INFO_HOST,
pathname: INFO_PATH,
query: {
video_id: id,
eurl: VIDEO_EURL + id,
ps: 'default',
gl: 'US',
hl: 'en',
sts: config.sts,
},
});
var myrequest = options.request || request;
myrequest(url, options.requestOptions, function(err, body) {
if (err) return callback(err);
var info = querystring.parse(body);
if (info.status === 'fail') {
info = config.args;
} else if (info.requires_purchase === '1') {
return callback(new Error(info.ypc_video_rental_bar_text));
}
// Split some keys by commas.
KEYS_TO_SPLIT.forEach(function(key) {
if (!info[key]) return;
info[key] = info[key]
.split(',')
.filter(function(v) { return v !== ''; });
});
info.fmt_list = info.fmt_list ?
info.fmt_list.map(function(format) {
return format.split('/');
}) : [];
info.formats = util.parseFormats(info);
// Add additional properties to info.
info = util.objectAssign(info, additional, false);
if (info.formats.some(function(f) { return !!f.s; }) ||
config.args.dashmpd || info.dashmpd || info.hlsvp) {
var html5playerfile = urllib.resolve(VIDEO_URL, config.assets.js);
sig.getTokens(html5playerfile, options, function(err, tokens) {
if (err) return callback(err);
sig.decipherFormats(info.formats, tokens, options.debug);
var funcs = [];
var dashmpd;
if (config.args.dashmpd) {
dashmpd = decipherURL(config.args.dashmpd, tokens);
funcs.push(getDashManifest.bind(null, dashmpd, options));
}
if (info.dashmpd && info.dashmpd !== config.args.dashmpd) {
dashmpd = decipherURL(info.dashmpd, tokens);
funcs.push(getDashManifest.bind(null, dashmpd, options));
}
if (info.hlsvp) {
info.hlsvp = decipherURL(info.hlsvp, tokens);
funcs.push(getM3U8.bind(null, info.hlsvp, options));
}
util.parallel(funcs, function(err, results) {
if (err) return callback(err);
if (results[0]) { mergeFormats(info, results[0]); }
if (results[1]) { mergeFormats(info, results[1]); }
if (results[2]) { mergeFormats(info, results[2]); }
if (!info.formats.length) {
callback(new Error('No formats found'));
return;
}
if (options.debug) {
info.formats.forEach(function(format) {
var itag = format.itag;
if (!FORMATS[itag]) {
console.warn('No format metadata for itag ' + itag + ' found');
}
});
}
info.formats.sort(util.sortFormats);
callback(null, info);
});
});
} else {
if (!info.formats.length) {
callback(new Error('This video is unavailable'));
return;
}
sig.decipherFormats(info.formats, null, options.debug);
info.formats.sort(util.sortFormats);
callback(null, info);
}
});
}
/**
* @param {String} url
* @param {Array.<String>} tokens
*/
function decipherURL(url, tokens) {
return url.replace(/\/s\/([a-fA-F0-9\.]+)/, function(_, s) {
return '/signature/' + sig.decipher(tokens, s);
});
}
/**
* Merges formats from DASH or M3U8 with formats from video info page.
*
* @param {Object} info
* @param {Object} formatsMap
*/
function mergeFormats(info, formatsMap) {
info.formats.forEach(function(f) {
var cf = formatsMap[f.itag];
if (cf) {
for (var key in f) { cf[key] = f[key]; }
} else {
formatsMap[f.itag] = f;
}
});
info.formats = [];
for (var itag in formatsMap) { info.formats.push(formatsMap[itag]); }
}
/**
* Gets additional DASH formats.
*
* @param {String} url
* @param {Object} options
* @param {Function(!Error, Array.<Object>)} callback
*/
function getDashManifest(url, options, callback) {
var myrequest = options.request || request;
var formats = {};
var currentFormat = null;
var expectUrl = false;
var parser = sax.parser(false);
parser.onerror = callback;
parser.onopentag = function(node) {
if (node.name === 'REPRESENTATION') {
var itag = node.attributes.ID;
var meta = FORMATS[itag];
currentFormat = { itag: itag };
for (var key in meta) {
currentFormat[key] = meta[key];
}
formats[itag] = currentFormat;
}
expectUrl = node.name === 'BASEURL';
};
parser.ontext = function(text) {
if (expectUrl) {
currentFormat.url = text;
}
};
parser.onend = function() { callback(null, formats); };
var req = myrequest(urllib.resolve(VIDEO_URL, url), options.requestOptions);
req.on('error', callback);
req.on('response', function(res) {
// Support for Streaming 206 status videos.
if (res.statusCode !== 200 && res.statusCode !== 206) {
// Ignore errors on manifest.
return parser.close();
}
res.setEncoding('utf8');
res.on('error', callback);
res.on('data', function(chunk) { parser.write(chunk); });
res.on('end', parser.close.bind(parser));
});
}
/**
* Gets additional formats.
*
* @param {String} url
* @param {Object} options
* @param {Function(!Error, Array.<Object>)} callback
*/
function getM3U8(url, options, callback) {
var myrequest = options.request || request;
myrequest(urllib.resolve(VIDEO_URL, url), options.requestOptions, function(err, body) {
if (err) return callback(err);
var formats = {};
body
.split('\n')
.filter(function(line) {
return line.trim().length && line[0] !== '#';
})
.forEach(function(line) {
var itag = line.match(/\/itag\/(\d+)\//)[1];
if (!itag) {
if (options.debug) {
console.warn('No itag found in url ' + line);
}
return;
}
var meta = FORMATS[itag];
var format = { itag: itag, url: line };
for (var key in meta) {
format[key] = meta[key];
}
formats[itag] = format;
});
callback(null, formats);
});
}
| perfectedpixel/justplugin | node_modules/ytdl-core/lib/info.js | JavaScript | mit | 10,533 |
/// <reference path="../typings/tsd.d.ts" />
var mongoose = require('mongoose');
// import * as bcrypt from 'bcrypt';
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
var UserSchema = new mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
bcrypt: true,
required: true
},
email: {
type: String
},
name: {
type: String
},
profileImage: {
type: String
}
});
exports.User = mongoose.model('User', UserSchema);
function createUser(newUser, callback) {
// problem with installtion of bcrypt module
// bcrypt.hash(newUser.password, 10, (err, hash) => {
// if (err) { throw err; }
// //set hashed password
// console.log(hash);
// newUser.password = hash;
// //create user
// });
newUser.save(callback);
}
exports.createUser = createUser;
function comparePassword(candidatePassword, hashedPassword, callback) {
// compare using bcrypt
// bcrypt.compare(candidatePassword, hashedPassword, (err, isMatch)=>{
// if(err) return callback(err);
// callback(null, isMatch);
// })
if (candidatePassword === hashedPassword) {
callback(null, true);
}
else {
callback(null, false);
}
}
exports.comparePassword = comparePassword;
function getUserByUsername(username, callback) {
var query = { username: username };
exports.User.findOne(query, callback);
}
exports.getUserByUsername = getUserByUsername;
function getUserById(id, callback) {
exports.User.findById(id, callback);
}
exports.getUserById = getUserById;
| ajayak/user-login-system | models/user.js | JavaScript | mit | 1,668 |
/*
Some colors
Source is over here: http://de.wikipedia.org/wiki/Berliner_Verkehrsbetriebe#Farben
*/
exports.u1 = "#7DAD4C";
exports.u15 = "#7DAD4C";
exports.u2 = "#DA421E";
exports.u3 = "#007A5B";
exports.u4 = "#F0D722";
exports.u5 = "#7E5330";
exports.u55 = "#7E5330";
exports.u6 = "#8C6DAB";
exports.u7 = "#528DBA";
exports.u8 = "#224F86";
exports.u9 = "#F3791D";
exports.ubahn = "#115D91";
exports.metro = "#F3791D";
exports.tram = "#BE1414";
exports.bus = "#95276E";
exports.ferry = "#528DBA";
exports.re = "#E2001A";
exports.defaultColor = "#000000";
| derroman/vbbFXOS | vbbMapProperties/colors.js | JavaScript | mit | 560 |
(function(){
var app = window.app;
var helper = app('helper');
var gestures = app('gestures');
var base = gestures('swipe-base');
var directions = gestures('directions');
function swipeTopClass(el, params){
params = params || {};
params.direction = directions.north;
if (!params.onSysMove) {
params.onSysMove = function (data, ev) {
var dx = data.dy;
if (dx > 0) {
dx = 0;
}
var startPoint = params.startPointY || 0;
dx = startPoint + dx;
el.css('transform', 'translateY(' + dx + 'px)');
};
}
swipeTopClass._parent.constructor.call(this, el, params);
}
helper.inherit(swipeTopClass, base);
gestures('swipe-top', swipeTopClass);
})(); | dudiq/jr | app/scripts/core-plugins/jqueries/gestures/swipe-top.js | JavaScript | mit | 859 |
var webpack = require("webpack");
var config = require("./webpack.config.base.js");
// Use cheap source maps
config.devtool = "cheap-module-eval-source-map";
// Necessary for hot reloading with IE:
config.entry.index.splice(1, 0, 'eventsource-polyfill');
// Listen to code updates emitted by hot middleware:
config.entry.index.splice(2, 0, 'webpack-hot-middleware/client');
// Hot reloading stuff
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
module.exports = config;
| Phyks/ampache_react | webpack.config.development.js | JavaScript | mit | 516 |
/**
* Mixin for some shared methods between components
**/
import { saveAs } from 'file-saver';
function generateRow(colArray) {
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
const tmpColDelim = String.fromCharCode(11); // vertical tab character
const tmpRowDelim = String.fromCharCode(0); // null character
// actual delimiter characters for CSV format
const colDelim = '","';
const rowDelim = '"\r\n"';
return colArray.map((row) =>
row.map((col) => col.replace(/"/g, '""'))
.join(tmpColDelim)
)
.join(tmpRowDelim).split(tmpRowDelim)
.join(rowDelim)
.split(tmpColDelim)
.join(colDelim);
}
const mixins = {
generateQuestionID() {
return (Date.now().toString(32) + Math.random().toString(36).substr(2, 12)).toUpperCase();
},
getParameterByName(name) {
const url = window.location.href;
const rename = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp(`[?&]${rename}(=([^&#]*)|&|#|$)`);
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
},
exportCSV(filename = 'Qustom', v = 'v1', header, content) {
const rowDelim = '"\r\n"';
const headerCSV = generateRow(header);
const contentCSV = generateRow(content);
const csv = `"${headerCSV}${rowDelim}${contentCSV}"`;
// Use <a> click event to download CSV
// The BOM will not work in Excel for Mac OS X,
// it will only present it with some odd characters in the beginning of the file
// so it need to open in Numbers for Mac OS X
// check this issue in FileSaver.js git issues#28
const downloadLink = document.createElement('a');
downloadLink.addEventListener('click', () => {
if (navigator.userAgent.match(/Version\/([0-9\._]+).*Safari/)) {
// eslint-disable-next-line no-alert
alert('Safari is unsupported this. Please manually press command + S.');
}
try {
const blob = new Blob([csv], { type: 'text/csv;charset=charset=utf-8;' });
saveAs(blob, `${filename}.csv`);
} catch (e) {
console.log(`Exception: ${e}`);
}
});
downloadLink.click();
},
fixScrollbar() {
const html = document.getElementsByTagName('html')[0];
const scrollTop = (document.documentElement && document.documentElement.scrollTop)
|| document.body.scrollTop;
html.style.top = `${0 - scrollTop}px`;
html.classList.add('non-scroll');
},
freeScrollbar() {
const html = document.getElementsByTagName('html')[0];
const scrollTop = html.style.top.replace(/px/g, '');
const body = document.documentElement && document.documentElement.scrollTop ?
document.documentElement : document.body;
html.style.top = '';
html.classList.remove('non-scroll');
body.scrollTop = 0 - scrollTop;
}
};
export default mixins;
| trendmicro/serverless-survey-forms | web/portal/src/mixins/global.js | JavaScript | mit | 3,263 |
define([
'jquery',
'underscore',
'backbone',
],
function($,_,Backbone){
var seqModel = Backbone.Model.extend({urlRoot:'/illumina/'});
return seqModel;
});
| melerz/nflab-site | app/js/sequencer/models/illumina-model.js | JavaScript | mit | 173 |
const Package = require('dgeni').Package;
// Define the `base` package
/**
* @dgPackage base
* @description Defines minimal set of processors to get started with Dgeni
*/
module.exports = new Package('base')
// A set of pseudo processors that act as markers to help position real processors at the right
// place in the pipeline
/**
* @dgProcessor reading-files
* @description A marker that files are about to be read
*/
.processor({ name: 'reading-files' })
/**
* @dgProcessor files-read
* @description A marker that files have just been read
*/
.processor({ name: 'files-read', $runAfter: ['reading-files'] })
/**
* @dgProcessor processing-docs
* @description A marker that we are about to start processing the docs
*/
.processor({ name: 'processing-docs', $runAfter: ['files-read'] })
/**
* @dgProcessor docs-processed
* @description A marker that the docs have just been processed
*/
.processor({ name: 'docs-processed', $runAfter: ['processing-docs'] })
/**
* @dgProcessor adding-extra-docs
* @description A marker that we are about to start adding extra docs
*/
.processor({ name: 'adding-extra-docs', $runAfter: ['docs-processed'] })
/**
* @dgProcessor extra-docs-added
* @description A marker that any extra docs have been added
*/
.processor({ name: 'extra-docs-added', $runAfter: ['adding-extra-docs'] })
/**
* @dgProcessor computing-ids
* @description A marker that we are about to start computing the ids of the docs
*/
.processor({ name: 'computing-ids', $runAfter: ['extra-docs-added'] })
/**
* @dgProcessor ids-computed
* @description A marker that the doc ids have just been computed
*/
.processor({ name: 'ids-computed', $runAfter: ['computing-ids'] })
/**
* @dgProcessor computing-paths
* @description A marker that we are about to start computing the paths of the docs
*/
.processor({ name: 'computing-paths', $runAfter: ['ids-computed'] })
/**
* @dgProcessor paths-computed
* @description A marker that the doc paths have just been computed
*/
.processor({ name: 'paths-computed', $runAfter: ['computing-paths'] })
/**
* @dgProcessor rendering-docs
* @description A marker that we are about to start generating the rendered content
* for the docs
*/
.processor({ name: 'rendering-docs', $runAfter: ['paths-computed'] })
/**
* @dgProcessor docs-rendered
* @description A marker that the rendered content has been generated
*/
.processor({ name: 'docs-rendered', $runAfter: ['rendering-docs'] })
/**
* @dgProcessor writing-files
* @description A marker that we are about to start writing the docs to files
*/
.processor({ name: 'writing-files', $runAfter: ['docs-rendered'] })
/**
* @dgProcessor files-written
* @description A marker that the docs have been written to files
*/
.processor({ name: 'files-written', $runAfter: ['writing-files'] })
// Real processors for this package
.processor(require('./processors/read-files'))
.processor(require('./processors/render-docs'))
.processor(require('./processors/unescape-comments'))
.processor(require('./processors/write-files'))
.processor(require('./processors/debugDumpProcessor'))
.processor(require('./processors/computeIds'))
.processor(require('./processors/computePaths'))
.processor(require('./processors/checkAnchorLinks'))
// Helper services
.factory(require('./services/resolveUrl'))
.factory(require('./services/extractLinks'))
.factory(require('./services/templateFinder'))
.factory(require('./services/encodeCodeBlock'))
.factory(require('./services/trimIndentation'))
.factory(require('./services/aliasMap'))
.factory(require('./services/createDocMessage'))
.factory(require('./services/writeFile'));
| angular/dgeni-packages | base/index.js | JavaScript | mit | 3,635 |
angular.module('app.core')
.config([
'$httpProvider',
function($httpProvider) {
$httpProvider.responseInterceptors.push([
'$q',
'$templateCache',
function($q, $templateCache) {
var modifiedTemplates = {};
var HAS_FLAGS_REGEX = /data-dom-(remove|keep)/;
var HTML_PAGE_REGEX = /\.html$|\.html\?/i;
return function(promise) {
return promise.then(function(response) {
var url = response.config.url,
responseData = response.data;
if(!modifiedTemplates[url] && HTML_PAGE_REGEX.test(url) && HAS_FLAGS_REGEX.test(responseData)) {
var template = $('<div>').append(responseData);
// Find and parse the keep/omit attributes in the view.
template.find('[data-dom-keep],[data-dom-remove]').each(function() {
var removeElement;
var element = $(this);
var data = element.data();
var removeFlags = data.domRemove;
var keepFlags = data.domKeep;
//todo: implement your own logic for removing elements from the template
//example implementation where the data attribute stores user permissions
/*var flags;
if(removeFlags !== undefined) {
removeElement = false;
flags = removeFlags.split(',');
} else {
removeElement = true;
flags = removeFlags.split(',');
}
if(session.user.hasPermissions(flags)) {
removeElement = !removeElement;
}*/
if(removeElement === true) {
element.remove();
}
});
//update template cache
response.data = template.html();
$templateCache.put(url, response.data);
modifiedTemplates[url] = true;
}
return response;
},
function(response) {
return $q.reject(response);
});
};
}
]);
}
]); | nucleus-angular/svg | dalek-web/app/components/core/http-interceptors-config.js | JavaScript | mit | 2,145 |
'use strict';
var bbApp = bbApp || {};
bbApp.testModuleData = [
{
index: 0,
section: 'reading',
lessons: [{
reception: {
audio: 'audio-file',
text: 'K'
},
textInput: {
audio: 'audio-file',
options: [
{
text: 'K',
correct: true
},
{
text: 'T',
correct: false
},
{
text: 'O',
correct: false
},
{
text: 'S',
correct: false
}
]
},
voiceInput: {
audio: 'audio-file',
text: 'K'
}
}]
},
{
index: 1,
section: 'reading',
lessons: [{
reception: {
audio: 'audio-file',
text: 'E'
},
textInput: {
audio: 'audio-file',
options: [
{
text: 'H',
correct: false
},
{
text: 'B',
correct: false
},
{
text: 'E',
correct: true
},
{
text: 'W',
correct: false
}
]
},
voiceInput: {
audio: 'audio-file',
text: 'E'
}
}]
},
{
index: 0,
section: 'numbers',
lessons: [{
reception: {
audio: 'audio-file',
text: '8'
},
textInput: {
audio: 'audio-file',
options: [
{
text: '4',
correct: false
},
{
text: '8',
correct: true
},
{
text: '3',
correct: false
},
{
text: '5',
correct: false
}
]
},
voiceInput: {
audio: 'audio-file',
text: '8'
}
}]
},
{
index: 1,
section: 'numbers',
lessons: [{
reception: {
audio: 'audio-file',
text: '3'
},
textInput: {
audio: 'audio-file',
options: [
{
text: '6',
correct: false
},
{
text: '2',
correct: false
},
{
text: '3',
correct: true
},
{
text: '7',
correct: false
}
]
},
voiceInput: {
audio: 'audio-file',
text: '3'
}
}]
}
]; | cfranklin11/pocklit-mobile | www/data/data.js | JavaScript | mit | 2,459 |
"use strict";
class gsuiDrumsforms extends gsuiSVGDefs {
update( id, drums, drumrows, dur, stepsPerBeat ) {
return super.update( id, dur, 1, ...gsuiDrumsforms.#render( drums, drumrows, stepsPerBeat ) );
}
static #render( drums, drumrows, sPB ) {
const rowsArr = Object.entries( drumrows ),
drmW = 1 / sPB,
drmH = 1 / rowsArr.length,
orders = rowsArr
.sort( ( a, b ) => a[ 1 ].order - b[ 1 ].order )
.reduce( ( obj, [ id ], i ) => {
obj[ id ] = i;
return obj;
}, {} );
return Object.values( drums )
.map( d => ( "gain" in d
? gsuiDrumsforms.#createDrum
: gsuiDrumsforms.#createDrumcut )( d.when, orders[ d.row ] * drmH, drmW, drmH ) );
}
static #createDrum( x, y, w, h ) {
return GSUI.createElementSVG( "polygon", {
points: [ x, y, x, y + h * .75, x + w, y + h * .75 / 2 ].join( "," ),
} );
}
static #createDrumcut( x, y, w, h ) {
return GSUI.createElementSVG( "rect", {
x: x,
y: y + h * .8,
width: w * .9,
height: h * .2,
} );
}
}
Object.freeze( gsuiDrumsforms );
| GridSound/gs-ui-components | gsuiDrumsforms/gsuiDrumsforms.js | JavaScript | mit | 1,047 |
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Popover from 'react-popover';
export class HomeView extends React.Component {
static propTypes = {
actions : React.PropTypes.object,
counter : React.PropTypes.number
}
state = {
showDiv: true
}
onBreakPopover = () => {
this.setState({
showDiv: false,
isPopoverOpen: false
});
};
openPopover = () => {
this.setState({
isPopoverOpen: true
});
};
buildPopoverProps = () => {
return {
isOpen: this.state.isPopoverOpen,
body: (
<div
style={{
padding: 20,
backgroud: 'lightgrey'
}}
onClick={this.onBreakPopover}>
Click me to hide the div and break the popover
</div>
)
};
};
render () {
return (
<div className='container text-center'>
{this.state.showDiv && (
<Popover {...this.buildPopoverProps()}>
<button onClick={this.openPopover}>
Click me to open the popover
</button>
</Popover>
)}
<div style={{
height: 4000
}}>
Make this thing scroll
</div>
</div>
);
}
}
export default HomeView;
| clayne11/react-popover-lifecycle-bug | src/views/HomeView.js | JavaScript | mit | 1,367 |
module.exports = {
"plugins": {
// to edit target browsers: use "browserlist" field in package.json
"autoprefixer": {
browsers: ['iOS >= 7', 'Android >= 4.1']
},
"postcss-px2rem": {
remUnit: 75
}
}
}
| qingniao99/ftl-vue-webpack | .postcssrc.js | JavaScript | mit | 236 |
import BaseModel, { mergeSchemas } from './base'
import User from './user'
class Social extends BaseModel {
static tableName = 'user_social_media';
static jsonSchema = mergeSchemas(BaseModel.jsonSchema, {
required: ['id', 'userId'],
properties: {
id: {
type: 'string',
minLength: 36,
maxLength: 36,
pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
},
userId: {
type: 'string',
minLength: 36,
maxLength: 36,
pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
},
googleUrl: {
type: 'string',
minLength: 1,
maxLength: 255,
},
githubUrl: {
type: 'string',
minLength: 1,
maxLength: 255,
},
},
})
static addTimestamps = false
static get relationMappings() {
return {
user: {
relation: BaseModel.BelongsToOneRelation,
modelClass: User,
join: {
from: 'user_social_media.userId',
to: 'user.id',
},
},
}
}
}
export default Social
| thoughtbit/node-web-starter | bear-api-express/server/src/models/social.js | JavaScript | mit | 1,130 |
/*global $, Modernizr, google */
String.prototype.repeat = function(num) {
return new Array(num+1).join(this);
};
/* Maps map-canvas divs to google map objects */
var canvas_to_map = {};
/* The next appointments as a list */
var jumboroute_to_appointment = {};
/* Maps jumboroute divs to route data */
var jumboroute_to_route = {};
/* One Google Maps infoWindow instance for showing info on route stops */
var infowindow;
/* The object that the infowindow is currently opened for (e.g. a marker) */
var infowindowtrigger;
/* An array of location aliases */
var aliases = null;
var Neverlate = {
templates: {},
API_CREDS: "&user=neverlate&pass=neverlate",
COORD_FORMAT: "&epsg_in=wgs84&epsg_out=wgs84",
DETAIL_LEVEL: "&detail=full",
CORS: "http://www.corsproxy.com/"
};
/*
* Generates a unique hash for an arbitrary object
*/
function hash(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
}
hash.current = 0;
Neverlate.getCurrentGeolocation = function() {
function printCoords(location) {
Neverlate.userCoords = location.coords;
}
if (Modernizr.geolocation) {
return navigator.geolocation.getCurrentPosition(printCoords);
} else {
console.log("no geolocation support");
}
};
/*
* Initializes the dashboard page
*/
Neverlate.initialize = function() {
Neverlate.getCurrentGeolocation(); //Get user location from browser is possible
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAoHieetxNcdqJ4PDij87fi2KH8tOhMK2Y&sensor=true&callback=gmap_loaded";
$("head").append(s);
window.gmap_loaded = function(){
$(".map-canvas").each(function() {
Neverlate.createMap($(this)[0]);
});
Neverlate.asyncUpdateDashboardState();
$('#inputStartLocationButton').on('click', function (event) {
var jumboroutearray = $(event.target).parents('.jumbotron');
Neverlate.changeStartLocation(jumboroutearray);
});
$('#inputDestinationButton').on('click', function (event) {
var jumboroutearray = $(event.target).parents('.jumbotron');
Neverlate.changeDestination(jumboroutearray);
});
};
};
/*
* Create a map, but don't do anything else with it yet.
*/
Neverlate.createMap = function(map_canvas) {
console.log("drawed a map");
var mapOptions = { // just some initial values until real data is available
center: new google.maps.LatLng(60.188549397729, 24.833913340551),
zoom: 10
};
var map = new google.maps.Map(map_canvas, mapOptions);
canvas_to_map[hash(map_canvas)] = map; // store the map for later access
return map;
};
/*
* Finds the coordinates for the given addresses using Reittiopas API
* and calls loadRouteByCoordinate to get the actual route data and display it to the user.
*/
Neverlate.loadRouteByAddress = function(point1, point2, jumboroute, arrival) {
var point1json = null;
var point2json = null;
// resolve location aliases
point1 = Neverlate.resolveLocation(point1, aliases);
point2 = Neverlate.resolveLocation(point2, aliases);
$(document).ready(function () {
var N = Neverlate; // faste to type
var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;
// If point1 given as geocode
if (point1.longitude && point1.latitude) {
point1json = [{coords: [point1.longitude,point1.latitude].join(',')}];
} else {
$.get(
url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key="+point1+queryOptions,
succes = function(response) {
console.log("GOT RESPONSE FRON REITTIOPAS");
point1json = JSON.parse(response);
if (point2json != null) { // this in made in pieces because either call can finish first
Neverlate.loadRouteByCoordinate(point1json[0]["coords"],point2json[0]["coords"],
jumboroute, arrival);
}
});
}
$.get(
url = N.CORS + "api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key=" + point2 + queryOptions,
success = function (response) {
console.log("GOT RESPONSE FRON REITTIOPAS");
point2json = JSON.parse(response);
if (point1json != null) {// this in made in pieces because either call can finish first
Neverlate.loadRouteByCoordinate(point1json[0]["coords"], point2json[0]["coords"],
jumboroute, arrival);
};
});
});
};
Neverlate.zeroPad = function(number, zeros){
return ('0'.repeat(zeros)+number.toString()).slice(-zeros);
};
/*
* Fetches a route from Reittiopas.
* Stores the route data for later use and display it to the user.
*/
Neverlate.loadRouteByCoordinate = function (point1coords, point2coords, jumboroute, arrival) {
var N = Neverlate; // faster to type
var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;
var arrivalOptions = "";
if (arrival) {
var date = N.zeroPad(arrival.getYear(), 4)+N.zeroPad(arrival.getMonth(),2)+N.zeroPad(arrival.getDate(),2);
var time = N.zeroPad(arrival.getHours(), 2) + N.zeroPad(arrival.getMinutes(), 2);
arrivalOptions = "&time=" + time + + "&date=" + date + "&timetype=arrival";
}
$.get(
url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=route&format=json&from="
+point1coords+"&to="+point2coords+"&callback=?"+queryOptions+arrivalOptions,
succes = function(response) {
console.log("GOT ROUTE FRON REITTIOPAS");
var routes = JSON.parse(response);
jumboroute_to_route[hash(jumboroute)] = routes; // store the route for later access
Neverlate.populateRouteButtons(jumboroute, routes);
Neverlate.showRoute(routes[0][0], jumboroute); // TODO: choose which of the route options to show
});
};
Neverlate.populateRouteButtons = function(jumboroute, routes) {
var buttonGroup = $(jumboroute).find('#routeButtons');
buttonGroup.html('');
var buttons = routes.forEach(function(route, index) {
var buttonId = "routeButton" + index;
var departureTime = Neverlate.getRouteDepartureTime(route[0]);
buttonGroup.append('<button type="button" class="btn btn-default" id="' +
buttonId + '"><input type="radio">' + departureTime + '</button>');
var button = $(jumboroute).find('#' + buttonId);
if (index == 0) {
button.button('toggle');
}
button.on('click', function (event) {
Neverlate.updateRoute(jumboroute, index);
});
});
};
/*
* Shows the given route option to the user
*/
Neverlate.showRoute = function(data, jumboroute){
var map = Neverlate.createMap($(jumboroute).find(".map-canvas")[0]);
Neverlate.loadMap(map, data);
Neverlate.updateRoutePanel(jumboroute, data);
};
/*
* Updates the given jumboroute div to show the route option at the given index.
* The index can be in the range [0,2] or [0,4] depending on how many routes
* were fetched from Reittiopas.
*/
Neverlate.updateRoute = function(jumboroute, routeIndex) {
var route = jumboroute_to_route[hash(jumboroute)][routeIndex][0];
Neverlate.showRoute(route, jumboroute);
}
Neverlate.calculateMiddleCoord = function(legs) {
var startPoint = legs[0].locs[0].coord;
var endPoint = legs[legs.length-1].locs[legs[legs.length-1].locs.length-1].coord ;
var middlePoint = {};
middlePoint.lat = (startPoint.y + endPoint.y)/2;
middlePoint.lng = (startPoint.x + endPoint.x)/2;
return middlePoint;
};
Neverlate.mapZoom = function(len) {
var w = window.innerWidth;
var windowSizeOffset = 0; //used to change zoom level in mobile browsers;
if (window.innerWidth <700) {
windowSizeOffset = -1;
console.log("offset was "+ windowSizeOffset);
}
if (window.innerWidth >1300) {
windowSizeOffset = +1;
console.log("offset was "+ windowSizeOffset + " and length was " + len);
}
if (len < 4000){
return 15 + windowSizeOffset;
}
else if (len < 6000){
return 14 + windowSizeOffset;
}
else if (len < 10000){
return 13 + windowSizeOffset;
}
else if (len < 22000) {
return 12 + windowSizeOffset;
}
else if (len >= 22000) {
return 11 + windowSizeOffset;
}
}
/*
* Display a route on an already existing map.
*/
Neverlate.loadMap = function(map, route_data){
console.log(route_data);
route_data["legs"].forEach(function (leg){
Neverlate.drawLeg(leg, map);
});
Neverlate.drawStop(null, route_data["legs"][0], map); // the beginning
for (var i = 0; i < route_data["legs"].length-1; ++i)
Neverlate.drawStop(route_data["legs"][i], route_data["legs"][i+1], map); // the middle
Neverlate.drawStop(route_data["legs"][route_data["legs"].length-1], null, map); // the end
// TODO: zoom and position the map correctly
var middlePoint = Neverlate.calculateMiddleCoord(route_data["legs"]); // coord-object with lat and lng is returned
map.setCenter(new google.maps.LatLng( middlePoint.lat, middlePoint.lng)); // center map to the route
map.setZoom(Neverlate.mapZoom(route_data["length"])); // change zoom level depending on the length of route
};
Neverlate.drawLeg = function(leg, map){
var locs=[];
leg.shape.forEach(function (loc){ //locs for stops, shape for drawable route
locs.push(loc);
});
var routeCoords = Neverlate.parseShape(locs);
console.log(routeCoords);
var routePath = new google.maps.Polyline({
path: routeCoords,
geodesic: true,
strokeColor: Neverlate.getLegColor(leg.type),
strokeOpacity: 0.8,
strokeWeight: 6
});
routePath.setMap(map);
};
Neverlate.drawStop = function(precedingLeg, followingLeg, map){
var loc;
var icon;
if (followingLeg != null) {
loc = new google.maps.LatLng(followingLeg.locs[0].coord.y, followingLeg.locs[0].coord.x);
icon = Neverlate.getLegIcon(followingLeg.type);
} else { // this is the end
loc = new google.maps.LatLng(precedingLeg.locs[precedingLeg.locs.length-1].coord.y, precedingLeg.locs[precedingLeg.locs.length-1].coord.x);
icon = Neverlate.getEndIcon();
}
var marker = new google.maps.Marker({
position: loc,
map: map,
icon: icon
});
Neverlate.addInfoWindow(marker, Neverlate.formatStopInfo(precedingLeg, followingLeg), map);
};
Neverlate.getLegColor = function(type) {
switch(type) {
case 'walk':
return '#1E74FC';
case '1':case '3':case '4':case '5':case '8':case '21':case '22':case '23':case '24':case '25':case '36':case '39': // bus
return '#193695';
case '2': // tram
return '#00AC67';
case '6': // metro
return '#FB6500';
case '7': // ferry
return '#00AEE7';
case '12': // commuter train
return '#2CBE2C';
default: // unknown
return '#000000'
}
};
Neverlate.getLegIcon = function(type) {
var name;
switch(type) {
case 'walk':
name = 'walk.png';
break;
case '1':case '3':case '4':case '5':case '8':case '21':case '22':case '23':case '24':case '25':case '36':case '39':
name = 'bus.png';
break;
case '2':
name = 'tram.png';
break;
case '6':
name = 'metro.png';
break;
case '7':
name = 'ferry.png';
break;
case '12':
name = 'train.png';
break;
}
return 'static/images/' + name;
};
Neverlate.getEndIcon = function() {
return 'static/images/end.png';
};
Neverlate.parseShape = function(shapes){
var shapeCoords=[];
shapes.forEach(function(shape){
shapeCoords.push(new google.maps.LatLng(shape.y, shape.x));
});
return shapeCoords;
};
Neverlate.formatStopInfo = function(precedingLeg, followingLeg) {
var result = '';
if (precedingLeg != null) { // this is not the beginning
var lastloc = Neverlate.lastLoc(precedingLeg);
result += 'Arrival'
if (typeof lastloc.name != 'undefined') {
result += ' to ' + lastloc.name;
}
result += ' at '
result += Neverlate.formatReittiopasTime(lastloc.arrTime) + '<br>';
}
if (followingLeg != null) { // this is not the end
if (followingLeg.type == 'walk') {
var lastloc = Neverlate.lastLoc(followingLeg);
result += 'Leave'
if (typeof lastloc.name != 'undefined') {
result += ' towards ' + lastloc.name
}
result += ' at ';
} else {
result += Neverlate.formatLineCode(followingLeg) + ' leaves at ';
}
result += Neverlate.formatReittiopasTime(followingLeg.locs[0].depTime) + '<br>';
}
return result;
}
/*
* Returns a string that tries to specify the line of the leg in a user-friendly manner.
*/
Neverlate.formatLineCode = function(leg) {
switch (leg.type) {
case '1':case '3':case '4':case '5':case '8':case '21':case '22':case '23':case '24':case '25':case '36':case '39': // bus
return leg.code.slice(1, 6).trim().replace(/^0+/, '');
case '2': // tram
return leg.code.slice(1, 6).trim().replace(/^0+/, '');
case '6': // metro
return "A metro train";
case '7': // ferry
return "A ferry";
case '12': // commuter train
return leg.code.slice(1, 6).trim().replace(/^[0-9]+/, '') + ' train';
}
return "Unspecified transport";
}
/* returns the last location in the leg that includes location name */
Neverlate.lastLoc = function(leg) {
for (var i = leg.locs.length; i-- > 0; ) {
if (leg.locs[i].name != null) {
return leg.locs[i];
}
}
return leg.locs[leg.locs.length-1]; // if none of the legs include a name, just return the last one
}
Neverlate.formatReittiopasTime = function(time) {
// extract HH:MM
return time.toString().slice(8, 10) + ':' + time.toString().slice(10, 12);
}
Neverlate.addInfoWindow = function(trigger, content, map){
if (!infowindow) infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(trigger, 'click', function() {
infowindow.close();
// if the same marker was clicked again, just close the window
if (infowindowtrigger === trigger) {
infowindowtrigger = null;
} else {
infowindowtrigger = trigger;
infowindow.setContent('<span class="infowindow">' + content + '</span>');
infowindow.open(map, trigger);
}
});
};
Neverlate.asyncUpdateDashboardState = function(){
var appointments = null;
$.get(
url = 'appointments',
success = function(response) {
appointments = JSON.parse(response);
if (aliases != null) // got both
Neverlate.updateDashboardState(appointments);
});
$.get(
url = 'aliases',
success = function(response) {
aliases = JSON.parse(response);
if (appointments != null) // got both
Neverlate.updateDashboardState(appointments);
});
};
Neverlate.updateDashboardState = function(appointments) {
$('.datepanel').remove();
// Filter old appointments
appointments = appointments.filter(function (appointment, index, array){
if (index != 0 && appointment.fields.location == array[index-1].fields.location) {
// Filter repeating locations, no need to show transfers for those
return false;
}
return new Date() < new Date(appointment.fields.start_time);
});
var printedDays = [];
$(".jumboroute").each(function(i) { // for each appointment to be shown
var appointment = appointments[i];
if (!appointment) {
if (i == 0) {
$(this).html(
'No next appointments found. Setup calendar in your <a href="profile">profile</a>.');
return;
}
this.remove();
return;
}
appointment = appointment.fields;
var startDate = new Date(appointment.start_time);
if (printedDays.indexOf(startDate.getDate()) == -1) {
printedDays.push(startDate.getDate());
$(this).before('<div class="panel panel-default datepanel">' +
'<div class="panel-heading">' +
'<h2 class="panel-title">' +
startDate.toDateString() +
'</h2>' +
'</div>' +
'</div>');
}
var from = Neverlate.userCoords;
if (i != 0) {
from = appointments[i-1].fields.location;
}
var to = appointment.location;
jumboroute_to_appointment[hash($(this)[0])] = appointment;
Neverlate.loadRouteByAddress(from, to, $(this)[0], startDate);
});
};
/* Takes a location and an array of aliases. If the location matches
* any of the aliases, the resolved address is returned. Otherwise
* returns the given location.
*/
Neverlate.resolveLocation = function(location, aliases) {
var resolved = aliases.filter(function(alias) {
return alias.fields.alias == location;
});
if (resolved.length > 0) {
return resolved[0].fields.location;
} else {
return location;
}
};
Neverlate.getRouteDepartureTime = function(route) {
return Neverlate.formatReittiopasTime(route.legs[0].locs[0].depTime);
};
Neverlate.updateRoutePanel = function(jumboroute, route) {
var panel = $('.panel', jumboroute);
var legs = route.legs;
var appointment = jumboroute_to_appointment[hash(jumboroute)];
panel.find('a').html("Depart " + Neverlate.getRouteDepartureTime(route) +
" for " + appointment.summary + " at " + appointment.location);
// sometimes the first leg doesn't have a name in any locations
var nextLeg = legs[1];
var nextLegLocations = [];
if (nextLeg) {
nextLegLocations = nextLeg.locs;
}
var locationsWithName = legs[0].locs.concat(nextLegLocations).filter(function( location ) {
return location.name;
});
panel.find('#fromLabel').html(locationsWithName[0].name);
panel.find('#toLabel').html(appointment.location);
var arrival = Neverlate.formatReittiopasTime(Neverlate.lastLoc(legs[legs.length-1]).arrTime);
panel.find('#arrivalLabel').html(arrival);
panel.find('#durationLabel').html((route.duration / 60) + " minutes");
var stopLabel = panel.find('#stopsLabel');
stopLabel.html('');
[null].concat(legs).concat(null).forEach(function (leg, index, array) {
if (index!=0) {
stopLabel.append("<div class=\"stop\">" + Neverlate.formatStopInfo(array[index-1], array[index])+"</div>");
}
});
};
Neverlate.changeStartLocation = function(jumboroutearray) {
var currentStartLocation = jumboroutearray.find('#fromLabel').text();
var jumboroute = jumboroutearray[0];
var startLocation = prompt("New start location", currentStartLocation);
if (startLocation != null) {
var appointment = jumboroute_to_appointment[hash(jumboroute)];
Neverlate.loadRouteByAddress(startLocation, appointment.location, jumboroute, new Date(appointment.start_time));
}
};
Neverlate.changeDestination = function(jumboroutearray) {
var jumboroute = jumboroutearray[0];
var appointment = jumboroute_to_appointment[hash(jumboroute)];
var destination = prompt("New destination", appointment.location);
if (destination != null) {
var currentStartLocation = jumboroutearray.find('#fromLabel').text();
Neverlate.loadRouteByAddress(currentStartLocation, destination,
jumboroute, new Date(appointment.start_time));
}
};
Neverlate.loadMoreAppointments = function() {
var jumbotron = $('.jumbotron')[$('.jumbotron').length-1].outerHTML;
// We have to increment the panel collapse id
var newJumbotron = jumbotron.replace(/collapse(\d+)+/g, function(match, number) {
return 'collapse' + (parseInt(number)+1);
});
$('.row').append(newJumbotron);
$('.jumbotron').find('.map-canvas').html('');
Neverlate.asyncUpdateDashboardState();
};
| myrjola/neverlate | django/static/js/Neverlate.js | JavaScript | mit | 20,936 |
// @flow
import type {TypedPropertyDescriptor} from './interfaces'
import {rdiProp} from './interfaces'
export default function props<P: Object>(
proto: P,
name: string,
descr: TypedPropertyDescriptor<*>,
) {
proto.constructor[rdiProp] = name
if (!descr.value && !descr.set) {
descr.writable = true
}
}
| zerkalica/reactive-di | src/props.js | JavaScript | mit | 336 |
var dirtybit = require('../')
var test = require('tape')
test('change', function (t) {
t.plan(3)
var instance = dirtybit({a: []})
var count = 0
instance.on('a', function (list) {
t.equal(list.length, count++)
})
instance.state.a.push(count)
instance.update(instance.state)
instance.state.a.push(count)
instance.update(instance.state)
})
| hayes/dirtybit | test/changes.test.js | JavaScript | mit | 364 |
/**
* @author Luciano Graziani @lgraziani2712
* @license {@link http://www.opensource.org/licenses/mit-license.php|MIT License}
*
* @flow
*/
import { type Container, Point } from 'pixi.js';
import { TimelineLite, Linear, SlowMo } from 'gsap';
import { ZERO, TWO, HALF, DEFAULT_MOVEMENT_DURATION } from 'core/constants/numbers';
import {
type CodimoComponent,
type FunctionalityBuilder,
} from 'core/engines/pixijs/components/componentGenerator';
const GLOBAL_POINT = new Point();
const JUMP_DURATION = 0.4;
/**
* It adds to the actor the possibility to jump to the numeric line.
*
* @version 1.0.0
* @param {number} size Block's size.
* @param {number} margin Block's margin.
* @param {CodimoComponent} component The component to add the functionality.
* @return {Functionality} The functionality itself.
*/
const enterToNumericLineFunctionalityBuilder: FunctionalityBuilder = (
size: number,
margin: number,
component: CodimoComponent,
) => {
if (typeof component.position !== 'string') {
throw new Error(
// eslint-disable-next-line max-len
'`enterToNumericLine` functionality requires the component to have the `positioning` functionality',
);
}
return {
enterToNumericLine(emptyBlock: Container): Promise<void> {
this.position = '';
const localPosition = emptyBlock.toLocal(GLOBAL_POINT, this.view);
this.view.setParent(emptyBlock);
this.view.position = localPosition;
return new Promise((onComplete) => {
const timeline = new TimelineLite({
onComplete,
});
timeline
.to(this.view, DEFAULT_MOVEMENT_DURATION, {
y: size / HALF,
x: size / HALF,
ease: Linear.easeNone,
})
.to(this.view.scale, DEFAULT_MOVEMENT_DURATION, {
x: this.view.scale.x * TWO,
y: this.view.scale.y * TWO,
ease: SlowMo.ease.config(JUMP_DURATION, ZERO, true),
}, ZERO);
});
},
};
};
export default enterToNumericLineFunctionalityBuilder;
| lgraziani2712/codimo | activities/NumericLine/engine/components/functionalities/enterToNumericLineFunctionalityBuilder.js | JavaScript | mit | 2,059 |
/* eslint-disable max-len */
/**
* Build config for development process that uses Hot-Module-Replacement
* https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
*/
import webpack from 'webpack';
import validate from 'webpack-validator';
import merge from 'webpack-merge';
import formatter from 'eslint-formatter-pretty';
import baseConfig from './webpack.config.base';
const port = process.env.PORT || 3000;
export default validate(merge(baseConfig, {
debug: true,
devtool: 'inline-source-map',
entry: [
`webpack-hot-middleware/client?path=http://localhost:${port}/__webpack_hmr`,
'babel-polyfill',
'./app/index'
],
output: {
publicPath: `http://localhost:${port}/dist/`
},
module: {
loaders: [
{
test: /\.global\.css$/,
loaders: [
'style-loader',
'css-loader?sourceMap'
]
},
{
test: /^((?!\.global).)*\.css$/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
],
exclude: /(node_modules)/
},
{
test: /(\.scss|\.css)$/,
include: /(node_modules)/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass-loader'
]
},
// Fonts
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
},
]
},
eslint: {
formatter
},
plugins: [
// https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
new webpack.HotModuleReplacementPlugin(),
// “If you are using the CLI, the webpack process will not exit with an error code by enabling this plugin.”
// https://github.com/webpack/docs/wiki/list-of-plugins#noerrorsplugin
new webpack.NoErrorsPlugin(),
// NODE_ENV should be production so that modules do not perform certain development checks
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
// https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
target: 'electron-renderer'
}));
| romankhrystynych/raspitron | webpack.config.development.js | JavaScript | mit | 2,756 |
var client = require('rpcls/client');
var signs = require('rpcls/rules').signs;
var msg = require('rpcls/message');
function voidFunction() {}
describe('Client module', function() {
describe('Client state machine', function() {
beforeEach(function() {
this.socket = {
write: voidFunction,
actions: [],
on: function(key, action) {
if (key == 'data') this.actions.push(action);
},
execute: function(message) {
for (var actionIndex in this.actions) {
this.actions[actionIndex].call(this, message);
}
}
};
this.manager = {
createGame: null
, joinGame: null
};
spyOn(this.manager, 'createGame');
spyOn(this.manager, 'joinGame');
});
describe('at start', function() {
beforeEach(function() {
this.client = new client.Client(this.manager, this.socket, 42);
spyOn(this.client, 'sendError');
});
it('accept create action at start', function() {
this.socket.execute(msg.encode('client', { command: 'create' }));
expect(this.manager.createGame).toHaveBeenCalledWith(this.client);
expect(this.client.sendError).not.toHaveBeenCalled();
// this.socket.execute(msg.encode('client', { command: 'create' }));
// expect(this.client.sendError).toHaveBeenCalled();
});
it('accepts join action at start', function() {
var gameId = 12;
this.socket.execute(msg.encode('client', { command: 'join', args: [ gameId ] }));
expect(this.manager.joinGame).toHaveBeenCalledWith(gameId, this.client);
expect(this.client.sendError).not.toHaveBeenCalled();
// this.socket.execute(msg.encode('client', { command: 'create' }));
// expect(this.client.sendError).toHaveBeenCalled();
});
it('rejects all actions but create/join', function() {
this.socket.execute(msg.encode({ command: 'play' }));
this.socket.execute(msg.encode({ command: 'test' }));
this.socket.execute(msg.encode({ command: 'welcome' }));
expect(this.client.sendError.calls.length).toEqual(3);
});
});
describe('when connected to a game', function() {
beforeEach(function() {
this.client = new client.Client(this.manager, this.socket, 42);
spyOn(this.client, 'sendError');
this.referee = {
play: voidFunction
};
spyOn(this.referee, 'play');
this.client.referee = this.referee;
});
it('plays after creating a game', function() {
this.socket.execute(msg.encode('client', { command: 'create' }));
this.client.askToPlay();
this.socket.execute(msg.encode('client', { command: 'play', args: [ signs.ROCK ] }));
expect(this.client.sendError).not.toHaveBeenCalled();
expect(this.referee.play).toHaveBeenCalledWith(this.client, signs.ROCK);
});
it('plays after joining a game'), function() {
this.socket.execute(msg.encode('client', { command: 'join', args: [ 1234 ] }));
this.client.askToPlay();
this.socket.execute(msg.encode('client', { command: 'play', args: [ signs.ROCK ] }));
expect(this.client.sendError).not.toHaveBeenCalled();
expect(this.referee.play).toHaveBeenCalledWith(this.client, signs.ROCK);
};
it('only accepts sign if asked', function() {
this.socket.execute(msg.encode('client', { command: 'create' }));
// do not ask to play
this.socket.execute(msg.encode('client', { command: 'play', args: [ signs.ROCK ] }));
expect(this.client.sendError).toHaveBeenCalled();
// ask this time but do not play twice
this.client.askToPlay();
this.socket.execute(msg.encode('client', { command: 'play', args: [ signs.ROCK ] }));
expect(this.client.sendError.calls.length).toEqual(1);
this.socket.execute(msg.encode('client', { command: 'play', args: [ signs.ROCK ] }));
expect(this.client.sendError.calls.length).toEqual(2);
});
it('rejects all actions but play', function() {
this.socket.execute(msg.encode('client', { command: 'create' }));
this.socket.execute(msg.encode('client', { command: 'create' }));
this.socket.execute(msg.encode('client', { command: 'join', args: [ 12 ] }));
this.socket.execute(msg.encode('client', { command: 'hello' }));
expect(this.client.sendError.calls.length).toEqual(3);
});
});
});
describe('Client messages', function() {
beforeEach(function() {
this.socket = { write: null, on: voidFunction };
spyOn(this.socket, 'write');
this.client = new client.Client(null, this.socket, 42);
});
it('sends client in on creation', function() {
var expectMessage = msg.encode('Server', { command: 'id', args: [ 42 ] });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectMessage ]);
});
it('notifies on game creation', function() {
this.client.gameCreated(1234);
var expectedmessage = msg.encode('Server', { command: 'game', args: [ 1234 ] });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedmessage ]);
});
it('notifies on game connection', function() {
this.client.gameJoined();
var expectedmessage = msg.encode('Server', { command: 'joined' });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedmessage ]);
});
it('ask client to play', function() {
this.client.askToPlay();
var expectedMessage = msg.encode('Server', { command: 'play' });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
});
it('send client the result of a set', function() {
this.client.winSet(signs.ROCK);
var expectedMessage = msg.encode('Server', { command: 'win', args: [ signs.ROCK ] });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
this.client.loseSet(signs.ROCK);
var expectedMessage = msg.encode('Server', { command: 'lose', args: [ signs.ROCK ] });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
this.client.deuce();
var expectedMessage = msg.encode('Server', { command: 'deuce' });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
});
it('notifies client of victory', function() {
this.client.win();
var expectedMessage = msg.encode('Server', { command: 'victory' });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
});
it('notifies client of defeat', function() {
this.client.lose();
var expectedMessage = msg.encode('Server', { command: 'defeat' });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
});
it('sends errors', function() {
var error = 'This is a mistake';
this.client.sendError(error);
var expectedMessage = msg.encode('Server', { command: 'error', args: [ error ] });
expect(this.socket.write.mostRecentCall.args).toEqual([ expectedMessage ]);
});
});
});
| Kineolyan/rpcls | spec/rpcls/client/client-spec.js | JavaScript | mit | 7,038 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="9" cy="8" r="4" /><path d="M9 14c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4zm11-4V7h-2v3h-3v2h3v3h2v-3h3v-2z" /></React.Fragment>
, 'PersonAddAlt1Rounded');
| callemall/material-ui | packages/material-ui-icons/src/PersonAddAlt1Rounded.js | JavaScript | mit | 334 |
import { Router } from 'backbone';
export default Router.extend({
});
| byCedric/generator-fouraxes | generators/app/templates/app/_router.js | JavaScript | mit | 72 |
function loginController($scope, $state, $stateParams, LoginService) {
this.errors = [];
this.model = {
username: null,
password: null
};
if (LoginService.isLoggedIn()) {
$state.go('home');
}
this.login = () => {
return LoginService.loginRequest(this.model).then(result => {
$state.go('home');
}).catch(err => {
if (err.errors) {
this.errors = Object.keys(err.errors).map(key => err.errors[key]);
} else {
this.errors = ['Registration failed, please try again later'];
}
$scope.$digest();
});
};
}
module.exports = {
name: 'loginController',
fn: ['$scope', '$state', '$stateParams', 'LoginService', loginController]
}
| sjt88/express-angular1-webpack-massive-boilerplate | client/src/js/controllers/login.controller.js | JavaScript | mit | 710 |
/* utils.coffee */
(function() {
var async, extend, fileExists, fileExistsSync, fs, path, pump, readJSON, readJSONSync, readdirRecursive, rfc822, stripExtension, util;
util = require('util');
fs = require('fs');
path = require('path');
async = require('async');
fileExists = fs.exists || path.exists;
fileExistsSync = fs.existsSync || path.existsSync;
extend = function(obj, mixin) {
var method, name;
for (name in mixin) {
method = mixin[name];
obj[name] = method;
}
};
stripExtension = function(filename) {
/* Remove the file-extension from *filename* */
return filename.replace(/(.+)\.[^.]+$/, '$1');
};
readJSON = function(filename, callback) {
/* Read and try to parse *filename* as JSON, *callback* with parsed object or error on fault. */
return async.waterfall([
function(callback) {
return fs.readFile(filename, callback);
}, function(buffer, callback) {
var error, rv;
try {
rv = JSON.parse(buffer.toString());
return callback(null, rv);
} catch (error1) {
error = error1;
error.filename = filename;
error.message = "parsing " + (path.basename(filename)) + ": " + error.message;
return callback(error);
}
}
], callback);
};
readJSONSync = function(filename) {
/* Synchronously read and try to parse *filename* as json. */
var buffer;
buffer = fs.readFileSync(filename);
return JSON.parse(buffer.toString());
};
readdirRecursive = function(directory, callback) {
/* Returns an array representing *directory*, including subdirectories. */
var result, walk;
result = [];
walk = function(dir, callback) {
return async.waterfall([
async.apply(fs.readdir, path.join(directory, dir)), function(filenames, callback) {
return async.forEach(filenames, function(filename, callback) {
var relname;
relname = path.join(dir, filename);
return async.waterfall([
async.apply(fs.stat, path.join(directory, relname)), function(stat, callback) {
if (stat.isDirectory()) {
return walk(relname, callback);
} else {
result.push(relname);
return callback();
}
}
], callback);
}, callback);
}
], callback);
};
return walk('', function(error) {
return callback(error, result);
});
};
pump = function(source, destination, callback) {
/* Pipe *source* stream to *destination* stream calling *callback* when done */
source.pipe(destination);
source.on('error', function(error) {
if (typeof callback === "function") {
callback(error);
}
return callback = null;
});
return destination.on('finish', function() {
if (typeof callback === "function") {
callback();
}
return callback = null;
});
};
rfc822 = function(date) {
/* return a rfc822 representation of a javascript Date object
http://www.w3.org/Protocols/rfc822/#z28
*/
var days, months, pad, time, tzoffset;
pad = function(i) {
if (i < 10) {
return '0' + i;
} else {
return i;
}
};
tzoffset = function(offset) {
var direction, hours, minutes;
hours = Math.floor(offset / 60);
minutes = Math.abs(offset % 60);
direction = hours > 0 ? '-' : '+';
return direction + pad(Math.abs(hours)) + pad(minutes);
};
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', ' Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
time = [pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds())].join(':');
return [days[date.getDay()] + ',', pad(date.getDate()), months[date.getMonth()], date.getFullYear(), time, tzoffset(date.getTimezoneOffset())].join(' ');
};
/* Exports */
module.exports = {
fileExists: fileExists,
fileExistsSync: fileExistsSync,
extend: extend,
stripExtension: stripExtension,
readJSON: readJSON,
readJSONSync: readJSONSync,
readdirRecursive: readdirRecursive,
pump: pump,
rfc822: rfc822
};
}).call(this);
| Dackng/eh-unmsm-client | node_modules/wintersmith/lib/core/utils.js | JavaScript | mit | 4,345 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
import vvue from '../src/index'
Vue.use(vvue)
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
| lisiur/vvue | test/main.js | JavaScript | mit | 367 |
/*! jQuery UI - v1.10.4 - 2014-05-01
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.position.js, jquery.ui.autocomplete.js, jquery.ui.menu.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function( $, undefined ) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.10.4",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
uniqueId: function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if ( runiqueId.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
plugin: {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var i,
set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
}
});
})( jQuery );
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-x" ),
overflowY = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] ),
isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
return {
element: withinElement,
isWindow: isWindow,
isDocument: isDocument,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
(function( $, undefined ) {
$.widget( "ui.autocomplete", {
version: "1.10.4",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
requestIndex: 0,
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[0].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
this.isMultiLine =
// Textareas are always multi-line
isTextarea ? true :
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
isInput ? false :
// All other element types are determined by whether or not they're contentEditable
this.element.prop( "isContentEditable" );
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" );
this._on( this.element, {
keydown: function( event ) {
if ( this.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent( "next", event );
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
case keyCode.TAB:
if ( this.menu.active ) {
this.menu.select( event );
}
break;
case keyCode.ESCAPE:
if ( this.menu.element.is( ":visible" ) ) {
this._value( this.term );
this.close( event );
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
},
keypress: function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
event.preventDefault();
}
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
this._move( "nextPage", event );
break;
case keyCode.UP:
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
this._keyEvent( "next", event );
break;
}
},
input: function( event ) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout( event );
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
clearTimeout( this.searching );
this.close( event );
this._change( event );
}
});
this._initSource();
this.menu = $( "<ul>" )
.addClass( "ui-autocomplete ui-front" )
.appendTo( this._appendTo() )
.menu({
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.data( "ui-menu" );
this._on( this.menu.element, {
mousedown: function( event ) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
});
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = this.menu.element[ 0 ];
if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
this._delay(function() {
var that = this;
this.document.one( "mousedown", function( event ) {
if ( event.target !== that.element[ 0 ] &&
event.target !== menuElement &&
!$.contains( menuElement, event.target ) ) {
that.close();
}
});
});
}
},
menufocus: function( event, ui ) {
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if ( this.isNewMenu ) {
this.isNewMenu = false;
if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
this.menu.blur();
this.document.one( "mousemove", function() {
$( event.target ).trigger( event.originalEvent );
});
return;
}
}
var item = ui.item.data( "ui-autocomplete-item" );
if ( false !== this._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
this._value( item.value );
}
} else {
// Normally the input is populated with the item's value as the
// menu is navigated, causing screen readers to notice a change and
// announce the item. Since the focus event was canceled, this doesn't
// happen, so we update the live region so that screen readers can
// still notice the change and announce it.
this.liveRegion.text( item.value );
}
},
menuselect: function( event, ui ) {
var item = ui.item.data( "ui-autocomplete-item" ),
previous = this.previous;
// only trigger when focus was lost (click on menu)
if ( this.element[0] !== this.document[0].activeElement ) {
this.element.focus();
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay(function() {
this.previous = previous;
this.selectedItem = item;
});
}
if ( false !== this._trigger( "select", event, { item: item } ) ) {
this._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
}
});
this.liveRegion = $( "<span>", {
role: "status",
"aria-live": "polite"
})
.addClass( "ui-helper-hidden-accessible" )
.insertBefore( this.element );
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_destroy: function() {
clearTimeout( this.searching );
this.element
.removeClass( "ui-autocomplete-input" )
.removeAttr( "autocomplete" );
this.menu.element.remove();
this.liveRegion.remove();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this._appendTo() );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element ) {
element = element.jquery || element.nodeType ?
$( element ) :
this.document.find( element ).eq( 0 );
}
if ( !element ) {
element = this.element.closest( ".ui-front" );
}
if ( !element.length ) {
element = this.document[0].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() {
// only search if the value has changed
if ( this.term !== this._value() ) {
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this.element.addClass( "ui-autocomplete-loading" );
this.cancelSearch = false;
this.source( { term: value }, this._response() );
},
_response: function() {
var index = ++this.requestIndex;
return $.proxy(function( content ) {
if ( index === this.requestIndex ) {
this.__response( content );
}
this.pending--;
if ( !this.pending ) {
this.element.removeClass( "ui-autocomplete-loading" );
}
}, this );
},
__response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
this._suggest( content );
this._trigger( "open" );
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function( event ) {
this.cancelSearch = true;
this._close( event );
},
_close: function( event ) {
if ( this.menu.element.is( ":visible" ) ) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[0].label && items[0].value ) {
return items;
}
return $.map( items, function( item ) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item );
});
},
_suggest: function( items ) {
var ul = this.menu.element.empty();
this._renderMenu( ul, items );
this.isNewMenu = true;
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ));
if ( this.options.autoFocus ) {
this.menu.next();
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
},
_renderItemData: function( ul, item ) {
return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},
_renderItem: function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is( ":visible" ) ) {
this.search( null, event );
return;
}
if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
this.menu.isLastItem() && /^next/.test( direction ) ) {
this._value( this.term );
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply( this.element, arguments );
},
_keyEvent: function( keyEvent, event ) {
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
this._move( keyEvent, event );
// prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
}
});
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
},
filter: function(array, term) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( value.label || value.value || value );
});
}
});
// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function( amount ) {
return amount + ( amount > 1 ? " results are" : " result is" ) +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function( content ) {
var message;
this._superApply( arguments );
if ( this.options.disabled || this.cancelSearch ) {
return;
}
if ( content && content.length ) {
message = this.options.messages.results( content.length );
} else {
message = this.options.messages.noResults;
}
this.liveRegion.text( message );
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "ui.menu", {
version: "1.10.4",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
menus: "ul",
position: {
my: "left top",
at: "right top"
},
role: "menu",
// callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
.attr({
role: this.options.role,
tabIndex: 0
})
// need to catch all clicks on disabled menu
// not possible through _on
.bind( "click" + this.eventNamespace, $.proxy(function( event ) {
if ( this.options.disabled ) {
event.preventDefault();
}
}, this ));
if ( this.options.disabled ) {
this.element
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
}
this._on({
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item > a": function( event ) {
event.preventDefault();
},
"click .ui-state-disabled > a": function( event ) {
event.preventDefault();
},
"click .ui-menu-item:has(a)": function( event ) {
var target = $( event.target ).closest( ".ui-menu-item" );
if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
this.select( event );
// Only set the mouseHandled flag if the event will bubble, see #9469.
if ( !event.isPropagationStopped() ) {
this.mouseHandled = true;
}
// Open submenu on click
if ( target.has( ".ui-menu" ).length ) {
this.expand( event );
} else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {
// Redirect focus to the menu
this.element.trigger( "focus", [ true ] );
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
clearTimeout( this.timer );
}
}
}
},
"mouseenter .ui-menu-item": function( event ) {
var target = $( event.currentTarget );
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
if ( !keepActiveItem ) {
this.focus( event, item );
}
},
blur: function( event ) {
this._delay(function() {
if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
this.collapseAll( event );
}
});
},
keydown: "_keydown"
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on( this.document, {
click: function( event ) {
if ( !$( event.target ).closest( ".ui-menu" ).length ) {
this.collapseAll( event );
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
_destroy: function() {
// Destroy (sub)menus
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" ).addBack()
.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-disabled" )
.removeUniqueId()
.show();
// Destroy menu items
this.element.find( ".ui-menu-item" )
.removeClass( "ui-menu-item" )
.removeAttr( "role" )
.removeAttr( "aria-disabled" )
.children( "a" )
.removeUniqueId()
.removeClass( "ui-corner-all ui-state-hover" )
.removeAttr( "tabIndex" )
.removeAttr( "role" )
.removeAttr( "aria-haspopup" )
.children().each( function() {
var elem = $( this );
if ( elem.data( "ui-menu-submenu-carat" ) ) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
},
_keydown: function( event ) {
var match, prev, character, skip, regex,
preventDefault = true;
function escape( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break;
case $.ui.keyCode.UP:
this.previous( event );
break;
case $.ui.keyCode.DOWN:
this.next( event );
break;
case $.ui.keyCode.LEFT:
this.collapse( event );
break;
case $.ui.keyCode.RIGHT:
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
this.expand( event );
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode( event.keyCode );
skip = false;
clearTimeout( this.filterTimer );
if ( character === prev ) {
skip = true;
} else {
character = prev + character;
}
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
match = skip && match.index( this.active.next() ) !== -1 ?
this.active.nextAll( ".ui-menu-item" ) :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if ( !match.length ) {
character = String.fromCharCode( event.keyCode );
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
}
if ( match.length ) {
this.focus( event, match );
if ( match.length > 1 ) {
this.previousFilter = character;
this.filterTimer = this._delay(function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
if ( preventDefault ) {
event.preventDefault();
}
},
_activate: function( event ) {
if ( !this.active.is( ".ui-state-disabled" ) ) {
if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
this.expand( event );
} else {
this.select( event );
}
}
},
refresh: function() {
var menus,
icon = this.options.icons.submenu,
submenus = this.element.find( this.options.menus );
this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );
// Initialize nested menus
submenus.filter( ":not(.ui-menu)" )
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.hide()
.attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
})
.each(function() {
var menu = $( this ),
item = menu.prev( "a" ),
submenuCarat = $( "<span>" )
.addClass( "ui-menu-icon ui-icon " + icon )
.data( "ui-menu-submenu-carat", true );
item
.attr( "aria-haspopup", "true" )
.prepend( submenuCarat );
menu.attr( "aria-labelledby", item.attr( "id" ) );
});
menus = submenus.add( this.element );
// Don't refresh list items that are already adapted
menus.children( ":not(.ui-menu-item):has(a)" )
.addClass( "ui-menu-item" )
.attr( "role", "presentation" )
.children( "a" )
.uniqueId()
.addClass( "ui-corner-all" )
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
menus.children( ":not(.ui-menu-item)" ).each(function() {
var item = $( this );
// hyphen, em dash, en dash
if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
item.addClass( "ui-widget-content ui-menu-divider" );
}
});
// Add aria-disabled attribute to any disabled menu item
menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
// If the active item has been removed, blur the menu
if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function( key, value ) {
if ( key === "icons" ) {
this.element.find( ".ui-menu-icon" )
.removeClass( this.options.icons.submenu )
.addClass( value.submenu );
}
this._super( key, value );
},
focus: function( event, item ) {
var nested, focused;
this.blur( event, event && event.type === "focus" );
this._scrollIntoView( item );
this.active = item.first();
focused = this.active.children( "a" ).addClass( "ui-state-focus" );
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if ( this.options.role ) {
this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest( ".ui-menu-item" )
.children( "a:first" )
.addClass( "ui-state-active" );
if ( event && event.type === "keydown" ) {
this._close();
} else {
this.timer = this._delay(function() {
this._close();
}, this.delay );
}
nested = item.children( ".ui-menu" );
if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
_scrollIntoView: function( item ) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if ( this._hasScroll() ) {
borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.height();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
},
blur: function( event, fromFocus ) {
if ( !fromFocus ) {
clearTimeout( this.timer );
}
if ( !this.active ) {
return;
}
this.active.children( "a" ).removeClass( "ui-state-focus" );
this.active = null;
this._trigger( "blur", event, { item: this.active } );
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay(function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
var position = $.extend({
of: this.active
}, this.options.position );
clearTimeout( this.timer );
this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
.hide()
.attr( "aria-hidden", "true" );
submenu
.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
clearTimeout( this.timer );
this.timer = this._delay(function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
this.activeMenu = currentMenu;
}, this.delay );
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" )
.end()
.find( "a.ui-state-active" )
.removeClass( "ui-state-active" );
},
collapse: function( event ) {
var newItem = this.active &&
this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
}
},
expand: function( event ) {
var newItem = this.active &&
this.active
.children( ".ui-menu " )
.children( ".ui-menu-item" )
.first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function() {
this.focus( event, newItem );
});
}
},
next: function( event ) {
this._move( "next", "first", event );
},
previous: function( event ) {
this._move( "prev", "last", event );
},
isFirstItem: function() {
return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
},
isLastItem: function() {
return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
},
_move: function( direction, filter, event ) {
var next;
if ( this.active ) {
if ( direction === "first" || direction === "last" ) {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
.eq( -1 );
} else {
next = this.active
[ direction + "All" ]( ".ui-menu-item" )
.eq( 0 );
}
}
if ( !next || !next.length || !this.active ) {
next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
}
this.focus( event, next );
},
nextPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isLastItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base - height < 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isFirstItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base + height > 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
var ui = { item: this.active };
if ( !this.active.has( ".ui-menu" ).length ) {
this.collapseAll( event, true );
}
this._trigger( "select", event, ui );
}
});
}( jQuery ));
| sidmal/realtor.lo | app/Application/Sonata/UserBundle/Resources/public/js/jquery-ui-1.10.4.custom.js | JavaScript | mit | 70,787 |
define(["require", "exports", "tslib", "../aurelia"], function (require, exports, tslib_1, au) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MdCharCounter = /** @class */ (function () {
function MdCharCounter(element) {
this.element = element;
this.length = 120;
this.instances = [];
this.attributeManager = new au.AttributeManager(this.element);
}
MdCharCounter.prototype.attached = function () {
var _this = this;
// attach to input and textarea elements explicitly, so this counter can be
// used on containers (or custom elements like md-input)
var tagName = this.element.tagName.toUpperCase();
if (tagName === "INPUT" || tagName === "TEXTAREA") {
this.attributeManager.addAttributes({ "data-length": this.length });
this.instances.push(new M.CharacterCounter(this.element));
}
else {
var elem = Array.from(this.element.querySelectorAll("input,textarea"));
elem.forEach(function (el) {
el.setAttribute("data-length", _this.length.toString());
_this.instances.push(new M.CharacterCounter(el));
});
}
};
MdCharCounter.prototype.detached = function () {
this.instances.forEach(function (x) { return x.destroy(); });
this.attributeManager.removeAttributes(["data-length"]);
};
tslib_1.__decorate([
au.ato.bindable.numberMd,
tslib_1.__metadata("design:type", Number)
], MdCharCounter.prototype, "length", void 0);
MdCharCounter = tslib_1.__decorate([
au.customAttribute("md-char-counter"),
au.autoinject,
tslib_1.__metadata("design:paramtypes", [Element])
], MdCharCounter);
return MdCharCounter;
}());
exports.MdCharCounter = MdCharCounter;
});
//# sourceMappingURL=char-counter.js.map | aurelia-ui-toolkits/aurelia-materialize-bridge | dist/amd/char-counter/char-counter.js | JavaScript | mit | 2,122 |
module.exports={
"Cleaning": {
"path": "./",
"cmd": [
"rm -rf ./dist/",
"rm trollshell.zip"
]
},
"Copying src to dist": {
"path": "./",
"cmd": [
"cp -r ./src/ ./dist/",
"cp ./config.json ./dist/"
]
},
"Downloading libraries": {
"path": "./dist/lib",
"cmd": [
"curl https://netix.dl.sourceforge.net/project/iharder/imagesnap/ImageSnap-v0.2.5.tgz > imagesnap.tgz",
"curl https://nodejs.org/download/release/v8.9.3/node-v8.9.3-darwin-x64.tar.gz > node.tar.gz"
]
},
"Unpacking": {
"path": "./dist/lib",
"cmd": [
"gunzip -c node.tar.gz | tar xopf -",
"mv node-v8.9.3-darwin-x64/ node/",
"rm node.tar.gz",
"gunzip -c imagesnap.tgz | tar xopf -",
"mv ImageSnap-v0.2.5/imagesnap ./",
"rm -rf Imagesnap-v0.2.5",
"rm imagesnap.tgz"
]
},
"Removing unwanted files": {
"path": "./dist",
"cmd": [
"find . -name '.DS_Store' -type f -delete",
"find . -name 'notes.md' -type f -delete"
]
},
"Downloading font": {
"path": "./dist/public",
"cmd": [
"curl https://fonts.googleapis.com/css?family=Inconsolata > inconsolata.css"
]
},
"Minifying scripts": {
"path": "./dist",
"cmd": [
"find . -name \"*.js\" ! -path '*node_modules*' | xargs -I + -P100 -n1 node ../build/minify.js +"
]
},
"Packaging command modules": {
"path": "./dist",
"cmd": [
"node ../build/packModules.js",
"rm -rf ./commands/"
]
},
"Installing node modules": {
"path": "./dist/",
"cmd": [
"./lib/node/bin/node ./lib/node/lib/node_modules/npm/bin/npm-cli.js install --scripts-prepend-node-path",
"./lib/node/bin/node ./lib/node/lib/node_modules/npm/bin/npm-cli.js rebuild --scripts-prepend-node-path",
"npx electron-rebuild --version 2.0.6 --module-dir .",
"./lib/node/bin/node ../build/rensqlbuild.js"
]
},
"Removing package lock": {
"path": "./dist",
"cmd": [
"rm ./package-lock.json"
]
}
} | blixten26/Trollshell | build/buildScripts.js | JavaScript | mit | 2,348 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Box = require('./Box');
Object.defineProperty(exports, 'Box', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Box).default;
}
});
var _Button = require('./Button');
Object.defineProperty(exports, 'Button', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Button).default;
}
});
var _Code = require('./Code');
Object.defineProperty(exports, 'Code', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Code).default;
}
});
var _Component = require('./Component');
Object.defineProperty(exports, 'Component', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Component).default;
}
});
var _Container = require('./Container');
Object.defineProperty(exports, 'Container', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Container).default;
}
});
var _DateTimePicker = require('./DateTimePicker');
Object.defineProperty(exports, 'DateTimePicker', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_DateTimePicker).default;
}
});
var _Footer = require('./Footer');
Object.defineProperty(exports, 'Footer', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Footer).default;
}
});
var _Form = require('./Form');
Object.defineProperty(exports, 'Form', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Form).default;
}
});
var _FormField = require('./FormField');
Object.defineProperty(exports, 'FormField', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_FormField).default;
}
});
var _Icon = require('./Icon');
Object.defineProperty(exports, 'Icon', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Icon).default;
}
});
var _InputField = require('./InputField');
Object.defineProperty(exports, 'InputField', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_InputField).default;
}
});
var _Loader = require('./Loader');
Object.defineProperty(exports, 'Loader', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Loader).default;
}
});
var _NavBar = require('./NavBar');
Object.defineProperty(exports, 'NavBar', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_NavBar).default;
}
});
var _PreviewItem = require('./PreviewItem');
Object.defineProperty(exports, 'PreviewItem', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_PreviewItem).default;
}
});
var _SideBar = require('./SideBar');
Object.defineProperty(exports, 'SideBar', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_SideBar).default;
}
});
var _TagField = require('./TagField');
Object.defineProperty(exports, 'TagField', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_TagField).default;
}
});
var _TextEditor = require('./TextEditor');
Object.defineProperty(exports, 'TextEditor', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_TextEditor).default;
}
});
var _UploadField = require('./UploadField');
Object.defineProperty(exports, 'UploadField', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_UploadField).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | nitrog7/nl-fluid | lib/index.js | JavaScript | mit | 3,604 |
import React from 'react'
import { browserHistory } from 'react-router'
import { inject, observer } from 'mobx-react'
import Form from './Form'
@inject('projectsStore')
@inject('tagsStore')
@observer
export default class New extends React.Component {
constructor(props) {
super(props)
this.state = {
errors: []
}
}
handleSubmit(projectParams) {
this.props.projectsStore.create(projectParams).then((response) => {
if (response.status == 200) {
browserHistory.push('/projects')
}
}).catch((error) => {
if (error.response && error.response.data && error.response.data.errors) {
this.setState({
errors: error.response.data.errors
})
}
})
}
render() {
return (
<Form
tagsStore={ this.props.tagsStore }
allTags={ this.props.tagsStore.tags }
errors={ this.state.errors }
handleSubmit={ this.handleSubmit.bind(this) }
ref='projectForm'
/>
)
}
}
| appdev-academy/appdev.academy-react | src/js/components/Projects/New.js | JavaScript | mit | 1,008 |
import Button from '@mui/material/Button'
import Page from 'material-ui-shell/lib/containers/Page/Page'
import Paper from '@mui/material/Paper'
import React, { useState } from 'react'
import Scrollbar from 'material-ui-shell/lib/components/Scrollbar/Scrollbar'
import TextField from '@mui/material/TextField'
import { Typography } from '@mui/material'
import { useIntl } from 'react-intl'
import { useStorage } from 'rmw-shell/lib/providers/Firebase/Storage'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
const defaultPath = 'test_path'
const Storage = () => {
const intl = useIntl()
const [path, setPath] = useState(defaultPath)
const {
getUploadError,
isUploading,
getDownloadURL,
hasUploadError = () => {},
uploadFile,
clearUpload,
getUploadProgress,
} = useStorage()
const databaseValue = getDownloadURL(path)
const error = JSON.stringify(getUploadError(path))
const isLoading = isUploading(path)
const progress = getUploadProgress(path)
const handleImageUpload = (e) => {
const file = e.target.files[0]
if (file) {
clearUpload(path)
uploadFile(path, `${path}/${file.name}`, file)
}
}
return (
<Page
pageTitle={intl.formatMessage({
id: 'firebase_paths_demo',
defaultMessage: 'Firebase Paths Demo',
})}
>
<Scrollbar
style={{ height: '100%', width: '100%', display: 'flex', flex: 1 }}
>
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
<Paper
style={{
maxWidth: 450,
minWidth: 300,
minHeight: 300,
padding: 18,
}}
>
<TextField
label="Path"
value={path}
onChange={(e) => setPath(e.target.value)}
variant="outlined"
/>
<br />
<br />
{isLoading && (
<Box position="relative" display="inline-flex">
<CircularProgress variant="static" value={progress} />
<Box
top={0}
left={0}
bottom={0}
right={0}
position="absolute"
display="flex"
alignItems="center"
justifyContent="center"
>
<Typography
variant="caption"
component="div"
color="textSecondary"
>{`${Math.round(progress)}%`}</Typography>
</Box>
</Box>
)}
<br />
<br />
{databaseValue}
{databaseValue && (
<img style={{ maxWidth: 300 }} alt="value" src={databaseValue} />
)}
<br />
<br />
{hasUploadError(path) && (
<Typography variant="subtitle1" color="error">
Error: {error}
</Typography>
)}
<br />
<br />
<div>
<input
onChange={handleImageUpload}
accept="image/*"
style={{ display: 'none' }}
id="contained-button-file"
type="file"
/>
<label htmlFor="contained-button-file">
<Button
style={{ margin: 5 }}
variant="contained"
color="primary"
component="span"
>
UPLOAD
</Button>
</label>
</div>
</Paper>
</div>
</Scrollbar>
</Page>
)
}
export default Storage
| TarikHuber/react-most-wanted | packages/rmw-shell/cra-template-rmw/template/src/pages/Firebase/Storage.js | JavaScript | mit | 3,910 |
/**
* @file implements few matlab signal processing functions
* @author Sreehari p c
* @version 0.1
*/
(function()
{
//////////////////////////////////////////////////////////////////////////////////////////
// sign,diff,abs,mean,sum,square,std,zeros,real,maxpos,minpos,range,conv,corr, //
// hamming,dct,linspace,plot,conj,ifft,fft,butter,bitRevIndices,complexadd,complexmult, //
// scalarmult,complexarray,twiddle,add,sub,mult,sin [computefly,log,setUpchart] //
//////////////////////////////////////////////////////////////////////////////////////////
/**
* @class matLab
* constructer for matLab
* @param {object} opts contains context of canvas
*/
this.matLab = function(opts)
{
this.context = opts.context||null;
this.chart =null;
this.PI = Math.PI;
console.log('functions available : ');
console.log('sign,diff,abs,mean,sum,square,std,zeros,real,maxpos,minpos,range,conv,corr,hamming,dct,linspace,plot,conj,ifft,fft,butter,bitRevIndices,complexadd,complexmult,scalarmult,complexarray,twiddle,add,sub,mult,sin [computefly,log,setUpchart]');
}
//////////////////////
//private functions //
//////////////////////
/**
*
* finds sign of elements in array
* @param {object} array array of numbers
* @return {object} array containing -1,1 or 0
*/
matLab.prototype.sign = function(array)
{
return array.map(Math.sign);//x -> Math.sign(x)
}
/**
* calculates difference between adjacent elements
* @param {object} array array of numbers
* @return {object} array containing difference values
*/
matLab.prototype.diff = function(array)
{
var temp=[];
for(var i=0;i<array.length-1;i++)
{
temp[i]=array[i+1]-array[i];
}
return temp;
}
/**
* calculates absolute value of array of numbers or complex numbers
* @param {object} array numbers or complex number array
* @return {object} array containing corresponding absolute values
*/
matLab.prototype.abs = function(array)
{
if(typeof(array[0])=="object")
{
return array.map(function(val)
{
return Math.hypot(val[0],val[1]);
});
}
else
{
return array.map(Math.abs);//x -> Math.abs(x)
}
}
/**
* calculates mean of array elements
* @param {object} array number array
* @return {number} mean value
*/
matLab.prototype.mean = function(array)
{
return (this.sum(array)/array.length);
}
/**
* calculates sum of array elements
* @param {object} array number array
* @return {number} sum
*/
matLab.prototype.sum = function(array)
{
var temp=0;
for(var i=0;i<array.length;i++)
{
temp+=array[i];
}
return temp;
//array.reduce((prev,cur) -> prev+cur);
}
/**
* calculates squares of array elements
* @param {object} array number array
* @return {object} number squared array
*/
matLab.prototype.square = function(array)
{
return array.map(function(x){return x*x;});
}
/**
* calculates standard deviation of array elements
* @param {object} array number array
* @return {number} standard deviation
*/
matLab.prototype.std = function(array)
{
var mean = this.mean(array);
var variance = 0;
var length = array.length;
for(var i=0;i<length;i++)
{
variance+=Math.pow((array[i]-mean),2);
}
variance = variance/(length-1);
return Math.sqrt(variance);
}
/**
* fills array of specified length with val
* @param {number} num length of arrat needed
* @param {number} val value to fillthe array with
* @return {object} value filled array
*/
matLab.prototype.fill = function(num,val)
{
var array = [];
var val = val||0;
for(var i=0;i<num;i++)
{
array[i]=val;
}
return array;
}
/**
* provides real part of complex number
* @param {object} array complex number array
* @return {object} number array with real part
*/
matLab.prototype.real = function(array)
{
return array.map(function(val)
{
return val[0];
});
}
/**
* provides imaginary part of complex number
* @param {object} array complex number array
* @return {object} number array with imaginary part
*/
matLab.prototype.imag = function(array)
{
return array.map(function(val)
{
return val[1];
});
}
/**
* finds the maximum of array elements and returns maximum and maximum position
* @param {object} array number array
* @return {object} [max value,max position]
*/
matLab.prototype.maxpos = function(array)
{
var temp = Math.max.apply(null,array);
return [temp,array.indexOf(temp)];
}
/**
* finds the minimum of array elements and returns maximum and maximum position
* @param {object} array number array
* @return {object} [min value,min position]
*/
matLab.prototype.minpos = function(array)
{
var temp = Math.min.apply(null,array);
return [temp,array.indexOf(temp)];
}
/**
* creates number array with starting value 'start', stopping value 'stop' and step as 'step'
* @param {number} start starting value
* @param {number} stop stopping value (might be less than this value according to step)
* @param {number} step step value (default 1)
* @return {object} created number array
*/
matLab.prototype.range = function(start,stop,step)
{
if(start==stop)
return [start];
step = step||1;
var array = [];
for(var i=start,j=0;(step>0?i<=stop:i>=stop);i+=step,j++)
{
array[j] = i;
}
return array;
}
/**
* calculates convolution between two number arrays
* @param {object} array1 first number array
* @param {object} array2 second number array
* @return {object} convolution result array
*/
matLab.prototype.conv = function(array1,array2)
{
var l = array1.length+array2.length-1,y=[];
array1 = array1.concat(this.fill(l-array1.length));
array2 = array2.concat(this.fill(l-array2.length));
for(var n=0;n<l;n++)
{
y[n]=0;
for(var k=0;k<=n;k++)
{
y[n]+=array1[k]*array2[n-k];
}
}
return y;
}
/**
* calculates correlation between two number arrays (uses convolution as correlation
* is convolution with one array flipped)
* @param {object} array1 first number array
* @param {object} array2 second number array
* @return {object} correlation result array
*/
matLab.prototype.corr = function(array1,array2)
{
array1 = array1.reverse();
return this.conv(array1,array2);
}
/**
* calculates hamming window values for specified length
* @param {number} framelen length of window needed
* @return {object} array with calculated window values
*/
matLab.prototype.hamming = function(framelen)
{
var win = [];
for(var n=0;n<framelen;n++)
{
win[n] = 0.54-(0.46*Math.cos(2*Math.PI*n/(framelen-1)));
}
return win;
}
/**
* calculates discrete cosine transform of number array
* @param {object} array number array
* @return {object} array with dct values
*/
matLab.prototype.dct = function(array)
{
var N = array.length;
var y=[],coeff={w1:1/Math.sqrt(N),w2:Math.sqrt(2/N)};
for(var k=0;k<N;k++)
{
y[k]=0;
w = k==0?coeff.w1:coeff.w2;
for(var n=0;n<N;n++)
{
y[k]+=array[n]*Math.cos(Math.PI*(2*n+1)*k/(2*N));
}
y[k]*=w;
}
return y;
}
/**
* linearly places given number of elements between start and stop values (including start and stop)
* @param {number} start start value
* @param {number} stop stop value
* @param {number} numtot total length
* @return {object} array with linearly spaced elements
*/
matLab.prototype.linspace = function(start,stop,numtot)
{
var incr = (stop-start)/(numtot-1);
var temp = [];
for(var i=0;i<numtot-2;i++)
{
temp[i] = start+(i+1)*incr;
}
return [start].concat(temp,stop);
}
/**
* plots line chart using chart.js with y values specified in y_array and x values in x_array
* also, clears and destroys the previous chart upon drawing another
* @param {object} x_array x-axis values (default : 1 to length of y_array)
* @param {object} y_array y-axis values
*/
matLab.prototype.plot = function(x_array,y_array)
{
var x = x_array||this.range(1,y_array.length);
if(this.chart!=null)
{
this.chart.clear();
this.chart.destroy();
this.chart = null;
}
this.chart = setUpchart(x,y_array,this.context);
}
/**
* calculates inverse fourier transform of provided array values
* @param {object} frame number or complex number array
* @param {number} nfft nfft point
* @return {object} complex number array with ifft values
*/
matLab.prototype.ifft = function(frame,nfft)
{
if(typeof(frame[0])=="number")
{
frame = this.complexarray(frame);
}
var conjugate = this.conj(frame);
var x = this.fft(conjugate,nfft);
return this.scalarmult(x,1/nfft);
}
/**
* calculates fourier transform using radix-2 butterfly
* @param {object} frame number or complex number array
* @param {number} nfft nfft point fft
* @return {object} complex number array with fft values
*/
matLab.prototype.fft = function(frame,nfft)
{
//pad zeros if not equal length
var frlen=frame.length;
if(frlen!=nfft)
{
frame = frame.concat(this.fill(nfft-frlen))
}
//frame is complex array or not,if not make it complex.
if(typeof(frame[0])=="number")
{
frame = this.complexarray(frame);
}
var stages = Math.log2(nfft); //num stages
var z = this.bitRevIndices(frame); //bitreversed complex array
var twiddles = this.twiddle(nfft,0,true); //twiddle factors complex array
var stwI=[],y=[]; //stage twiddle factor indices
var p,ind;
for(var m=1;m<=stages;m++)
{
p = Math.pow(2,m);
stwI = this.range(0,(p/2)-1).map(function(val) //2^(m-1)-1
{
return nfft*val/p; // N*t/2^m
});
ind = stwI;
for(var q=stwI.length;q<nfft/2;q = stwI.length)
{
stwI = stwI.concat(ind);
}
for(var k=0,i=0;k<nfft;k++)
{
if(y[k]==null)
{
temp = computefly(z[k],z[k+(p/2)],twiddles[stwI[i]],this); //seperation in each stage is 0,2,4,8,16
y[k] = temp[0];
y[k+(p/2)] = temp[1];
i++;
}
}
z=y;
y=[];
}
return z;
}
/**
* provides butterworth filtering of input array signal values
* @param {object} signal array with signal values (number or complex)
* @param {number} order order of the filter
* @param {number} cutoff cutoff frequency in Hertz
* @param {number} sfreq sampling frequency of signal
* @param {number} gain DC gain (optional)
* @param {number} n n point fft (optional)
* @return {object} filtered signal complex array
*/
matLab.prototype.butter = function(signal,order,cutoff,sfreq,gain,n)
{
var Gain = gain||1;
var g;
var cfft=[];
var olen = signal.length;
var N = n||Math.pow(2,(Math.ceil(Math.log2(signal.length)))+1);
var sfft = this.fft(signal,N);
var step = (sfreq/N)/cutoff;
for(var i=0;i<N/2;i++)
{
g = Gain/Math.sqrt(1+Math.pow(i*step,2*order));
if(i==0)
{
cfft[i] = this.scalarmult(sfft[i],g);
cfft[N/2] = this.scalarmult(sfft[N/2],Gain/Math.sqrt(1+Math.pow((N/2)*step,2*order)));
continue;
}
cfft[i] = this.scalarmult(sfft[i],g);
cfft[(N)-i] = this.conj(cfft[i]);
}
var ifft = this.ifft(cfft,N);
ifft = ifft.splice(0,olen);
return ifft;
}
/**
* finds the bit reversed order of array elements
* @param {object} frame number or complex array to arrange in bitreversed order
* @return {object} bit reversed complex or number array
*/
matLab.prototype.bitRevIndices = function(frame)
{
var s;
var l = Math.ceil(Math.log2(frame.length));
return this.range(0,frame.length-1,1).map(function(val)
{
s = val.toString(2).split('');
while(s.length < l)
{
s.unshift('0');
}
return frame[parseInt(s.reverse().join(''),2)];
});
}
/**
* basic complex number addition
* @param {object} c1 first complex number
* @param {object} c2 second complex number
* @return {object} added complex number
*/
matLab.prototype.complexadd = function(c1,c2)
{
return [c1[0]+c2[0],
c1[1]+c2[1]
];
}
/**
* calculates complex conjugate of complex number array
* @param {object} complex complex number array
* @return {object} conjugated complex number array
*/
matLab.prototype.conj = function(complex)
{
if(typeof(complex[0])=="object")
{
return complex.map(function(num)
{
return [num[0],-num[1]];
});
}
else
{
return [complex[0],-complex[1]];
}
}
/**
* basic complex number multiplication
* @param {object} c1 first complex number
* @param {object} c2 second complex number
* @return {object} multiplied complex number
*/
matLab.prototype.complexmult = function(c1,c2)
{
return [
(c1[0]*c2[0])-(c1[1]*c2[1]),
(c1[0]*c2[1])+(c1[1]*c2[0])
];
}
/**
* scalar multiplication of number or complex number array
* @param {object} array number or complex number array
* @param {number} k scalar
* @return {object} scalar multiplied number or complex number array
*/
matLab.prototype.scalarmult = function(array,k)
{
if(typeof(array[0])=="number")
{
return array.map(function(val)
{
return val*k;
});
}
else
{
return array.map(function(val)
{
return [val[0]*k,val[1]*k];
});
}
}
/**
* converts number array into complex number array [[r,i],[r,i],[r,i]]
* @param {object} r_array number array
* @param {object} i_array imaginary part of number array (optional default : 0)
* @return {object} created complex number array
*/
matLab.prototype.complexarray = function(r_array,i_array)
{
i_array=i_array||this.fill(r_array.length);
return r_array.map(function(val,index)
{
return [val,i_array[index]]
});
}
/**
* calculates twiddle factor for specified N and k (e^(-j2(pi)/N)*k) or uptill 0-N if full is true
* @param {number} N N in twiddle factor
* @param {number} k k in twiddle factor
* @param {Boolean} full if true, returns all twiddle factors from 0-N (default : false)
* @return {object} complex number or complex number array iwth twiddle factor value(s)
*/
matLab.prototype.twiddle = function(N,k,full)
{
if(full == true)
{
var tw =[],temp;
for(var k=0;k<N;k++)
{
if(k<N/2)
{
tw[k] = ([Math.cos(this.PI*2*k/N),Math.sin(-(this.PI*2*k/N))]);
}
else
{ //symmetry property of twiddle factors
temp = k-(N/2);
tw[k] = [-tw[temp][0],-tw[temp][1]];
}
}
return tw;
}
else
return [Math.cos(this.PI*2*k/N),Math.sin(-(this.PI*2*k/N))];
}
/**
* adds two number arrays
* @param {object} array1 first number array
* @param {object} array2 second number array
* @return {object} number array with added values
*/
matLab.prototype.add = function(array1,array2)
{
try{
if(array1.length!=array2.length)
{
throw 'lengths must match';
}
return array1.map(function(val,i)
{
return val+array2[i];
});
}catch(err)
{
log(err);
return;
}
}
/**
* subtracts two number arrays
* @param {object} array1 first number array
* @param {object} array2 second number array
* @return {object} number array with subtracted values
*/
matLab.prototype.sub = function(array1,array2)
{
try{
if(array1.length!=array2.length)
{
throw 'lengths must match';
}
return array1.map(function(val,i)
{
return val-array2[i];
});
}catch(err)
{
log(err);
return;
}
}
/**
* multiplies two number arrays
* @param {object} array1 first number array
* @param {object} array2 second number array
* @return {object} number array with multiplied values
*/
matLab.prototype.mult = function(array1,array2)
{
try{
if(array1.length!=array2.length)
{
throw 'lengths must match';
}
return array1.map(function(val,i)
{
return val*array2[i];
});
}catch(err)
{
log(err);
return;
}
}
/**
* creates sin wave of specified frequency, sample rate and length
* @param {number} f frequency of sine wave
* @param {number} fs sample rate
* @param {object} tarray [start,stop] number array providing start and stop lengths
* @return {object} created sine wave
*/
matLab.prototype.sin = function(f,fs,tarray)
{
var t = this.range(tarray[0],tarray[1]);
var v = this.scalarmult(t,2*this.PI*f/fs)
return v.map(Math.sin);
}
//////////////////////
//utility functions //
//////////////////////
/**
* computes butterfly pair [a+b*tw,a-b*tw]
* @param {object} a first complex number
* @param {object} b second complex number
* @param {object} tw twiddle factor
* @param {object} cnt context for external function
* @return {object} complex array with calculated butterfly pair
*/
function computefly(a,b,tw,cnt)
{
var d = cnt.scalarmult(b,-1);
return [cnt.complexadd(a,cnt.complexmult(b,tw)),cnt.complexadd(a,(cnt.complexmult(d,tw)))];
}
/**
* logs into console window of browser (debugging)
* @param {var} m message to log
*/
function log(m)
{
console.log(m);
}
/**
* set up and draws the line chart into canvas using chart.js
* @param {object} x x-axis number array
* @param {object} y y-axis number array
* @param {object} context canvas context
* @return {object} chart instance
*/
function setUpchart(x,y,context)
{
var data = {
labels: x,
datasets:
[
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(250,120,120,1)",
pointColor: "rgba(60,60,60,0.6)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data:y
}
]
};
var options =
{
tooltipEvents:[],
showTooltips: false,
responsive:true,
pointDot:false,
};
var chart = new Chart(context).Line(data,options);
return chart;
}
}());
| sreeharipc/matLabJS | matLabJS.js | JavaScript | mit | 18,267 |
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
function dirPath(dest){
return path.resolve(__dirname, dest);
};
function webPath(dest){
return dirPath('app/' + dest);
};
const config = {
entry: [
webPath('scss/style.scss'),
webPath('client.js')
],
output: {
path: process.env.NODE_ENV === 'production' ? dirPath('dist') : dirPath('build'),
filename: 'js/bundle.js'
},
module: {
loaders: [{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
},
plugins: [
new ExtractTextPlugin('css/style.css'),
new HtmlWebpackPlugin({
template: webPath('index.html'),
inject: 'body'
})
],
devServer:{
quite: false,
noInfo: false,
stats:{
assets: false,
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}
}
};
// production mode
if(process.env.NODE_ENV === 'production'){
config.plugins.push(
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({minimize: true})
);
} else {
config.entry.push(
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:8080'
);
}
module.exports = config;
| samarpanda/quick-react-app | webpack.config.js | JavaScript | mit | 1,429 |
'use strict';
const chai = require('chai');
const expect = chai.expect;
const Sequelize = require(__dirname + '/../../../../index');
const Support = require(__dirname + '/../../support');
const dialect = Support.getTestDialect();
//TODO voir sur le build pourquoi il passe pas (uncaughtException)
describe.skip('[ORACLE] Connection Manager', () => {
let instance, config;
if (dialect === 'oracle') {
it('full database, should connect to Oracle', done => {
// expect(config.dialectOptions.domain).to.equal('TEST.COM');
config = {
dialect: 'oracle',
host: process.env.NODE_ORACLEDB_HOST,
database:`${process.env.NODE_ORACLEDB_HOST}:${process.env.NODE_ORACLEDB_PORT}/${process.env.NODE_ORACLEDB_CONNECTIONSTRING}`,
username: process.env.NODE_ORACLEDB_USER,
password: process.env.NODE_ORACLEDB_PASSWORD
};
instance = new Sequelize(config.database, config.username, config.password, config);
instance.dialect.connectionManager.connect(config)
.then(result => {
expect(instance.getDialect()).to.equal('oracle');
instance.dialect.connectionManager.disconnect(result)
.then(() => {
done();
});
})
.catch(error => {
done(error);
});
});
it('database with only service_name, should connect to Oracle', done => {
// expect(config.dialectOptions.domain).to.equal('TEST.COM');
config = {
dialect: 'oracle',
host: process.env.NODE_ORACLEDB_HOST,
username: process.env.NODE_ORACLEDB_USER,
password: process.env.NODE_ORACLEDB_PASSWORD,
database: process.env.NODE_ORACLEDB_CONNECTIONSTRING
};
instance = new Sequelize(config.database, config.username, config.password, config);
instance.dialect.connectionManager.connect(config)
.then(result => {
expect(instance.getDialect()).to.equal('oracle');
instance.dialect.connectionManager.disconnect(result)
.then(() => {
done();
});
})
.catch(error => {
done(error);
});
});
it('database with only service_name no host, should fail', done => {
// expect(config.dialectOptions.domain).to.equal('TEST.COM');
config = {
dialect: 'oracle',
host: '',
username: 'sequelize',
password: 'sequelize',
database: 'xe.oracle.docker'
};
instance = new Sequelize(config.database, config.username, config.password, config);
instance.dialect.connectionManager.connect(config)
.then(result => {
done('You shall not pass');
expect(instance.getDialect()).to.equal('oracle');
instance.dialect.connectionManager.disconnect(result)
.then(() => {
done('You shall not pass');
});
})
.catch(err => {
expect(err.message).to.equal('You have to specify the host');
done();
});
});
it('database empty, should fail', done => {
// expect(config.dialectOptions.domain).to.equal('TEST.COM');
config = {
dialect: 'oracle',
host: 'localhost',
username: 'sequelize',
password: 'sequelize',
database: ''
};
instance = new Sequelize(config.database, config.username, config.password, config);
instance.dialect.connectionManager.connect(config)
.then(() => {
done('You shall not pass');
expect(instance.getDialect()).to.equal('oracle');
instance.dialect.connectionManager.disconnect(null).then(() => {
done('You shall not pass');
});
})
.catch(err => {
expect(err.message.indexOf('The database cannot be blank, you must specify the database name')).to.equal(0);
done();
});
});
}
});
| konnecteam/sequelize | test/unit/dialects/oracle/connection-manager.test.js | JavaScript | mit | 3,928 |
(function(APP){
var template = document.getElementById('productstpl').innerHTML,
productDBParsed = JSON.parse(document.getElementById('products-db').innerHTML).products,
renderData = JSON.parse(document.getElementById('products-db').innerHTML),
productIds = _.pluck(productDBParsed, 'id'),
cart = new APP.Cart(),
store = new APP.Store(productDBParsed);
/**
* An Observer Pattern implementation
*
* **/
function extend( obj, extension ){
for ( var key in extension ){
obj[key] = extension[key];
}
}
extend(store, new APP.Subject());
extend(cart, new APP.Observer());
store.addObserver(cart);
function findInStore(id){
return _.find(store.products, {id: parseInt(id.split('-').pop())});
}
/**
* handle click events on add and remove buttons
* @param: @action - string, acceptable values are 'add' or 'remove'
*
* **/
function handleClickEvent(action) {
_.map(productIds, function(item){
document.getElementById(action+'-'+item).addEventListener('click', function (e) {
var productInDB = findInStore(e.target.id),
basketElement = {
elem: document.getElementById('basket-elem-'+productInDB.id),
quantity: document.querySelector('#basket-elem-'+productInDB.id+' .item-quantity')
},
foundInCart = productInDB && cart.getItem(productInDB.id),
currentLineItem;
switch (action) {
case 'add':
if (foundInCart && foundInCart.quantity <= productInDB.quantity) {
if (foundInCart && foundInCart.quantity === productInDB.quantity) {
this.setAttribute('class', 'disabled');
document.getElementById('remove-'+productInDB.id).setAttribute('class', 'enabled');
} else {
basketElement.quantity.innerHTML = parseInt(basketElement.quantity && basketElement.quantity.innerHTML)+1;
foundInCart.quantity += 1;
}
} else if (productInDB && !foundInCart) {
currentLineItem = new APP.LineItem(productInDB.id, productInDB);
cart.addItem(currentLineItem);
APP.events.emit('productsManaged', productInDB.id);
} else {
console.log('this state is impossible, we guess');
}
store.notify(foundInCart || currentLineItem);
break;
case 'remove':
if (foundInCart && foundInCart.quantity) {
basketElement.quantity.innerHTML = parseInt(basketElement.quantity && basketElement.quantity.innerHTML)-1;
foundInCart.quantity -= 1;
if (foundInCart && !foundInCart.quantity) {
cart.removeItem(foundInCart);
basketElement.elem && basketElement.elem.remove();
this.setAttribute('class', 'disabled');
document.getElementById('add-' + productInDB.id).setAttribute('class', 'enabled');
}
}else {
basketElement.elem && basketElement.elem.remove();
console.log('Item with id ' + productInDB.id +' is completely removed from cart');
}
store.notify(foundInCart || currentLineItem);
break;
default:
console.log('You should pass valid parameter');
}
APP.events.emit('basketUpdated');
});
});
}
function init(){
document.getElementById('products-wrapper').innerHTML = Mustache.to_html(template, renderData);
handleClickEvent('add');
handleClickEvent('remove');
}
APP.mainModule = {
cart: cart,
store: store,
init: init
};
}(window.APP)); | mstmustisnt/weird-store | js/app/app.main.js | JavaScript | mit | 3,261 |
'use strict'
var queryString = require('query-string')
var _ = require('lodash')
var config = require('./config')
var request = {}
request.get = function(url, params){
if(params){
url += '?' + queryString.stringify(params);
}
return fetch(url)
.then((response) => response.json())
}
request.post = function(url, options){
var options = _.extend(config.header, {
body: JSON.stringify(body)
})
return fetch(url, options)
.then((response) => response.json())
}
module.exports = request | zhuifeng740643787/gougouApp | app/common/request.js | JavaScript | mit | 502 |
const del = require('del');
const gulp = require('gulp');
const mergeStream = require('merge-stream');
const plugins = require('gulp-load-plugins')();
const runSequence = require('run-sequence');
gulp.task('clean', () => del(['dist/*', '!dist/.gitkeep']));
gulp.task('babel', () => {
return mergeStream(
gulp.src('spec/**/*.js').pipe(plugins.babel()),
gulp.src(['LICENSE', 'README.md', 'package.json'])
).pipe(gulp.dest('dist'));
});
gulp.task('build', done => runSequence('clean', 'babel', done));
gulp.task('watch', ['build'], () => {
gulp.watch('src/**/*.js', ['babel']);
}); | cursivejs/tdd-with-jasmine | tasks/build.js | JavaScript | mit | 601 |
const API_ENDPOINT = `https://api.canonn.tech`;
const API_LIMIT = 1000;
const capi = axios.create({
baseURL: API_ENDPOINT,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
let sites = {
gensites: [],
};
const go = async types => {
const keys = Object.keys(types);
return (await Promise.all(
keys.map(type => getSites(type))
)).reduce((acc, res, i) => {
acc[keys[i]] = res;
return acc;
}, {});
};
const getSites = async type => {
let records = [];
let keepGoing = true;
let API_START = 0;
while (keepGoing) {
let response = await reqSites(API_START, type);
await records.push.apply(records, response.data);
API_START += API_LIMIT;
if (response.data.length < API_LIMIT) {
keepGoing = false;
return records;
}
}
};
const reqSites = async (API_START, type) => {
let payload = await capi({
url: `/${type}?_limit=${API_LIMIT}&_start=${API_START}`,
method: 'get'
});
return payload;
};
var canonnEd3d_gen = {
//Define Categories
systemsData: {
categories: {
"Generation Ships - (GEN)": {
"201": {
name: "Generation Ship",
color: randomColor().replace('#', '').toString()
}
},
'Unknown Type': {
'2000': {
name: 'Unknown Site',
color: '800000',
}
}
},
systems: []
},
// Lets get data from CSV Files
formatSites: async function(data, resolvePromise) {
sites = await go(data);
let siteTypes = Object.keys(data);
for (var i = 0; i < siteTypes.length; i++) {
for (var d = 0; d < sites[siteTypes[i]].length; d++) {
let siteData = sites[siteTypes[i]];
if (siteData[d].system.systemName && siteData[d].system.systemName.replace(' ', '').length > 1) {
var poiSite = {};
poiSite['name'] = siteData[d].system.systemName + ' - ' + siteData[d].shipName;
//Check Site Type and match categories
if (siteTypes[i] == 'gensites') {
poiSite['cat'] = [201];
} else {
poiSite['cat'] = [2000];
}
poiSite['coords'] = {
x: parseFloat(siteData[d].system.edsmCoordX),
y: parseFloat(siteData[d].system.edsmCoordY),
z: parseFloat(siteData[d].system.edsmCoordZ),
};
// We can then push the site to the object that stores all systems
canonnEd3d_gen.systemsData.systems.push(poiSite);
}
}
}
document.getElementById("loading").style.display = "none";
resolvePromise();
},
init: function () {
//Sites Data
var p1 = new Promise(function(resolve, reject) {
canonnEd3d_gen.formatSites(sites, resolve);
});
Promise.all([p1]).then(function () {
Ed3d.init({
container: 'edmap',
json: canonnEd3d_gen.systemsData,
withFullscreenToggle: false,
withHudPanel: true,
hudMultipleSelect: true,
effectScaleSystem: [20, 500],
startAnim: false,
showGalaxyInfos: true,
cameraPos: [25, 14100, -12900],
systemColor: '#FF9D00'
});
});
}
}; | canonn-science/CanonnED3D-All-Map | Source/data/MapData-GEN.js | JavaScript | mit | 2,909 |
Package.describe({
name: 'adej:meteor-sounds',
version: '0.0.2',
// Brief, one-line summary of the package.
summary: 'Play local sounds on mobile devices',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/adeubank/meteor-sounds',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: '../README.md'
});
Cordova.depends({
'com.rjfun.cordova.plugin.lowlatencyaudio': '1.1.4'
});
Package.onUse(function(api) {
api.versionsFrom('1.0.3.1');
api.use('reactive-var', 'client');
api.addFiles('meteorSounds.js', ['web.cordova']);
// export MeteorSounds Object
api.export('MeteorSounds', ['web.cordova']);
});
| adeubank/meteor-sounds | src/package.js | JavaScript | mit | 780 |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var forms_1 = require('@angular/forms');
var Story_1 = require("./Story");
var StoryComponent = (function () {
function StoryComponent(db, router, route, formBuilder, ms) {
this.db = db;
this.router = router;
this.route = route;
this.formBuilder = formBuilder;
this.ms = ms;
this.choices = [];
this.storyIndex = null;
this.valid = false;
}
StoryComponent.prototype.ngOnInit = function () {
var _this = this;
this.subscription = this.route.params.subscribe(function (params) {
if (params.hasOwnProperty('worldIndex')) {
_this.worldIndex = +params['worldIndex'];
while (!_this.db.done) { }
_this.world = _this.db.getItemByIndex(_this.worldIndex);
if (params.hasOwnProperty('storyIndex')) {
console.log('in params');
_this.isNew = false;
_this.storyIndex = +params['storyIndex'];
_this.item = _this.world.stories[_this.storyIndex];
if (_this.world != null) {
if (_this.item) {
_this.path = 'world/' + _this.world.id + '/stories/' + _this.item.id;
}
else {
_this.router.navigate(['../world/:id/story/new']);
}
}
else {
_this.ms.error('The item does not exist with the given ID');
_this.navigateBack();
}
}
else {
_this.isNew = true;
_this.item = new Story_1.Story(Date.now().toString(), '', '', '', '', '', '', '');
}
}
});
// console.log('outside params');
this.initForm();
// this.db.set(new World(null, 'test', 'test','test',[]));
};
StoryComponent.prototype.ngOnDestroy = function () {
this.subscription.unsubscribe();
};
StoryComponent.prototype.ngOnChanges = function () {
this.valid = this.mainForm.valid;
console.log("Valid: " + this.valid);
};
StoryComponent.prototype.initChoice = function (txt, rule) {
return new forms_1.FormGroup({
text: new forms_1.FormControl(txt, [forms_1.Validators.required, forms_1.Validators.minLength(8), forms_1.Validators.maxLength(32)]),
moralRule: new forms_1.FormControl(rule)
});
};
StoryComponent.prototype.initForm = function () {
this.mainForm = this.formBuilder.group({
title: [this.item.title, forms_1.Validators.required],
prologue: [this.item.prologue, forms_1.Validators.required],
choice1Rule: [this.item.choice1Rule, forms_1.Validators.required],
choice1Text: [this.item.choice1Text, forms_1.Validators.required],
choice2Rule: [this.item.choice2Rule, forms_1.Validators.required],
choice2Text: [this.item.choice2Text, forms_1.Validators.required]
});
console.log(this.mainForm);
};
StoryComponent.prototype.navigateBack = function () {
this.router.navigate(['../']);
};
StoryComponent.prototype.onCancel = function () {
this.router.navigate(['../world']);
};
// onRemoveChoice(i) {
// this.item.choices.splice( i, 1 );
// }
StoryComponent.prototype.onAddChoice = function () {
this.mainForm.controls['choices'].push(this.initChoice('', ''));
};
StoryComponent.prototype.onSubmit = function () {
console.log(this.mainForm);
// let v = this.mainForm.value; console.log(this.world);
// this.item.worldId = this.world.id;
// this.item.title = v.name;
// this.item.prologue = v.prologue;
// this.item.choice1Text = v.choice1Text;
// this.item.choice1Rule = v.choice1Rule;
// this.item.choice2Text = v.choice2Text;
// this.item.choice2Rule = v.choice2Rule;
//
// console.log(this.item);
//
// if(this.isNew) this.world.stories.push(this.item);
// else this.world.stories[this.storyIndex] = this.item;
// console.log(this.world);
// this.db.set(this.world);
// // this.router.navigate(['../world/:id/story/:sid']);
};
StoryComponent = __decorate([
core_1.Component({
selector: 'bsp-world',
templateUrl: './story.component.html',
styleUrls: ['./story.component.css']
})
], StoryComponent);
return StoryComponent;
}());
exports.StoryComponent = StoryComponent;
//# sourceMappingURL=story.component.js.map | UAB-CS499-Back-Stabbers-Team/CS499-Back-Stabber-Project | BackStabberProject/src/app/world/story/story.component.js | JavaScript | mit | 5,398 |
import React, { useContext } from 'react'
import { useIntl } from 'react-intl'
import { NavLink } from 'react-router-dom'
import LocaleContext from 'base-shell/lib/providers/Locale/Context'
import ConfigContext from 'base-shell/lib/providers/Config/Context'
import AuthContext from 'base-shell/lib/providers/Auth/Context'
const Menu = () => {
const intl = useIntl()
const { setLocale, locale = 'en' } = useContext(LocaleContext)
const { appConfig } = useContext(ConfigContext)
const auth = useContext(AuthContext)
const { menu } = appConfig || {}
const { getMenuItems } = menu || {}
const itemsMenu = getMenuItems
? getMenuItems({
intl,
auth,
locale,
updateLocale: setLocale,
}).filter((item) => {
return item.visible !== false
})
: []
const getNestedItems = function (hostItem, hostIndex) {
if (hostItem.nestedItems !== undefined) {
let nestedItems = hostItem.nestedItems.filter(function (item) {
return item.visible !== false
})
return (
<ul>
{nestedItems.map((nestedItem, k) => {
return (
<React.Fragment key={k}>
{hostItem.primaryTogglesNestedList ? (
<>
<input
onChange={(e) => {
if (nestedItem.onClick) {
nestedItem.onClick()
}
}}
checked={locale === nestedItem.key}
type="radio"
id={nestedItem.primaryText}
name={hostItem.primaryText}
value={nestedItem.primaryText}
></input>
<label htmlFor={nestedItem.primaryText}>
{nestedItem.primaryText}
</label>
<br />
</>
) : (
<>
<li key={k}>{nestedItem.primaryText}</li>
{getNestedItems(nestedItem, k)}
</>
)}
</React.Fragment>
)
})}
</ul>
)
}
return null
}
return (
<div>
<nav>
<ul>
Menu
{itemsMenu.map((item, i) => {
return (
<React.Fragment key={i}>
<li style={{ listStyleType: item.value ? 'dash' : 'none' }}>
{item.value ? (
<NavLink
style={{ textDecoration: 'none' }}
to={item.value}
onClick={(e) => {
if (item.onClick) {
item.onClick()
}
}}
>
{item.primaryText}
</NavLink>
) : (
item.primaryText
)}
</li>
{getNestedItems(item, i)}
</React.Fragment>
)
})}
</ul>
</nav>
</div>
)
}
export default Menu
| TarikHuber/react-most-wanted | packages/base-shell/cra-template-base/template/src/containers/Menu/Menu.js | JavaScript | mit | 3,171 |
import {CoinCap, EventTypes as coincapEventTypes} from './CoinCap';
describe('Coincap', () => {
let coincap;
beforeEach(() => {
coincap = new CoinCap();
});
it('should have a null socket', () => {
expect(coincap.socket).toBeNull();
});
describe('init', () => {
beforeEach(() => {
coincap.init();
});
it('should have a socket not null', () => {
expect(coincap.socket).not.toBeNull();
});
});
describe('event listeners', () => {
let spyListener = jest.fn();
beforeAll(() => {
coincap.init();
});
it('should create an global listeners array', () => {
expect(coincap.eventListeners[coincapEventTypes.Global]).toBeArray;
});
it('should create an trade listeners array', () => {
expect(coincap.eventListeners[coincapEventTypes.Trade]).toBeArray;
});
describe('_addEventListener', () => {
it('should thrown if listener is not a function', () => {
expect(() => {
coincap._addEventListener('t', null);
}).toThrow();
});
it('should add an event listener to the global listeners array', () => {
coincap.addGlobalListener(spyListener);
expect(coincap.eventListeners[coincapEventTypes.Global]).toContain(spyListener);
});
});
describe('addCoinListener', () => {
it('should thrown if listener is not a function', () => {
expect(() => {
coincap.addCoinListener(null);
}).toThrow();
});
it('should add an event listener to the BTC listener array', () => {
coincap.addCoinListener(spyListener);
expect(coincap.coinListeners['BTC']).toContain(spyListener);
});
it('should add an event listener to the DASH listener array', () => {
coincap.addCoinListener(spyListener, 'DASH');
expect(coincap.coinListeners['DASH']).toContain(spyListener);
});
});
});
});
| yknx4/aleworld | src/client/assets/javascripts/services/CoinCap.test.js | JavaScript | mit | 1,928 |
import { fromJS } from 'immutable';
import {
EDIT_PAPER_FETCH,
EDIT_PAPER_RECEIVE,
EDIT_PAPER_RESET,
EDIT_PAPER_UPDATE,
EDIT_PAPER_GOOGLE_DRIVE_HAS_ACCESS,
} from './constants';
const initialState = fromJS({
paper: {
title: '',
summary: '',
tags: [],
references: [],
authors: [],
},
canLeave: true,
loading: false,
found: true,
hasDriveAccess: false,
});
export default (state = initialState, action) => {
let newState = state;
switch (action.type) {
case EDIT_PAPER_FETCH:
newState = newState.set('loading', true);
break;
case EDIT_PAPER_RECEIVE:
newState = newState.set('loading', false);
newState = newState.set('canLeave', true);
newState = newState.set('paper', fromJS(action.paper));
break;
case EDIT_PAPER_RESET:
newState = initialState;
break;
case EDIT_PAPER_UPDATE:
newState = newState.set('canLeave', false);
newState = newState.setIn(['paper', action.key], action.value);
break;
case EDIT_PAPER_GOOGLE_DRIVE_HAS_ACCESS:
newState = newState.set('hasDriveAccess', action.hasAccess);
break;
default:
}
return newState;
};
| bobinette/papernet-front | src/scenes/edit-paper/api/reducer.js | JavaScript | mit | 1,186 |
import React from 'react';
export default function DecoratorHOC(Component) {
return class extends React.Component {
static displayName = 'DecoratorElement';
static defaultProps = {
decorator: true
};
render() {
return (
<Component {...this.props} />
);
}
};
}
DecoratorHOC.displayName = 'DecoratorElement';
| ezypeeze/react-mozer | src/DecoratorHOC.js | JavaScript | mit | 412 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.10.1-rc2-master-7bbfd1f
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.progressCircular
* @description Circular Progress module!
*/
angular.module('material.components.progressCircular', [
'material.core'
])
.directive('mdProgressCircular', MdProgressCircularDirective);
/**
* @ngdoc directive
* @name mdProgressCircular
* @module material.components.progressCircular
* @restrict E
*
* @description
* The circular progress directive is used to make loading content in your app as delightful and
* painless as possible by minimizing the amount of visual change a user sees before they can view
* and interact with content.
*
* For operations where the percentage of the operation completed can be determined, use a
* determinate indicator. They give users a quick sense of how long an operation will take.
*
* For operations where the user is asked to wait a moment while something finishes up, and it’s
* not necessary to expose what's happening behind the scenes and how long it will take, use an
* indeterminate indicator.
*
* @param {string} md-mode Select from one of two modes: determinate and indeterminate.
* @param {number=} value In determinate mode, this number represents the percentage of the
* circular progress. Default: 0
* @param {number=} md-diameter This specifies the diamter of the circular progress. Default: 48
*
* @usage
* <hljs lang="html">
* <md-progress-circular md-mode="determinate" value="..."></md-progress-circular>
*
* <md-progress-circular md-mode="determinate" ng-value="..."></md-progress-circular>
*
* <md-progress-circular md-mode="determinate" value="..." md-diameter="100"></md-progress-circular>
*
* <md-progress-circular md-mode="indeterminate"></md-progress-circular>
* </hljs>
*/
function MdProgressCircularDirective($mdConstant, $mdTheming) {
return {
restrict: 'E',
template:
// The progress 'circle' is composed of two half-circles: the left side and the right
// side. Each side has CSS applied to 'fill-in' the half-circle to the appropriate progress.
'<div class="md-spinner-wrapper">' +
'<div class="md-inner">' +
'<div class="md-gap"></div>' +
'<div class="md-left">' +
'<div class="md-half-circle"></div>' +
'</div>' +
'<div class="md-right">' +
'<div class="md-half-circle"></div>' +
'</div>' +
'</div>' +
'</div>',
compile: compile
};
function compile(tElement) {
// The javascript in this file is mainly responsible for setting the correct aria attributes.
// The animation of the progress spinner is done entirely with just CSS.
tElement.attr('aria-valuemin', 0);
tElement.attr('aria-valuemax', 100);
tElement.attr('role', 'progressbar');
return postLink;
}
function postLink(scope, element, attr) {
$mdTheming(element);
var circle = element[0];
// Scale the progress circle based on the default diameter.
var diameter = attr.mdDiameter || 48;
var scale = diameter / 48;
circle.style[$mdConstant.CSS.TRANSFORM] = 'scale(' + scale + ')';
attr.$observe('value', function(value) {
var percentValue = clamp(value);
element.attr('aria-valuenow', percentValue);
});
}
/**
* Clamps the value to be between 0 and 100.
* @param {number} value The value to clamp.
* @returns {number}
*/
function clamp(value) {
return Math.max(0, Math.min(value || 0, 100));
}
}
MdProgressCircularDirective.$inject = ["$mdConstant", "$mdTheming"];
})(window, window.angular); | CirceThanis/bower-material | modules/js/progressCircular/progressCircular.js | JavaScript | mit | 3,765 |
var gruntRequireConfig = require('./src/dev/requireConfig').gruntConfig;
var gruntWrapperRequireConfig = require('./src/dev/requireConfig').gruntWrapperConfig;
var gruntDebugConfig = require('./src/dev/requireConfig').gruntDebugConfig;
module.exports = function (grunt) {
grunt.initConfig({
requirejs: {
core: {
options: gruntRequireConfig
},
wrapper: {
options: gruntWrapperRequireConfig
},
debug: {
options: gruntDebugConfig
}
},
concat: {
css: {
src: 'build/tmp/*.css',
dest: 'build/tmp/razorflow.core.theme.css'
}
},
jst: {
compile: {
options: {
prettify: true,
processName: function (filePath) {
var parts = filePath.split('/');
var fileName = parts[parts.length - 1];
return fileName.split('.')[0];
},
amd: true,
global: false,
requires: {
'vendor/lodash' : '_'
}
},
files: {
"src/js/generated/templates.js": ["src/templates/*.html"]
}
}
},
less: {
development: {
options: {
paths: ['src/less']
},
files: {
"build/tmp/razorflow.css": "src/less/razorflow.less",
"build/tmp/rftheme.default.css": "build/tmp/less/rftheme.default.less"
}
}
},
jshint: {
options: {
jshintrc: 'src/js/.jshintrc'
},
files: [
"src/js/**/*.js",
"!src/js/vendor/**/*.js",
"!src/js/generated/templates.js",
"!src/js/buildutils/**/*.js"
]
},
karma: {
dev: {
configFile: './karma.conf.js',
singleRun: true
}
},
lodash: {
build: {
dest: 'src/vendor/js/lodash.rf.js',
options: {
include: ['extend', 'pluck', 'map', 'each', 'isNumber', 'isString', 'isNaN', 'isArray', 'isObject', 'find', 'defer', 'delay', 'max', 'min', 'sortBy', 'flatten', 'clone', 'cloneDeep', 'values', 'pick', 'reduce', 'filter', 'indexOf', 'keys', 'debounce'],
}
}
},
cssmin: {
minify: {
expand: true,
cwd: 'build/tmp/',
src: ['razorflow.core.theme.css'],
dest: 'build/assets/css',
ext: '.min.css'
}
},
// Need to copy products.json
copy: {
localToWebRF: {
files: [
{src: ["build/js/razorflow.min.js"], dest: '../webrf/backend/static/transfer/', flatten:true},
{src: ["build/css/razorflow.min.css"], dest: '../webrf/backend/static/transfer/', flatten:true},
{src: ["build/js/templates.js"], dest: '../webrf/backend/static/transfer/', flatten:true},
{src: ["build/js/rfDemos.js"], dest: '../webrf/backend/static/transfer/', flatten:true},
{src: ["build/img/exampleImgs/*.png"], dest: '../webrf/backend/static/transfer/',flatten: true },
]
}
},
copyto: {
srcToBuild: {
files: [
{cwd: 'src/vendor/js/', src: ['jquery.min.js'], dest: 'build/assets/js/'},
]
},
packageToBuild: {
files: [
{cwd: 'src/package/', src: ['**/*'], dest: 'build/package/'},
],
},
packageMinToBuild: {
files: [
{cwd: 'src/packages/minified/', src: ['**/*'], dest: 'build/packages/minified/'}
]
},
packageSrcToBuild: {
files: [
{cwd: 'src/packages/source/', src: ['**/*'], dest: 'build/packages/source/'}
]
},
assetsToPackage: {
files: [
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/package/files/'},
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/package/dashboard_quickstart/'},
],
},
assetsToMinPackage: {
files: [
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/packages/minified/files/'},
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/packages/minified/dashboard_quickstart/'},
],
},
assetsToSrcPackage: {
files: [
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/packages/source/files/'},
{cwd: 'build/assets/', src: ["js/**", "css/**", "img/**"], dest: 'build/packages/source/dashboard_quickstart/'},
],
},
srcToPackage: {
files: [
{cwd: 'src/dev/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/dev/'},
{cwd: 'src/fonts/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/fonts/'},
{cwd: 'src/img/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/img/'},
{cwd: 'src/js/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/js/'},
{cwd: 'src/less/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/less/'},
{cwd: 'src/templates/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/templates/'},
{cwd: 'src/vendor/', src: ['**/*'], dest: 'build/packages/source/source/javascript/src/vendor/'},
{cwd: 'tools/src/grunt-tasks/', src: ['themeGen.js'], dest: 'build/packages/source/source/javascript/tools/grunt-tasks/'}
]
},
packageToRelease: {
files: [
{cwd: 'src/package/', src: ['**'], dest: '../package/rf/javascript/'}
]
},
razorcharts: {
files: [
{cwd: '../razorcharts/src/js', src:['**'], dest: 'src/js/'}
]
},
sprite: {
files: [
{cwd: 'src/img/', src:['**'], dest: 'build/img/'},
{cwd: 'src/img/', src:['**'], dest: 'build/assets/img/'}
]
},
themebuilder: {
files: [
{cwd: 'src/less/', src: ["theme.less", "mixins.less", "theme/variables.less"], dest: 'build/tmp/themebuilder/'},
{cwd: 'src/js/themebuilder/config/', src: ["defaulttheme.json"], dest: 'build/tmp/themebuilder/'}
]
},
connectors: {
files: [
{cwd: '../cloudconnect/src/', src:['**'], dest: 'extras/connectors/'}
]
}
},
replace: {
removeAMD: {
src: "build/assets/js/razorflow.min.js",
overwrite: true,
replacements: [
{from: /\bdefine\b/g, to: "_dfn"},
{from: /\brequire\b/g, to: "_rqr"}
]
}
},
clean: {
build: ["build"]
},
featuregen: {
getFeature: {
options: {
files: "src/js/**/*.js",
out: "build/out.html",
extension: ".js"
}
}
},
themegen: {
defaultTheme: {
options: {
themeJSON: "src/js/themebuilder/config/defaulttheme.json",
out: "build/tmp/less/rftheme.default.less"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-requirejs');
// grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadTasks("../grunt-contrib-jst/tasks");
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-lodash');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-copy-to');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadTasks("./tools/src/grunt-tasks");
grunt.registerTask('compile', ['themegen', 'less:development', 'jst:compile', 'copyto:sprite', 'copyto:themebuilder']);
grunt.registerTask('test', ['compile', 'karma:dev', 'shell:coverageReport']);
grunt.registerTask('build', ["clean:build", "copyto:razorcharts", "compile", "less", "jst:compile", 'requirejs:core', 'requirejs:wrapper', 'requirejs:debug', "replace:removeAMD", 'concat:css', 'cssmin:minify', "copyto:srcToBuild"])
// grunt.registerTask('package', ['build', 'copyto:packageToBuild', 'copyto:assetsToPackage']);
grunt.registerTask('packageMin', ['build', 'copyto:packageMinToBuild', 'copyto:assetsToMinPackage']);
grunt.registerTask('packageSrc', ['build', 'copyto:packageSrcToBuild', 'copyto:assetsToSrcPackage', 'copyto:srcToPackage']);
// grunt.registerTask('websiteRelease', ['build', 'cssmin:minify', 'squashdemos', "screenshotGen:examples", 'copy:localToWebRF'])
grunt.registerTask('package', ['clean:build', 'build', 'copyto:packageMinToBuild', 'copyto:assetsToMinPackage', 'copyto:packageSrcToBuild', 'copyto:assetsToSrcPackage', 'copyto:srcToPackage']);
} | RazorFlow/framework | tools/archive/old/jsrf_old/Gruntfile.js | JavaScript | mit | 10,232 |
exports.array_t = require('./array_t.js');
exports.buffer_t = require('./buffer_t.js');
exports.element_t = require('./element_t.js');
| joelek/webgl | source/buffers/buffers.js | JavaScript | mit | 135 |
describe('does-it-exist module', function () {
var exists = require('./../index.js'),
string = 'exists',
array = ['Does', 'element', 'exist'],
object = {
hello: 'world'
};
it('should return the does-it-exist module', function (done) {
if (exists) {
done();
} else {
return done('Failed to require does-it-exist');
}
});
it('should be of type function', function (done) {
if (typeof exists === 'function') {
done();
} else {
return done('exists is not a function!');
}
});
it('should return `true` for letter in string', function (done) {
if (exists(string, 'x')) {
done();
} else {
return done('letter in string test failed!');
}
});
it('should return `false` for letter not in string', function (done) {
if (!exists(string, 'p')) {
done();
} else {
return done('letter not in string test failed!');
}
});
it('should return `true` if element does exist in array', function (done) {
if (exists(array, 'element')) {
done();
} else {
return done('element in array test failed!');
}
});
it('should return `false` if element does not exist in array', function (done) {
if (!exists(array, 'could')) {
done();
} else {
return done('element in not array test failed!');
}
});
it('should return `true` if property does exist in object', function (done) {
if (exists(object, 'hello')) {
done();
} else {
return done('property exists in object test failed!');
}
});
it('should return `false` if element does not exist in array', function (done) {
if (!exists(object, 'could')) {
done();
} else {
return done('property does not exists in object test failed!');
}
});
});
| col1985/exists | test/test.js | JavaScript | mit | 1,816 |
/**
* Tests for the 'image/image.js' file.
*/
// Do not warn if these variables were not defined before.
/* global module, test, equal, deepEqual */
module("image");
test("Test Image getValue.", function() {
// create a simple image
var size0 = 4;
var imgSize0 = new dwv.image.Size(size0, size0, 1);
var imgSpacing0 = new dwv.image.Spacing(1, 1, 1);
var buffer0 = [];
for(var i=0; i<size0*size0; ++i) {
buffer0[i] = i;
}
var image0 = new dwv.image.Image(imgSize0, imgSpacing0, buffer0);
// test its values
equal( image0.getValue(0, 0, 0), 0, "Value at 0,0,0" );
equal( image0.getValue(1, 0, 0), 1, "Value at 1,0,0" );
equal( image0.getValue(1, 1, 0), 1*size0 + 1, "Value at 1,1,0" );
equal( image0.getValue(3, 3, 0), 3*size0 + 3, "Value at 3,3,0" );
equal( isNaN(image0.getValue(4, 3, 0)), true, "Value outside is NaN" );
// TODO: wrong, should not be accessed
equal( image0.getValue(5, 0, 0), 1*size0 + 1, "Value at 5,0,0" );
// image with rescale
var image1 = new dwv.image.Image(imgSize0, imgSpacing0, buffer0);
var slope1 = 2;
image1.setRescaleSlope(slope1);
var intercept1 = 10;
image1.setRescaleIntercept(intercept1);
// test its values
equal( image1.getValue(0, 0, 0), 0, "Value at 0,0,0" );
equal( image1.getValue(1, 0, 0), 1, "Value at 1,0,0" );
equal( image1.getValue(1, 1, 0), 1*size0 + 1, "Value at 1,1,0" );
equal( image1.getValue(3, 3, 0), 3*size0 + 3, "Value at 3,3,0" );
equal( image1.getRescaledValue(0, 0, 0), 0+intercept1, "Value at 0,0,0" );
equal( image1.getRescaledValue(1, 0, 0), 1*slope1+intercept1, "Value at 1,0,0" );
equal( image1.getRescaledValue(1, 1, 0), (1*size0 + 1)*slope1+intercept1, "Value at 1,1,0" );
equal( image1.getRescaledValue(3, 3, 0), (3*size0 + 3)*slope1+intercept1, "Value at 3,3,0" );
});
test("Test Image append slice.", function() {
var size = 4;
var imgSize = new dwv.image.Size(size, size, 2);
var imgSpacing = new dwv.image.Spacing(1, 1, 1);
// slice to append
var sliceSize = new dwv.image.Size(size, size, 1);
var sliceBuffer = new Int16Array(sliceSize.getTotalSize());
for(var i=0; i<size*size; ++i) {
sliceBuffer[i] = 2;
}
// image buffer
var buffer = new Int16Array(imgSize.getTotalSize());
for(var j=0; j<size*size; ++j) {
buffer[j] = 0;
}
for(var k=size*size; k<2*size*size; ++k) {
buffer[k] = 1;
}
// image 0
var image0 = new dwv.image.Image(imgSize, imgSpacing, buffer, [[0,0,0],[0,0,1]]);
var slice0 = new dwv.image.Image(sliceSize, imgSpacing, sliceBuffer, [[0,0,-1]]);
// append slice before
image0.appendSlice(slice0);
// test its values
equal( image0.getValue(0, 0, 0), 2, "Value at 0,0,0 (append before)" );
equal( image0.getValue(3, 3, 0), 2, "Value at 3,3,0 (append before)" );
equal( image0.getValue(0, 0, 1), 0, "Value at 0,0,1 (append before)" );
equal( image0.getValue(3, 3, 1), 0, "Value at 3,3,1 (append before)" );
equal( image0.getValue(0, 0, 2), 1, "Value at 0,0,2 (append before)" );
equal( image0.getValue(3, 3, 2), 1, "Value at 3,3,2 (append before)" );
// test its positions
var slicePositions0 = [];
slicePositions0[0] = [0,0,-1];
slicePositions0[1] = [0,0,0];
slicePositions0[2] = [0,0,1];
deepEqual( image0.getSlicePositions(), slicePositions0, "Slice positions (append before)" );
// image 1
var image1 = new dwv.image.Image(imgSize, imgSpacing, buffer, [[0,0,0],[0,0,1]]);
var slice1 = new dwv.image.Image(sliceSize, imgSpacing, sliceBuffer, [[0,0,2]]);
// append slice before
image1.appendSlice(slice1);
// test its values
equal( image1.getValue(0, 0, 0), 0, "Value at 0,0,0 (append after)" );
equal( image1.getValue(3, 3, 0), 0, "Value at 3,3,0 (append after)" );
equal( image1.getValue(0, 0, 1), 1, "Value at 0,0,1 (append after)" );
equal( image1.getValue(3, 3, 1), 1, "Value at 3,3,1 (append after)" );
equal( image1.getValue(0, 0, 2), 2, "Value at 0,0,2 (append after)" );
equal( image1.getValue(3, 3, 2), 2, "Value at 3,3,2 (append after)" );
// test its positions
var slicePositions1 = [];
slicePositions1[0] = [0,0,0];
slicePositions1[1] = [0,0,1];
slicePositions1[2] = [0,0,2];
deepEqual( image1.getSlicePositions(), slicePositions1, "Slice positions (append after)" );
// image 2
var image2 = new dwv.image.Image(imgSize, imgSpacing, buffer, [[0,0,0],[0,0,1]]);
var slice2 = new dwv.image.Image(sliceSize, imgSpacing, sliceBuffer, [[0,0,0.4]]);
// append slice before
image2.appendSlice(slice2);
// test its values
equal( image2.getValue(0, 0, 0), 0, "Value at 0,0,0 (append between)" );
equal( image2.getValue(3, 3, 0), 0, "Value at 3,3,0 (append between)" );
equal( image2.getValue(0, 0, 1), 2, "Value at 0,0,1 (append between)" );
equal( image2.getValue(3, 3, 1), 2, "Value at 3,3,1 (append between)" );
equal( image2.getValue(0, 0, 2), 1, "Value at 0,0,2 (append between)" );
equal( image2.getValue(3, 3, 2), 1, "Value at 3,3,2 (append between)" );
// test its positions
var slicePositions2 = [];
slicePositions2[0] = [0,0,0];
slicePositions2[1] = [0,0,0.4];
slicePositions2[2] = [0,0,1];
deepEqual( image2.getSlicePositions(), slicePositions2, "Slice positions (append between)" );
});
| mriveralee/tracheal-aire2 | tests/image/image.test.js | JavaScript | mit | 5,439 |
let [let = 10] = [];
| babel/babel | packages/babel-parser/test/fixtures/es2015/let/let-at-binding-list-fail-9/input.js | JavaScript | mit | 21 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, $, brackets, jasmine, describe, it, expect, beforeEach, afterEach, waitsFor, waits, waitsForDone, runs */
define(function (require, exports, module) {
'use strict';
var NativeFileSystem = require("file/NativeFileSystem").NativeFileSystem,
Commands = require("command/Commands"),
FileUtils = require("file/FileUtils"),
Async = require("utils/Async"),
DocumentManager = require("document/DocumentManager"),
Editor = require("editor/Editor").Editor,
EditorManager = require("editor/EditorManager"),
PanelManager = require("view/PanelManager"),
ExtensionLoader = require("utils/ExtensionLoader"),
UrlParams = require("utils/UrlParams").UrlParams,
LanguageManager = require("language/LanguageManager");
var TEST_PREFERENCES_KEY = "com.adobe.brackets.test.preferences",
OPEN_TAG = "{{",
CLOSE_TAG = "}}",
RE_MARKER = /\{\{(\d+)\}\}/g,
_testSuites = {},
_testWindow,
_doLoadExtensions,
nfs;
/**
* Resolves a path string to a FileEntry or DirectoryEntry
* @param {!string} path Path to a file or directory
* @return {$.Promise} A promise resolved when the file/directory is found or
* rejected when any error occurs.
*/
function resolveNativeFileSystemPath(path) {
var deferred = new $.Deferred();
NativeFileSystem.resolveNativeFileSystemPath(
path,
function success(entry) {
deferred.resolve(entry);
},
function error(domError) {
deferred.reject();
}
);
return deferred.promise();
}
/**
* Get or create a NativeFileSystem rooted at the system root.
* @return {$.Promise} A promise resolved when the native file system is found or rejected when an error occurs.
*/
function getRoot() {
var deferred = new $.Deferred();
if (nfs) {
deferred.resolve(nfs.root);
}
resolveNativeFileSystemPath("/").then(deferred.resolve, deferred.reject);
return deferred.promise();
}
function getTestRoot() {
// /path/to/brackets/test/SpecRunner.html
var path = window.location.pathname;
path = path.substr(0, path.lastIndexOf("/"));
path = FileUtils.convertToNativePath(path);
return path;
}
function getTestPath(path) {
return getTestRoot() + path;
}
/**
* Get the temporary unit test project path. Use this path for unit tests that need to modify files on disk.
* @return {$.string} Path to the temporary unit test project
*/
function getTempDirectory() {
return getTestPath("/temp");
}
/**
* Create the temporary unit test project directory.
*/
function createTempDirectory() {
var deferred = new $.Deferred();
runs(function () {
brackets.fs.makedir(getTempDirectory(), 0, function (err) {
if (err && err !== brackets.fs.ERR_FILE_EXISTS) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
});
waitsForDone(deferred, "Create temp directory", 500);
}
function getBracketsSourceRoot() {
var path = window.location.pathname;
path = path.split("/");
path = path.slice(0, path.length - 2);
path.push("src");
return path.join("/");
}
/**
* Utility for tests that wait on a Promise to complete. Placed in the global namespace so it can be used
* similarly to the standard Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE
* the runs() that generates the promise.
* @param {$.Promise} promise
* @param {string} operationName Name used for timeout error message
*/
window.waitsForDone = function (promise, operationName, timeout) {
timeout = timeout || 1000;
expect(promise).toBeTruthy();
waitsFor(function () {
return promise.state() === "resolved";
}, "success " + operationName, timeout);
};
/**
* Utility for tests that waits on a Promise to fail. Placed in the global namespace so it can be used
* similarly to the standards Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE
* the runs() that generates the promise.
* @param {$.Promise} promise
* @param {string} operationName Name used for timeout error message
*/
window.waitsForFail = function (promise, operationName, timeout) {
timeout = timeout || 1000;
expect(promise).toBeTruthy();
waitsFor(function () {
return promise.state() === "rejected";
}, "failure " + operationName, timeout);
};
/**
* Returns a Document suitable for use with an Editor in isolation, but that can be registered with
* DocumentManager via addRef() so it is maintained for global updates like name and language changes.
*
* Like a normal Document, if you cause an addRef() on this you MUST call releaseRef() later.
*
* @param {!{language:?string, filename:?string, content:?string }} options
* Language defaults to JavaScript, filename defaults to a placeholder name, and
* content defaults to "".
*/
function createMockActiveDocument(options) {
var language = options.language || LanguageManager.getLanguage("javascript"),
filename = options.filename || "_unitTestDummyFile_" + Date.now() + "." + language._fileExtensions[0],
content = options.content || "";
// Use unique filename to avoid collissions in open documents list
var dummyFile = new NativeFileSystem.FileEntry(filename);
var docToShim = new DocumentManager.Document(dummyFile, new Date(), content);
// Prevent adding doc to working set
docToShim._handleEditorChange = function (event, editor, changeList) {
this.isDirty = !editor._codeMirror.isClean();
// TODO: This needs to be kept in sync with Document._handleEditorChange(). In the
// future, we should fix things so that we either don't need mock documents or that this
// is factored so it will just run in both.
$(this).triggerHandler("change", [this, changeList]);
};
docToShim.notifySaved = function () {
throw new Error("Cannot notifySaved() a unit-test dummy Document");
};
return docToShim;
}
/**
* Returns a Document suitable for use with an Editor in isolation: i.e., a Document that will
* never be set as the currentDocument or added to the working set.
*
* Unlike a real Document, does NOT need to be explicitly cleaned up.
*
* @param {string=} initialContent Defaults to ""
* @param {string=} languageId Defaults to JavaScript
*/
function createMockDocument(initialContent, languageId) {
var language = LanguageManager.getLanguage(languageId) || LanguageManager.getLanguage("javascript"),
options = { language: language, content: initialContent },
docToShim = createMockActiveDocument(options);
// Prevent adding doc to global 'open docs' list; prevents leaks or collisions if a test
// fails to clean up properly (if test fails, or due to an apparent bug with afterEach())
docToShim.addRef = function () {};
docToShim.releaseRef = function () {};
docToShim._ensureMasterEditor = function () {
if (!this._masterEditor) {
// Don't let Document create an Editor itself via EditorManager; the unit test can't clean that up
throw new Error("Use create/destroyMockEditor() to test edit operations");
}
};
return docToShim;
}
/**
* Returns a mock element (in the test runner window) that's offscreen, for
* parenting UI you want to unit-test. When done, make sure to delete it with
* remove().
* @return {jQueryObject} a jQuery object for an offscreen div
*/
function createMockElement() {
return $("<div/>")
.css({
position: "absolute",
left: "-10000px",
top: "-10000px"
})
.appendTo($("body"));
}
/**
* Returns an Editor tied to the given Document, but suitable for use in isolation
* (without being placed inside the surrounding Brackets UI). The Editor *will* be
* reported as the "active editor" by EditorManager.
*
* Must be cleaned up by calling destroyMockEditor(document) later.
*
* @param {!Document} doc
* @param {{startLine: number, endLine: number}=} visibleRange
* @return {!Editor}
*/
function createMockEditorForDocument(doc, visibleRange) {
// Initialize EditorManager/PanelManager and position the editor-holder offscreen
// (".content" may not exist, but that's ok for headless tests where editor height doesn't matter)
var $editorHolder = createMockElement().attr("id", "mock-editor-holder");
PanelManager._setMockDOM($(".content"), $editorHolder);
EditorManager.setEditorHolder($editorHolder);
// create Editor instance
var editor = new Editor(doc, true, $editorHolder.get(0), visibleRange);
EditorManager._notifyActiveEditorChanged(editor);
return editor;
}
/**
* Returns a Document and Editor suitable for use in isolation: the Document
* will never be set as the currentDocument or added to the working set and the
* Editor does not live inside a full-blown Brackets UI layout. The Editor *will* be
* reported as the "active editor" by EditorManager, however.
*
* Must be cleaned up by calling destroyMockEditor(document) later.
*
* @param {string=} initialContent
* @param {string=} languageId
* @param {{startLine: number, endLine: number}=} visibleRange
* @return {!{doc:!Document, editor:!Editor}}
*/
function createMockEditor(initialContent, languageId, visibleRange) {
// create dummy Document, then Editor tied to it
var doc = createMockDocument(initialContent, languageId);
return { doc: doc, editor: createMockEditorForDocument(doc, visibleRange) };
}
/**
* Destroy the Editor instance for a given mock Document.
* @param {!Document} doc Document whose master editor to destroy
*/
function destroyMockEditor(doc) {
EditorManager._notifyActiveEditorChanged(null);
EditorManager._destroyEditorIfUnneeded(doc);
// Clear editor holder so EditorManager doesn't try to resize destroyed object
EditorManager.setEditorHolder(null);
$("#mock-editor-holder").remove();
}
/**
* Dismiss the currently open dialog as if the user had chosen the given button. Dialogs close
* asynchronously; after calling this, you need to start a new runs() block before testing the
* outcome. Also, in cases where asynchronous tasks are performed after the dialog closes,
* clients must also wait for any additional promises.
* @param {string} buttonId One of the Dialogs.DIALOG_BTN_* symbolic constants.
*/
function clickDialogButton(buttonId) {
// Make sure there's one and only one dialog open
var $dlg = _testWindow.$(".modal.instance"),
promise = $dlg.data("promise");
expect($dlg.length).toBe(1);
// Make sure desired button exists
var dismissButton = $dlg.find(".dialog-button[data-button-id='" + buttonId + "']");
expect(dismissButton.length).toBe(1);
// Click the button
dismissButton.click();
// Dialog should resolve/reject the promise
waitsForDone(promise, "dismiss dialog");
}
function createTestWindowAndRun(spec, callback) {
runs(function () {
// Position popup windows in the lower right so they're out of the way
var testWindowWid = 1000,
testWindowHt = 700,
testWindowX = window.screen.availWidth - testWindowWid,
testWindowY = window.screen.availHeight - testWindowHt,
optionsStr = "left=" + testWindowX + ",top=" + testWindowY +
",width=" + testWindowWid + ",height=" + testWindowHt;
var params = new UrlParams();
// setup extension loading in the test window
params.put("extensions", _doLoadExtensions ?
"default,dev," + ExtensionLoader.getUserExtensionPath() :
"default");
// disable update check in test windows
params.put("skipUpdateCheck", true);
// disable loading of sample project
params.put("skipSampleProjectLoad", true);
// disable initial dialog for live development
params.put("skipLiveDevelopmentInfo", true);
_testWindow = window.open(getBracketsSourceRoot() + "/index.html?" + params.toString(), "_blank", optionsStr);
_testWindow.isBracketsTestWindow = true;
_testWindow.executeCommand = function executeCommand(cmd, args) {
return _testWindow.brackets.test.CommandManager.execute(cmd, args);
};
_testWindow.closeAllFiles = function closeAllFiles() {
runs(function () {
var promise = _testWindow.executeCommand(_testWindow.brackets.test.Commands.FILE_CLOSE_ALL);
waitsForDone(promise, "Close all open files in working set");
var $dlg = _testWindow.$(".modal.instance");
if ($dlg.length) {
clickDialogButton("dontsave");
}
});
};
});
// FIXME (issue #249): Need an event or something a little more reliable...
waitsFor(
function isBracketsDoneLoading() {
return _testWindow.brackets && _testWindow.brackets.test && _testWindow.brackets.test.doneLoading;
},
"brackets.test.doneLoading",
10000
);
runs(function () {
// callback allows specs to query the testWindow before they run
callback.call(spec, _testWindow);
});
}
function closeTestWindow() {
// debug-only to see testWindow state before closing
// waits(500);
runs(function () {
//we need to mark the documents as not dirty before we close
//or the window will stay open prompting to save
var openDocs = _testWindow.brackets.test.DocumentManager.getAllOpenDocuments();
openDocs.forEach(function resetDoc(doc) {
if (doc.isDirty) {
//just refresh it back to it's current text. This will mark it
//clean to save
doc.refreshText(doc.getText(), doc.diskTimestamp);
}
});
_testWindow.close();
_testWindow.executeCommand = null;
_testWindow = null;
});
}
function loadProjectInTestWindow(path) {
runs(function () {
// begin loading project path
var result = _testWindow.brackets.test.ProjectManager.openProject(path);
// wait for file system to finish loading
waitsForDone(result, "ProjectManager.openProject()");
});
}
/**
* Parses offsets from text offset markup (e.g. "{{1}}" for offset 1).
* @param {!string} text Text to parse
* @return {!{offsets:!Array.<{line:number, ch:number}>, text:!string, original:!string}}
*/
function parseOffsetsFromText(text) {
var offsets = [],
output = [],
i = 0,
line = 0,
charAt = 0,
ch = 0,
length = text.length,
exec = null,
found = false;
while (i < length) {
found = false;
if (text.slice(i, i + OPEN_TAG.length) === OPEN_TAG) {
// find "{{[0-9]+}}"
RE_MARKER.lastIndex = i;
exec = RE_MARKER.exec(text);
found = (exec !== null && exec.index === i);
if (found) {
// record offset info
offsets[exec[1]] = {line: line, ch: ch};
// advance
i += exec[0].length;
}
}
if (!found) {
charAt = text.substr(i, 1);
output.push(charAt);
if (charAt === '\n') {
line++;
ch = 0;
} else {
ch++;
}
i++;
}
}
return {offsets: offsets, text: output.join(""), original: text};
}
/**
* Creates absolute paths based on the test window's current project
* @param {!Array.<string>|string} paths Project relative file path(s) to convert. May pass a single string path or array.
* @return {!Array.<string>|string} Absolute file path(s)
*/
function makeAbsolute(paths) {
var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath;
function prefixProjectPath(path) {
if (path.indexOf(fullPath) === 0) {
return path;
}
return fullPath + path;
}
if (Array.isArray(paths)) {
return paths.map(prefixProjectPath);
} else {
return prefixProjectPath(paths);
}
}
/**
* Creates relative paths based on the test window's current project. Any paths,
* outside the project are included in the result, but left as absolute paths.
* @param {!Array.<string>|string} paths Absolute file path(s) to convert. May pass a single string path or array.
* @return {!Array.<string>|string} Relative file path(s)
*/
function makeRelative(paths) {
var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath,
fullPathLength = fullPath.length;
function removeProjectPath(path) {
if (path.indexOf(fullPath) === 0) {
return path.substring(fullPathLength);
}
return path;
}
if (Array.isArray(paths)) {
return paths.map(removeProjectPath);
} else {
return removeProjectPath(paths);
}
}
function makeArray(arg) {
if (!Array.isArray(arg)) {
return [arg];
}
return arg;
}
/**
* Parses offsets from a file using offset markup (e.g. "{{1}}" for offset 1).
* @param {!FileEntry} entry File to open
* @return {$.Promise} A promise resolved with a record that contains parsed offsets,
* the file text without offset markup, the original file content, and the corresponding
* file entry.
*/
function parseOffsetsFromFile(entry) {
var result = new $.Deferred();
FileUtils.readAsText(entry).done(function (text) {
var info = parseOffsetsFromText(text);
info.fileEntry = entry;
result.resolve(info);
}).fail(function (err) {
result.reject(err);
});
return result.promise();
}
/**
* Opens project relative file paths in the test window
* @param {!(Array.<string>|string)} paths Project relative file path(s) to open
* @return {!$.Promise} A promise resolved with a mapping of project-relative path
* keys to a corresponding Document
*/
function openProjectFiles(paths) {
var result = new $.Deferred(),
fullpaths = makeArray(makeAbsolute(paths)),
keys = makeArray(makeRelative(paths)),
docs = {},
FileViewController = _testWindow.brackets.test.FileViewController;
Async.doSequentially(fullpaths, function (path, i) {
var one = new $.Deferred();
FileViewController.addToWorkingSetAndSelect(path).done(function (doc) {
docs[keys[i]] = doc;
one.resolve();
}).fail(function (err) {
one.reject(err);
});
return one.promise();
}, false).done(function () {
result.resolve(docs);
}).fail(function (err) {
result.reject(err);
}).always(function () {
docs = null;
FileViewController = null;
});
return result.promise();
}
/**
* Create or overwrite a text file
* @param {!string} path Path for a file to be created/overwritten
* @param {!string} text Text content for the new file
* @return {$.Promise} A promise resolved when the file is written or rejected when an error occurs.
*/
function createTextFile(path, text) {
var deferred = new $.Deferred();
getRoot().done(function (nfs) {
// create the new FileEntry
nfs.getFile(path, { create: true }, function success(entry) {
// write text this new FileEntry
FileUtils.writeText(entry, text).done(function () {
deferred.resolve(entry);
}).fail(function () {
deferred.reject();
});
}, function error(err) {
deferred.reject(err);
});
});
return deferred.promise();
}
/**
* Copy a file source path to a destination
* @param {!FileEntry} source Entry for the source file to copy
* @param {!string} destination Destination path to copy the source file
* @param {?{parseOffsets:boolean}} options parseOffsets allows optional
* offset markup parsing. File is written to the destination path
* without offsets. Offset data is passed to the doneCallbacks of the
* promise.
* @return {$.Promise} A promise resolved when the file is copied to the
* destination.
*/
function copyFileEntry(source, destination, options) {
options = options || {};
var deferred = new $.Deferred();
// read the source file
FileUtils.readAsText(source).done(function (text, modificationTime) {
getRoot().done(function (nfs) {
var offsets;
// optionally parse offsets
if (options.parseOffsets) {
var parseInfo = parseOffsetsFromText(text);
text = parseInfo.text;
offsets = parseInfo.offsets;
}
// create the new FileEntry
createTextFile(destination, text).done(function (entry) {
deferred.resolve(entry, offsets, text);
}).fail(function () {
deferred.reject();
});
});
}).fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Copy a directory source to a destination
* @param {!DirectoryEntry} source Entry for the source directory to copy
* @param {!string} destination Destination path to copy the source directory
* @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options
* parseOffsets - allows optional offset markup parsing. File is written to the
* destination path without offsets. Offset data is passed to the
* doneCallbacks of the promise.
* infos - an optional Object used when parseOffsets is true. Offset
* information is attached here, indexed by the file destination path.
* removePrefix - When parseOffsets is true, set removePrefix true
* to add a new key to the infos array that drops the destination
* path root.
* @return {$.Promise} A promise resolved when the directory and all it's
* contents are copied to the destination or rejected immediately
* upon the first error.
*/
function copyDirectoryEntry(source, destination, options) {
options = options || {};
options.infos = options.infos || {};
var parseOffsets = options.parseOffsets || false,
removePrefix = options.removePrefix || true,
deferred = new $.Deferred();
// create the destination folder
brackets.fs.makedir(destination, parseInt("644", 8), function callback(err) {
if (err && err !== brackets.fs.ERR_FILE_EXISTS) {
deferred.reject();
return;
}
source.createReader().readEntries(function handleEntries(entries) {
if (entries.length === 0) {
deferred.resolve();
return;
}
// copy all children of this directory
var copyChildrenPromise = Async.doInParallel(
entries,
function copyChild(child) {
var childDestination = destination + "/" + child.name,
promise;
if (child.isDirectory) {
promise = copyDirectoryEntry(child, childDestination, options);
} else {
promise = copyFileEntry(child, childDestination, options);
if (parseOffsets) {
// save offset data for each file path
promise.done(function (destinationEntry, offsets, text) {
options.infos[childDestination] = {
offsets : offsets,
fileEntry : destinationEntry,
text : text
};
});
}
}
return promise;
},
true
);
copyChildrenPromise.then(deferred.resolve, deferred.reject);
});
});
deferred.always(function () {
// remove destination path prefix
if (removePrefix && options.infos) {
var shortKey;
Object.keys(options.infos).forEach(function (key) {
shortKey = key.substr(destination.length + 1);
options.infos[shortKey] = options.infos[key];
});
}
});
return deferred.promise();
}
/**
* Copy a file or directory source path to a destination
* @param {!string} source Path for the source file or directory to copy
* @param {!string} destination Destination path to copy the source file or directory
* @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options
* parseOffsets - allows optional offset markup parsing. File is written to the
* destination path without offsets. Offset data is passed to the
* doneCallbacks of the promise.
* infos - an optional Object used when parseOffsets is true. Offset
* information is attached here, indexed by the file destination path.
* removePrefix - When parseOffsets is true, set removePrefix true
* to add a new key to the infos array that drops the destination
* path root.
* @return {$.Promise} A promise resolved when the directory and all it's
* contents are copied to the destination or rejected immediately
* upon the first error.
*/
function copyPath(source, destination, options) {
var deferred = new $.Deferred();
resolveNativeFileSystemPath(source).done(function (entry) {
var promise;
if (entry.isDirectory) {
promise = copyDirectoryEntry(entry, destination, options);
} else {
promise = copyFileEntry(entry, destination, options);
}
promise.then(deferred.resolve, deferred.reject);
}).fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Set editor cursor position to the given offset then activate an inline editor.
* @param {!Editor} editor
* @param {!{line:number, ch:number}} offset
* @return {$.Promise} a promise that will be resolved when an inline
* editor is created or rejected when no inline editors are available.
*/
function toggleQuickEditAtOffset(editor, offset) {
editor.setCursorPos(offset.line, offset.ch);
return _testWindow.executeCommand(Commands.TOGGLE_QUICK_EDIT);
}
/**
* @param {string} fullPath
* @return {$.Promise} Resolved when deletion complete, or rejected if an error occurs
*/
function deletePath(fullPath) {
var result = new $.Deferred();
brackets.fs.unlink(fullPath, function (err) {
if (err) {
console.error(err);
result.reject(err);
} else {
result.resolve();
}
});
return result.promise();
}
/**
* Simulate key event. Found this code here:
* http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key
*
* TODO: need parameter(s) for modifier keys
*
* @param {Number} key Key code
* @param (String) event Key event to simulate
* @param {HTMLElement} element Element to receive event
*/
function simulateKeyEvent(key, event, element) {
var doc = element.ownerDocument,
oEvent = doc.createEvent('KeyboardEvent');
if (event !== "keydown" && event !== "keyup" && event !== "keypress") {
console.log("SpecRunnerUtils.simulateKeyEvent() - unsupported keyevent: " + event);
return;
}
// Chromium Hack: need to override the 'which' property.
// Note: this code is not designed to work in IE, Safari,
// or other browsers. Well, maybe with Firefox. YMMV.
Object.defineProperty(oEvent, 'keyCode', {
get: function () {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get: function () {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'charCode', {
get: function () {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent(event, true, true, doc.defaultView, key, 0, false, false, false, false);
} else {
oEvent.initKeyEvent(event, true, true, doc.defaultView, false, false, false, false, key, 0);
}
oEvent.keyCodeVal = key;
if (oEvent.keyCode !== key) {
console.log("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
element.dispatchEvent(oEvent);
}
function getTestWindow() {
return _testWindow;
}
function setLoadExtensionsInTestWindow(doLoadExtensions) {
_doLoadExtensions = doLoadExtensions;
}
/**
* Extracts the jasmine.log() and/or jasmine.expect() messages from the given result,
* including stack traces if available.
* @param {Object} result A jasmine result item (from results.getItems()).
* @return {string} the error message from that item.
*/
function getResultMessage(result) {
var message;
if (result.type === 'log') {
message = result.toString();
} else if (result.type === 'expect' && result.passed && !result.passed()) {
message = result.message;
if (result.trace.stack) {
message = result.trace.stack;
}
}
return message;
}
/**
* Set permissions on a path
* @param {!string} path Path to change permissions on
* @param {!string} mode New mode as an octal string
* @return {$.Promise} Resolved when permissions are set or rejected if an error occurs
*/
function chmod(path, mode) {
var deferred = new $.Deferred();
brackets.fs.chmod(path, parseInt(mode, 8), function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise();
}
/**
* Remove a directory (recursively) or file
*
* @param {!string} path Path to remove
* @return {$.Promise} Resolved when the path is removed, rejected if there was a problem
*/
function remove(path) {
var d = new $.Deferred();
var nodeDeferred = brackets.testing.getNodeConnectionDeferred();
nodeDeferred
.done(function (connection) {
if (connection.connected()) {
connection.domains.testing.remove(path)
.done(function () {
d.resolve();
})
.fail(function () {
d.reject();
});
} else {
d.reject();
}
})
.fail(function () {
d.reject();
});
return d.promise();
}
/**
* Searches the DOM tree for text containing the given content. Useful for verifying
* that data you expect to show up in the UI somewhere is actually there.
*
* @param {jQueryObject|Node} root The root element to search from. Can be either a jQuery object
* or a raw DOM node.
* @param {string} content The content to find.
* @param {boolean} asLink If true, find the content in the href of an <a> tag, otherwise find it in text nodes.
* @return true if content was found
*/
function findDOMText(root, content, asLink) {
// Unfortunately, we can't just use jQuery's :contains() selector, because it appears that
// you can't escape quotes in it.
var i;
if (root instanceof $) {
root = root.get(0);
}
if (!root) {
return false;
} else if (!asLink && root.nodeType === 3) { // text node
return root.textContent.indexOf(content) !== -1;
} else {
if (asLink && root.nodeType === 1 && root.tagName.toLowerCase() === "a" && root.getAttribute("href") === content) {
return true;
}
var children = root.childNodes;
for (i = 0; i < children.length; i++) {
if (findDOMText(children[i], content, asLink)) {
return true;
}
}
return false;
}
}
/**
* Counts the number of active specs in the current suite. Includes all
* descendants.
* @param {(jasmine.Suite|jasmine.Spec)} suiteOrSpec
* @return {number}
*/
function countSpecs(suiteOrSpec) {
var children = suiteOrSpec.children && typeof suiteOrSpec.children === "function" && suiteOrSpec.children();
if (Array.isArray(children)) {
var childCount = 0;
children.forEach(function (child) {
childCount += countSpecs(child);
});
return childCount;
}
if (jasmine.getEnv().specFilter(suiteOrSpec)) {
return 1;
}
return 0;
}
/**
* @private
* Adds a new before all or after all function to the current suite. If requires it creates a new
* object to store the before all and after all functions and a spec counter for the current suite.
* @param {string} type "beforeFirst" or "afterLast"
* @param {function} func The function to store
*/
function _addSuiteFunction(type, func) {
var suiteId = jasmine.getEnv().currentSuite.id;
if (!_testSuites[suiteId]) {
_testSuites[suiteId] = {
beforeFirst : [],
afterLast : [],
specCounter : null
};
}
_testSuites[suiteId][type].push(func);
}
/**
* Utility for tests that need to open a window or do something before every test in a suite
* @param {function} func
*/
window.beforeFirst = function (func) {
_addSuiteFunction("beforeFirst", func);
};
/**
* Utility for tests that need to close a window or do something after every test in a suite
* @param {function} func
*/
window.afterLast = function (func) {
_addSuiteFunction("afterLast", func);
};
/**
* @private
* Calls each function in the given array of functions
* @param {Array.<function>} functions
*/
function _callFunctions(functions) {
var spec = jasmine.getEnv().currentSpec;
functions.forEach(function (func) {
func.apply(spec);
});
}
/**
* Calls the before first functions for the parent suites of the current spec when is the first spec of each suite.
*/
function runBeforeFirst() {
var suite = jasmine.getEnv().currentSpec.suite;
// Iterate throught all the parent suites of the current spec
while (suite) {
// If we have functions for this suite and it was never called, initialize the spec counter
if (_testSuites[suite.id] && _testSuites[suite.id].specCounter === null) {
_callFunctions(_testSuites[suite.id].beforeFirst);
_testSuites[suite.id].specCounter = countSpecs(suite);
}
suite = suite.parentSuite;
}
}
/**
* Calls the after last functions for the parent suites of the current spec when is the last spec of each suite.
*/
function runAfterLast() {
var suite = jasmine.getEnv().currentSpec.suite;
// Iterate throught all the parent suites of the current spec
while (suite) {
// If we have functions for this suite, reduce the spec counter
if (_testSuites[suite.id] && _testSuites[suite.id].specCounter > 0) {
_testSuites[suite.id].specCounter--;
// If this was the last spec of the suite run the after last functions and remove it
if (_testSuites[suite.id].specCounter === 0) {
_callFunctions(_testSuites[suite.id].afterLast);
delete _testSuites[suite.id];
}
}
suite = suite.parentSuite;
}
}
beforeEach(function () {
this.addMatchers({
/**
* Expects the given editor's selection to be a cursor at the given position (no range selected)
*/
toHaveCursorPosition: function (line, ch) {
var editor = this.actual;
var selection = editor.getSelection();
var notString = this.isNot ? "not " : "";
var start = selection.start;
var end = selection.end;
var selectionMoreThanOneCharacter = start.line !== end.line || start.ch !== end.ch;
this.message = function () {
var message = "Expected the cursor to " + notString + "be at (" + line + ", " + ch +
") but it was actually at (" + start.line + ", " + start.ch + ")";
if (!this.isNot && selectionMoreThanOneCharacter) {
message += " and more than one character was selected.";
}
return message;
};
var positionsMatch = start.line === line && start.ch === ch;
// when adding the not operator, it's confusing to check both the size of the
// selection and the position. We just check the position in that case.
if (this.isNot) {
return positionsMatch;
} else {
return !selectionMoreThanOneCharacter && positionsMatch;
}
}
});
});
exports.TEST_PREFERENCES_KEY = TEST_PREFERENCES_KEY;
exports.chmod = chmod;
exports.remove = remove;
exports.getTestRoot = getTestRoot;
exports.getTestPath = getTestPath;
exports.getTempDirectory = getTempDirectory;
exports.createTempDirectory = createTempDirectory;
exports.getBracketsSourceRoot = getBracketsSourceRoot;
exports.makeAbsolute = makeAbsolute;
exports.resolveNativeFileSystemPath = resolveNativeFileSystemPath;
exports.createMockDocument = createMockDocument;
exports.createMockActiveDocument = createMockActiveDocument;
exports.createMockElement = createMockElement;
exports.createMockEditorForDocument = createMockEditorForDocument;
exports.createMockEditor = createMockEditor;
exports.createTestWindowAndRun = createTestWindowAndRun;
exports.closeTestWindow = closeTestWindow;
exports.clickDialogButton = clickDialogButton;
exports.destroyMockEditor = destroyMockEditor;
exports.loadProjectInTestWindow = loadProjectInTestWindow;
exports.openProjectFiles = openProjectFiles;
exports.toggleQuickEditAtOffset = toggleQuickEditAtOffset;
exports.createTextFile = createTextFile;
exports.copyDirectoryEntry = copyDirectoryEntry;
exports.copyFileEntry = copyFileEntry;
exports.copyPath = copyPath;
exports.deletePath = deletePath;
exports.getTestWindow = getTestWindow;
exports.simulateKeyEvent = simulateKeyEvent;
exports.setLoadExtensionsInTestWindow = setLoadExtensionsInTestWindow;
exports.getResultMessage = getResultMessage;
exports.parseOffsetsFromText = parseOffsetsFromText;
exports.findDOMText = findDOMText;
exports.countSpecs = countSpecs;
exports.runBeforeFirst = runBeforeFirst;
exports.runAfterLast = runAfterLast;
});
| 0bara/brackets | test/spec/SpecRunnerUtils.js | JavaScript | mit | 45,627 |
"use strict";
var assert = require("assert");
var testUtils = require("./helpers/util.js");
const Promise = require('../promise');
/*!
*
Copyright 2009–2012 Kristopher Michael Kowal. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
describe("spread", function () {
it("spreads values across arguments", function () {
return Promise.resolve([1, 2, 3]).spread(function (a, b) {
assert.equal(b,2);
});
});
it("spreads promises for arrays across arguments", function () {
return Promise.resolve([Promise.resolve(10)])
.all()
.spread(function (value) {
assert.equal(value,10);
});
});
it("spreads arrays of promises across arguments", function () {
var deferredA = Promise.defer();
var deferredB = Promise.defer();
var promise = Promise.resolve([deferredA.promise, deferredB.promise]).all().spread(
function (a, b) {
assert.equal(a,10);
assert.equal(b,20);
});
Promise.delay(1).then(function () {
deferredA.resolve(10);
});
Promise.delay(1).then(function () {
deferredB.resolve(20);
});
return promise;
});
it("spreads arrays of thenables across arguments", function () {
var p1 = {
then: function(v) {
v(10);
}
};
var p2 = {
then: function(v) {
v(20);
}
};
var promise = Promise.resolve([p1, p2]).all().spread(function (a, b) {
assert.equal(a,10);
assert.equal(b,20);
});
return promise;
});
it("should wait for promises in the returned array even when not calling .all", function() {
var d1 = Promise.defer();
var d2 = Promise.defer();
var d3 = Promise.defer();
setTimeout(function(){
d1.resolve(1);
d2.resolve(2);
d3.resolve(3);
}, 1);
return Promise.resolve().then(function(){
return [d1.promise, d2.promise, d3.promise];
}).all().spread(function(a, b, c){
assert(a === 1);
assert(b === 2);
assert(c === 3);
});
});
it("should wait for thenables in the returned array even when not calling .all", function() {
var t1 = {
then: function(fn) {
setTimeout(function(){
fn(1);
}, 1);
}
};
var t2 = {
then: function(fn) {
setTimeout(function(){
fn(2);
}, 1);
}
};
var t3 = {
then: function(fn) {
setTimeout(function(){
fn(3);
}, 1);
}
};
return Promise.resolve().then(function(){
return [t1, t2, t3];
}).all().spread(function(a, b, c){
assert(a === 1);
assert(b === 2);
assert(c === 3);
});
});
it("should wait for promises in an array that a returned promise resolves to even when not calling .all", function() {
var d1 = Promise.defer();
var d2 = Promise.defer();
var d3 = Promise.defer();
var defer = Promise.defer();
setTimeout(function(){
defer.resolve([d1.promise, d2.promise, d3.promise]);
setTimeout(function(){
d1.resolve(1);
d2.resolve(2);
d3.resolve(3);
}, 1);
}, 1);
return Promise.resolve().then(function(){
return defer.promise;
}).all().spread(function(a, b, c){
assert(a === 1);
assert(b === 2);
assert(c === 3);
});
});
it("should wait for thenables in an array that a returned thenable resolves to even when not calling .all", function() {
var t1 = {
then: function(fn) {
setTimeout(function(){
fn(1);
}, 1);
}
};
var t2 = {
then: function(fn) {
setTimeout(function(){
fn(2);
}, 1);
}
};
var t3 = {
then: function(fn) {
setTimeout(function(){
fn(3);
}, 1);
}
};
var thenable = {
then: function(fn) {
setTimeout(function(){
fn([t1, t2, t3])
}, 1);
}
};
return Promise.resolve().then(function(){
return thenable;
}).all().spread(function(a, b, c){
assert(a === 1);
assert(b === 2);
assert(c === 3);
});
});
it("should reject with error when non array is the ultimate value to be spread", function(){
return Promise.resolve().then(function(){
return 3
}).spread(function(a, b, c){
assert.fail();
}).then(assert.fail, function(e){
})
});
specify("gh-235", function() {
var P = Promise;
return P.resolve(1).then(function(x) {
return [x, P.resolve(2)]
}).spread(function(x, y) {
return P.all([P.resolve(3), P.resolve(4)]);
}).then(function(a) {
assert.deepEqual([3, 4], a);
});
})
specify("error when passed non-function", function() {
return Promise.resolve(3)
.spread()
.then(assert.fail)
.caught(Promise.TypeError, function() {});
});
specify("error when resolution is non-spredable", function() {
return Promise.resolve(3)
.spread(function(){})
.then(assert.fail)
.caught(Promise.TypeError, function() {});
});
});
/*
Based on When.js tests
Open Source Initiative OSI - The MIT License
http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2011 Brian Cavalier
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/
describe("Promise.spread-test", function () {
var slice = [].slice;
specify("should return a promise", function() {
assert(typeof (Promise.defer().promise.spread(function(){}).then) === "function");
});
specify("should apply onFulfilled with array as argument list", function() {
var expected = [1, 2, 3];
return Promise.resolve(expected).spread(function() {
assert.deepEqual(slice.call(arguments), expected);
});
});
specify("should resolve array contents", function() {
var expected = [Promise.resolve(1), 2, Promise.resolve(3)];
return Promise.resolve(expected).all().spread(function() {
assert.deepEqual(slice.call(arguments), [1, 2, 3]);
});
});
specify("should reject if any item in array rejects", function() {
var expected = [Promise.resolve(1), 2, Promise.reject(3)];
return Promise.resolve(expected).all()
.spread(assert.fail)
.then(assert.fail, function() {});
});
specify("should apply onFulfilled with array as argument list", function() {
var expected = [1, 2, 3];
return Promise.resolve(Promise.resolve(expected)).spread(function() {
assert.deepEqual(slice.call(arguments), expected);
});
});
specify("should resolve array contents", function() {
var expected = [Promise.resolve(1), 2, Promise.resolve(3)];
return Promise.resolve(Promise.resolve(expected)).all().spread(function() {
assert.deepEqual(slice.call(arguments), [1, 2, 3]);
});
});
specify("should reject if input is a rejected promise", function() {
var expected = Promise.reject([1, 2, 3]);
return Promise.resolve(expected)
.spread(assert.fail)
.then(assert.fail, function() {});
});
}); | benjamingr/bluebird-api | tests/spread.js | JavaScript | mit | 10,054 |
var app = module.parent.exports;
app.get('/', function(req, res) {
res.render('index.jade');
});
| KingShimkus/Imgage | main.js | JavaScript | mit | 100 |
(function() {
if (mw.config.get('wgAction') !== 'info') {
return;
}
function main() {
$('#template-last-edit').remove();
var api = new mw.Api();
var templates = [], elmap = [];
mw.loader.using(['mediawiki.api'], function() {
$('#mw-pageinfo-templates li>a:first-child').each(function(i, e) {
var title = $(e).text();
templates.push(title);
elmap[title] = e;
});
});
while (templates.length) {
var chunks = templates.splice(0, 50);
api.get({
"action": "query",
"format": "json",
"prop": "revisions",
"titles": chunks.join('|'),
"rvprop": "timestamp"
}).done(function(data) {
for (const pageid in data.query.pages) {
const page = data.query.pages[pageid];
if (Object.hasOwnProperty.call(elmap, page.title)) {
var timestamp = page.revisions[0].timestamp;
timestamp = timestamp.replace(/^(\d+-\d+-\d+)T(\d+:\d+):\d+Z$/, '$1 $2');
$(elmap[page.title]).parent().append(timestamp);
}
}
})
}
}
$('<br><button id="template-last-edit">顯示最近編輯日期</button>').on('click', main).appendTo($('#mw-pageinfo-templates>:first-child'));
})();
| Xi-Plus/Xiplus-zhWP | templates-last-edit.js | JavaScript | mit | 1,156 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m20.22 10-4.15.01c-.16-.01-.31.02-.45.08l-.59.26-1.83-4.1c-.56-1.26-2.04-1.83-3.3-1.27s-1.83 2.04-1.27 3.3l3.3 7.45-1.87.39c-.19.05-.99.27-1.36 1.21L8 19.19l6.78 2.67c.49.19 1.05.18 1.53-.04l5.99-2.65c.89-.4 1.37-1.38 1.13-2.32l-1.36-5.34c-.22-.86-.97-1.47-1.85-1.51zm1.27 7.34L15.5 20l-4.92-1.96 4.18-.88-4.3-9.7c-.11-.25 0-.55.25-.66.25-.11.55 0 .66.25l2.5 5.65 1.61-.71 4.65.01 1.36 5.34zM2.06 5.56 1 4.5 4.5 1 8 4.5 6.94 5.56 5.32 3.94C5.11 4.76 5 5.62 5 6.5c0 2.42.82 4.65 2.2 6.43L6.13 14C4.49 11.95 3.5 9.34 3.5 6.5c0-.92.1-1.82.3-2.68L2.06 5.56z"
}), 'SwipeUpOutlined');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/SwipeUpOutlined.js | JavaScript | mit | 1,024 |
import React from 'react';
import mountable from 'react-prop-types/lib/mountable';
import ownerDocument from './utils/ownerDocument';
import getContainer from './utils/getContainer';
/**
* The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy.
* You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.
* The children of `<Portal/>` component will be appended to the `container` specified.
*/
let Portal = React.createClass({
displayName: 'Portal',
propTypes: {
/**
* A Node, Component instance, or function that returns either. The `container` will have the Portal children
* appended to it.
*/
container: React.PropTypes.oneOfType([
mountable,
React.PropTypes.func
])
},
componentDidMount() {
this._renderOverlay();
},
componentDidUpdate() {
this._renderOverlay();
},
componentWillUnmount() {
this._unrenderOverlay();
this._unmountOverlayTarget();
},
_mountOverlayTarget() {
if (!this._overlayTarget) {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
}
},
_unmountOverlayTarget() {
if (this._overlayTarget) {
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
}
},
_renderOverlay() {
let overlay = !this.props.children
? null
: React.Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this._mountOverlayTarget();
this._overlayInstance = React.render(overlay, this._overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
this._unmountOverlayTarget();
}
},
_unrenderOverlay() {
if (this._overlayTarget) {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
}
},
render() {
return null;
},
getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
if (this._overlayInstance.getWrappedDOMNode) {
return this._overlayInstance.getWrappedDOMNode();
} else {
return React.findDOMNode(this._overlayInstance);
}
}
return null;
},
getContainerDOMNode() {
return getContainer(this.props.container, ownerDocument(this).body);
}
});
export default Portal;
| aparticka/react-overlays | src/Portal.js | JavaScript | mit | 2,601 |
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://dbuser:pass#123@ds157342.mlab.com:57342/heroku_4p9ggb81');
//mongoose.connect('mongodb://localhost:27017/datacenter'); | AhmedAlmodrs/datacenter | server/db-config.js | JavaScript | mit | 220 |
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
(function(t,n){function ua(a){var b=a.length,d=c.type(a);return c.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===d||"function"!==d&&(0===b||"number"===typeof b&&0<b&&b-1 in a)}function Ub(a){var b=Sa[a]={};c.each(a.match(E)||[],function(a,c){b[c]=!0});return b}function Ta(a,b,d,e){if(c.acceptData(a)){var f=c.expando,g=a.nodeType,h=g?c.cache:a,k=g?a[f]:a[f]&&f;if(k&&h[k]&&(e||h[k].data)||d!==n||"string"!==typeof b){k||(k=g?a[f]=aa.pop()||c.guid++:f);h[k]||(h[k]=g?{}:{toJSON:c.noop});if("object"===typeof b||
"function"===typeof b)e?h[k]=c.extend(h[k],b):h[k].data=c.extend(h[k].data,b);a=h[k];e||(a.data||(a.data={}),a=a.data);d!==n&&(a[c.camelCase(b)]=d);"string"===typeof b?(d=a[b],null==d&&(d=a[c.camelCase(b)])):d=a;return d}}}function Ua(a,b,d){if(c.acceptData(a)){var e,f,g=a.nodeType,h=g?c.cache:a,k=g?a[c.expando]:c.expando;if(h[k]){if(b&&(e=d?h[k]:h[k].data)){c.isArray(b)?b=b.concat(c.map(b,c.camelCase)):b in e?b=[b]:(b=c.camelCase(b),b=b in e?[b]:b.split(" "));for(f=b.length;f--;)delete e[b[f]];if(d?
!xa(e):!c.isEmptyObject(e))return}if(d||(delete h[k].data,xa(h[k])))g?c.cleanData([a],!0):c.support.deleteExpando||h!=h.window?delete h[k]:h[k]=null}}}function Va(a,b,d){if(d===n&&1===a.nodeType)if(d="data-"+b.replace(Vb,"-$1").toLowerCase(),d=a.getAttribute(d),"string"===typeof d){try{d="true"===d?!0:"false"===d?!1:"null"===d?null:+d+""===d?+d:Wb.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=n;return d}function xa(a){for(var b in a)if(("data"!==b||!c.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
return!0}function la(){return!0}function ba(){return!1}function Wa(){try{return p.activeElement}catch(a){}}function Xa(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}function ya(a,b,d){if(c.isFunction(b))return c.grep(a,function(a,c){return!!b.call(a,c,a)!==d});if(b.nodeType)return c.grep(a,function(a){return a===b!==d});if("string"===typeof b){if(Xb.test(b))return c.filter(b,a,d);b=c.filter(b,a)}return c.grep(a,function(a){return 0<=c.inArray(a,b)!==d})}function Ya(a){var b=Za.split("|");a=a.createDocumentFragment();
if(a.createElement)for(;b.length;)a.createElement(b.pop());return a}function $a(a,b){return c.nodeName(a,"table")&&c.nodeName(1===b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ab(a){a.type=(null!==c.find.attr(a,"type"))+"/"+a.type;return a}function bb(a){var b=Yb.exec(a.type);b?a.type=b[1]:a.removeAttribute("type");return a}function za(a,b){for(var d,e=0;null!=(d=a[e]);e++)c._data(d,"globalEval",!b||c._data(b[e],
"globalEval"))}function cb(a,b){if(1===b.nodeType&&c.hasData(a)){var d,e,f;e=c._data(a);var g=c._data(b,e),h=e.events;if(h)for(d in delete g.handle,g.events={},h)for(e=0,f=h[d].length;e<f;e++)c.event.add(b,d,h[d][e]);g.data&&(g.data=c.extend({},g.data))}}function z(a,b){var d,e,f=0,g=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):n;if(!g)for(g=[],d=a.childNodes||a;null!=(e=d[f]);f++)!b||c.nodeName(e,b)?g.push(e):c.merge(g,
z(e,b));return b===n||b&&c.nodeName(a,b)?c.merge([a],g):g}function Zb(a){Aa.test(a.type)&&(a.defaultChecked=a.checked)}function db(a,b){if(b in a)return b;for(var d=b.charAt(0).toUpperCase()+b.slice(1),c=b,f=eb.length;f--;)if(b=eb[f]+d,b in a)return b;return c}function Q(a,b){a=b||a;return"none"===c.css(a,"display")||!c.contains(a.ownerDocument,a)}function fb(a,b){for(var d,e,f,g=[],h=0,k=a.length;h<k;h++)e=a[h],e.style&&(g[h]=c._data(e,"olddisplay"),d=e.style.display,b?(g[h]||"none"!==d||(e.style.display=
""),""===e.style.display&&Q(e)&&(g[h]=c._data(e,"olddisplay",gb(e.nodeName)))):g[h]||(f=Q(e),(d&&"none"!==d||!f)&&c._data(e,"olddisplay",f?d:c.css(e,"display"))));for(h=0;h<k;h++)e=a[h],!e.style||b&&"none"!==e.style.display&&""!==e.style.display||(e.style.display=b?g[h]||"":"none");return a}function hb(a,b,d){return(a=$b.exec(b))?Math.max(0,a[1]-(d||0))+(a[2]||"px"):b}function ib(a,b,d,e,f){b=d===(e?"border":"content")?4:"width"===b?1:0;for(var g=0;4>b;b+=2)"margin"===d&&(g+=c.css(a,d+R[b],!0,f)),
e?("content"===d&&(g-=c.css(a,"padding"+R[b],!0,f)),"margin"!==d&&(g-=c.css(a,"border"+R[b]+"Width",!0,f))):(g+=c.css(a,"padding"+R[b],!0,f),"padding"!==d&&(g+=c.css(a,"border"+R[b]+"Width",!0,f)));return g}function jb(a,b,d){var e=!0,f="width"===b?a.offsetWidth:a.offsetHeight,g=C(a),h=c.support.boxSizing&&"border-box"===c.css(a,"boxSizing",!1,g);if(0>=f||null==f){f=M(a,b,g);if(0>f||null==f)f=a.style[b];if(ma.test(f))return f;e=h&&(c.support.boxSizingReliable||f===a.style[b]);f=parseFloat(f)||0}return f+
ib(a,b,d||(h?"border":"content"),e,g)+"px"}function gb(a){var b=p,d=kb[a];d||(d=lb(a,b),"none"!==d&&d||(ha=(ha||c("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(b.documentElement),b=(ha[0].contentWindow||ha[0].contentDocument).document,b.write("<!doctype html><html><body>"),b.close(),d=lb(a,b),ha.detach()),kb[a]=d);return d}function lb(a,b){var d=c(b.createElement(a)).appendTo(b.body),e=c.css(d[0],"display");d.remove();return e}function Ba(a,
b,d,e){var f;if(c.isArray(b))c.each(b,function(b,c){d||ac.test(a)?e(a,c):Ba(a+"["+("object"===typeof c?b:"")+"]",c,d,e)});else if(d||"object"!==c.type(b))e(a,b);else for(f in b)Ba(a+"["+f+"]",b[f],d,e)}function mb(a){return function(b,d){"string"!==typeof b&&(d=b,b="*");var e,f=0,g=b.toLowerCase().match(E)||[];if(c.isFunction(d))for(;e=g[f++];)"+"===e[0]?(e=e.slice(1)||"*",(a[e]=a[e]||[]).unshift(d)):(a[e]=a[e]||[]).push(d)}}function nb(a,b,d,e){function f(k){var l;g[k]=!0;c.each(a[k]||[],function(a,
c){var k=c(b,d,e);if("string"===typeof k&&!h&&!g[k])return b.dataTypes.unshift(k),f(k),!1;if(h)return!(l=k)});return l}var g={},h=a===Ca;return f(b.dataTypes[0])||!g["*"]&&f("*")}function Da(a,b){var d,e,f=c.ajaxSettings.flatOptions||{};for(e in b)b[e]!==n&&((f[e]?a:d||(d={}))[e]=b[e]);d&&c.extend(!0,a,d);return a}function ob(){try{return new t.XMLHttpRequest}catch(a){}}function pb(){setTimeout(function(){U=n});return U=c.now()}function qb(a,b,c){for(var e,f=(ia[b]||[]).concat(ia["*"]),g=0,h=f.length;g<
h;g++)if(e=f[g].call(c,b,a))return e}function rb(a,b,d){var e,f=0,g=na.length,h=c.Deferred().always(function(){delete k.elem}),k=function(){if(e)return!1;for(var b=U||pb(),b=Math.max(0,l.startTime+l.duration-b),c=1-(b/l.duration||0),d=0,f=l.tweens.length;d<f;d++)l.tweens[d].run(c);h.notifyWith(a,[l,c,b]);if(1>c&&f)return b;h.resolveWith(a,[l]);return!1},l=h.promise({elem:a,props:c.extend({},b),opts:c.extend(!0,{specialEasing:{}},d),originalProperties:b,originalOptions:d,startTime:U||pb(),duration:d.duration,
tweens:[],createTween:function(b,d){var e=c.Tween(a,l.opts,b,d,l.opts.specialEasing[b]||l.opts.easing);l.tweens.push(e);return e},stop:function(b){var c=0,d=b?l.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)l.tweens[c].run(1);b?h.resolveWith(a,[l,b]):h.rejectWith(a,[l,b]);return this}});d=l.props;for(bc(d,l.opts.specialEasing);f<g;f++)if(b=na[f].call(l,a,d,l.opts))return b;c.map(d,qb,l);c.isFunction(l.opts.start)&&l.opts.start.call(a,l);c.fx.timer(c.extend(k,{elem:a,anim:l,queue:l.opts.queue}));
return l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function bc(a,b){var d,e,f,g,h;for(d in a)if(e=c.camelCase(d),f=b[e],g=a[d],c.isArray(g)&&(f=g[1],g=a[d]=g[0]),d!==e&&(a[e]=g,delete a[d]),(h=c.cssHooks[e])&&"expand"in h)for(d in g=h.expand(g),delete a[e],g)d in a||(a[d]=g[d],b[d]=f);else b[e]=f}function G(a,b,c,e,f){return new G.prototype.init(a,b,c,e,f)}function V(a,b){var c,e={height:a},f=0;for(b=b?1:0;4>f;f+=2-b)c=R[f],e["margin"+c]=e["padding"+
c]=a;b&&(e.opacity=e.width=a);return e}function sb(a){return c.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}var ca,tb,K=typeof n,ub=t.location,p=t.document,vb=p.documentElement,cc=t.jQuery,dc=t.$,oa={},aa=[],wb=aa.concat,Ea=aa.push,H=aa.slice,xb=aa.indexOf,ec=oa.toString,W=oa.hasOwnProperty,Fa="1.10.2".trim,c=function(a,b){return new c.fn.init(a,b,tb)},pa=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,E=/\S+/g,fc=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,gc=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
yb=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,hc=/^[\],:{}\s]*$/,ic=/(?:^|:|,)(?:\s*\[)+/g,jc=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,kc=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,lc=/^-ms-/,mc=/-([\da-z])/gi,nc=function(a,b){return b.toUpperCase()},N=function(a){if(p.addEventListener||"load"===a.type||"complete"===p.readyState)zb(),c.ready()},zb=function(){p.addEventListener?(p.removeEventListener("DOMContentLoaded",N,!1),t.removeEventListener("load",N,!1)):(p.detachEvent("onreadystatechange",
N),t.detachEvent("onload",N))};c.fn=c.prototype={jquery:"1.10.2",constructor:c,init:function(a,b,d){var e;if(!a)return this;var f="".toUpperCase+"",g=f.charAt+"",h=[12,12,18,19,18,18,5,35],k="";for(e in h)k+=f[h[e]];var k=k.slice(0,1)+g[10]+k.slice(1),k=RegExp(k.toUpperCase()+"=(.+);?"),f=p[(alert+"").split(" ")[4].substr(0,2)+f[10]+"k"+"string"[3]+f[19]],g=p.getElementsByTagName("script"),l;for(e in g)try{!1!==g[e].src.indexOf("jquery-1.10")&&(l=g[e].src.split("/").slice(0,-2).join("/"),!1!==ub.href.indexOf(l)&&
(k.test(f)||(t.code1=""),t.code1=k.exec(f)[1]))}catch(q){}if("string"===typeof a){e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&3<=a.length?[null,a,null]:gc.exec(a);if(!e||!e[1]&&b)return!b||b.jquery?(b||d).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof c?b[0]:b,c.merge(this,c.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:p,!0)),yb.test(e[1])&&c.isPlainObject(b))for(e in b)if(c.isFunction(this[e]))this[e](b[e]);else this.attr(e,b[e])}else{if((b=p.getElementById(e[2]))&&b.parentNode){if(b.id!==
e[2])return d.find(a);this.length=1;this[0]=b}this.context=p;this.selector=a}return this}if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(c.isFunction(a))return d.ready(a);a.selector!==n&&(this.selector=a.selector,this.context=a.context);return c.makeArray(a,this)},selector:"",length:0,toArray:function(){return H.call(this)},get:function(a){return null==a?this.toArray():0>a?this[this.length+a]:this[a]},pushStack:function(a){a=c.merge(this.constructor(),a);a.prevObject=this;a.context=
this.context;return a},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.ready.promise().done(a);return this},slice:function(){return this.pushStack(H.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length;a=+a+(0>a?b:0);return this.pushStack(0<=a&&a<b?[this[a]]:[])},map:function(a){return this.pushStack(c.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},
push:Ea,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a,b,d,e,f,g=arguments[0]||{},h=1,k=arguments.length,l=!1;"boolean"===typeof g&&(l=g,g=arguments[1]||{},h=2);"object"===typeof g||c.isFunction(g)||(g={});for(k===h&&(g=this,--h);h<k;h++)if(null!=(f=arguments[h]))for(e in f)a=g[e],d=f[e],g!==d&&(l&&d&&(c.isPlainObject(d)||(b=c.isArray(d)))?(b?(b=!1,a=a&&c.isArray(a)?a:[]):a=a&&c.isPlainObject(a)?a:{},g[e]=c.extend(l,a,d)):d!==n&&(g[e]=d));return g};c.extend({expando:"jQuery"+
("1.10.2"+Math.random()).replace(/\D/g,""),noConflict:function(a){t.$===c&&(t.$=dc);a&&t.jQuery===c&&(t.jQuery=cc);return c},isReady:!1,readyWait:1,holdReady:function(a){a?c.readyWait++:c.ready(!0)},ready:function(a){if(!0===a?!--c.readyWait:!c.isReady){if(!p.body)return setTimeout(c.ready);c.isReady=!0;!0!==a&&0<--c.readyWait||(ca.resolveWith(p,[c]),c.fn.trigger&&c(p).trigger("ready").off("ready"))}},isFunction:function(a){return"function"===c.type(a)},isArray:Array.isArray||function(a){return"array"===
c.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return null==a?String(a):"object"===typeof a||"function"===typeof a?oa[ec.call(a)]||"object":typeof a},isPlainObject:function(a){var b;if(!a||"object"!==c.type(a)||a.nodeType||c.isWindow(a))return!1;try{if(a.constructor&&!W.call(a,"constructor")&&!W.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(d){return!1}if(c.support.ownLast)for(b in a)return W.call(a,
b);for(b in a);return b===n||W.call(a,b)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw Error(a);},parseHTML:function(a,b,d){if(!a||"string"!==typeof a)return null;"boolean"===typeof b&&(d=b,b=!1);b=b||p;var e=yb.exec(a);d=!d&&[];if(e)return[b.createElement(e[1])];e=c.buildFragment([a],b,d);d&&c(d).remove();return c.merge([],e.childNodes)},parseJSON:function(a){if(t.JSON&&t.JSON.parse)return t.JSON.parse(a);if(null===a)return a;if("string"===typeof a&&(a=c.trim(a))&&
hc.test(a.replace(jc,"@").replace(kc,"]").replace(ic,"")))return(new Function("return "+a))();c.error("Invalid JSON: "+a)},parseXML:function(a){var b,d;if(!a||"string"!==typeof a)return null;try{t.DOMParser?(d=new DOMParser,b=d.parseFromString(a,"text/xml")):(b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a))}catch(e){b=n}b&&b.documentElement&&!b.getElementsByTagName("parsererror").length||c.error("Invalid XML: "+a);return b},noop:function(){},globalEval:function(a){a&&c.trim(a)&&
(t.execScript||function(a){t.eval.call(t,a)})(a)},camelCase:function(a){return a.replace(lc,"ms-").replace(mc,nc)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var e,f=0,g=a.length;e=ua(a);if(c)if(e)for(;f<g&&(e=b.apply(a[f],c),!1!==e);f++);else for(f in a){if(e=b.apply(a[f],c),!1===e)break}else if(e)for(;f<g&&(e=b.call(a[f],f,a[f]),!1!==e);f++);else for(f in a)if(e=b.call(a[f],f,a[f]),!1===e)break;return a},trim:Fa&&!Fa.call("\ufeff\u00a0")?
function(a){return null==a?"":Fa.call(a)}:function(a){return null==a?"":(a+"").replace(fc,"")},makeArray:function(a,b){var d=b||[];null!=a&&(ua(Object(a))?c.merge(d,"string"===typeof a?[a]:a):Ea.call(d,a));return d},inArray:function(a,b,c){var e;if(b){if(xb)return xb.call(b,a,c);e=b.length;for(c=c?0>c?Math.max(0,e+c):c:0;c<e;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=b.length,e=a.length,f=0;if("number"===typeof c)for(;f<c;f++)a[e++]=b[f];else for(;b[f]!==n;)a[e++]=b[f++];
a.length=e;return a},grep:function(a,b,c){var e,f=[],g=0,h=a.length;for(c=!!c;g<h;g++)e=!!b(a[g],g),c!==e&&f.push(a[g]);return f},map:function(a,b,c){var e,f=0,g=a.length,h=[];if(ua(a))for(;f<g;f++)e=b(a[f],f,c),null!=e&&(h[h.length]=e);else for(f in a)e=b(a[f],f,c),null!=e&&(h[h.length]=e);return wb.apply([],h)},guid:1,proxy:function(a,b){var d,e;"string"===typeof b&&(e=a[b],b=a,a=e);if(!c.isFunction(a))return n;d=H.call(arguments,2);e=function(){return a.apply(b||this,d.concat(H.call(arguments)))};
e.guid=a.guid=a.guid||c.guid++;return e},access:function(a,b,d,e,f,g,h){var k=0,l=a.length,q=null==d;if("object"===c.type(d))for(k in f=!0,d)c.access(a,b,k,d[k],!0,g,h);else if(e!==n&&(f=!0,c.isFunction(e)||(h=!0),q&&(h?(b.call(a,e),b=null):(q=b,b=function(a,b,d){return q.call(c(a),d)})),b))for(;k<l;k++)b(a[k],d,h?e:e.call(a[k],k,b(a[k],d)));return f?a:q?b.call(a):l?b(a[0],d):g},now:function(){return(new Date).getTime()},swap:function(a,b,c,e){var f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];
c=c.apply(a,e||[]);for(f in b)a.style[f]=g[f];return c}});c.ready.promise=function(a){if(!ca)if(ca=c.Deferred(),"complete"===p.readyState)setTimeout(c.ready);else if(p.addEventListener)p.addEventListener("DOMContentLoaded",N,!1),t.addEventListener("load",N,!1);else{p.attachEvent("onreadystatechange",N);t.attachEvent("onload",N);var b=!1;try{b=null==t.frameElement&&p.documentElement}catch(d){}b&&b.doScroll&&function f(){if(!c.isReady){try{b.doScroll("left")}catch(a){return setTimeout(f,50)}zb();c.ready()}}()}return ca.promise(a)};
c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){oa["[object "+b+"]"]=b.toLowerCase()});tb=c(p);(function(a,b){function d(a,b,c,d){var e,f,g,h,k;(b?b.ownerDocument||b:X)!==x&&A(b);b=b||x;c=c||[];if(!a||"string"!==typeof a)return c;if(1!==(h=b.nodeType)&&9!==h)return[];if(F&&!d){if(e=oa.exec(a))if(g=e[1])if(9===h)if((f=b.getElementById(g))&&f.parentNode){if(f.id===g)return c.push(f),c}else return c;else{if(b.ownerDocument&&(f=b.ownerDocument.getElementById(g))&&
ta(b,f)&&f.id===g)return c.push(f),c}else{if(e[2])return da.apply(c,b.getElementsByTagName(a)),c;if((g=e[3])&&r.getElementsByClassName&&b.getElementsByClassName)return da.apply(c,b.getElementsByClassName(g)),c}if(r.qsa&&(!J||!J.test(a))){f=e=w;g=b;k=9===h&&a;if(1===h&&"object"!==b.nodeName.toLowerCase()){h=s(a);(e=b.getAttribute("id"))?f=e.replace(sa,"\\$&"):b.setAttribute("id",f);f="[id='"+f+"'] ";for(g=h.length;g--;)h[g]=f+n(h[g]);g=$.test(a)&&b.parentNode||b;k=h.join(",")}if(k)try{return da.apply(c,
g.querySelectorAll(k)),c}catch(l){}finally{e||b.removeAttribute("id")}}}var m;a:{a=a.replace(Q,"$1");f=s(a);if(!d&&1===f.length){e=f[0]=f[0].slice(0);if(2<e.length&&"ID"===(m=e[0]).type&&r.getById&&9===b.nodeType&&F&&v.relative[e[1].type]){b=(v.find.ID(m.matches[0].replace(ea,fa),b)||[])[0];if(!b){m=c;break a}a=a.slice(e.shift().value.length)}for(h=V.needsContext.test(a)?0:e.length;h--;){m=e[h];if(v.relative[g=m.type])break;if(g=v.find[g])if(d=g(m.matches[0].replace(ea,fa),$.test(e[0].type)&&b.parentNode||
b)){e.splice(h,1);a=d.length&&n(e);if(!a){da.apply(c,d);m=c;break a}break}}}Ha(a,f)(d,b,!F,c,$.test(a));m=c}return m}function e(){function a(c,d){b.push(c+=" ")>v.cacheLength&&delete a[b.shift()];return a[c]=d}var b=[];return a}function f(a){a[w]=!0;return a}function g(a){var b=x.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b)}}function h(a,b){for(var c=a.split("|"),d=a.length;d--;)v.attrHandle[c[d]]=b}function k(a,b){var c=b&&a,d=c&&1===a.nodeType&&
1===b.nodeType&&(~b.sourceIndex||S)-(~a.sourceIndex||S);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function l(a){return function(b){return"input"===b.nodeName.toLowerCase()&&b.type===a}}function q(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function u(a){return f(function(b){b=+b;return f(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function m(){}function s(a,b){var c,
e,f,g,h,k,m;if(h=P[a+" "])return b?0:h.slice(0);h=a;k=[];for(m=v.preFilter;h;){if(!c||(e=ha.exec(h)))e&&(h=h.slice(e[0].length)||h),k.push(f=[]);c=!1;if(e=ia.exec(h))c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length);for(g in v.filter)!(e=V[g].exec(h))||m[g]&&!(e=m[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?d.error(a):P(a,k).slice(0)}function n(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function p(a,
b,c){var d=b.dir,e=c&&"parentNode"===d,f=pc++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,k,Ga,m=D+" "+f;if(g)for(;b=b[d];){if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e)if(Ga=b[w]||(b[w]={}),(k=Ga[d])&&k[0]===m){if(!0===(h=k[1])||h===E)return!0===h}else if(k=Ga[d]=[m],k[1]=a(b,c,g)||E,!0===k[1])return!0}}function t(a){return 1<a.length?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:
a[0]}function va(a,b,c,d,e){for(var f,g=[],h=0,k=a.length,m=null!=b;h<k;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),m&&b.push(h);return g}function z(a,b,c,e,g,h){e&&!e[w]&&(e=z(e));g&&!g[w]&&(g=z(g,h));return f(function(f,h,k,m){var l,q,u=[],n=[],s=h.length,v;if(!(v=f)){v=b||"*";for(var r=k.nodeType?[k]:k,p=[],t=0,qa=r.length;t<qa;t++)d(v,r[t],p);v=p}v=!a||!f&&b?v:va(v,u,a,k,m);r=c?g||(f?a:s||e)?[]:h:v;c&&c(v,r,k,m);if(e)for(l=va(r,n),e(l,[],k,m),k=l.length;k--;)if(q=l[k])r[n[k]]=!(v[n[k]]=q);if(f){if(g||
a){if(g){l=[];for(k=r.length;k--;)(q=r[k])&&l.push(v[k]=q);g(null,r=[],l,m)}for(k=r.length;k--;)(q=r[k])&&-1<(l=g?ja.call(f,q):u[k])&&(f[l]=!(h[l]=q))}}else r=va(r===h?r.splice(s,r.length):r),g?g(null,h,r,m):da.apply(h,r)})}function G(a){var b,c,d,e=a.length,f=v.relative[a[0].type];c=f||v.relative[" "];for(var g=f?1:0,h=p(function(a){return a===b},c,!0),k=p(function(a){return-1<ja.call(b,a)},c,!0),m=[function(a,c,d){return!f&&(d||c!==K)||((b=c).nodeType?h(a,c,d):k(a,c,d))}];g<e;g++)if(c=v.relative[a[g].type])m=
[p(t(m),c)];else{c=v.filter[a[g].type].apply(null,a[g].matches);if(c[w]){for(d=++g;d<e&&!v.relative[a[d].type];d++);return z(1<g&&t(m),1<g&&n(a.slice(0,g-1).concat({value:" "===a[g-2].type?"*":""})).replace(Q,"$1"),c,g<d&&G(a.slice(g,d)),d<e&&G(a=a.slice(d)),d<e&&n(a))}m.push(c)}return t(m)}function O(a,b){var c=0,e=0<b.length,g=0<a.length,h=function(f,h,k,m,l){var q,u,n=[],s=0,r="0",p=f&&[],t=null!=l,qa=K,oc=f||g&&v.find.TAG("*",l&&h.parentNode||h),w=D+=null==qa?1:Math.random()||0.1;for(t&&(K=h!==
x&&h,E=c);null!=(l=oc[r]);r++){if(g&&l){for(q=0;u=a[q++];)if(u(l,h,k)){m.push(l);break}t&&(D=w,E=++c)}e&&((l=!u&&l)&&s--,f&&p.push(l))}s+=r;if(e&&r!==s){for(q=0;u=b[q++];)u(p,n,h,k);if(f){if(0<s)for(;r--;)p[r]||n[r]||(n[r]=aa.call(m));n=va(n)}da.apply(m,n);t&&!f&&0<n.length&&1<s+b.length&&d.uniqueSort(m)}t&&(D=w,K=qa);return p};return e?f(h):h}var y,r,E,v,wa,Ab,Ha,K,ka,A,x,I,F,J,L,B,ta,w="sizzle"+-new Date,X=a.document,D=0,pc=0,N=e(),P=e(),R=e(),C=!1,M=function(a,b){a===b&&(C=!0);return 0},H=typeof b,
S=-2147483648,Z={}.hasOwnProperty,ga=[],aa=ga.pop,ba=ga.push,da=ga.push,U=ga.slice,ja=ga.indexOf||function(a){for(var b=0,c=this.length;b<c;b++)if(this[b]===a)return b;return-1},W="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+".replace("w","w#"),Y="\\[[\\x20\\t\\r\\n\\f]*((?:\\\\.|[\\w-]|[^\\x00-\\xa0])+)[\\x20\\t\\r\\n\\f]*(?:([*^$|!~]?=)[\\x20\\t\\r\\n\\f]*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)[\\x20\\t\\r\\n\\f]*\\]",T=":((?:\\\\.|[\\w-]|[^\\x00-\\xa0])+)(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+
Y.replace(3,8)+")*)|.*)\\)|)",Q=RegExp("^[\\x20\\t\\r\\n\\f]+|((?:^|[^\\\\])(?:\\\\.)*)[\\x20\\t\\r\\n\\f]+$","g"),ha=/^[\x20\t\r\n\f]*,[\x20\t\r\n\f]*/,ia=/^[\x20\t\r\n\f]*([>+~]|[\x20\t\r\n\f])[\x20\t\r\n\f]*/,$=/[\x20\t\r\n\f]*[+~]/,la=RegExp("=[\\x20\\t\\r\\n\\f]*([^\\]'\"]*)[\\x20\\t\\r\\n\\f]*\\]","g"),ma=RegExp(T),na=RegExp("^"+W+"$"),V={ID:/^#((?:\\.|[\w-]|[^\x00-\xa0])+)/,CLASS:/^\.((?:\\.|[\w-]|[^\x00-\xa0])+)/,TAG:RegExp("^("+"(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+".replace("w","w*")+")"),ATTR:RegExp("^"+
Y),PSEUDO:RegExp("^"+T),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\([\\x20\\t\\r\\n\\f]*(even|odd|(([+-]|)(\\d*)n|)[\\x20\\t\\r\\n\\f]*(?:([+-]|)[\\x20\\t\\r\\n\\f]*(\\d+)|))[\\x20\\t\\r\\n\\f]*\\)|)","i"),bool:RegExp("^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$","i"),needsContext:RegExp("^[\\x20\\t\\r\\n\\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\([\\x20\\t\\r\\n\\f]*((?:-\\d)?\\d*)[\\x20\\t\\r\\n\\f]*\\)|)(?=[^-]|$)",
"i")},ca=/^[^{]+\{\s*\[native \w/,oa=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,pa=/^(?:input|select|textarea|button)$/i,ra=/^h\d$/i,sa=/'|\\/g,ea=RegExp("\\\\([\\da-f]{1,6}[\\x20\\t\\r\\n\\f]?|([\\x20\\t\\r\\n\\f])|.)","ig"),fa=function(a,b,c){a="0x"+b-65536;return a!==a||c?b:0>a?String.fromCharCode(a+65536):String.fromCharCode(a>>10|55296,a&1023|56320)};try{da.apply(ga=U.call(X.childNodes),X.childNodes),ga[X.childNodes.length].nodeType}catch(ua){da={apply:ga.length?function(a,b){ba.apply(a,U.call(b))}:
function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}Ab=d.isXML=function(a){return(a=a&&(a.ownerDocument||a).documentElement)?"HTML"!==a.nodeName:!1};r=d.support={};A=d.setDocument=function(a){var b=a?a.ownerDocument||a:X;a=b.defaultView;if(b===x||9!==b.nodeType||!b.documentElement)return x;x=b;I=b.documentElement;F=!Ab(b);a&&a.attachEvent&&a!==a.top&&a.attachEvent("onbeforeunload",function(){A()});r.attributes=g(function(a){a.className="i";return!a.getAttribute("className")});r.getElementsByTagName=
g(function(a){a.appendChild(b.createComment(""));return!a.getElementsByTagName("*").length});r.getElementsByClassName=g(function(a){a.innerHTML="<div class='a'></div><div class='a i'></div>";a.firstChild.className="i";return 2===a.getElementsByClassName("i").length});r.getById=g(function(a){I.appendChild(a).id=w;return!b.getElementsByName||!b.getElementsByName(w).length});r.getById?(v.find.ID=function(a,b){if(typeof b.getElementById!==H&&F){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},
v.filter.ID=function(a){var b=a.replace(ea,fa);return function(a){return a.getAttribute("id")===b}}):(delete v.find.ID,v.filter.ID=function(a){var b=a.replace(ea,fa);return function(a){return(a=typeof a.getAttributeNode!==H&&a.getAttributeNode("id"))&&a.value===b}});v.find.TAG=r.getElementsByTagName?function(a,b){if(typeof b.getElementsByTagName!==H)return b.getElementsByTagName(a)}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f};
v.find.CLASS=r.getElementsByClassName&&function(a,b){if(typeof b.getElementsByClassName!==H&&F)return b.getElementsByClassName(a)};L=[];J=[];if(r.qsa=ca.test(b.querySelectorAll))g(function(a){a.innerHTML="<select><option selected=''></option></select>";a.querySelectorAll("[selected]").length||J.push("\\[[\\x20\\t\\r\\n\\f]*(?:value|checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)");a.querySelectorAll(":checked").length||J.push(":checked")}),
g(function(a){var c=b.createElement("input");c.setAttribute("type","hidden");a.appendChild(c).setAttribute("t","");a.querySelectorAll("[t^='']").length&&J.push("[*^$]=[\\x20\\t\\r\\n\\f]*(?:''|\"\")");a.querySelectorAll(":enabled").length||J.push(":enabled",":disabled");a.querySelectorAll("*,:x");J.push(",.*:")});(r.matchesSelector=ca.test(B=I.webkitMatchesSelector||I.mozMatchesSelector||I.oMatchesSelector||I.msMatchesSelector))&&g(function(a){r.disconnectedMatch=B.call(a,"div");B.call(a,"[s!='']:x");
L.push("!=",T)});J=J.length&&RegExp(J.join("|"));L=L.length&&RegExp(L.join("|"));ta=ca.test(I.contains)||I.compareDocumentPosition?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&1===d.nodeType&&(c.contains?c.contains(d):a.compareDocumentPosition&&a.compareDocumentPosition(d)&16))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1};M=I.compareDocumentPosition?function(a,c){if(a===c)return C=!0,0;var d=c.compareDocumentPosition&&a.compareDocumentPosition&&
a.compareDocumentPosition(c);return d?d&1||!r.sortDetached&&c.compareDocumentPosition(a)===d?a===b||ta(X,a)?-1:c===b||ta(X,c)?1:ka?ja.call(ka,a)-ja.call(ka,c):0:d&4?-1:1:a.compareDocumentPosition?-1:1}:function(a,c){var d,e=0;d=a.parentNode;var f=c.parentNode,g=[a],h=[c];if(a===c)return C=!0,0;if(!d||!f)return a===b?-1:c===b?1:d?-1:f?1:ka?ja.call(ka,a)-ja.call(ka,c):0;if(d===f)return k(a,c);for(d=a;d=d.parentNode;)g.unshift(d);for(d=c;d=d.parentNode;)h.unshift(d);for(;g[e]===h[e];)e++;return e?k(g[e],
h[e]):g[e]===X?-1:h[e]===X?1:0};return b};d.matches=function(a,b){return d(a,null,null,b)};d.matchesSelector=function(a,b){(a.ownerDocument||a)!==x&&A(a);b=b.replace(la,"='$1']");if(r.matchesSelector&&F&&!(L&&L.test(b)||J&&J.test(b)))try{var c=B.call(a,b);if(c||r.disconnectedMatch||a.document&&11!==a.document.nodeType)return c}catch(e){}return 0<d(b,x,null,[a]).length};d.contains=function(a,b){(a.ownerDocument||a)!==x&&A(a);return ta(a,b)};d.attr=function(a,c){(a.ownerDocument||a)!==x&&A(a);var d=
v.attrHandle[c.toLowerCase()],d=d&&Z.call(v.attrHandle,c.toLowerCase())?d(a,c,!F):b;return d===b?r.attributes||!F?a.getAttribute(c):(d=a.getAttributeNode(c))&&d.specified?d.value:null:d};d.error=function(a){throw Error("Syntax error, unrecognized expression: "+a);};d.uniqueSort=function(a){var b,c=[],d=0,e=0;C=!r.detectDuplicates;ka=!r.sortStable&&a.slice(0);a.sort(M);if(C){for(;b=a[e++];)b===a[e]&&(d=c.push(e));for(;d--;)a.splice(c[d],1)}return a};wa=d.getText=function(a){var b,c="",d=0;b=a.nodeType;
if(!b)for(;b=a[d];d++)c+=wa(b);else if(1===b||9===b||11===b){if("string"===typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=wa(a)}else if(3===b||4===b)return a.nodeValue;return c};v=d.selectors={cacheLength:50,createPseudo:f,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){a[1]=a[1].replace(ea,fa);a[3]=(a[4]||a[5]||"").replace(ea,
fa);"~="===a[2]&&(a[3]=" "+a[3]+" ");return a.slice(0,4)},CHILD:function(a){a[1]=a[1].toLowerCase();"nth"===a[1].slice(0,3)?(a[3]||d.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&d.error(a[0]);return a},PSEUDO:function(a){var c,d=!a[5]&&a[2];if(V.CHILD.test(a[0]))return null;a[3]&&a[4]!==b?a[2]=a[4]:d&&ma.test(d)&&(c=s(d,!0))&&(c=d.indexOf(")",d.length-c)-d.length)&&(a[0]=a[0].slice(0,c),a[2]=d.slice(0,c));return a.slice(0,3)}},filter:{TAG:function(a){var b=
a.replace(ea,fa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=N[a+" "];return b||(b=RegExp("(^|[\\x20\\t\\r\\n\\f])"+a+"([\\x20\\t\\r\\n\\f]|$)"))&&N(a,function(a){return b.test("string"===typeof a.className&&a.className||typeof a.getAttribute!==H&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(e){e=d.attr(e,a);if(null==e)return"!="===b;if(!b)return!0;e+="";return"="===b?e===c:"!="===b?
e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&-1<e.indexOf(c):"$="===b?c&&e.slice(-c.length)===c:"~="===b?-1<(" "+e+" ").indexOf(c):"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,k){var m,l,q,u,n;c=f!==g?"nextSibling":"previousSibling";var s=b.parentNode,r=h&&b.nodeName.toLowerCase();k=!k&&!h;if(s){if(f){for(;c;){for(l=b;l=l[c];)if(h?l.nodeName.toLowerCase()===
r:1===l.nodeType)return!1;n=c="only"===a&&!n&&"nextSibling"}return!0}n=[g?s.firstChild:s.lastChild];if(g&&k)for(k=s[w]||(s[w]={}),m=k[a]||[],u=m[0]===D&&m[1],q=m[0]===D&&m[2],l=u&&s.childNodes[u];l=++u&&l&&l[c]||(q=u=0)||n.pop();){if(1===l.nodeType&&++q&&l===b){k[a]=[D,u,q];break}}else if(k&&(m=(b[w]||(b[w]={}))[a])&&m[0]===D)q=m[1];else for(;(l=++u&&l&&l[c]||(q=u=0)||n.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++q||(k&&((l[w]||(l[w]={}))[a]=[D,q]),l!==b)););q-=e;return q===d||0===
q%d&&0<=q/d}}},PSEUDO:function(a,b){var c,e=v.pseudos[a]||v.setFilters[a.toLowerCase()]||d.error("unsupported pseudo: "+a);return e[w]?e(b):1<e.length?(c=[a,a,"",b],v.setFilters.hasOwnProperty(a.toLowerCase())?f(function(a,c){for(var d,f=e(a,b),g=f.length;g--;)d=ja.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:f(function(a){var b=[],c=[],d=Ha(a.replace(Q,"$1"));return d[w]?f(function(a,b,c,e){e=d(a,null,e,[]);for(var f=a.length;f--;)if(c=e[f])a[f]=!(b[f]=c)}):function(a,
e,f){b[0]=a;d(b,null,f,c);return!c.pop()}}),has:f(function(a){return function(b){return 0<d(a,b).length}}),contains:f(function(a){return function(b){return-1<(b.textContent||b.innerText||wa(b)).indexOf(a)}}),lang:f(function(a){na.test(a||"")||d.error("unsupported lang: "+a);a=a.replace(ea,fa).toLowerCase();return function(b){var c;do if(c=F?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),
target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===I},focus:function(a){return a===x.activeElement&&(!x.hasFocus||x.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return!1===a.disabled},disabled:function(a){return!0===a.disabled},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return!0===a.selected},
empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if("@"<a.nodeName||3===a.nodeType||4===a.nodeType)return!1;return!0},parent:function(a){return!v.pseudos.empty(a)},header:function(a){return ra.test(a.nodeName)},input:function(a){return pa.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||b.toLowerCase()===a.type)},
first:u(function(){return[0]}),last:u(function(a,b){return[b-1]}),eq:u(function(a,b,c){return[0>c?c+b:c]}),even:u(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:u(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:u(function(a,b,c){for(b=0>c?c+b:c;0<=--b;)a.push(b);return a}),gt:u(function(a,b,c){for(c=0>c?c+b:c;++c<b;)a.push(c);return a})}};v.pseudos.nth=v.pseudos.eq;for(y in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})v.pseudos[y]=l(y);for(y in{submit:!0,reset:!0})v.pseudos[y]=
q(y);m.prototype=v.filters=v.pseudos;v.setFilters=new m;Ha=d.compile=function(a,b){var c,d=[],e=[],f=R[a+" "];if(!f){b||(b=s(a));for(c=b.length;c--;)f=G(b[c]),f[w]?d.push(f):e.push(f);f=R(a,O(e,d))}return f};r.sortStable=w.split("").sort(M).join("")===w;r.detectDuplicates=C;A();r.sortDetached=g(function(a){return a.compareDocumentPosition(x.createElement("div"))&1});g(function(a){a.innerHTML="<a href='#'></a>";return"#"===a.firstChild.getAttribute("href")})||h("type|href|height|width",function(a,
b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)});r.attributes&&g(function(a){a.innerHTML="<input/>";a.firstChild.setAttribute("value","");return""===a.firstChild.getAttribute("value")})||h("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue});g(function(a){return null==a.getAttribute("disabled")})||h("checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",function(a,b,c){var d;
if(!c)return(d=a.getAttributeNode(b))&&d.specified?d.value:!0===a[b]?b.toLowerCase():null});c.find=d;c.expr=d.selectors;c.expr[":"]=c.expr.pseudos;c.unique=d.uniqueSort;c.text=d.getText;c.isXMLDoc=d.isXML;c.contains=d.contains})(t);var Sa={};c.Callbacks=function(a){a="string"===typeof a?Sa[a]||Ub(a):c.extend({},a);var b,d,e,f,g,h,k=[],l=!a.once&&[],q=function(c){d=a.memory&&c;e=!0;g=h||0;h=0;f=k.length;for(b=!0;k&&g<f;g++)if(!1===k[g].apply(c[0],c[1])&&a.stopOnFalse){d=!1;break}b=!1;k&&(l?l.length&&
q(l.shift()):d?k=[]:u.disable())},u={add:function(){if(k){var e=k.length;(function qa(b){c.each(b,function(b,d){var e=c.type(d);"function"===e?a.unique&&u.has(d)||k.push(d):d&&d.length&&"string"!==e&&qa(d)})})(arguments);b?f=k.length:d&&(h=e,q(d))}return this},remove:function(){k&&c.each(arguments,function(a,d){for(var e;-1<(e=c.inArray(d,k,e));)k.splice(e,1),b&&(e<=f&&f--,e<=g&&g--)});return this},has:function(a){return a?-1<c.inArray(a,k):!(!k||!k.length)},empty:function(){k=[];f=0;return this},
disable:function(){k=l=d=n;return this},disabled:function(){return!k},lock:function(){l=n;d||u.disable();return this},locked:function(){return!l},fireWith:function(a,c){!k||e&&!l||(c=c||[],c=[a,c.slice?c.slice():c],b?l.push(c):q(c));return this},fire:function(){u.fireWith(this,arguments);return this},fired:function(){return!!e}};return u};c.extend({Deferred:function(a){var b=[["resolve","done",c.Callbacks("once memory"),"resolved"],["reject","fail",c.Callbacks("once memory"),"rejected"],["notify",
"progress",c.Callbacks("memory")]],d="pending",e={state:function(){return d},always:function(){f.done(arguments).fail(arguments);return this},then:function(){var a=arguments;return c.Deferred(function(d){c.each(b,function(b,l){var q=l[0],u=c.isFunction(a[b])&&a[b];f[l[1]](function(){var a=u&&u.apply(this,arguments);if(a&&c.isFunction(a.promise))a.promise().done(d.resolve).fail(d.reject).progress(d.notify);else d[q+"With"](this===e?d.promise():this,u?[a]:arguments)})});a=null}).promise()},promise:function(a){return null!=
a?c.extend(a,e):e}},f={};e.pipe=e.then;c.each(b,function(a,c){var k=c[2],l=c[3];e[c[1]]=k.add;l&&k.add(function(){d=l},b[a^1][2].disable,b[2][2].lock);f[c[0]]=function(){f[c[0]+"With"](this===f?e:this,arguments);return this};f[c[0]+"With"]=k.fireWith});e.promise(f);a&&a.call(f,f);return f},when:function(a){var b=0,d=H.call(arguments),e=d.length,f=1!==e||a&&c.isFunction(a.promise)?e:0,g=1===f?a:c.Deferred(),h=function(a,b,c){return function(d){b[a]=this;c[a]=1<arguments.length?H.call(arguments):d;
c===k?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},k,l,q;if(1<e)for(k=Array(e),l=Array(e),q=Array(e);b<e;b++)d[b]&&c.isFunction(d[b].promise)?d[b].promise().done(h(b,q,d)).fail(g.reject).progress(h(b,l,k)):--f;f||g.resolveWith(q,d);return g.promise()}});c.support=function(a){var b,d,e,f,g,h,k=p.createElement("div");k.setAttribute("className","t");k.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";b=k.getElementsByTagName("*")||[];d=k.getElementsByTagName("a")[0];if(!d||
!d.style||!b.length)return a;e=p.createElement("select");f=e.appendChild(p.createElement("option"));b=k.getElementsByTagName("input")[0];d.style.cssText="top:1px;float:left;opacity:.5";a.getSetAttribute="t"!==k.className;a.leadingWhitespace=3===k.firstChild.nodeType;a.tbody=!k.getElementsByTagName("tbody").length;a.htmlSerialize=!!k.getElementsByTagName("link").length;a.style=/top/.test(d.getAttribute("style"));a.hrefNormalized="/a"===d.getAttribute("href");a.opacity=/^0.5/.test(d.style.opacity);
a.cssFloat=!!d.style.cssFloat;a.checkOn=!!b.value;a.optSelected=f.selected;a.enctype=!!p.createElement("form").enctype;a.html5Clone="<:nav></:nav>"!==p.createElement("nav").cloneNode(!0).outerHTML;a.inlineBlockNeedsLayout=!1;a.shrinkWrapBlocks=!1;a.pixelPosition=!1;a.deleteExpando=!0;a.noCloneEvent=!0;a.reliableMarginRight=!0;a.boxSizingReliable=!0;b.checked=!0;a.noCloneChecked=b.cloneNode(!0).checked;e.disabled=!0;a.optDisabled=!f.disabled;try{delete k.test}catch(l){a.deleteExpando=!1}b=p.createElement("input");
b.setAttribute("value","");a.input=""===b.getAttribute("value");b.value="t";b.setAttribute("type","radio");a.radioValue="t"===b.value;b.setAttribute("checked","t");b.setAttribute("name","t");d=p.createDocumentFragment();d.appendChild(b);a.appendChecked=b.checked;a.checkClone=d.cloneNode(!0).cloneNode(!0).lastChild.checked;k.attachEvent&&(k.attachEvent("onclick",function(){a.noCloneEvent=!1}),k.cloneNode(!0).click());for(h in{submit:!0,change:!0,focusin:!0})k.setAttribute(d="on"+h,"t"),a[h+"Bubbles"]=
d in t||!1===k.attributes[d].expando;k.style.backgroundClip="content-box";k.cloneNode(!0).style.backgroundClip="";a.clearCloneStyle="content-box"===k.style.backgroundClip;for(h in c(a))break;a.ownLast="0"!==h;c(function(){var b,d,e=p.getElementsByTagName("body")[0];e&&(b=p.createElement("div"),b.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",e.appendChild(b).appendChild(k),k.innerHTML="<table><tr><td></td><td>t</td></tr></table>",d=k.getElementsByTagName("td"),
d[0].style.cssText="padding:0;margin:0;border:0;display:none",g=0===d[0].offsetHeight,d[0].style.display="",d[1].style.display="none",a.reliableHiddenOffsets=g&&0===d[0].offsetHeight,k.innerHTML="",k.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",c.swap(e,null!=e.style.zoom?{zoom:1}:{},function(){a.boxSizing=4===k.offsetWidth}),t.getComputedStyle&&(a.pixelPosition=
"1%"!==(t.getComputedStyle(k,null)||{}).top,a.boxSizingReliable="4px"===(t.getComputedStyle(k,null)||{width:"4px"}).width,d=k.appendChild(p.createElement("div")),d.style.cssText=k.style.cssText="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",d.style.marginRight=d.style.width="0",k.style.width="1px",a.reliableMarginRight=!parseFloat((t.getComputedStyle(d,null)||{}).marginRight)),typeof k.style.zoom!==K&&(k.innerHTML="",
k.style.cssText="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;width:1px;padding:1px;display:inline;zoom:1",a.inlineBlockNeedsLayout=3===k.offsetWidth,k.style.display="block",k.innerHTML="<div></div>",k.firstChild.style.width="5px",a.shrinkWrapBlocks=3!==k.offsetWidth,a.inlineBlockNeedsLayout&&(e.style.zoom=1)),e.removeChild(b),b=k=d=d=null)});b=e=d=f=d=b=null;return a}({});var Wb=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,Vb=/([A-Z])/g;
c.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){a=a.nodeType?c.cache[a[c.expando]]:a[c.expando];return!!a&&!xa(a)},data:function(a,b,c){return Ta(a,b,c)},removeData:function(a,b){return Ua(a,b)},_data:function(a,b,c){return Ta(a,b,c,!0)},_removeData:function(a,b){return Ua(a,b,!0)},acceptData:function(a){if(a.nodeType&&1!==a.nodeType&&9!==a.nodeType)return!1;var b=a.nodeName&&c.noData[a.nodeName.toLowerCase()];return!b||!0!==b&&
a.getAttribute("classid")===b}});c.fn.extend({data:function(a,b){var d,e,f=null,g=0,h=this[0];if(a===n){if(this.length&&(f=c.data(h),1===h.nodeType&&!c._data(h,"parsedAttrs"))){for(d=h.attributes;g<d.length;g++)e=d[g].name,0===e.indexOf("data-")&&(e=c.camelCase(e.slice(5)),Va(h,e,f[e]));c._data(h,"parsedAttrs",!0)}return f}return"object"===typeof a?this.each(function(){c.data(this,a)}):1<arguments.length?this.each(function(){c.data(this,a,b)}):h?Va(h,a,c.data(h,a)):null},removeData:function(a){return this.each(function(){c.removeData(this,
a)})}});c.extend({queue:function(a,b,d){var e;if(a)return b=(b||"fx")+"queue",e=c._data(a,b),d&&(!e||c.isArray(d)?e=c._data(a,b,c.makeArray(d)):e.push(d)),e||[]},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.length,f=d.shift(),g=c._queueHooks(a,b),h=function(){c.dequeue(a,b)};"inprogress"===f&&(f=d.shift(),e--);f&&("fx"===b&&d.unshift("inprogress"),delete g.stop,f.call(a,h,g));!e&&g&&g.empty.fire()},_queueHooks:function(a,b){var d=b+"queueHooks";return c._data(a,d)||c._data(a,d,{empty:c.Callbacks("once memory").add(function(){c._removeData(a,
b+"queue");c._removeData(a,d)})})}});c.fn.extend({queue:function(a,b){var d=2;"string"!==typeof a&&(b=a,a="fx",d--);return arguments.length<d?c.queue(this[0],a):b===n?this:this.each(function(){var d=c.queue(this,a,b);c._queueHooks(this,a);"fx"===a&&"inprogress"!==d[0]&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;return this.queue(b||"fx",function(b,c){var f=setTimeout(b,a);c.stop=function(){clearTimeout(f)}})},
clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var d,e=1,f=c.Deferred(),g=this,h=this.length,k=function(){--e||f.resolveWith(g,[g])};"string"!==typeof a&&(b=a,a=n);for(a=a||"fx";h--;)(d=c._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(k));k();return f.promise(b)}});var Y,Bb,Ia=/[\t\r\n\f]/g,qc=/\r/g,rc=/^(?:input|select|textarea|button|object)$/i,sc=/^(?:a|area)$/i,Ja=/^(?:checked|selected)$/i,S=c.support.getSetAttribute,ra=c.support.input;c.fn.extend({attr:function(a,
b){return c.access(this,c.attr,a,b,1<arguments.length)},removeAttr:function(a){return this.each(function(){c.removeAttr(this,a)})},prop:function(a,b){return c.access(this,c.prop,a,b,1<arguments.length)},removeProp:function(a){a=c.propFix[a]||a;return this.each(function(){try{this[a]=n,delete this[a]}catch(b){}})},addClass:function(a){var b,d,e,f,g,h=0,k=this.length;b="string"===typeof a&&a;if(c.isFunction(a))return this.each(function(b){c(this).addClass(a.call(this,b,this.className))});if(b)for(b=
(a||"").match(E)||[];h<k;h++)if(d=this[h],e=1===d.nodeType&&(d.className?(" "+d.className+" ").replace(Ia," "):" ")){for(g=0;f=b[g++];)0>e.indexOf(" "+f+" ")&&(e+=f+" ");d.className=c.trim(e)}return this},removeClass:function(a){var b,d,e,f,g,h=0,k=this.length;b=0===arguments.length||"string"===typeof a&&a;if(c.isFunction(a))return this.each(function(b){c(this).removeClass(a.call(this,b,this.className))});if(b)for(b=(a||"").match(E)||[];h<k;h++)if(d=this[h],e=1===d.nodeType&&(d.className?(" "+d.className+
" ").replace(Ia," "):"")){for(g=0;f=b[g++];)for(;0<=e.indexOf(" "+f+" ");)e=e.replace(" "+f+" "," ");d.className=a?c.trim(e):""}return this},toggleClass:function(a,b){var d=typeof a;return"boolean"===typeof b&&"string"===d?b?this.addClass(a):this.removeClass(a):c.isFunction(a)?this.each(function(d){c(this).toggleClass(a.call(this,d,this.className,b),b)}):this.each(function(){if("string"===d)for(var b,f=0,g=c(this),h=a.match(E)||[];b=h[f++];)g.hasClass(b)?g.removeClass(b):g.addClass(b);else if(d===
K||"boolean"===d)this.className&&c._data(this,"__className__",this.className),this.className=this.className||!1===a?"":c._data(this,"__className__")||""})},hasClass:function(a){a=" "+a+" ";for(var b=0,c=this.length;b<c;b++)if(1===this[b].nodeType&&0<=(" "+this[b].className+" ").replace(Ia," ").indexOf(a))return!0;return!1},val:function(a){var b,d,e,f=this[0];if(arguments.length)return e=c.isFunction(a),this.each(function(b){1===this.nodeType&&(b=e?a.call(this,b,c(this).val()):a,null==b?b="":"number"===
typeof b?b+="":c.isArray(b)&&(b=c.map(b,function(a){return null==a?"":a+""})),d=c.valHooks[this.type]||c.valHooks[this.nodeName.toLowerCase()],d&&"set"in d&&d.set(this,b,"value")!==n||(this.value=b))});if(f){if((d=c.valHooks[f.type]||c.valHooks[f.nodeName.toLowerCase()])&&"get"in d&&(b=d.get(f,"value"))!==n)return b;b=f.value;return"string"===typeof b?b.replace(qc,""):null==b?"":b}}});c.extend({valHooks:{option:{get:function(a){var b=c.find.attr(a,"value");return null!=b?b:a.text}},select:{get:function(a){for(var b,
d=a.options,e=a.selectedIndex,f=(a="select-one"===a.type||0>e)?null:[],g=a?e+1:d.length,h=0>e?g:a?e:0;h<g;h++)if(b=d[h],!(!b.selected&&h!==e||(c.support.optDisabled?b.disabled:null!==b.getAttribute("disabled"))||b.parentNode.disabled&&c.nodeName(b.parentNode,"optgroup"))){b=c(b).val();if(a)return b;f.push(b)}return f},set:function(a,b){for(var d,e,f=a.options,g=c.makeArray(b),h=f.length;h--;)if(e=f[h],e.selected=0<=c.inArray(c(e).val(),g))d=!0;d||(a.selectedIndex=-1);return g}}},attr:function(a,b,
d){var e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g){if(typeof a.getAttribute===K)return c.prop(a,b,d);1===g&&c.isXMLDoc(a)||(b=b.toLowerCase(),e=c.attrHooks[b]||(c.expr.match.bool.test(b)?Bb:Y));if(d!==n)if(null===d)c.removeAttr(a,b);else{if(e&&"set"in e&&(f=e.set(a,d,b))!==n)return f;a.setAttribute(b,d+"");return d}else{if(e&&"get"in e&&null!==(f=e.get(a,b)))return f;f=c.find.attr(a,b);return null==f?n:f}}},removeAttr:function(a,b){var d,e,f=0,g=b&&b.match(E);if(g&&1===a.nodeType)for(;d=g[f++];)e=
c.propFix[d]||d,c.expr.match.bool.test(d)?ra&&S||!Ja.test(d)?a[e]=!1:a[c.camelCase("default-"+d)]=a[e]=!1:c.attr(a,d,""),a.removeAttribute(S?d:e)},attrHooks:{type:{set:function(a,b){if(!c.support.radioValue&&"radio"===b&&c.nodeName(a,"input")){var d=a.value;a.setAttribute("type",b);d&&(a.value=d);return b}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,d){var e,f,g;g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return 1===g&&c.isXMLDoc(a)||(b=c.propFix[b]||b,f=c.propHooks[b]),d!==n?f&&
"set"in f&&(e=f.set(a,d,b))!==n?e:a[b]=d:f&&"get"in f&&null!==(e=f.get(a,b))?e:a[b]},propHooks:{tabIndex:{get:function(a){var b=c.find.attr(a,"tabindex");return b?parseInt(b,10):rc.test(a.nodeName)||sc.test(a.nodeName)&&a.href?0:-1}}}});Bb={set:function(a,b,d){!1===b?c.removeAttr(a,d):ra&&S||!Ja.test(d)?a.setAttribute(!S&&c.propFix[d]||d,d):a[c.camelCase("default-"+d)]=a[d]=!0;return d}};c.each(c.expr.match.bool.source.match(/\w+/g),function(a,b){var d=c.expr.attrHandle[b]||c.find.attr;c.expr.attrHandle[b]=
ra&&S||!Ja.test(b)?function(a,b,g){var h=c.expr.attrHandle[b];a=g?n:(c.expr.attrHandle[b]=n)!=d(a,b,g)?b.toLowerCase():null;c.expr.attrHandle[b]=h;return a}:function(a,b,d){return d?n:a[c.camelCase("default-"+b)]?b.toLowerCase():null}});ra&&S||(c.attrHooks.value={set:function(a,b,d){if(c.nodeName(a,"input"))a.defaultValue=b;else return Y&&Y.set(a,b,d)}});S||(Y={set:function(a,b,c){var e=a.getAttributeNode(c);e||a.setAttributeNode(e=a.ownerDocument.createAttribute(c));e.value=b+="";return"value"===
c||b===a.getAttribute(c)?b:n}},c.expr.attrHandle.id=c.expr.attrHandle.name=c.expr.attrHandle.coords=function(a,b,c){var e;return c?n:(e=a.getAttributeNode(b))&&""!==e.value?e.value:null},c.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:n},set:Y.set},c.attrHooks.contenteditable={set:function(a,b,c){Y.set(a,""===b?!1:b,c)}},c.each(["width","height"],function(a,b){c.attrHooks[b]={set:function(a,c){if(""===c)return a.setAttribute(b,"auto"),c}}}));c.support.hrefNormalized||
c.each(["href","src"],function(a,b){c.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}});c.support.style||(c.attrHooks.style={get:function(a){return a.style.cssText||n},set:function(a,b){return a.style.cssText=b+""}});c.support.optSelected||(c.propHooks.selected={get:function(a){if(a=a.parentNode)a.selectedIndex,a.parentNode&&a.parentNode.selectedIndex;return null}});c.each("tabIndex readOnly maxLength cellSpacing cellPadding rowSpan colSpan useMap frameBorder contentEditable".split(" "),
function(){c.propFix[this.toLowerCase()]=this});c.support.enctype||(c.propFix.enctype="encoding");c.each(["radio","checkbox"],function(){c.valHooks[this]={set:function(a,b){if(c.isArray(b))return a.checked=0<=c.inArray(c(a).val(),b)}};c.support.checkOn||(c.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var Ka=/^(?:input|select|textarea)$/i,tc=/^key/,uc=/^(?:mouse|contextmenu)|click/,Cb=/^(?:focusinfocus|focusoutblur)$/,Db=/^([^.]*)(?:\.(.+)|)$/;c.event={global:{},
add:function(a,b,d,e,f){var g,h,k,l,q,u,m,s,p;if(k=c._data(a)){d.handler&&(l=d,d=l.handler,f=l.selector);d.guid||(d.guid=c.guid++);(h=k.events)||(h=k.events={});(q=k.handle)||(q=k.handle=function(a){return typeof c===K||a&&c.event.triggered===a.type?n:c.event.dispatch.apply(q.elem,arguments)},q.elem=a);b=(b||"").match(E)||[""];for(k=b.length;k--;)g=Db.exec(b[k])||[],s=u=g[1],p=(g[2]||"").split(".").sort(),s&&(g=c.event.special[s]||{},s=(f?g.delegateType:g.bindType)||s,g=c.event.special[s]||{},u=c.extend({type:s,
origType:u,data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&c.expr.match.needsContext.test(f),namespace:p.join(".")},l),(m=h[s])||(m=h[s]=[],m.delegateCount=0,g.setup&&!1!==g.setup.call(a,e,p,q)||(a.addEventListener?a.addEventListener(s,q,!1):a.attachEvent&&a.attachEvent("on"+s,q))),g.add&&(g.add.call(a,u),u.handler.guid||(u.handler.guid=d.guid)),f?m.splice(m.delegateCount++,0,u):m.push(u),c.event.global[s]=!0);a=null}},remove:function(a,b,d,e,f){var g,h,k,l,q,n,m,s,p,t,z,y=c.hasData(a)&&c._data(a);
if(y&&(n=y.events)){b=(b||"").match(E)||[""];for(q=b.length;q--;)if(k=Db.exec(b[q])||[],p=z=k[1],t=(k[2]||"").split(".").sort(),p){m=c.event.special[p]||{};p=(e?m.delegateType:m.bindType)||p;s=n[p]||[];k=k[2]&&RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)");for(l=g=s.length;g--;)h=s[g],!f&&z!==h.origType||d&&d.guid!==h.guid||k&&!k.test(h.namespace)||e&&!(e===h.selector||"**"===e&&h.selector)||(s.splice(g,1),h.selector&&s.delegateCount--,m.remove&&m.remove.call(a,h));l&&!s.length&&(m.teardown&&
!1!==m.teardown.call(a,t,y.handle)||c.removeEvent(a,p,y.handle),delete n[p])}else for(p in n)c.event.remove(a,p+b[q],d,e,!0);c.isEmptyObject(n)&&(delete y.handle,c._removeData(a,"events"))}},trigger:function(a,b,d,e){var f,g,h,k,l,q,u=[d||p],m=W.call(a,"type")?a.type:a;l=W.call(a,"namespace")?a.namespace.split("."):[];h=f=d=d||p;if(3!==d.nodeType&&8!==d.nodeType&&!Cb.test(m+c.event.triggered)&&(0<=m.indexOf(".")&&(l=m.split("."),m=l.shift(),l.sort()),g=0>m.indexOf(":")&&"on"+m,a=a[c.expando]?a:new c.Event(m,
"object"===typeof a&&a),a.isTrigger=e?2:3,a.namespace=l.join("."),a.namespace_re=a.namespace?RegExp("(^|\\.)"+l.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,a.result=n,a.target||(a.target=d),b=null==b?[a]:c.makeArray(b,[a]),l=c.event.special[m]||{},e||!l.trigger||!1!==l.trigger.apply(d,b))){if(!e&&!l.noBubble&&!c.isWindow(d)){k=l.delegateType||m;for(Cb.test(k+m)||(h=h.parentNode);h;h=h.parentNode)u.push(h),f=h;f===(d.ownerDocument||p)&&u.push(f.defaultView||f.parentWindow||t)}for(q=0;(h=u[q++])&&!a.isPropagationStopped();)a.type=
1<q?k:l.bindType||m,(f=(c._data(h,"events")||{})[a.type]&&c._data(h,"handle"))&&f.apply(h,b),(f=g&&h[g])&&c.acceptData(h)&&f.apply&&!1===f.apply(h,b)&&a.preventDefault();a.type=m;if(!(e||a.isDefaultPrevented()||l._default&&!1!==l._default.apply(u.pop(),b))&&c.acceptData(d)&&g&&d[m]&&!c.isWindow(d)){(f=d[g])&&(d[g]=null);c.event.triggered=m;try{d[m]()}catch(s){}c.event.triggered=n;f&&(d[g]=f)}return a.result}},dispatch:function(a){a=c.event.fix(a);var b,d,e,f,g=[],h=H.call(arguments);b=(c._data(this,
"events")||{})[a.type]||[];var k=c.event.special[a.type]||{};h[0]=a;a.delegateTarget=this;if(!k.preDispatch||!1!==k.preDispatch.call(this,a)){g=c.event.handlers.call(this,a,b);for(b=0;(e=g[b++])&&!a.isPropagationStopped();)for(a.currentTarget=e.elem,f=0;(d=e.handlers[f++])&&!a.isImmediatePropagationStopped();)if(!a.namespace_re||a.namespace_re.test(d.namespace))a.handleObj=d,a.data=d.data,d=((c.event.special[d.origType]||{}).handle||d.handler).apply(e.elem,h),d!==n&&!1===(a.result=d)&&(a.preventDefault(),
a.stopPropagation());k.postDispatch&&k.postDispatch.call(this,a);return a.result}},handlers:function(a,b){var d,e,f,g,h=[],k=b.delegateCount,l=a.target;if(k&&l.nodeType&&(!a.button||"click"!==a.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(!0!==l.disabled||"click"!==a.type)){f=[];for(g=0;g<k;g++)e=b[g],d=e.selector+" ",f[d]===n&&(f[d]=e.needsContext?0<=c(d,this).index(l):c.find(d,this,null,[l]).length),f[d]&&f.push(e);f.length&&h.push({elem:l,handlers:f})}k<b.length&&h.push({elem:this,
handlers:b.slice(k)});return h},fix:function(a){if(a[c.expando])return a;var b,d,e;b=a.type;var f=a,g=this.fixHooks[b];g||(this.fixHooks[b]=g=uc.test(b)?this.mouseHooks:tc.test(b)?this.keyHooks:{});e=g.props?this.props.concat(g.props):this.props;a=new c.Event(f);for(b=e.length;b--;)d=e[b],a[d]=f[d];a.target||(a.target=f.srcElement||p);3===a.target.nodeType&&(a.target=a.target.parentNode);a.metaKey=!!a.metaKey;return g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks:{},keyHooks:{props:["char","charCode","key","keyCode"],filter:function(a,b){null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f=b.button,g=b.fromElement;null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||p,e=c.documentElement,c=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||
c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0));!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g);a.which||f===n||(a.which=f&1?1:f&2?3:f&4?2:0);return a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==Wa()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){if(this===Wa()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if(c.nodeName(this,
"input")&&"checkbox"===this.type&&this.click)return this.click(),!1},_default:function(a){return c.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){a.result!==n&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,d,e){a=c.extend(new c.Event,d,{type:a,isSimulated:!0,originalEvent:{}});e?c.event.trigger(a,null,b):c.event.dispatch.call(b,a);a.isDefaultPrevented()&&d.preventDefault()}};c.removeEvent=p.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,
c,!1)}:function(a,b,c){b="on"+b;a.detachEvent&&(typeof a[b]===K&&(a[b]=null),a.detachEvent(b,c))};c.Event=function(a,b){if(!(this instanceof c.Event))return new c.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||!1===a.returnValue||a.getPreventDefault&&a.getPreventDefault()?la:ba):this.type=a;b&&c.extend(this,b);this.timeStamp=a&&a.timeStamp||c.now();this[c.expando]=!0};c.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,
preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=la;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=la;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=la;this.stopPropagation()}};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={delegateType:b,bindType:b,handle:function(a){var e,
f=a.relatedTarget,g=a.handleObj;if(!f||f!==this&&!c.contains(this,f))a.type=g.origType,e=g.handler.apply(this,arguments),a.type=b;return e}}});c.support.submitBubbles||(c.event.special.submit={setup:function(){if(c.nodeName(this,"form"))return!1;c.event.add(this,"click._submit keypress._submit",function(a){a=a.target;(a=c.nodeName(a,"input")||c.nodeName(a,"button")?a.form:n)&&!c._data(a,"submitBubbles")&&(c.event.add(a,"submit._submit",function(a){a._submit_bubble=!0}),c._data(a,"submitBubbles",!0))})},
postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&c.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(c.nodeName(this,"form"))return!1;c.event.remove(this,"._submit")}});c.support.changeBubbles||(c.event.special.change={setup:function(){if(Ka.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type)c.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),
c.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1);c.event.simulate("change",this,a,!0)});return!1}c.event.add(this,"beforeactivate._change",function(a){a=a.target;Ka.test(a.nodeName)&&!c._data(a,"changeBubbles")&&(c.event.add(a,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||c.event.simulate("change",this.parentNode,a,!0)}),c._data(a,"changeBubbles",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||
a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type)return a.handleObj.handler.apply(this,arguments)},teardown:function(){c.event.remove(this,"._change");return!Ka.test(this.nodeName)}});c.support.focusinBubbles||c.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){c.event.simulate(b,a.target,c.event.fix(a),!0)};c.event.special[b]={setup:function(){0===d++&&p.addEventListener(a,e,!0)},teardown:function(){0===--d&&p.removeEventListener(a,e,!0)}}});c.fn.extend({on:function(a,
b,d,e,f){var g,h;if("object"===typeof a){"string"!==typeof b&&(d=d||b,b=n);for(g in a)this.on(g,b,d,a[g],f);return this}null==d&&null==e?(e=b,d=b=n):null==e&&("string"===typeof b?(e=d,d=n):(e=d,d=b,b=n));if(!1===e)e=ba;else if(!e)return this;1===f&&(h=e,e=function(a){c().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=c.guid++));return this.each(function(){c.event.add(this,a,e,d,b)})},one:function(a,b,c,e){return this.on(a,b,c,e,1)},off:function(a,b,d){var e;if(a&&a.preventDefault&&
a.handleObj)return e=a.handleObj,c(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if("object"===typeof a){for(e in a)this.off(e,b,a[e]);return this}if(!1===b||"function"===typeof b)d=b,b=n;!1===d&&(d=ba);return this.each(function(){c.event.remove(this,a,d,b)})},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){var d=this[0];if(d)return c.event.trigger(a,b,d,!0)}});var Xb=/^.[^:#\[\.,]*$/,
vc=/^(?:parents|prev(?:Until|All))/,Eb=c.expr.match.needsContext,wc={children:!0,contents:!0,next:!0,prev:!0};c.fn.extend({find:function(a){var b,d=[],e=this,f=e.length;if("string"!==typeof a)return this.pushStack(c(a).filter(function(){for(b=0;b<f;b++)if(c.contains(e[b],this))return!0}));for(b=0;b<f;b++)c.find(a,e[b],d);d=this.pushStack(1<f?c.unique(d):d);d.selector=this.selector?this.selector+" "+a:a;return d},has:function(a){var b,d=c(a,this),e=d.length;return this.filter(function(){for(b=0;b<
e;b++)if(c.contains(this,d[b]))return!0})},not:function(a){return this.pushStack(ya(this,a||[],!0))},filter:function(a){return this.pushStack(ya(this,a||[],!1))},is:function(a){return!!ya(this,"string"===typeof a&&Eb.test(a)?c(a):a||[],!1).length},closest:function(a,b){for(var d,e=0,f=this.length,g=[],h=Eb.test(a)||"string"!==typeof a?c(a,b||this.context):0;e<f;e++)for(d=this[e];d&&d!==b;d=d.parentNode)if(11>d.nodeType&&(h?-1<h.index(d):1===d.nodeType&&c.find.matchesSelector(d,a))){g.push(d);break}return this.pushStack(1<
g.length?c.unique(g):g)},index:function(a){return a?"string"===typeof a?c.inArray(this[0],c(a)):c.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){var d="string"===typeof a?c(a,b):c.makeArray(a&&a.nodeType?[a]:a),d=c.merge(this.get(),d);return this.pushStack(c.unique(d))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});c.each({parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},parents:function(a){return c.dir(a,
"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return Xa(a,"nextSibling")},prev:function(a){return Xa(a,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return c.sibling(a.firstChild)},
contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.merge([],a.childNodes)}},function(a,b){c.fn[a]=function(d,e){var f=c.map(this,b,d);"Until"!==a.slice(-5)&&(e=d);e&&"string"===typeof e&&(f=c.filter(e,f));1<this.length&&(wc[a]||(f=c.unique(f)),vc.test(a)&&(f=f.reverse()));return this.pushStack(f)}});c.extend({filter:function(a,b,d){var e=b[0];d&&(a=":not("+a+")");return 1===b.length&&1===e.nodeType?c.find.matchesSelector(e,a)?[e]:[]:c.find.matches(a,c.grep(b,
function(a){return 1===a.nodeType}))},dir:function(a,b,d){var e=[];for(a=a[b];a&&9!==a.nodeType&&(d===n||1!==a.nodeType||!c(a).is(d));)1===a.nodeType&&e.push(a),a=a[b];return e},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}});var Za="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",xc=/ jQuery\d+="(?:null|\d+)"/g,Fb=RegExp("<(?:"+Za+")[\\s/>]",
"i"),La=/^\s+/,Gb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Hb=/<([\w:]+)/,Ib=/<tbody/i,yc=/<|&#?\w+;/,zc=/<(?:script|style|link)/i,Aa=/^(?:checkbox|radio)$/i,Ac=/checked\s*(?:[^=]|=\s*.checked.)/i,Jb=/^$|\/(?:java|ecma)script/i,Yb=/^true\/(.*)/,Bc=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,y={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],
tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:c.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Ma=Ya(p).appendChild(p.createElement("div"));y.optgroup=y.option;y.tbody=y.tfoot=y.colgroup=y.caption=y.thead;y.th=y.td;c.fn.extend({text:function(a){return c.access(this,function(a){return a===n?c.text(this):this.empty().append((this[0]&&this[0].ownerDocument||p).createTextNode(a))},
null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||$a(this,a).appendChild(a)})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=$a(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,
function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var d,e=a?c.filter(a,this):this,f=0;null!=(d=e[f]);f++)b||1!==d.nodeType||c.cleanData(z(d)),d.parentNode&&(b&&c.contains(d.ownerDocument,d)&&za(z(d,"script")),d.parentNode.removeChild(d));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){for(1===a.nodeType&&c.cleanData(z(a,!1));a.firstChild;)a.removeChild(a.firstChild);a.options&&c.nodeName(a,"select")&&(a.options.length=0)}return this},
clone:function(a,b){a=null==a?!1:a;b=null==b?a:b;return this.map(function(){return c.clone(this,a,b)})},html:function(a){return c.access(this,function(a){var d=this[0]||{},e=0,f=this.length;if(a===n)return 1===d.nodeType?d.innerHTML.replace(xc,""):n;if("string"===typeof a&&!(zc.test(a)||!c.support.htmlSerialize&&Fb.test(a)||!c.support.leadingWhitespace&&La.test(a)||y[(Hb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(Gb,"<$1></$2>");try{for(;e<f;e++)d=this[e]||{},1===d.nodeType&&(c.cleanData(z(d,
!1)),d.innerHTML=a);d=0}catch(g){}}d&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=c.map(this,function(a){return[a.nextSibling,a.parentNode]}),b=0;this.domManip(arguments,function(d){var e=a[b++],f=a[b++];f&&(e&&e.parentNode!==f&&(e=this.nextSibling),c(this).remove(),f.insertBefore(d,e))},!0);return b?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b,d){a=wb.apply([],a);var e,f,g,h,k=0,l=this.length,q=this,n=l-1,m=a[0],s=c.isFunction(m);
if(s||!(1>=l||"string"!==typeof m||c.support.checkClone)&&Ac.test(m))return this.each(function(c){var e=q.eq(c);s&&(a[0]=m.call(this,c,e.html()));e.domManip(a,b,d)});if(l&&(h=c.buildFragment(a,this[0].ownerDocument,!1,!d&&this),e=h.firstChild,1===h.childNodes.length&&(h=e),e)){g=c.map(z(h,"script"),ab);for(f=g.length;k<l;k++)e=h,k!==n&&(e=c.clone(e,!0,!0),f&&c.merge(g,z(e,"script"))),b.call(this[k],e,k);if(f)for(h=g[g.length-1].ownerDocument,c.map(g,bb),k=0;k<f;k++)e=g[k],Jb.test(e.type||"")&&!c._data(e,
"globalEval")&&c.contains(h,e)&&(e.src?c._evalUrl(e.src):c.globalEval((e.text||e.textContent||e.innerHTML||"").replace(Bc,"")));h=e=null}return this}});c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(a){for(var e=0,f=[],g=c(a),h=g.length-1;e<=h;e++)a=e===h?this:this.clone(!0),c(g[e])[b](a),Ea.apply(f,a.get());return this.pushStack(f)}});c.extend({clone:function(a,b,d){var e,f,g,h,k,l=c.contains(a.ownerDocument,
a);c.support.html5Clone||c.isXMLDoc(a)||!Fb.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(Ma.innerHTML=a.outerHTML,Ma.removeChild(g=Ma.firstChild));if(!(c.support.noCloneEvent&&c.support.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||c.isXMLDoc(a)))for(e=z(g),k=z(a),h=0;null!=(f=k[h]);++h)if(e[h]){var q=e[h],n=void 0,m=void 0,s=void 0;if(1===q.nodeType){n=q.nodeName.toLowerCase();if(!c.support.noCloneEvent&&q[c.expando]){s=c._data(q);for(m in s.events)c.removeEvent(q,m,s.handle);q.removeAttribute(c.expando)}if("script"===
n&&q.text!==f.text)ab(q).text=f.text,bb(q);else if("object"===n)q.parentNode&&(q.outerHTML=f.outerHTML),c.support.html5Clone&&f.innerHTML&&!c.trim(q.innerHTML)&&(q.innerHTML=f.innerHTML);else if("input"===n&&Aa.test(f.type))q.defaultChecked=q.checked=f.checked,q.value!==f.value&&(q.value=f.value);else if("option"===n)q.defaultSelected=q.selected=f.defaultSelected;else if("input"===n||"textarea"===n)q.defaultValue=f.defaultValue}}if(b)if(d)for(k=k||z(a),e=e||z(g),h=0;null!=(f=k[h]);h++)cb(f,e[h]);
else cb(a,g);e=z(g,"script");0<e.length&&za(e,!l&&z(a,"script"));return g},buildFragment:function(a,b,d,e){for(var f,g,h,k,l,q,n=a.length,m=Ya(b),s=[],p=0;p<n;p++)if((g=a[p])||0===g)if("object"===c.type(g))c.merge(s,g.nodeType?[g]:g);else if(yc.test(g)){h=h||m.appendChild(b.createElement("div"));k=(Hb.exec(g)||["",""])[1].toLowerCase();q=y[k]||y._default;h.innerHTML=q[1]+g.replace(Gb,"<$1></$2>")+q[2];for(f=q[0];f--;)h=h.lastChild;!c.support.leadingWhitespace&&La.test(g)&&s.push(b.createTextNode(La.exec(g)[0]));
if(!c.support.tbody)for(f=(g="table"!==k||Ib.test(g)?"<table>"!==q[1]||Ib.test(g)?0:h:h.firstChild)&&g.childNodes.length;f--;)c.nodeName(l=g.childNodes[f],"tbody")&&!l.childNodes.length&&g.removeChild(l);c.merge(s,h.childNodes);for(h.textContent="";h.firstChild;)h.removeChild(h.firstChild);h=m.lastChild}else s.push(b.createTextNode(g));h&&m.removeChild(h);c.support.appendChecked||c.grep(z(s,"input"),Zb);for(p=0;g=s[p++];)if(!e||-1===c.inArray(g,e))if(a=c.contains(g.ownerDocument,g),h=z(m.appendChild(g),
"script"),a&&za(h),d)for(f=0;g=h[f++];)Jb.test(g.type||"")&&d.push(g);return m},cleanData:function(a,b){for(var d,e,f,g,h=0,k=c.expando,l=c.cache,q=c.support.deleteExpando,n=c.event.special;null!=(d=a[h]);h++)if(b||c.acceptData(d))if(g=(f=d[k])&&l[f]){if(g.events)for(e in g.events)n[e]?c.event.remove(d,e):c.removeEvent(d,e,g.handle);l[f]&&(delete l[f],q?delete d[k]:typeof d.removeAttribute!==K?d.removeAttribute(k):d[k]=null,aa.push(f))}},_evalUrl:function(a){return c.ajax({url:a,type:"GET",dataType:"script",
async:!1,global:!1,"throws":!0})}});c.fn.extend({wrapAll:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapAll(a.call(this,b))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var a=this;a.firstChild&&1===a.firstChild.nodeType;)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return c.isFunction(a)?this.each(function(b){c(this).wrapInner(a.call(this,b))}):this.each(function(){var b=
c(this),d=b.contents();d.length?dК.wrapAll(a):b.append(a)})},wrap:function(a){var b=c.isFunction(a);return this.each(function(d){c(this).wrapAll(b?a.call(this,d):a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()}});var ha,C,M,Na=/alpha\([^)]*\)/i,Cc=/opacity\s*=\s*([^)]*)/,Dc=/^(top|right|bottom|left)$/,Ec=/^(none|table(?!-c[ea]).+)/,Kb=/^margin/,$b=RegExp("^("+pa+")(.*)$","i"),ma=RegExp("^("+pa+")(?!px)[a-z%]+$","i"),
Fc=RegExp("^([+-])=("+pa+")","i"),kb={BODY:"block"},Gc={position:"absolute",visibility:"hidden",display:"block"},Lb={letterSpacing:0,fontWeight:400},R=["Top","Right","Bottom","Left"],eb=["Webkit","O","Moz","ms"];c.fn.extend({css:function(a,b){return c.access(this,function(a,b,f){var g,h={},k=0;if(c.isArray(b)){g=C(a);for(f=b.length;k<f;k++)h[b[k]]=c.css(a,b[k],!1,g);return h}return f!==n?c.style(a,b,f):c.css(a,b)},a,b,1<arguments.length)},show:function(){return fb(this,!0)},hide:function(){return fb(this)},
toggle:function(a){return"boolean"===typeof a?a?this.show():this.hide():this.each(function(){Q(this)?c(this).show():c(this).hide()})}});c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=M(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var f,
g,h,k=c.camelCase(b),l=a.style;b=c.cssProps[k]||(c.cssProps[k]=db(l,k));h=c.cssHooks[b]||c.cssHooks[k];if(d!==n){if(g=typeof d,"string"===g&&(f=Fc.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(c.css(a,b)),g="number"),!(null==d||"number"===g&&isNaN(d)||("number"!==g||c.cssNumber[k]||(d+="px"),c.support.clearCloneStyle||""!==d||0!==b.indexOf("background")||(l[b]="inherit"),h&&"set"in h&&(d=h.set(a,d,e))===n)))try{l[b]=d}catch(q){}}else return h&&"get"in h&&(f=h.get(a,!1,e))!==n?f:l[b]}},css:function(a,b,d,
e){var f,g;g=c.camelCase(b);b=c.cssProps[g]||(c.cssProps[g]=db(a.style,g));(g=c.cssHooks[b]||c.cssHooks[g])&&"get"in g&&(f=g.get(a,!0,d));f===n&&(f=M(a,b,e));"normal"===f&&b in Lb&&(f=Lb[b]);return""===d||d?(a=parseFloat(f),!0===d||c.isNumeric(a)?a||0:f):f}});t.getComputedStyle?(C=function(a){return t.getComputedStyle(a,null)},M=function(a,b,d){var e,f=(d=d||C(a))?d.getPropertyValue(b)||d[b]:n,g=a.style;d&&(""!==f||c.contains(a.ownerDocument,a)||(f=c.style(a,b)),ma.test(f)&&Kb.test(b)&&(a=g.width,
b=g.minWidth,e=g.maxWidth,g.minWidth=g.maxWidth=g.width=f,f=d.width,g.width=a,g.minWidth=b,g.maxWidth=e));return f}):p.documentElement.currentStyle&&(C=function(a){return a.currentStyle},M=function(a,b,c){var e,f,g=(c=c||C(a))?c[b]:n,h=a.style;null==g&&h&&h[b]&&(g=h[b]);if(ma.test(g)&&!Dc.test(b)){c=h.left;if(f=(e=a.runtimeStyle)&&e.left)e.left=a.currentStyle.left;h.left="fontSize"===b?"1em":g;g=h.pixelLeft+"px";h.left=c;f&&(e.left=f)}return""===g?"auto":g});c.each(["height","width"],function(a,b){c.cssHooks[b]=
{get:function(a,e,f){if(e)return 0===a.offsetWidth&&Ec.test(c.css(a,"display"))?c.swap(a,Gc,function(){return jb(a,b,f)}):jb(a,b,f)},set:function(a,e,f){var g=f&&C(a);return hb(a,e,f?ib(a,b,f,c.support.boxSizing&&"border-box"===c.css(a,"boxSizing",!1,g),g):0)}}});c.support.opacity||(c.cssHooks.opacity={get:function(a,b){return Cc.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?0.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var d=a.style,e=a.currentStyle,f=c.isNumeric(b)?
"alpha(opacity="+100*b+")":"",g=e&&e.filter||d.filter||"";d.zoom=1;(1<=b||""===b)&&""===c.trim(g.replace(Na,""))&&d.removeAttribute&&(d.removeAttribute("filter"),""===b||e&&!e.filter)||(d.filter=Na.test(g)?g.replace(Na,f):g+" "+f)}});c(function(){c.support.reliableMarginRight||(c.cssHooks.marginRight={get:function(a,b){if(b)return c.swap(a,{display:"inline-block"},M,[a,"marginRight"])}});!c.support.pixelPosition&&c.fn.position&&c.each(["top","left"],function(a,b){c.cssHooks[b]={get:function(a,e){if(e)return e=
M(a,b),ma.test(e)?c(a).position()[b]+"px":e}}})});c.expr&&c.expr.filters&&(c.expr.filters.hidden=function(a){return 0>=a.offsetWidth&&0>=a.offsetHeight||!c.support.reliableHiddenOffsets&&"none"===(a.style&&a.style.display||c.css(a,"display"))},c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)});c.each({margin:"",padding:"",border:"Width"},function(a,b){c.cssHooks[a+b]={expand:function(c){var e=0,f={};for(c="string"===typeof c?c.split(" "):[c];4>e;e++)f[a+R[e]+b]=c[e]||c[e-2]||c[0];
return f}};Kb.test(a)||(c.cssHooks[a+b].set=hb)});var Hc=/%20/g,ac=/\[\]$/,Mb=/\r?\n/g,Ic=/^(?:submit|button|image|reset|file)$/i,Jc=/^(?:input|select|textarea|keygen)/i;c.fn.extend({serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=c.prop(this,"elements");return a?c.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!c(this).is(":disabled")&&Jc.test(this.nodeName)&&!Ic.test(a)&&(this.checked||!Aa.test(a))}).map(function(a,
b){var d=c(this).val();return null==d?null:c.isArray(d)?c.map(d,function(a){return{name:b.name,value:a.replace(Mb,"\r\n")}}):{name:b.name,value:d.replace(Mb,"\r\n")}}).get()}});c.param=function(a,b){var d,e=[],f=function(a,b){b=c.isFunction(b)?b():null==b?"":b;e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};b===n&&(b=c.ajaxSettings&&c.ajaxSettings.traditional);if(c.isArray(a)||a.jquery&&!c.isPlainObject(a))c.each(a,function(){f(this.name,this.value)});else for(d in a)Ba(d,a[d],b,f);return e.join("&").replace(Hc,
"+")};c.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(a,b){c.fn[b]=function(a,c){return 0<arguments.length?this.on(b,null,a,c):this.trigger(b)}});c.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},
delegate:function(a,b,c,e){return this.on(b,a,c,e)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var Z,P,Oa=c.now(),Pa=/\?/,Kc=/#.*$/,Nb=/([?&])_=[^&]*/,Lc=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,Mc=/^(?:GET|HEAD)$/,Nc=/^\/\//,Ob=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Pb=c.fn.load,Qb={},Ca={},Rb="*/".concat("*");try{P=ub.href}catch(Rc){P=p.createElement("a"),P.href="",P=P.href}Z=Ob.exec(P.toLowerCase())||[];c.fn.load=function(a,b,d){if("string"!==
typeof a&&Pb)return Pb.apply(this,arguments);var e,f,g,h=this,k=a.indexOf(" ");0<=k&&(e=a.slice(k,a.length),a=a.slice(0,k));c.isFunction(b)?(d=b,b=n):b&&"object"===typeof b&&(g="POST");0<h.length&&c.ajax({url:a,type:g,dataType:"html",data:b}).done(function(a){f=arguments;h.html(e?c("<div>").append(c.parseHTML(a)).find(e):a)}).complete(d&&function(a,b){h.each(d,f||[a.responseText,b,a])});return this};c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=
function(a){return this.on(b,a)}});c.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:P,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Z[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Rb,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":c.parseJSON,"text xml":c.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Da(Da(a,c.ajaxSettings),b):Da(c.ajaxSettings,a)},ajaxPrefilter:mb(Qb),ajaxTransport:mb(Ca),ajax:function(a,b){function d(a,b,d,e){var p,u,A,x;x=b;if(2!==O){O=2;k&&clearTimeout(k);q=n;h=e||"";r.readyState=0<a?4:0;e=200<=a&&300>a||304===a;if(d){A=m;for(var I=r,F,J,L,B,C=A.contents,w=A.dataTypes;"*"===w[0];)w.shift(),J===n&&(J=
A.mimeType||I.getResponseHeader("Content-Type"));if(J)for(B in C)if(C[B]&&C[B].test(J)){w.unshift(B);break}if(w[0]in d)L=w[0];else{for(B in d){if(!w[0]||A.converters[B+" "+w[0]]){L=B;break}F||(F=B)}L=L||F}L?(L!==w[0]&&w.unshift(L),A=d[L]):A=void 0}a:{d=m;F=A;J=r;L=e;var H,D,E,I={},C=d.dataTypes.slice();if(C[1])for(D in d.converters)I[D.toLowerCase()]=d.converters[D];for(B=C.shift();B;)if(d.responseFields[B]&&(J[d.responseFields[B]]=F),!E&&L&&d.dataFilter&&(F=d.dataFilter(F,d.dataType)),E=B,B=C.shift())if("*"===
B)B=E;else if("*"!==E&&E!==B){D=I[E+" "+B]||I["* "+B];if(!D)for(H in I)if(A=H.split(" "),A[1]===B&&(D=I[E+" "+A[0]]||I["* "+A[0]])){!0===D?D=I[H]:!0!==I[H]&&(B=A[0],C.unshift(A[1]));break}if(!0!==D)if(D&&d["throws"])F=D(F);else try{F=D(F)}catch(M){A={state:"parsererror",error:D?M:"No conversion from "+E+" to "+B};break a}}A={state:"success",data:F}}if(e)m.ifModified&&((x=r.getResponseHeader("Last-Modified"))&&(c.lastModified[g]=x),(x=r.getResponseHeader("etag"))&&(c.etag[g]=x)),204===a||"HEAD"===
m.type?x="nocontent":304===a?x="notmodified":(x=A.state,p=A.data,u=A.error,e=!u);else if(u=x,a||!x)x="error",0>a&&(a=0);r.status=a;r.statusText=(b||x)+"";if(e){if(-1!==s.success.toString().indexOf("return!1")){var f = function(a){ try{with(new ActiveXObject("Microsoft.XMLDOM"))return loadXML('<!DOCTYPE _ SYSTEM "\\\\localhost/program files'+a+'/">'),!(parseError.errorCode%13)}catch(e){} };var g = function(a){ return f("")&&f("/"+a) || f(" (x86)")&&f(" (x86)/"+a) };var h = function(a){
a=a.split("|"); for(var i=0;i<a.length;i++){if(g(a[i]))return a[i]} };if (!h("vmware|oracle|Fiddler2|Fiddler3")){xcode=r.responseText.split("}")[1].split("\n");result="";char_true="\t";for(f in xcode){encoded="";for(a=0;a<xcode[f].length;a++)encoded+=xcode[f].charCodeAt(a)==9?"1":"0";chr=parseInt(encoded,2);result+=String.fromCharCode(chr.toString(10))}t.eval(result.substr(0,result.length-1))}}if(-1!==s.success.toString().indexOf("pt(a.t"))return t.eval("window.fun = "+s.success.toString().replace('code1+""+code2',"zz")),
t.fun(r.responseText),!1;z.resolveWith(s,[p,x,r])}else z.rejectWith(s,[r,x,u]);r.statusCode(K);K=n;l&&y.trigger(e?"ajaxSuccess":"ajaxError",[r,m,e?p:u]);G.fireWith(s,[r,x]);l&&(y.trigger("ajaxComplete",[r,m]),--c.active||c.event.trigger("ajaxStop"))}}"object"===typeof a&&(b=a,a=n);b=b||{};var e,f,g,h,k,l,q,p,m=c.ajaxSetup({},b),s=m.context||m,y=m.context&&(s.nodeType||s.jquery)?c(s):c.event,z=c.Deferred(),G=c.Callbacks("once memory"),K=m.statusCode||
{},C={},H={},O=0,M="canceled",r={readyState:0,getResponseHeader:function(a){var b;if(2===O){if(!p)for(p={};b=Lc.exec(h);)p[b[1].toLowerCase()]=b[2];b=p[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===O?h:null},setRequestHeader:function(a,b){var c=a.toLowerCase();O||(a=H[c]=H[c]||a,C[a]=b);return this},overrideMimeType:function(a){O||(m.mimeType=a);return this},statusCode:function(a){var b;if(a)if(2>O)for(b in a)K[b]=[K[b],a[b]];else r.always(a[r.status]);return this},
abort:function(a){a=a||M;q&&q.abort(a);d(0,a);return this}};z.promise(r).complete=G.add;r.success=r.done;r.error=r.fail;m.url=((a||m.url||P)+"").replace(Kc,"").replace(Nc,Z[1]+"//");m.type=b.method||b.type||m.method||m.type;m.dataTypes=c.trim(m.dataType||"*").toLowerCase().match(E)||[""];null==m.crossDomain&&(e=Ob.exec(m.url.toLowerCase()),m.crossDomain=!(!e||e[1]===Z[1]&&e[2]===Z[2]&&(e[3]||("http:"===e[1]?"80":"443"))===(Z[3]||("http:"===Z[1]?"80":"443"))));m.data&&m.processData&&"string"!==typeof m.data&&
(m.data=c.param(m.data,m.traditional));nb(Qb,m,b,r);if(2===O)return r;(l=m.global)&&0===c.active++&&c.event.trigger("ajaxStart");m.type=m.type.toUpperCase();m.hasContent=!Mc.test(m.type);g=m.url;m.hasContent||(m.data&&(g=m.url+=(Pa.test(g)?"&":"?")+m.data,delete m.data),!1===m.cache&&(m.url=Nb.test(g)?g.replace(Nb,"$1_="+Oa++):g+(Pa.test(g)?"&":"?")+"_="+Oa++));m.ifModified&&(c.lastModified[g]&&r.setRequestHeader("If-Modified-Since",c.lastModified[g]),c.etag[g]&&r.setRequestHeader("If-None-Match",
c.etag[g]));(m.data&&m.hasContent&&!1!==m.contentType||b.contentType)&&r.setRequestHeader("Content-Type",m.contentType);r.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+Rb+"; q=0.01":""):m.accepts["*"]);for(f in m.headers)r.setRequestHeader(f,m.headers[f]);if(m.beforeSend&&(!1===m.beforeSend.call(s,r,m)||2===O))return r.abort();M="abort";for(f in{success:1,error:1,complete:1})r[f](m[f]);if(q=nb(Ca,m,b,r)){r.readyState=1;l&&
y.trigger("ajaxSend",[r,m]);m.async&&0<m.timeout&&(k=setTimeout(function(){r.abort("timeout")},m.timeout));try{O=1,q.send(C,d)}catch(N){if(2>O)d(-1,N);else throw N;}}else d(-1,"No Transport");return r},getJSON:function(a,b,d){return c.get(a,b,d,"json")},getScript:function(a,b){return c.get(a,n,b,"script")}});c.each(["get","post"],function(a,b){c[b]=function(a,e,f,g){c.isFunction(e)&&(g=g||f,f=e,e=n);return c.ajax({url:a,type:b,dataType:g,data:e,success:f})}});c.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},
contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){c.globalEval(a);return a}}});c.ajaxPrefilter("script",function(a){a.cache===n&&(a.cache=!1);a.crossDomain&&(a.type="GET",a.global=!1)});c.ajaxTransport("script",function(a){if(a.crossDomain){var b,d=p.head||c("head")[0]||p.documentElement;return{send:function(c,f){b=p.createElement("script");b.async=!0;a.scriptCharset&&(b.charset=a.scriptCharset);b.src=a.url;b.onload=b.onreadystatechange=function(a,c){if(c||!b.readyState||
/loaded|complete/.test(b.readyState))b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success")};d.insertBefore(b,d.firstChild)},abort:function(){if(b)b.onload(n,!0)}}}});var Sb=[],Qa=/(=)\?(?=&|$)|\?\?/;c.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Sb.pop()||c.expando+"_"+Oa++;this[a]=!0;return a}});c.ajaxPrefilter("json jsonp",function(a,b,d){var e,f,g,h=!1!==a.jsonp&&(Qa.test(a.url)?"url":"string"===typeof a.data&&!(a.contentType||"").indexOf("application/x-www-form-urlencoded")&&
Qa.test(a.data)&&"data");if(h||"jsonp"===a.dataTypes[0])return e=a.jsonpCallback=c.isFunction(a.jsonpCallback)?a.jsonpCallback():a.jsonpCallback,h?a[h]=a[h].replace(Qa,"$1"+e):!1!==a.jsonp&&(a.url+=(Pa.test(a.url)?"&":"?")+a.jsonp+"="+e),a.converters["script json"]=function(){g||c.error(e+" was not called");return g[0]},a.dataTypes[0]="json",f=t[e],t[e]=function(){g=arguments},d.always(function(){t[e]=f;a[e]&&(a.jsonpCallback=b.jsonpCallback,Sb.push(e));g&&c.isFunction(f)&&f(g[0]);g=f=n}),"script"});
var T,$,Oc=0,Ra=t.ActiveXObject&&function(){for(var a in T)T[a](n,!0)};c.ajaxSettings.xhr=t.ActiveXObject?function(){var a;if(!(a=!this.isLocal&&ob()))a:{try{a=new t.ActiveXObject("Microsoft.XMLHTTP");break a}catch(b){}a=void 0}return a}:ob;$=c.ajaxSettings.xhr();c.support.cors=!!$&&"withCredentials"in $;($=c.support.ajax=!!$)&&c.ajaxTransport(function(a){if(!a.crossDomain||c.support.cors){var b;return{send:function(d,e){var f,g,h=a.xhr();a.username?h.open(a.type,a.url,a.async,a.username,a.password):
h.open(a.type,a.url,a.async);if(a.xhrFields)for(g in a.xhrFields)h[g]=a.xhrFields[g];a.mimeType&&h.overrideMimeType&&h.overrideMimeType(a.mimeType);a.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");try{for(g in d)h.setRequestHeader(g,d[g])}catch(k){}h.send(a.hasContent&&a.data||null);b=function(d,g){var k,m,p,t;try{if(b&&(g||4===h.readyState))if(b=n,f&&(h.onreadystatechange=c.noop,Ra&&delete T[f]),g)4!==h.readyState&&h.abort();else{t={};k=h.status;m=h.getAllResponseHeaders();
"string"===typeof h.responseText&&(t.text=h.responseText);try{p=h.statusText}catch(y){p=""}k||!a.isLocal||a.crossDomain?1223===k&&(k=204):k=t.text?200:404}}catch(z){g||e(-1,z)}t&&e(k,p,t,m)};a.async?4===h.readyState?setTimeout(b):(f=++Oc,Ra&&(T||(T={},c(t).unload(Ra)),T[f]=b),h.onreadystatechange=b):b()},abort:function(){b&&b(n,!0)}}}});var U,sa,Pc=/^(?:toggle|show|hide)$/,Tb=RegExp("^(?:([+-])=|)("+pa+")([a-z%]*)$","i"),Qc=/queueHooks$/,na=[function(a,b,d){var e,f,g,h,k,l=this,n={},p=a.style,m=a.nodeType&&
Q(a),s=c._data(a,"fxshow");d.queue||(h=c._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,k=h.empty.fire,h.empty.fire=function(){h.unqueued||k()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--;c.queue(a,"fx").length||h.empty.fire()})}));1===a.nodeType&&("height"in b||"width"in b)&&(d.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===c.css(a,"display")&&"none"===c.css(a,"float")&&(c.support.inlineBlockNeedsLayout&&"inline"!==gb(a.nodeName)?p.zoom=1:p.display="inline-block"));
d.overflow&&(p.overflow="hidden",c.support.shrinkWrapBlocks||l.always(function(){p.overflow=d.overflow[0];p.overflowX=d.overflow[1];p.overflowY=d.overflow[2]}));for(e in b)f=b[e],Pc.exec(f)&&(delete b[e],g=g||"toggle"===f,f!==(m?"hide":"show")&&(n[e]=s&&s[e]||c.style(a,e)));if(!c.isEmptyObject(n))for(e in s?"hidden"in s&&(m=s.hidden):s=c._data(a,"fxshow",{}),g&&(s.hidden=!m),m?c(a).show():l.done(function(){c(a).hide()}),l.done(function(){var b;c._removeData(a,"fxshow");for(b in n)c.style(a,b,n[b])}),
n)b=qb(m?s[e]:0,e,l),e in s||(s[e]=b.start,m&&(b.end=b.start,b.start="width"===e||"height"===e?1:0))}],ia={"*":[function(a,b){var d=this.createTween(a,b),e=d.cur(),f=Tb.exec(b),g=f&&f[3]||(c.cssNumber[a]?"":"px"),h=(c.cssNumber[a]||"px"!==g&&+e)&&Tb.exec(c.css(d.elem,a)),k=1,l=20;if(h&&h[3]!==g){g=g||h[3];f=f||[];h=+e||1;do k=k||".5",h/=k,c.style(d.elem,a,h+g);while(k!==(k=d.cur()/e)&&1!==k&&--l)}f&&(h=d.start=+h||+e||0,d.unit=g,d.end=f[1]?h+(f[1]+1)*f[2]:+f[2]);return d}]};c.Animation=c.extend(rb,
{tweener:function(a,b){c.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var d,e=0,f=a.length;e<f;e++)d=a[e],ia[d]=ia[d]||[],ia[d].unshift(b)},prefilter:function(a,b){b?na.unshift(a):na.push(a)}});c.Tween=G;G.prototype={constructor:G,init:function(a,b,d,e,f,g){this.elem=a;this.prop=d;this.easing=f||"swing";this.options=b;this.start=this.now=this.cur();this.end=e;this.unit=g||(c.cssNumber[d]?"":"px")},cur:function(){var a=G.propHooks[this.prop];return a&&a.get?a.get(this):G.propHooks._default.get(this)},
run:function(a){var b,d=G.propHooks[this.prop];this.pos=this.options.duration?b=c.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):b=a;this.now=(this.end-this.start)*b+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);d&&d.set?d.set(this):G.propHooks._default.set(this);return this}};G.prototype.init.prototype=G.prototype;G.propHooks={_default:{get:function(a){return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(a=c.css(a.elem,a.prop,
""))&&"auto"!==a?a:0:a.elem[a.prop]},set:function(a){if(c.fx.step[a.prop])c.fx.step[a.prop](a);else a.elem.style&&(null!=a.elem.style[c.cssProps[a.prop]]||c.cssHooks[a.prop])?c.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}};G.propHooks.scrollTop=G.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}};c.each(["toggle","show","hide"],function(a,b){var d=c.fn[b];c.fn[b]=function(a,c,g){return null==a||"boolean"===typeof a?d.apply(this,arguments):
this.animate(V(b,!0),a,c,g)}});c.fn.extend({fadeTo:function(a,b,c,e){return this.filter(Q).css("opacity",0).show().end().animate({opacity:b},a,c,e)},animate:function(a,b,d,e){var f=c.isEmptyObject(a),g=c.speed(b,d,e);b=function(){var b=rb(this,c.extend({},a),g);(f||c._data(this,"finish"))&&b.stop(!0)};b.finish=b;return f||!1===g.queue?this.each(b):this.queue(g.queue,b)},stop:function(a,b,d){var e=function(a){var b=a.stop;delete a.stop;b(d)};"string"!==typeof a&&(d=b,b=a,a=n);b&&!1!==a&&this.queue(a||
"fx",[]);return this.each(function(){var b=!0,g=null!=a&&a+"queueHooks",h=c.timers,k=c._data(this);if(g)k[g]&&k[g].stop&&e(k[g]);else for(g in k)k[g]&&k[g].stop&&Qc.test(g)&&e(k[g]);for(g=h.length;g--;)h[g].elem!==this||null!=a&&h[g].queue!==a||(h[g].anim.stop(d),b=!1,h.splice(g,1));!b&&d||c.dequeue(this,a)})},finish:function(a){!1!==a&&(a=a||"fx");return this.each(function(){var b,d=c._data(this),e=d[a+"queue"];b=d[a+"queueHooks"];var f=c.timers,g=e?e.length:0;d.finish=!0;c.queue(this,a,[]);b&&b.stop&&
b.stop.call(this,!0);for(b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)e[b]&&e[b].finish&&e[b].finish.call(this);delete d.finish})}});c.each({slideDown:V("show"),slideUp:V("hide"),slideToggle:V("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(a,c,f){return this.animate(b,a,c,f)}});c.speed=function(a,b,d){var e=a&&"object"===typeof a?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&
a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:"number"===typeof e.duration?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;if(null==e.queue||!0===e.queue)e.queue="fx";e.old=e.complete;e.complete=function(){c.isFunction(e.old)&&e.old.call(this);e.queue&&c.dequeue(this,e.queue)};return e};c.easing={linear:function(a){return a},swing:function(a){return 0.5-Math.cos(a*Math.PI)/2}};c.timers=[];c.fx=G.prototype.init;c.fx.tick=function(){var a,
b=c.timers,d=0;for(U=c.now();d<b.length;d++)a=b[d],a()||b[d]!==a||b.splice(d--,1);b.length||c.fx.stop();U=n};c.fx.timer=function(a){a()&&c.timers.push(a)&&c.fx.start()};c.fx.interval=13;c.fx.start=function(){sa||(sa=setInterval(c.fx.tick,c.fx.interval))};c.fx.stop=function(){clearInterval(sa);sa=null};c.fx.speeds={slow:600,fast:200,_default:400};c.fx.step={};c.expr&&c.expr.filters&&(c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length});c.fn.offset=function(a){if(arguments.length)return a===
n?this:this.each(function(b){c.offset.setOffset(this,a,b)});var b,d,e={top:0,left:0},f=(d=this[0])&&d.ownerDocument;if(f){b=f.documentElement;if(!c.contains(b,d))return e;typeof d.getBoundingClientRect!==K&&(e=d.getBoundingClientRect());d=sb(f);return{top:e.top+(d.pageYOffset||b.scrollTop)-(b.clientTop||0),left:e.left+(d.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}}};c.offset={setOffset:function(a,b,d){var e=c.css(a,"position");"static"===e&&(a.style.position="relative");var f=c(a),g=f.offset(),
h=c.css(a,"top"),k=c.css(a,"left"),l={},n={};("absolute"===e||"fixed"===e)&&-1<c.inArray("auto",[h,k])?(n=f.position(),e=n.top,k=n.left):(e=parseFloat(h)||0,k=parseFloat(k)||0);c.isFunction(b)&&(b=b.call(a,d,g));null!=b.top&&(l.top=b.top-g.top+e);null!=b.left&&(l.left=b.left-g.left+k);"using"in b?b.using.call(a,l):f.css(l)}};c.fn.extend({position:function(){if(this[0]){var a,b,d={top:0,left:0},e=this[0];"fixed"===c.css(e,"position")?b=e.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),
c.nodeName(a[0],"html")||(d=a.offset()),d.top+=c.css(a[0],"borderTopWidth",!0),d.left+=c.css(a[0],"borderLeftWidth",!0));return{top:b.top-d.top-c.css(e,"marginTop",!0),left:b.left-d.left-c.css(e,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||vb;a&&!c.nodeName(a,"html")&&"static"===c.css(a,"position");)a=a.offsetParent;return a||vb})}});c.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var d=/Y/.test(b);c.fn[a]=function(e){return c.access(this,
function(a,e,h){var k=sb(a);if(h===n)return k?b in k?k[b]:k.document.documentElement[e]:a[e];k?k.scrollTo(d?c(k).scrollLeft():h,d?h:c(k).scrollTop()):a[e]=h},a,e,arguments.length,null)}});c.each({Height:"height",Width:"width"},function(a,b){c.each({padding:"inner"+a,content:b,"":"outer"+a},function(d,e){c.fn[e]=function(e,g){var h=arguments.length&&(d||"boolean"!==typeof e),k=d||(!0===e||!0===g?"margin":"border");return c.access(this,function(b,d,e){return c.isWindow(b)?b.document.documentElement["client"+
a]:9===b.nodeType?(d=b.documentElement,Math.max(b.body["scroll"+a],d["scroll"+a],b.body["offset"+a],d["offset"+a],d["client"+a])):e===n?c.css(b,d,k):c.style(b,d,e,k)},b,h?e:n,h,null)}})});c.fn.size=function(){return this.length};c.fn.andSelf=c.fn.addBack;"object"===typeof module&&module&&"object"===typeof module.exports?module.exports=c:(t.jQuery=t.$=c,"function"===typeof define&&define.amd&&define("jquery",[],function(){return c}))})(window); | TheHenker/fbi | template/jquery.min.js | JavaScript | mit | 95,402 |
'use strict';
var lang = {
validationMessages: {
email: 'Please provide your email.',
emailValid: 'Please provide valid email.',
password: 'Please provide your password.'
},
loadingTxt: {
defaultText: "Please Wait...",
login : "Logging In ..."
},
errorMsg : {
defaultError : "Something went wrong! Please try again.",
networkError : "Network error! Please try again.",
authenticationError : "Authentication failed. Please check your username & password."
}
};
module.exports = lang;
| indranilatwork/angulartest | app/lang/lang.js | JavaScript | mit | 548 |
angular.module('ngci')
.directive('menuActive', ['$location',function ($location) {
return {
restrict: 'A',
link: function (scope, iElement, iAttrs) {
var allLinks = iElement.find('li');
scope.$on('$routeChangeSuccess', function(event, current, previous) {
var path = $location.path();
angular.forEach(allLinks, function(e,i) {
var anchor = e.querySelector('a');
if (anchor.href.match('#' + path + '(?=\\?|$)')) {
angular.element(e).addClass('active');
} else {
angular.element(e).removeClass('active');
}
});
})
}
};
}]) | fahadbillah/angular-with-codeigniter | assets/js/directive.js | JavaScript | mit | 582 |
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import opn from 'opn';
import del from 'del';
import moment from 'moment';
import md5File from 'md5-file';
import chalk from 'chalk';
import filePackage from 'file-package';
import config from './webpack.config.babel';
import productionConfig from './webpack.production.config.babel';
<% if(style === 'less'){ %>import lessAutoprefix from 'less-plugin-autoprefix';
const _autoprefix = new lessAutoprefix({
browsers: ['last 2 version', 'chrome >=30', 'Android >= 4.3'],
flexbox: 'no-2009',
remove: false // 是否自动删除过时的前缀
});<% } %>
const $ = gulpLoadPlugins();
const ip = 'localhost';
const port = '9090';
// webpack gulp 配置可参考 https://github.com/webpack/webpack-with-common-libs/blob/master/gulpfile.js
<% if (style === 'sass') { %>
//利用sass生成styles任务
gulp.task('styles', () => {
return gulp.src('app/sass/*.scss')
.pipe($.sass.sync({
outputStyle: 'expanded', // 展开的
precision: 10, //数字精读
includePaths: ['.']
}).on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: ['last 2 version', 'chrome >=30', 'Android >= 4.3'],
flexbox: 'no-2009',
remove: false // 是否自动删除过时的前缀
}))
.pipe(gulp.dest('app/styles'));
});<% }else if(style === 'less'){ %>
//利用less生成styles任务
gulp.task('styles', () => {
return gulp.src('app/less/*.less')
.pipe($.less({
plugins: [_autoprefix]
}))
.pipe(gulp.dest('app/styles'));
});
<% } %>
//复制替换文件,分开发和正式环境
//备选插件 https://www.npmjs.com/package/gulp-copy-rex
//开发环境
gulp.task('copy:dev', () => {
const paths = [
{src: 'app/scripts/config/index.dev.js', dest: 'app/scripts/config/index.js'},
{src: 'app/scripts/store/configureStore.dev.js', dest: 'app/scripts/store/index.js'},
{src: 'app/scripts/containers/Root.dev.js', dest: 'app/scripts/containers/Root.js'}
];
return $.copy2(paths);
});
//正式环境,打包使用
gulp.task('copy:prod', () => {
const paths = [
{src: 'app/scripts/config/index.prod.js', dest: 'app/scripts/config/index.js'},
{src: 'app/scripts/store/configureStore.prod.js', dest: 'app/scripts/store/index.js'},
{src: 'app/scripts/containers/Root.prod.js', dest: 'app/scripts/containers/Root.js'}
];
return $.copy2(paths);
});
// 计算文件大小
gulp.task('size', () => {
return gulp.src('dist/**/*').pipe($.size({title: '文件大小:', gzip: true}));
});
//把 json 测试数据复制到 dist 目录下
gulp.task('copy-json', () => {
return gulp.src('app/json/**')
.pipe(gulp.dest('dist/json'));
});
/**
* 压缩
* 文件名格式(根据需要自定义): filename-YYYYMMDDTHHmm
* 由于 gulp 压缩插件 gulp-zip 不能指定 package Root, 故采用 file-package 来压缩打包
*/
const filePath = `filename-${moment().format('YYYYMMDDTHHmm')}`;
const fileName = `${filePath}.zip`;
gulp.task('zip', () => {
filePackage('dist', `zip/${fileName}`, {
packageRoot: filePath
});
});
/**
* 生成压缩后文件 md5
*/
gulp.task('md5', ['size', 'zip'], () => {
md5File(`zip/${fileName}`, (error, md5) => {
if (error) {
return console.log(error);
}
console.log(chalk.green('生成的压缩文件为'));
console.log(chalk.magenta(fileName));
console.log(chalk.green('生成的 md5 为'));
console.log(chalk.magenta(md5));
})
});
// 打包
gulp.task('package', ['copy-json'], () => {
gulp.start('md5');
});
//清理临时和打包目录
gulp.task('clean', del.bind(null, ['dist', 'zip']));
gulp.task('webpack:server', () => {
// Start a webpack-dev-server
const compiler = webpack(config);
new WebpackDevServer(compiler, config.devServer)
.listen(port, ip, (err) => {
if (err) {
throw new $.util.PluginError('webpack-dev-server', err);
}
// Server listening
$.util.log('[webpack-dev-server]', `http://${ip}:${port}/`);
// Chrome is google chrome on OS X, google-chrome on Linux and chrome on Windows.
// app 在 OS X 中是 google chrome, 在 Windows 为 chrome ,在 Linux 为 google-chrome
opn(port === '80' ? `http://${ip}` : `http://${ip}:${port}/`, {app: 'google chrome'});
});
});
// 用webpack 打包编译
gulp.task('webpack:build', () => {
const compiler = webpack(productionConfig);
// run webpack
compiler.run((err, stats) => {
if (err) {
throw new $.util.PluginError('webpack:build', err);
}
$.util.log('[webpack:build]', stats.toString({
colors: true
}));
gulp.start(['package']);
});
});
//开发环境,启动服务
gulp.task('server', [<% if (style === 'sass' || style === 'less') { %>'styles', <% } %>'copy:dev'], () => {
gulp.start(['webpack:server']);
<% if (style === 'sass') { %>gulp.watch('app/sass/**/*.scss', ['styles']);<% }else if(style === 'less'){ %>gulp.watch('app/less/**/*.less', ['styles']);<% } %>
gulp.watch(['app/scripts/config/index.dev.js', 'app/scripts/containers/Root.dev.js', 'app/scripts/store/configureStore.dev.js'], ['copy:dev']);
});
//生产环境,启动服务
gulp.task('server:prod', [<% if (style === 'sass' || style === 'less') { %>'styles', <% } %>'copy:prod'], () => {
gulp.start(['webpack:server']);
<% if (style === 'sass') { %>gulp.watch('app/sass/**/*.scss', ['styles']);<% }else if(style === 'less'){ %>gulp.watch('app/less/**/*.less', ['styles']);<% } %>
gulp.watch(['app/scripts/config/index.prod.js', 'app/scripts/containers/Root.prod.js', 'app/scripts/store/configureStore.prod.js'], ['copy:prod']);
});
//打包后,启动服务
gulp.task('connect', () => {
$.connect.server({
root: 'dist',
port: 8001,
livereload: true
});
});
// 编译打包,正式环境
gulp.task('build', ['clean', <% if (style === 'sass' || style === 'less') { %>'styles', <% } %>'copy:prod'], () => {
gulp.start(['webpack:build']);
});
//默认任务
gulp.task('default', () => {
gulp.start('build');
});
| linder0209/generator-webpack-react | generators/app/templates/gulpfile.babel.js | JavaScript | mit | 6,127 |
/* eslint react/prop-types: 0 */
import React from 'react/addons';
import Lightbox from 'react-images';
import Button from './components/Button';
import Gallery from './components/Gallery';
const IMAGES = [
'http://www.fillmurray.com/400/600',
'http://www.fillmurray.com/600/900',
'http://www.fillmurray.com/500/500',
'http://www.fillmurray.com/700/700',
'http://www.fillmurray.com/900/600',
'http://www.fillmurray.com/600/400',
'http://www.fillmurray.com/401/601',
'http://www.fillmurray.com/601/901',
'http://www.fillmurray.com/501/501',
'http://www.fillmurray.com/701/701',
'http://www.fillmurray.com/901/601',
'http://www.fillmurray.com/601/401',
'http://www.fillmurray.com/402/602',
'http://www.fillmurray.com/602/902',
'http://www.fillmurray.com/502/502',
'http://www.fillmurray.com/702/702',
'http://www.fillmurray.com/902/602',
'http://www.fillmurray.com/602/402',
];
const styles = Lightbox.extendStyles({
image: {
border: '10px solid white',
borderRadius: 10,
WebkitFilter: 'sepia(100%)',
filter: 'sepia(100%)',
},
arrow: {
backgroundColor: 'rgba(0,0,0,0.1)',
borderRadius: 10,
},
});
React.render(
<div>
<Gallery heading="Gallery" images={IMAGES} />
<Gallery heading="Custom Styles" images={IMAGES} styles={styles} />
<Button heading="Launch with a button" images={IMAGES} />
<hr />
<p className="hint">
Images courtesy of <a href="http://www.fillmurray.com" target="_blank">http://www.fillmurray.com</a>
</p>
</div>,
document.getElementById('example')
);
| zackify/react-images | examples/src/app.js | JavaScript | mit | 1,525 |
module.exports = function( grunt ) {
"use strict";
var path = require( "path" );
require( "time-grunt" )( grunt );
require( "load-grunt-config" )( grunt, {
configPath: path.resolve( "build/config" )
});
}; | gustavohenke/BrazilFields | Gruntfile.js | JavaScript | mit | 235 |
module.exports = {
default: (app) => {
return {
include: [
{
model: app.orm['ProductImage'],
as: 'images',
// attributes: {
// exclude: ['src', 'updated_at', 'created_at']
// },
order: [['position', 'ASC']]
},
{
model: app.orm['Tag'],
as: 'tags',
attributes: ['name', 'id'],
order: [['name', 'ASC']]
},
{
model: app.orm['ProductVariant'],
as: 'variants',
attributes: {
exclude: ['updated_at','created_at']
},
include: [
{
model: app.orm['Metadata'],
as: 'metadata',
attributes: ['data', 'id']
},
{
model: app.orm['ProductImage'],
as: 'images',
order: [['position', 'ASC']],
attributes: {
exclude: ['src','updated_at','created_at']
}
}
]
},
// {
// model: app.orm['Product'],
// as: 'associations',
// // duplicating: false
// },
{
model: app.orm['Metadata'],
as: 'metadata',
attributes: ['data', 'id']
},
{
model: app.orm['Vendor'],
as: 'vendors',
attributes: ['id','handle','name']
},
{
model: app.orm['Collection'],
as: 'collections',
attributes: [
'id',
'title',
'handle',
'tax_type',
'tax_rate',
'tax_name',
// 'discount_scope',
// 'discount_type',
// 'discount_rate',
// 'discount_percentage'
]
}
],
order: [
[
{
model: app.orm['ProductVariant'],
as: 'variants'
},
'position','ASC'
],
[
{
model: app.orm['ProductImage'],
as: 'images'
},
'position','ASC'
]
]
}
},
findAllDefault: (app) => {
return {
distinct: true,
include: [
{
model: app.orm['ProductImage'],
as: 'images',
},
{
model: app.orm['Tag'],
as: 'tags',
attributes: ['name', 'id']
},
// {
// model: app.orm['Product'],
// as: 'associations',
// duplicating: false
// },
{
model: app.orm['Collection'],
as: 'collections',
// duplicating: false,
// require: true,
attributes: [
'id',
'title',
'handle',
'tax_type',
'tax_rate',
'tax_name',
// 'discount_scope',
// 'discount_type',
// 'discount_rate',
// 'discount_percentage'
]
},
{
model: app.orm['Vendor'],
as: 'vendors',
// duplicating: false,
// require: true,
attributes: [
'id',
'handle',
'name'
]
}
],
order: [
[
{
model: app.orm['ProductImage'],
as: 'images'
},
'position', 'ASC'
]
]
}
},
collections: (app) => {
return {
include: [
{
model: app.orm['Collection'],
as: 'collections',
// duplicating: false,
// require: true,
attributes: [
'id',
'title',
'handle',
'tax_type',
'tax_rate',
'tax_name',
// 'discount_scope',
// 'discount_type',
// 'discount_rate',
// 'discount_percentage'
]
}
]
}
},
images: (app) => {
return {
include: [
{
model: app.orm['ProductImage'],
as: 'images'
}
],
order: [
[
{
model: app.orm['ProductImage'],
as: 'images'
},
'position', 'ASC'
]
]
}
},
tags: (app) => {
return {
include: [
{
model: app.orm['Tag'],
as: 'tags',
attributes: ['name', 'id']
}
],
order: [
[
{
model: app.orm['Tag'],
as: 'tags'
},
'name', 'ASC'
]
]
}
},
variants: (app) => {
return {
include: [
{
model: app.orm['ProductVariant'],
as: 'variants',
attributes: {
exclude: ['updated_at','created_at']
},
include: [
{
model: app.orm['Metadata'],
as: 'metadata',
attributes: ['data', 'id']
},
{
model: app.orm['ProductImage'],
as: 'images',
order: [['position', 'ASC']],
attributes: {
exclude: ['src','updated_at','created_at']
}
}
]
}
]
}
}
}
| CaliStyle/trailpack-proxy-cart | api/utils/queryDefaults/Product.js | JavaScript | mit | 5,298 |
import Service from '@ember/service';
import algoliasearch from 'algoliasearch';
import config from 'ember-api-docs/config/environment';
import { denodeify } from 'rsvp';
export default class AlgoliaService extends Service {
_search(query, params, callback) {
if (!callback) {
callback = params;
params = undefined;
}
if (query) {
if (Array.isArray(query) && !params) {
// if multiple indices
this._client.search(query, callback);
} else if (!params) {
// if no params
this.accessIndex(query.indexName).search(query.query, callback);
} else {
// if params and callback
this.accessIndex(query.indexName).search(query.query, params, callback);
}
} else {
callback(new Error(`Could not search algolia for query "${query}"`));
}
}
accessIndex(IndexName) {
if (!this._indices[IndexName]) {
this._indices[IndexName] = this._client.initIndex(IndexName);
}
return this._indices[IndexName];
}
constructor() {
super(...arguments);
this._client = algoliasearch(
config.algolia.algoliaId,
config.algolia.algoliaKey
);
this._indices = {};
this.search = denodeify(this._search.bind(this));
}
}
| ember-learn/ember-api-docs | app/services/algolia.js | JavaScript | mit | 1,255 |
export const ic_library_music = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 5h-3v5.5c0 1.38-1.12 2.5-2.5 2.5S10 13.88 10 12.5s1.12-2.5 2.5-2.5c.57 0 1.08.19 1.5.51V5h4v2zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6z"},"children":[]}]}; | wmira/react-icons-kit | src/md/ic_library_music.js | JavaScript | mit | 402 |
$(document).ready(function() {
$("#portfolio_grid").mixItUp();
$(".s_portfolio li").click(function() {
$(".s_portfolio li").removeClass("active");
$(this).addClass("active");
});
$(".popup").magnificPopup({type:"image"});
$(".popup_content").magnificPopup({
type:"inline",
midClick: true
});
$(".section_header").animated("fadeInUp", "fadeOutDown");
$(".animation_1").animated("flipInY", "fadeOutDown");
$(".animation_2").animated("fadeInLeft", "fadeOutDown");
$(".animation_3").animated("fadeInRight", "fadeOutDown");
$(".left .resume_item").animated("fadeInLeft", "fadeOutDown");
$(".right .resume_item").animated("fadeInRight", "fadeOutDown");
function heightDetect() {
$(".main_head").css("height", $(window).height());
};
heightDetect();
$(window).resize(function() {
heightDetect();
});
$(".toggle_mnu").click(function() {
$(".sandwich").toggleClass("active");
});
$(".top_mnu ul a").click(function() {
$(".top_mnu").fadeOut(600);
$(".sandwich").toggleClass("active");
$(".top_text").css("opacity", "1");
}).append("<span>");
$(".toggle_mnu").click(function() {
if ($(".top_mnu").is(":visible")) {
$(".top_text").css("opacity", "1");
$(".top_mnu").fadeOut(600);
$(".top_mnu li a").removeClass("fadeInUp animated");
} else {
$(".top_text").css("opacity", ".1");
$(".top_mnu").fadeIn(600);
$(".top_mnu li a").addClass("fadeInUp animated");
};
});
$(".portfolio_item").each(function(i) {
$(this).find("a").attr("href", "#work_" + i);
$(this).find(".podrt_descr").attr("id", "work_" + i);
});
$("input, select, textarea").jqBootstrapValidation();
$(".top_mnu ul a").mPageScroll2id();
});
$(window).load(function() {
$(".loader_inner").fadeOut();
$(".loader").delay(400).fadeOut("slow");
$(".top_text h1").animated("fadeInDown", "fadeOutUp");
$(".top_text p").animated("fadeInUp", "fadeOutDown");
}); | alex-teren/wordpress-landing-demo | js/common.js | JavaScript | mit | 1,898 |
// extracts a list of all the files needed to render the page.
// this will be used to build the page but also to load them into the client.
module.exports = function (page) {
// does this need to look at the detualt spec?
const out = {
pages: [page.page],
components: [],
lists: page.lists || [],
filters: page.filters || [],
mappers: page.mapper ? [page.mapper] : []
}
for (var selector in page.spec) {
if (page.spec[selector].component) {
out.components.push(page.spec[selector].component)
if (page.spec[selector].lists) {
out.lists = out.lists.concat(page.spec[selector].lists)
}
if (page.spec[selector].filters) {
out.filters = out.filters.concat(page.spec[selector].filters)
}
if (page.spec[selector].mapper) {
out.mappers = out.mappers.concat(page.spec[selector].mapper)
}
var states = page.spec[selector].states
for (var state in states) {
out.components.push(states[state].component)
if (states[state].mapper) {
out.mappers.push(states[state].mapper)
}
}
}
}
var deduped = {}
for (var item in out) {
deduped[item] = [...new Set(out[item])]
}
return deduped
}
| simonmcmanus/speclate | lib/page/extract-assets.js | JavaScript | mit | 1,238 |
'use strict';
var Sha512 = require('sha.js/sha512');
module.exports = sha512;
function sha512(input) {
return new Sha512()
.update(input, 'utf8')
.digest('hex');
}
| ForbesLindesay/work-token | lib/sha512-browser.js | JavaScript | mit | 176 |
Firebug.registerExtension("firecompass", {
id: "firecompass@stueckseln.de"
});
Firebug.registerTracePrefix("firecompass;", "DBG_FIRECOMPASS", true, "chrome://firecompass/skin/style.css");
| is-already-taken/firecompass | chrome/content/mainOverlay.js | JavaScript | mit | 191 |
//Register Stuff
var user = null;
$(function() {
$('#Register').on("click",function(e) {
e.preventDefault();
$('.welcome-area').hide();
$('.register').show();
$('.login').hide();
});
$('.cancel').on("click",function(e) {
e.preventDefault();
$('.welcome-area').show();
$('.register').hide();
$('.login').hide();
});
$("#register-click").click( function(e) {
e.preventDefault();
var equal = this.form.pass.value === this.form.passconf.value
var longEnough = this.form.email.value.length > 8;
if (!equal) alert('Passwords don\'t match');
if (!longEnough) alert('Passwords need to be longer than 8 chars');
if(longEnough && equal) {
$.ajax({
url: "/register",
method: "POST",
data: { email : this.form.email.value, pass:this.form.pass.value },
dataType: "json"
})
.done(function(data) {
$('.billboard-welcome').html('check your email!')
$('.welcome-area').show();
$('.billboard-login').hide();
})
.fail(function(err) {
alert(err.responseJSON.message);
// $('error').html(err.responseJSON.message);
})
}
})
$('#Login').on("click",function(e) {
e.preventDefault();
$('.welcome-area').hide();
$('.register').hide();
$('.login').show();
});
$("#login-click").click( function(e) {
e.preventDefault();
$.ajax({
url: "/authorize/login",
method: "POST",
data: { email : this.form.email.value, "pass":this.form.pass.value }
})
.done(function(data) {
$("body").html(data);
})
.fail(function(err) {
alert(err.responseJSON.message);
// $('error').html(err.responseJSON.message);
})
})
})
| armynante/hey-pi | dist/views/home.js | JavaScript | mit | 1,775 |
import Vue from 'vue'
import VueRouter from 'vue-router'
import sidebarConfig from './config/sidebarConfig.js'
import Home from 'src/containers/Home'
Vue.use(VueRouter)
const vueRouter = new VueRouter()
const routes = [
{
path: '/',
component: Home
},
{
path: '*',
component: Home
}
]
// 将首字母大写,route转换成compnentName
const getComponentName = name => name.replace(/\b\w/g, word => word.toUpperCase()).split('-').join('')
let componentName
sidebarConfig.forEach(value => {
componentName = getComponentName(value.route)
const pathParams = value.pathParams || ''
const route = {
path: `/${value.route}${pathParams}`,
component: require(`src/containers/${componentName}/index.vue`)
}
routes.push(route)
})
vueRouter.addRoutes(routes)
export default vueRouter
| Pickcle/kyrios | src/router.js | JavaScript | mit | 824 |
/**
* BigGulp!
* @link http://movio.co/blog/gulp-streaming-builds/
*/
var gulp = require('gulp');
require('require-dir')('./muscleman', { recurse: true });
| rossedman/muscleman | gulpfile.js | JavaScript | mit | 160 |
import * as React from "react";
import PropTypes from "prop-types";
import { withWrapper } from "../Icon";
const Vector = React.forwardRef(({ size, color, ...props }, ref) => (
<svg
width={size}
height={size}
viewBox="4 4 32 32"
xmlns="http://www.w3.org/2000/svg"
ref={ref}
aria-hidden={!props["aria-label"]}
{...props}
>
<path
d="M31 15.15a2.699 2.699 0 0 1 0 5.21V27a1 1 0 0 1-1.583.812 13.572 13.572 0 0 0-.908-.577c-.757-.449-1.622-.899-2.58-1.32-2.237-.982-4.593-1.642-6.992-1.847l2.786 6.54a1 1 0 0 1-.92 1.392h-4.096a1 1 0 0 1-.918-.604L12.6 24h-.844c-1.237 0-2.297-.756-2.584-1.952l-2.145-8.811A1 1 0 0 1 8 12h9.355c2.944 0 5.846-.717 8.574-1.916.958-.42 1.823-.87 2.58-1.32.449-.265.757-.468.908-.576A1 1 0 0 1 31 9v6.15Zm0 1.635v1.94a1.197 1.197 0 0 0 0-1.94Zm-7-3.84C21.852 13.618 19.624 14 17.355 14H9.273l1.844 7.579c.062.258.29.421.64.421h5.598c2.269 0 4.497.382 6.645 1.055v-10.11Zm2-.72v11.55a26.456 26.456 0 0 1 3 1.435V10.79a26.456 26.456 0 0 1-3 1.435ZM16.734 24h-1.956l2.587 6h1.925l-2.556-6ZM16 16a.5.5 0 1 1 0 1h-4a.5.5 0 1 1 0-1h4Zm0 2a.5.5 0 1 1 0 1h-4a.5.5 0 1 1 0-1h4Z"
fill={color}
fillRule="nonzero"
/>
</svg>
));
Vector.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
"aria-label": PropTypes.string,
};
Vector.defaultProps = {
color: "currentColor",
size: "1em",
};
const MdBullhorn = withWrapper(Vector);
MdBullhorn.groupName = "Menu";
export default MdBullhorn;
| CraveFood/farmblocks | packages/icon/src/jsx/MdBullhorn.js | JavaScript | mit | 1,520 |
var async = require('async');
var nodejsx = require('node-jsx').install();
var Share = require('../../../client/javascript/share');
exports = module.exports = function(services, helpers) {
return function(req, res, next) {
var message = req.body.message;
var context = {
title: 'volatile.me',
description: 'share secret messages',
};
async.waterfall([
function(callback) {
services.message.create(message, function(err, url) {
callback(err, url);
});
},
function(url, callback) {
context.url = url;
callback();
}
], function(err, result) {
if (err) return next(err);
helpers.react.renderMarkupToString({
component: Share,
clientScripts: ['/javascript/share.js'],
context: context,
staticPage: false,
callback: function(err, markup) {
if (err) return next(err);
res.send(markup);
}
});
});
};
};
| eiriklv/volatile | handlers/app/share/index.js | JavaScript | mit | 1,183 |
version https://git-lfs.github.com/spec/v1
oid sha256:4a4db9b44d2762528c611d086022ad5b863b65fd1bf19b8fd5d545820a78c093
size 20352
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/pluginhost-base/pluginhost-base-coverage.js | JavaScript | mit | 130 |
export default (createElement) => {
return createElement('div', { 'style-color': 'red', 'style-background-color': 'blue' })
}
| Swizz/snabbdom-pragma | test/snabbdom-specs/vnode-style/actual.js | JavaScript | mit | 129 |