code
stringlengths
2
1.05M
window.TMPL = { issueModal: "\ <div class='modal'>\ <div class='modal-header'>\ <button href='#' class='close' data-dismiss>x</button>\ <h3>Hey <em>{{username}}</em>! You were just awarded \ this awesome badge!</h3>\ </div>\ <div class='modal-body'>\ <h4>{{badge.name}}</h4>\ <img src='{{badge.image}}' />\ <div class='details'>\ {{badge.details}} \ </div>\ <ul>\ <li><a hrew='#'>View all your badges!</a></li>\ </ul>\ </div>\ </div>\ " }
Template.header.created = function () { Session.set('isActive', false); Session.set('showLogin', false); }; Template['header'].helpers({ showLogin: function () { return Session.get('showLogin'); }, isActive: function () { return Session.get('isActive') ? 'active' : ''; }, animateClass: function () { return Session.get('isActive') ? 'fadeIn' : 'fadeOut'; }, iconClass: function () { return Meteor.user() ? 'user' : 'sign in'; } }); Template['header'].events({ //showing the login screen depending on a user click 'click .resize.button' : function () { text = $('.white.button').text() if (text == 'Sign In') { $('.white.button').text('Close'); } else { $('.white.button').text('Sign In'); } var showLogin = Session.get('showLogin'); Session.set('isActive', !Session.get('isActive')); setTimeout(function () { Session.set('showLogin', !Session.get('showLogin')); }, 600); }, 'click .log-out.button' : function () { Meteor.logout(); } });
"use strict"; var url = require("url"); var Config = require("./Config"); var Context = require("./Context"); var Contracts = require("../Declarations/Contracts"); var Channel = require("./Channel"); var TelemetryProcessors = require("../TelemetryProcessors"); var CorrelationContextManager_1 = require("../AutoCollection/CorrelationContextManager"); var Sender = require("./Sender"); var Util = require("./Util"); var Logging = require("./Logging"); var EnvelopeFactory = require("./EnvelopeFactory"); /** * Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and * and manually trigger immediate sending (flushing) */ var TelemetryClient = (function () { /** * Constructs a new client of the client * @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified) */ function TelemetryClient(setupString) { this._telemetryProcessors = []; var config = new Config(setupString); this.config = config; this.context = new Context(); this.commonProperties = {}; var sender = new Sender(this.config); this.channel = new Channel(function () { return config.disableAppInsights; }, function () { return config.maxBatchSize; }, function () { return config.maxBatchIntervalMs; }, sender); } /** * Log information about availability of an application * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackAvailability = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Availability); }; /** * Log a trace message * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackTrace = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Trace); }; /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackMetric = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Metric); }; /** * Log an exception * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackException = function (telemetry) { if (telemetry && telemetry.exception && !Util.isError(telemetry.exception)) { telemetry.exception = new Error(telemetry.exception.toString()); } this.track(telemetry, Contracts.TelemetryType.Exception); }; /** * Log a user action or other occurrence. * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackEvent = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Event); }; /** * Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests * that aren't automatically captured or if you've disabled automatic request collection. * * @param telemetry Object encapsulating tracking options */ TelemetryClient.prototype.trackRequest = function (telemetry) { this.track(telemetry, Contracts.TelemetryType.Request); }; /** * Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies * that aren't automatically captured or if you've disabled automatic dependency collection. * * @param telemetry Object encapsulating tracking option * */ TelemetryClient.prototype.trackDependency = function (telemetry) { if (telemetry && !telemetry.target && telemetry.data) { // url.parse().host returns null for non-urls, // making this essentially a no-op in those cases // If this logic is moved, update jsdoc in DependencyTelemetry.target telemetry.target = url.parse(telemetry.data).host; } this.track(telemetry, Contracts.TelemetryType.Dependency); }; /** * Immediately send all queued telemetry. * @param options Flush options, including indicator whether app is crashing and callback */ TelemetryClient.prototype.flush = function (options) { this.channel.triggerSend(options ? !!options.isAppCrashing : false, options ? options.callback : undefined); }; /** * Generic track method for all telemetry types * @param data the telemetry to send * @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes */ TelemetryClient.prototype.track = function (telemetry, telemetryType) { if (telemetry && Contracts.telemetryTypeToBaseType(telemetryType)) { var envelope = EnvelopeFactory.createEnvelope(telemetry, telemetryType, this.commonProperties, this.context, this.config); // Set time on the envelope if it was set on the telemetry item if (telemetry.time) { envelope.time = telemetry.time.toISOString(); } var accepted = this.runTelemetryProcessors(envelope, telemetry.contextObjects); // Ideally we would have a central place for "internal" telemetry processors and users can configure which ones are in use. // This will do for now. Otherwise clearTelemetryProcessors() would be problematic. accepted = accepted && TelemetryProcessors.samplingTelemetryProcessor(envelope, { correlationContext: CorrelationContextManager_1.CorrelationContextManager.getCurrentContext() }); TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient); if (accepted) { this.channel.send(envelope); } } else { Logging.warn("track() requires telemetry object and telemetryType to be specified."); } }; /** * Adds telemetry processor to the collection. Telemetry processors will be called one by one * before telemetry item is pushed for sending and in the order they were added. * * @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean */ TelemetryClient.prototype.addTelemetryProcessor = function (telemetryProcessor) { this._telemetryProcessors.push(telemetryProcessor); }; /* * Removes all telemetry processors */ TelemetryClient.prototype.clearTelemetryProcessors = function () { this._telemetryProcessors = []; }; TelemetryClient.prototype.runTelemetryProcessors = function (envelope, contextObjects) { var accepted = true; var telemetryProcessorsCount = this._telemetryProcessors.length; if (telemetryProcessorsCount === 0) { return accepted; } contextObjects = contextObjects || {}; contextObjects['correlationContext'] = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); for (var i = 0; i < telemetryProcessorsCount; ++i) { try { var processor = this._telemetryProcessors[i]; if (processor) { if (processor.apply(null, [envelope, contextObjects]) === false) { accepted = false; break; } } } catch (error) { accepted = true; Logging.warn("One of telemetry processors failed, telemetry item will be sent.", error, envelope); } } return accepted; }; return TelemetryClient; }()); module.exports = TelemetryClient; //# sourceMappingURL=TelemetryClient.js.map
'use strict'; /** * @namespace */ var VJS = VJS || {}; /*** Imports ***/ VJS.cameras = VJS.cameras || require('./cameras/cameras'); VJS.core = VJS.core || require('./core/core'); VJS.extras = VJS.extras || require('./extras/extras'); VJS.geometries = VJS.geometries || require('./geometries/geometries'); VJS.helpers = VJS.helpers || require('./helpers/helpers'); VJS.loaders = VJS.loaders || require('./loaders/loaders'); VJS.models = VJS.models || require('./models/models'); VJS.parsers = VJS.parsers || require('./parsers/parsers'); VJS.widgets = VJS.widgets || require('./widgets/widgets'); /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = VJS; }
;(function ( $, window, document, undefined ) { var pluginName = "clear", defaults = { }; function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { var plugin = this; $(this.element).append("<img src='"+this.options.tool.icon+"' style='max-height:30px'/><span>"+this.options.tool.label+"</span>"); if (this.options.tool.toggle){ $(this.element).addClass('toggle'); } $(this.element).click(function(){ }); } }; $.fn[pluginName] = function ( options ) { return this.each(function () { //if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); //} }); }; })( jQuery, window, document );
module.exports = function ( karma ) { karma.set({ /** * From where to look for files, starting with the location of this file. */ basePath: '../', /** * This is the list of file patterns to load into the browser during testing. */ files: [ <% scripts.forEach( function ( file ) { %>'<%= file %>', <% }); %> 'src/**/*.js', 'src/**/*.coffee', ], exclude: [ 'src/assets/**/*.js', 'src/server/**/*.js' ], frameworks: [ 'jasmine' ], plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-coffee-preprocessor' ], preprocessors: { '**/*.coffee': 'coffee', }, /** * How to report, by default. */ reporters: 'dots', /** * On which port should the browser connect, on which port is the test runner * operating, and what is the URL path for the browser to use. */ port: 9018, runnerPort: 9100, urlRoot: '/', /** * Disable file watching by default. */ autoWatch: false, /** * The list of browsers to launch to test on. This includes only "Firefox" by * default, but other browser names include: * Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS * * Note that you can also use the executable name of the browser, like "chromium" * or "firefox", but that these vary based on your operating system. * * You may also leave this blank and manually navigate your browser to * http://localhost:9018/ when you're running tests. The window/tab can be left * open and the tests will automatically occur there during the build. This has * the aesthetic advantage of not launching a browser every time you save. */ browsers: [ 'Firefox' ] }); };
goog.module('test_files.decorator_nested_scope.decorator_nested_scope');var module = module || {id: 'test_files/decorator_nested_scope/decorator_nested_scope.js'};/** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ class SomeService { } /** * @return {void} */ function main() { class TestComp3 { /** * @param {!SomeService} service */ constructor(service) { } } TestComp3.decorators = [ { type: Component }, ]; /** @nocollapse */ TestComp3.ctorParameters = () => [ { type: SomeService, }, ]; function TestComp3_tsickle_Closure_declarations() { /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */ TestComp3.decorators; /** * @nocollapse * @type {function(): !Array<(null|{type: ?, decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>)})>} */ TestComp3.ctorParameters; } } exports.main = main;
const livingBeings = { init: function (state) { this.species = state.species return this }, getSpecies: function () { return this.species } } const plantae = Object.create(livingBeings) plantae.init = function (state) { this.species = state.species return this } const animalia = Object.create(livingBeings) animalia.init = function (state) { this.species = state.species this.sound = state.sound return this } animalia.talk = function () { return this.sound } const fox = Object.create(animalia).init({ species: 'Vulpis vulpis', sound: 'ringdingding ding ding ding' }) const rosemary = Object.create(plantae).init({ species: 'Rosmarinus officinalis' }) let a = fox.talk() let b = rosemary.getSpecies() console.log(a,b)
module.exports = { description: 'does not tree-shake unknown tokens', options: { acorn: { plugins: { doTestExpressions: true } }, acornInjectPlugins: [ acorn => { acorn.plugins.doTestExpressions = function doTestExpressions(instance) { instance.extend( 'parseExprAtom', superF => function parseExprAtom(...args) { if (this.type === acorn.tokTypes._do) { this.eat(acorn.tokTypes._do); const node = this.startNode(); node.body = this.parseBlock(); return this.finishNode(node, 'DoExpression'); } return Reflect.apply(superF, this, args); } ); }; return acorn; } ] } };
angular.module("adExtreme") .service('RestService', function(HttpRequestService) { var restFactory = {}; var urlInicial = "https://ad-extreme-projeto.herokuapp.com"; restFactory.find = function(url, callback) { HttpRequestService(urlInicial + url, "GET", {}, callback); }; restFactory.add = function(url, data, callback) { HttpRequestService(urlInicial + url, "POST", data, callback); }; restFactory.edit = function(url, data, callback) { HttpRequestService(urlInicial + url, "PUT", data, callback); }; restFactory.delete = function(url,callback) { HttpRequestService(urlInicial + url, "DELETE", {}, callback); }; return restFactory; });
import leafletImage from 'leaflet-image'; import LMap from './map'; import { getMapPanelHeightDiff } from './ui'; const freeDraw = new FreeDraw({ mode: FreeDraw.ALL }); /** * * @param {*} imageID * @param {*} imageClasses */ export function generateMapViewScreenshot(id, imageClasses) { const alt = 'Map view screenshot image'; return new Promise((resolve, reject) => { leafletImage(LMap, (error, canvas) => { if (error) { reject(error); } const dimensions = LMap.getSize(); const $img = $('<img />', { src: canvas.toDataURL(), width: dimensions.x, height: dimensions.y, class: imageClasses, alt, id }); resolve($img); }); }); } export function addFreeDrawLayerToMap() { // Attaches draw layer to the map LMap.addLayer(freeDraw); // sets the height equal to map view for better UX const firstDrawClass = '.free-draw'; const mapPanelHeightDiff = getMapPanelHeightDiff(); const $freeDrawSvgTag = $(firstDrawClass).first(); $freeDrawSvgTag.css('height', `${mapPanelHeightDiff}px`); } export function onFreeDrawMarkersPlaced(fn) { freeDraw.on('markers', fn); }
/** * 登录js */ /* // 没个js文件都要用这段代码包着, 相当于document ready $(function () { }); */ $(function () { // test // console.log($); var loginBox = $('#j-login-box'); var uname = loginBox.find('.username'); var upwd = loginBox.find('.password'); var vCode = loginBox.find('.verify-code'); var btnSubmit = loginBox.find('.btn-submit'); /** * 提交验证及请求 * @return {[type]} [description] */ function submitCheckAndRequest () { if ( uname.val() === '' ) { alert('用户名不能为空!'); } else if ( upwd.val() === '' ) { alert('密码不能为空!'); } else if ( vCode.val() === '' ) { alert('验证码不能为空!'); } else if ( isNaN(vCode.val()) ) { alert('验证码必须是数字!'); } else { alert('可以提交了,向后台发送请求吧 ~(@^_^@)~'); $.post('后台地址', { username: uname.val(), password: upwd.val() }).done(function (res) { // 后台返回数据 // console.log(res); // 根据后台返回的数据进行处理, 一般以json方式返回 }); return true; } } /** * 点击登录按钮提交 * @return {[type]} [description] */ function clickToSubmit () { btnSubmit.click(function () { submitCheckAndRequest(); return false; }); } /** * 按回车键提交 * @return {[type]} [description] */ function enterToSubmit () { // loginBox.find('.username, .password, .verify-code')... // 只有焦点在输入框里时,按回车才会提交 loginBox.find('.username, .password, .verify-code').keydown(function (e) { if (e.keyCode === 13) { // alert('在表单里按了回车!'); submitCheckAndRequest(); } }); } enterToSubmit(); clickToSubmit(); });
/* Manifest * * - &Create variable references * - &Autoload gulp plugins * - &Load common gulp utilities * - &Create comments for minified files * - &Lint the code * - &Minify and bundle the JavaScript * - &CSS Preprocessing * - &Minify and bundle the CSS * - &Bundle the JS, CSS, and compress images * - &Compress images * - &Run builds for staging/production: switch. Run `gulp --production` * - &Copy left over files to builds and show a toast. * - &Clean - remove all files from the output folder * - &Watch file and re-run the linter to search for section: &<section> */ //---------------------------------------------------------------------------------------| /* * &Create variable references */ /* * &Autoload gulp plugins */ /* * &Load common gulp utilities */ /* * &Create comments for minified files */ /* * &Lint the code */ /* * &Minify and bundle the JavaScript */ /* * &CSS Preprocessing */ /* * Minify and bundle the CSS */ /* * Compress images */ /* * &Run builds for staging/production: switch. Run `gulp --production` */ /* * &Copy left over files to builds and show a toast. */ /* * &Copy left over files to builds and show a toast. */ /* * &Watch file and re-run the linter */
(function () { 'use strict'; let XHRLoader = require('../util/XHRLoader'); module.exports = function(gltf, description, done) { // load shader source XHRLoader.load({ url: description.uri, responseType: 'text', success: source => { description.source = source; done(null); }, error: err => { done(err); } }); }; }());
import * as lamb from "../.."; import { wannabeEmptyObjects } from "../../__tests__/commons"; describe("ownPairs / pairs", function () { var baseFoo = Object.create({ a: 1 }, { b: { value: 2 } }); var foo = Object.create(baseFoo, { c: { value: 3 }, d: { value: 4, enumerable: true } }); it("should convert an object in a list of key / value pairs", function () { var source = { a: 1, b: 2, c: 3 }; var result = [["a", 1], ["b", 2], ["c", 3]]; expect(lamb.ownPairs(source)).toEqual(result); expect(lamb.pairs(source)).toEqual(result); }); it("should keep `undefined` values in the result", function () { var source = { a: null, b: void 0 }; var result = [["a", null], ["b", void 0]]; expect(lamb.ownPairs(source)).toStrictEqual(result); expect(lamb.pairs(source)).toStrictEqual(result); }); it("should work with array-like objects", function () { var r1 = [["0", 1], ["1", 2], ["2", 3]]; var r2 = [["0", "a"], ["1", "b"], ["2", "c"]]; expect(lamb.ownPairs([1, 2, 3])).toEqual(r1); expect(lamb.ownPairs("abc")).toEqual(r2); expect(lamb.pairs([1, 2, 3])).toEqual(r1); expect(lamb.pairs("abc")).toEqual(r2); }); it("should throw an exception if called without arguments", function () { expect(lamb.ownPairs).toThrow(); expect(lamb.pairs).toThrow(); }); it("should throw an exception if supplied with `null` or `undefined`", function () { expect(function () { lamb.ownPairs(null); }).toThrow(); expect(function () { lamb.ownPairs(void 0); }).toThrow(); expect(function () { lamb.pairs(null); }).toThrow(); expect(function () { lamb.pairs(void 0); }).toThrow(); }); it("should consider other values as empty objects", function () { wannabeEmptyObjects.forEach(function (value) { expect(lamb.ownPairs(value)).toEqual([]); expect(lamb.pairs(value)).toEqual([]); }); }); describe("ownPairs", function () { it("should use only the own enumerable properties of the source object", function () { expect(lamb.ownPairs(foo)).toEqual([["d", 4]]); }); }); describe("pairs", function () { it("should use all the enumerable properties of the source object, inherited or not", function () { expect(lamb.pairs(foo)).toEqual([["d", 4], ["a", 1]]); }); }); });
function encode(string) { const lookupTable = {}; let charValue = 122; // 'z' char const maxWordSize = 5; let currentWordSize = 0; let output = ''; let currentChar = ''; const lowerCaseString = string.toLowerCase(); // ignore uppercase // setup the table for easy lookup // from 'a' to 'z' for (let i = 97; i < 123; i++) { // set values from 'z' to 'a' // console.log(`[${String.fromCharCode(i)}] | ${String.fromCharCode(charValue)}`); lookupTable[String.fromCharCode(i)] = String.fromCharCode(charValue); charValue--; // move from 'z' to 'a' } for (let i = 0; i < lowerCaseString.length; i++) { currentChar = lowerCaseString.charAt(i); // it's a lowercase letter or number if (currentChar.search(/[a-z0-9]/g) !== -1) { if (currentWordSize >= maxWordSize) { output += ' '; currentWordSize = 0; // reset counter } // it's a number if (currentChar.search(/[0-9]/g) !== -1) { output += currentChar; } else { output += lookupTable[currentChar]; } currentWordSize++; } } // console.log(`Result: ${output}`); return output; } module.exports = { encode };
import test from 'ava'; import purifyHtml from './purifyHtml.js'; test('purifyHtml return same string if no tags present', t => { t.is(purifyHtml('Hello world'), 'Hello world'); }); test('return same string if no tags present', t => { t.is(purifyHtml('Hello world'), 'Hello world'); }); test('should remove some tags, but keep others', t => { t.is(purifyHtml('<h1><b>Hello</b> World</h1>'), '<b>Hello</b> World'); }); test('should not crash if input is not a string', t => { t.notThrows(() => purifyHtml(null)); t.notThrows(() => purifyHtml(undefined)); t.notThrows(() => purifyHtml(42)); t.notThrows(() => purifyHtml({ foo: 'bar' })); }); test('should return the input value if undefined or null', t => { t.is(purifyHtml(null), null); t.is(purifyHtml(undefined), undefined); }); test('should remove script tags', t => { t.is(purifyHtml('<script>alert("foo")</script>'), 'alert("foo")'); }); test('should keep script tags if we explicitly allow it', t => { t.is(purifyHtml('<script>alert("foo")</script>', '<script>'), '<script>alert("foo")</script>'); }); test('links get target="_blank" and rel="" set automatically', t => { t.is( purifyHtml('check out <a href="https://example.com">this link</a>!'), 'check out <a href="https://example.com" target="_blank" rel="nofollow noopener noreferrer">this link</a>!' ); }); test('links with existing target != _self get overwritten', t => { t.is( purifyHtml('check out <a href="https://example.com" target="_parent">this link</a>!'), 'check out <a href="https://example.com" target="_blank" rel="nofollow noopener noreferrer">this link</a>!' ); }); test('links with existing target _self dont get overwritten', t => { t.is( purifyHtml('check out <a href="https://example.com" target="_self">this link</a>!'), 'check out <a href="https://example.com" target="_self" rel="nofollow noopener noreferrer">this link</a>!' ); }); test('test if styles are kept in', t => { t.is( purifyHtml('this is <span style="color:red">red</span>!'), 'this is <span style="color:red">red</span>!' ); }); test('test if onclick handlers are removed', t => { t.is( purifyHtml('<a href="https://example.com" onclick="alert(42)">click me!</a>'), '<a href="https://example.com" target="_blank" rel="nofollow noopener noreferrer">click me!</a>' ); }); test('test if javascript urls are removed', t => { t.is( purifyHtml('<a href="javascript:alert(42)">click me!</a>'), '<a href="" target="_blank" rel="nofollow noopener noreferrer">click me!</a>' ); }); test('test if javascript urls with leading whitespace are removed', t => { t.is( purifyHtml('<a href=" javascript:alert(42)">click me!</a>'), '<a href="" target="_blank" rel="nofollow noopener noreferrer">click me!</a>' ); }); test('test if vbscript and data urls are removed', t => { t.is( purifyHtml('<a href="vbscript:alert(42)">click me!</a>'), '<a href="" target="_blank" rel="nofollow noopener noreferrer">click me!</a>' ); t.is( purifyHtml('<a href="data:alert(42)">click me!</a>'), '<a href="" target="_blank" rel="nofollow noopener noreferrer">click me!</a>' ); }); test('test if multiple on* handlers are removed', t => { t.is( purifyHtml('<span onmouseover="diversion" onclick="alert(document.domain)">span</span>'), '<span>span</span>' ); }); test('javascript link with special chars', t => { t.is( purifyHtml( '<a href="ja&Tab;va&NewLine;script&colon;alert&lpar;document.domain&rpar;" target="_self">link</a>' ), '<a href="" target="_self" rel="nofollow noopener noreferrer">link</a>' ); }); test('prevent unclosed tag exploit', t => { const el = document.createElement('p'); const purified = purifyHtml('<img src=x onerror=alert(1);"" onload="a="'); el.innerHTML = `<span>${purified}</span>`; t.is(el.childNodes[0].tagName, 'SPAN'); t.is(el.childNodes[0].innerHTML, '<img src="x" <="" span="">'); t.is(el.childNodes[0].childNodes[0].tagName, 'IMG'); t.is(el.childNodes[0].childNodes[0].getAttribute('onerror'), null); t.is(el.childNodes[0].childNodes[0].getAttribute('onload'), null); }); test('prevent hacky javascript links', t => { t.is( purifyHtml('<a href=javAscript:alert(1) target=_self>link</a>'), '<a href="" target="_self" rel="nofollow noopener noreferrer">link</a>' ); });
var scm = new Scm.Core("node"), bg = new Scm.Layer(), psM = new Scm.Layer(), ship = new Scm.Layer(), psB = new Scm.Layer(); scm.push(bg, psM, ship, psB); var path = "parallaxScrolling/misc/"; bg.setBackgroundImg(path+"bg.jpg"); psB.setParallaxScrolling("left", 5, path+"psBig1.png", path+"psBig2.png", path+"psBig3.png"); psM.setParallaxScrolling("left", 3, path+"psMid1.png", path+"psMid2.png", path+"psMid3.png"); ship.draw(new Scm.Image(path+"ship.gif", 200, 180));
export { default } from './TodoHeaderContainer.js';
import React, { Component } from 'react' const md5 = require('md5') const dateformat = require('dateformat') const base64 = require('Base64') class RadioType extends Component { constructor (props) { super(props) this.state = { data: [], pageNum: 1, imgUrl: location.search.split('=')[1] } } ajaxData = (interFace) => { const time = new Date() // 2.根据当前时间, 进行格式化 yyyymmddHHMMss const timestamp = dateformat(time.getTime(), 'yyyymmddHHMMss') // 3.将字符串 0+''+timestamp 转成MD5, 并变为全大写 const sig = md5('0' + '' + timestamp).toUpperCase() const Authorization = base64.btoa('' + ':' + timestamp) const url = '/api' + interFace + '&sig=' + sig fetch(url, { method: 'GET', headers: { Authorization: Authorization } }) .then(response => { return response.json() }) .then(response => { this.setState({ data: this.state.data.concat(response.data) }) }) } componentDidMount () { let numArr = document.querySelectorAll('.radio_title') numArr.forEach((item) => { // 获取name的值和传入的值作对比,相同的赋予初始样式 if (item.getAttribute('name') === location.search.split('=')[1]) { item.className = 'radio_title radio_active' } }) this.ajaxData('/ting/listByStyle.php' + location.search + '&sort=1&pageSize=9&pageNum=' + this.state.pageNum) } componentDidUpdate () { window.addEventListener('scroll', this.handleScroll) } // 滚动添加数据 handleScroll = () => { let STop = document.body.scrollTop const DHeight = document.documentElement.clientHeight const SHeight = document.documentElement.scrollHeight if (SHeight === STop + DHeight) { this.setState({ pageNum: this.state.pageNum + 1 }, () => { this.ajaxData('/ting/listByStyle.php?style=' + this.state.imgUrl + '&sort=1&pageSize=9&pageNum=' + this.state.pageNum) }) } } click = (ev) => { let numArr = document.querySelectorAll('.radio_title') numArr.forEach((item) => { // 赋予初始的样式 item.className = 'radio_title' }) // 点击添加样式 ev.target.className = 'radio_title radio_active' // 获取添加的name的值 let a = ev.target.getAttribute('name') this.setState({ imgUrl: a, data: [] }) this.ajaxData('/ting/listByStyle.php?style=' + a + '&sort=1&pageNum=1&pageSize=9') } render () { let RadioTypeArray = this.state.data.map((item, index) => { return ( <div key={index.toString()} className="recommend_ting"> <a href={'tingInfo.html?tingid=' + item.tingid} target='blank'> <div className="recommend_img_wrap"> <img src={item.imgUrl} className="recommend_img" /> <div className="coverDiv" /> </div> </a> <div className="recommend_ting_introduce"> <a href={'tingInfo.html?tingid=' + item.tingid} target='blank'><p className="recommend_ting_name">{item.title}</p></a> <a href={'user.html?uid=' + item.userinfo.uid} target='blank'><p className="recommend_ting_anchor">主播/{item.userinfo.uname}</p></a> <span>{(item.plays / 1000).toFixed(1)}次播放 |</span> <span> 评论:{item.comments} | </span> <span> 喜欢:{item.likes}</span> </div> </div> ) }) return ( <div className="radioType_wrap"> <div className="radio_type_top"> <div className="radio_type_loveImg"> <img src={require('../../assets/images/radio-type' + this.state.imgUrl + '.png')} /> </div> <div className='radioType_title_wrap'> <div className='radio_type_title'> 分类: <a onClick={this.click} name={2} className="radio_title">故事</a> <a onClick={this.click} name={4} className="radio_title">音乐</a> <a onClick={this.click} name={6} className="radio_title">读诗</a> <a onClick={this.click} name={5} className="radio_title">电影</a> <a onClick={this.click} name={3} className="radio_title">旅行</a> <a onClick={this.click} name={1} className="radio_title">爱情</a> </div> </div> </div> <div className="radioType_ting_wrap"> <div className="radioType_ting"> {RadioTypeArray} </div> </div> </div> ) } } export default RadioType
var {expect} = require('chai'); var {addClass} = require('../dist/cloud-utils'); describe('#addClass() 为元素添加某个 class', function () { it('应该添加 class 到元素', function () { var element = {className: 'box flex'}; addClass(element, 'flex1'); expect(element.className).to.eql('box flex flex1'); }); it('不应该添加已经存在的 class', function () { var element = {className: 'box flex'}; addClass(element, 'flex'); expect(element.className).to.eql('box flex'); }); });
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $('[data-toggle="tooltip"]').tooltip(); $(document).ready(function () { if ($('#datatable-list').length) { $('#datatable-list').DataTable({ responsive: true }); } // Formulário SkPhoto if ($('#skaphandrus_appbundle_skphoto_model').length) { $('#skaphandrus_appbundle_skphoto_model').autocompleter({url_list: '/en/ajax_search_photo_machine_model/', url_get: '/en/ajax_get_photo_machine_model/'}); } if ($('#skaphandrus_appbundle_skphoto_species').length) { $('#skaphandrus_appbundle_skphoto_species').autocompleter({url_list: '/en/ajax_search_species/', url_get: '/en/ajax_get_species/'}); } if ($('#skaphandrus_appbundle_skphoto_spot').length) { $('#skaphandrus_appbundle_skphoto_spot').autocompleter({url_list: '/en/ajax_search_spot/', url_get: '/en/ajax_get_spot/'}); } // Formulário Identification Group if ($('#skaphandrus_appbundle_skidentificationgroup_genus').length) { $('#skaphandrus_appbundle_skidentificationgroup_genus').autocompleter({url_list: '/en/ajax_search_genus/', url_get: '/en/ajax_get_genus/'}); } if ($('#skaphandrus_appbundle_skidentificationgroup_family').length) { $('#skaphandrus_appbundle_skidentificationgroup_family').autocompleter({url_list: '/en/ajax_search_family/', url_get: '/en/ajax_get_family/'}); } if ($('#skaphandrus_appbundle_skidentificationgroup_order').length) { $('#skaphandrus_appbundle_skidentificationgroup_order').autocompleter({url_list: '/en/ajax_search_order/', url_get: '/en/ajax_get_order/'}); } if ($('#skaphandrus_appbundle_skidentificationgroup_class').length) { $('#skaphandrus_appbundle_skidentificationgroup_class').autocompleter({url_list: '/en/ajax_search_class/', url_get: '/en/ajax_get_class/'}); } if ($('#skaphandrus_appbundle_skidentificationgroup_phylum').length) { $('#skaphandrus_appbundle_skidentificationgroup_phylum').autocompleter({url_list: '/en/ajax_search_phylum/', url_get: '/en/ajax_get_phylum/'}); } // Filtro Identification Species Index $('#form_module_filter_form_id').change(function () { // var id = $(this).val(); // get selected value // if (id) { // require a URL // window.location = '/identification_species_admin/' + id; // redirect // } // return false; $(this).parent('form').submit(); }); // Formulário skPerson if ($('#skaphandrus_appbundle_skperson_skaphandrusId').length) { $('#skaphandrus_appbundle_skperson_skaphandrusId').autocompleter({url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); } // Formulário FOSMessage new message if ($('#message_recipient').length) { $('#message_recipient').autocompleter({url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); } // Formulário SkSpot if ($('#skaphandrus_appbundle_skspot_location').length) { $('#skaphandrus_appbundle_skspot_location').autocompleter({url_list: '/en/ajax_search_location/', url_get: '/en/ajax_get_location/'}); } // Formulário photo validation if ($('#skaphandrus_appbundle_skphotovalidation_species').length) { $('#skaphandrus_appbundle_skphotovalidation_species').autocompleter({url_list: '/en/ajax_search_species/', url_get: '/en/ajax_get_species/', appendTo: '#validationForm'}); } if ($('#skaphandrus_appbundle_skphotosugestion_species').length) { $('#skaphandrus_appbundle_skphotosugestion_species').autocompleter({url_list: '/en/ajax_search_species/', url_get: '/en/ajax_get_species/', appendTo: '#validationForm'}); } // Formulário SkPhotoContestJudge if ($('#skaphandrus_appbundle_skphotocontestjudge_fosUser').length) { $('#skaphandrus_appbundle_skphotocontestjudge_fosUser').autocompleter({url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); } // Formulário skPhotoContestAward if ($('#skaphandrus_appbundle_skphotocontestaward_winnerFosUser').length) { $('#skaphandrus_appbundle_skphotocontestaward_winnerFosUser').autocompleter({url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); } // Formulário skPhotoContestSponsor if ($('#skaphandrus_appbundle_skphotocontestsponsor_business').length) { $('#skaphandrus_appbundle_skphotocontestsponsor_business').autocompleter({url_list: '/en/ajax_search_business/', url_get: '/en/ajax_get_business/'}); } // Formulário SkBusiness if ($('#skaphandrus_appbundle_skbusiness_address_location').length) { $('#skaphandrus_appbundle_skbusiness_address_location').autocompleter({url_list: '/en/ajax_search_location/', url_get: '/en/ajax_get_location/'}); } // Formulário SkProfile if ($('#skaphandrus_appbundle_fosuser_address_location').length) { $('#skaphandrus_appbundle_fosuser_address_location').autocompleter({url_list: '/en/ajax_search_location/', url_get: '/en/ajax_get_location/'}); } // Formulário SkBusinessDiveSpot if ($('#skaphandrus_appbundle_skbusiness_spotAutocomplete').length) { $('#skaphandrus_appbundle_skbusiness_spotAutocomplete').autocompleterMultiple({form_name: 'skaphandrus_appbundle_skbusiness', field_name: 'spotChoices', url_list: '/en/ajax_search_spot/', url_get: '/en/ajax_get_spot/'}); } // Formulário SkBusinessSettingsAdmins if ($('#skaphandrus_appbundle_skbusiness_adminAutocomplete').length) { $('#skaphandrus_appbundle_skbusiness_adminAutocomplete').autocompleterMultiple({form_name: 'skaphandrus_appbundle_skbusiness', field_name: 'adminChoices', url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); //$('#skaphandrus_appbundle_skbusiness_adminAutocomplete').attr("Add the users who works and manage your page."); } // Formulário SkBooking if ($('#skaphandrus_appbundle_skbooking_business').length) { $('#skaphandrus_appbundle_skbooking_business').autocompleter({url_list: '/en/ajax_search_business/', url_get: '/en/ajax_get_business/'}); } // Formulário SkBooking if ($('#skaphandrus_appbundle_skphoto_business').length) { $('#skaphandrus_appbundle_skphoto_business').autocompleter({url_list: '/en/ajax_search_business/', url_get: '/en/ajax_get_business/'}); } // Formulario SKFilterGallery if ($('#skaphandrus_filter_gallery_fosUser').length) { $('#skaphandrus_filter_gallery_fosUser').autocompleter({url_list: '/en/ajax_search_fosUser/', url_get: '/en/ajax_get_fosUser/'}); } if ($('#skaphandrus_filter_gallery_location').length) { $('#skaphandrus_filter_gallery_location').autocompleter({url_list: '/en/ajax_search_location/', url_get: '/en/ajax_get_location/'}); } if ($('#skaphandrus_filter_gallery_region').length) { $('#skaphandrus_filter_gallery_region').autocompleter({url_list: '/en/ajax_search_region/', url_get: '/en/ajax_get_region/'}); } // if ($('#skaphandrus_filter_gallery_country').length) { // $('#skaphandrus_filter_gallery_country').autocompleter({url_list: '/en/ajax_search_country/', url_get: '/en/ajax_get_country/'}); // } if ($('#skaphandrus_filter_gallery_species').length) { $('#skaphandrus_filter_gallery_species').autocompleter({url_list: '/en/ajax_search_species/', url_get: '/en/ajax_get_species/'}); } if ($('#skaphandrus_filter_gallery_genus').length) { $('#skaphandrus_filter_gallery_genus').autocompleter({url_list: '/en/ajax_search_genus/', url_get: '/en/ajax_get_genus/'}); } if ($('#skaphandrus_filter_gallery_family').length) { $('#skaphandrus_filter_gallery_family').autocompleter({url_list: '/en/ajax_search_family/', url_get: '/en/ajax_get_family/'}); } if ($('#skaphandrus_filter_gallery_order').length) { $('#skaphandrus_filter_gallery_order').autocompleter({url_list: '/en/ajax_search_order/', url_get: '/en/ajax_get_order/'}); } if ($('#skaphandrus_filter_gallery_class').length) { $('#skaphandrus_filter_gallery_class').autocompleter({url_list: '/en/ajax_search_class/', url_get: '/en/ajax_get_class/'}); } if ($('#skaphandrus_filter_gallery_phylum').length) { $('#skaphandrus_filter_gallery_phylum').autocompleter({url_list: '/en/ajax_search_phylum/', url_get: '/en/ajax_get_phylum/'}); } if ($('#skaphandrus_filter_gallery_kingdom').length) { $('#skaphandrus_filter_gallery_kingdom').autocompleter({url_list: '/en/ajax_search_kingdom/', url_get: '/en/ajax_get_kingdom/'}); } });
'use strict'; var should = require('should'); var app = require('../../app'); var request = require('supertest'); describe('GET /api/reservations', function() { it('should respond with JSON array', function(done) { request(app) .get('/api/reservations') .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); res.body.should.be.instanceof(Array); done(); }); }); });
/** * @file valuelistcontext.js * @brief Value list context menu * @author Medhi BOULNEMOUR (INRA UMR1095) * @date 2018-02-26 * @copyright Copyright (c) 2016 INRA/CIRAD * @license MIT (see LICENSE file) * @details */ let Marionette = require('backbone.marionette'); let View = Marionette.View.extend({ tagName: 'div', template: require('../../main/templates/contextmenu.html'), className: "context value-list", templateContext: function () { return { actions: this.getOption('actions'), options: { 'create-value': {className: 'btn-default', label: _t('Create value')}, } } }, ui: { 'create-value': 'button[name="create-value"]', }, triggers: { "click @ui.create-value": "value:create", }, initialize: function(options) { options || (options = {actions: []}); } }); module.exports = View;
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/extensions/mml2jax.js * * Implements the MathML to Jax preprocessor that locates <math> nodes * within the text of a document and replaces them with SCRIPT tags * for processing by MathJax. * * --------------------------------------------------------------------- * * Copyright (c) 2010-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Extension.mml2jax = { version: "2.7.0-beta", config: { preview: "mathml" // Use the <math> element as the // preview. Set to "none" for no preview, // set to "alttext" to use the alttext attribute // of the <math> element, set to "altimg" to use // an image described by the altimg* attributes // or set to an array specifying an HTML snippet // to use a fixed preview for all math }, MMLnamespace: "http://www.w3.org/1998/Math/MathML", PreProcess: function (element) { if (!this.configured) { this.config = MathJax.Hub.CombineConfig("mml2jax",this.config); if (this.config.Augment) {MathJax.Hub.Insert(this,this.config.Augment)} this.InitBrowser(); this.configured = true; } if (typeof(element) === "string") {element = document.getElementById(element)} if (!element) {element = document.body} var mathArray = []; // // Handle all math tags with no namespaces // this.PushMathElements(mathArray,element,"math"); // // Handle math with namespaces in XHTML // this.PushMathElements(mathArray,element,"math",this.MMLnamespace); // // Handle math with namespaces in HTML // var i, m; if (typeof(document.namespaces) !== "undefined") { // // IE namespaces are listed in document.namespaces // try { for (i = 0, m = document.namespaces.length; i < m; i++) { var ns = document.namespaces[i]; if (ns.urn === this.MMLnamespace) {this.PushMathElements(mathArray,element,ns.name+":math")} } } catch (err) {} } else { // // Everybody else // var html = document.getElementsByTagName("html")[0]; if (html) { for (i = 0, m = html.attributes.length; i < m; i++) { var attr = html.attributes[i]; if (attr.nodeName.substr(0,6) === "xmlns:" && attr.nodeValue === this.MMLnamespace) {this.PushMathElements(mathArray,element,attr.nodeName.substr(6)+":math")} } } } this.ProcessMathArray(mathArray); }, PushMathElements: function (array,element,name,namespace) { var math, preview = MathJax.Hub.config.preRemoveClass; if (namespace) { if (!element.getElementsByTagNameNS) return; math = element.getElementsByTagNameNS(namespace,name); } else { math = element.getElementsByTagName(name); } for (var i = 0, m = math.length; i < m; i++) { var parent = math[i].parentNode; if (parent && parent.className !== preview && !parent.isMathJax && !math[i].prefix === !namespace) array.push(math[i]); } }, ProcessMathArray: function (math) { var i, m = math.length; if (m) { if (this.MathTagBug) { for (i = 0; i < m; i++) { if (math[i].nodeName === "MATH") {this.ProcessMathFlattened(math[i])} else {this.ProcessMath(math[i])} } } else { for (i = 0; i < m; i++) {this.ProcessMath(math[i])} } } }, ProcessMath: function (math) { var parent = math.parentNode; if (!parent || parent.className === MathJax.Hub.config.preRemoveClass) return; var script = document.createElement("script"); script.type = "math/mml"; parent.insertBefore(script,math); if (this.AttributeBug) { var html = this.OuterHTML(math); if (this.CleanupHTML) { html = html.replace(/<\?import .*?>/i,"").replace(/<\?xml:namespace .*?\/>/i,""); html = html.replace(/&nbsp;/g,"&#xA0;"); } MathJax.HTML.setScript(script,html); parent.removeChild(math); } else { var span = MathJax.HTML.Element("span"); span.appendChild(math); MathJax.HTML.setScript(script,span.innerHTML); } if (this.config.preview !== "none") {this.createPreview(math,script)} }, ProcessMathFlattened: function (math) { var parent = math.parentNode; if (!parent || parent.className === MathJax.Hub.config.preRemoveClass) return; var script = document.createElement("script"); script.type = "math/mml"; parent.insertBefore(script,math); var mml = "", node, MATH = math; while (math && math.nodeName !== "/MATH") { node = math; math = math.nextSibling; mml += this.NodeHTML(node); node.parentNode.removeChild(node); } if (math && math.nodeName === "/MATH") {math.parentNode.removeChild(math)} script.text = mml + "</math>"; if (this.config.preview !== "none") {this.createPreview(MATH,script)} }, NodeHTML: function (node) { var html, i, m; if (node.nodeName === "#text") { html = this.quoteHTML(node.nodeValue); } else if (node.nodeName === "#comment") { html = "<!--" + node.nodeValue + "-->" } else { // In IE, outerHTML doesn't properly quote attributes, so quote them by hand // In Opera, HTML special characters aren't quoted in attributes, so quote them html = "<"+node.nodeName.toLowerCase(); for (i = 0, m = node.attributes.length; i < m; i++) { var attribute = node.attributes[i]; if (attribute.specified && attribute.nodeName.substr(0,10) !== "_moz-math-") { // Opera 11.5 beta turns xmlns into xmlns:xmlns, so put it back (*** check after 11.5 is out ***) html += " "+attribute.nodeName.toLowerCase().replace(/xmlns:xmlns/,"xmlns")+"="; var value = attribute.nodeValue; // IE < 8 doesn't properly set style by setAttributes if (value == null && attribute.nodeName === "style" && node.style) {value = node.style.cssText} html += '"'+this.quoteHTML(value)+'"'; } } html += ">"; // Handle internal HTML (possibly due to <semantics> annotation or missing </math>) if (node.outerHTML != null && node.outerHTML.match(/(.<\/[A-Z]+>|\/>)$/)) { for (i = 0, m = node.childNodes.length; i < m; i++) {html += this.OuterHTML(node.childNodes[i])} html += "</"+node.nodeName.toLowerCase()+">"; } } return html; }, OuterHTML: function (node) { if (node.nodeName.charAt(0) === "#") {return this.NodeHTML(node)} if (!this.AttributeBug) {return node.outerHTML} var html = this.NodeHTML(node); for (var i = 0, m = node.childNodes.length; i < m; i++) {html += this.OuterHTML(node.childNodes[i]);} html += "</"+node.nodeName.toLowerCase()+">"; return html; }, quoteHTML: function (string) { if (string == null) {string = ""} return string.replace(/&/g,"&#x26;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;"); }, createPreview: function (math,script) { var preview = this.config.preview; if (preview === "none") return; var isNodePreview = false; var previewClass = MathJax.Hub.config.preRemoveClass; if ((script.previousSibling||{}).className === previewClass) return; if (preview === "mathml") { isNodePreview = true; // mathml preview does not work with IE < 9, so fallback to alttext. if (this.MathTagBug) {preview = "alttext"} else {preview = math.cloneNode(true)} } if (preview === "alttext" || preview === "altimg") { isNodePreview = true; var alttext = this.filterPreview(math.getAttribute("alttext")); if (preview === "alttext") { if (alttext != null) {preview = MathJax.HTML.TextNode(alttext)} else {preview = null} } else { var src = math.getAttribute("altimg"); if (src != null) { // FIXME: use altimg-valign when display="inline"? var style = {width: math.getAttribute("altimg-width"), height: math.getAttribute("altimg-height")}; preview = MathJax.HTML.Element("img",{src:src,alt:alttext,style:style}); } else {preview = null} } } if (preview) { var span; if (isNodePreview) { span = MathJax.HTML.Element("span",{className:previewClass}); span.appendChild(preview); } else { span = MathJax.HTML.Element("span",{className:previewClass},preview); } script.parentNode.insertBefore(span,script); } }, filterPreview: function (text) {return text}, InitBrowser: function () { var test = MathJax.HTML.Element("span",{id:"<", className: "mathjax", innerHTML: "<math><mi>x</mi><mspace /></math>"}); var html = test.outerHTML || ""; this.AttributeBug = html !== "" && !( html.match(/id="&lt;"/) && // "<" should convert to "&lt;" html.match(/class="mathjax"/) && // IE leaves out quotes html.match(/<\/math>/) // Opera 9 drops tags after self-closing tags ); this.MathTagBug = test.childNodes.length > 1; // IE < 9 flattens unknown tags this.CleanupHTML = MathJax.Hub.Browser.isMSIE; // remove namespace and other added tags } }; // // We register the preprocessors with the following priorities: // - mml2jax.js: 5 // - jsMath2jax.js: 8 // - asciimath2jax.js, tex2jax.js: 10 (default) // See issues 18 and 484 and the other *2jax.js files. // MathJax.Hub.Register.PreProcessor(["PreProcess",MathJax.Extension.mml2jax],5); MathJax.Ajax.loadComplete("[MathJax]/extensions/mml2jax.js");
// Import dependencies const webpack = require('webpack'); const path = require('path'); const NodeObjectHash = require('node-object-hash'); const ManifestPlugin = require('webpack-manifest-plugin'); const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin'); const WebpackMd5Hash = require('webpack-md5-hash'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); // Config variables const nodeEnv = process.env.NODE_ENV; const isProd = nodeEnv === 'production'; const nodeModulesPath = path.join(__dirname, '../node_modules'); const cachePath = path.join(nodeModulesPath, './.cache'); const resourcePath = path.join(__dirname, './resources/assets'); const buildPath = path.join(__dirname, './build'); // Common plugins const plugins = [ // Make sure Webpack is given current environment with quotes ("") new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }, }), // Provide plugin to prevent "moment is not defined" or "$ is not defined" new webpack.ProvidePlugin({ moment: 'moment', $: 'jquery', jQuery: 'jquery', 'window.$': 'jquery', 'window.jQuery': 'jquery', }), ]; // Common loaders const imageLoader = []; const loaders = [ // Use babel-loader to transpile file with JS/JSX extension { test: /\.(jsx|js)$/, loader: 'babel-loader', exclude: /node_modules/, options: { babelrc: false, presets: [ ['es2015'], 'react', 'stage-2', ], }, }, // Use file-loader to load fonts { test: /\.(woff2?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, use: isProd ? 'file-loader?publicPath=../&name=fonts/[name].[hash].[ext]' : 'file-loader?name=fonts/[name].[ext]', }, // Use imageLoader to load images { test: /.*\.(gif|png|jpe?g)$/i, loaders: imageLoader, }, ]; // Configure plugins and loaders depending on environment settings if (isProd) { plugins.push( // [NEW]: enable caching to improve build performance new HardSourceWebpackPlugin({ cacheDirectory: `${cachePath}/hard-source/[confighash]`, recordsPath: `${cachePath}/hard-source/[confighash]/records.json`, configHash: NodeObjectHash({ sort: false }).hash, }), // Add global options for all loaders new webpack.LoaderOptionsPlugin({ minimize: true, debug: false, }), // Uglify Javascript files new webpack.optimize.UglifyJsPlugin(), // Split each entry to app and vendor bundle // Common vendor new webpack.optimize.CommonsChunkPlugin({ name: 'vendor-common', chunks: [ 'app1', 'app2', 'app3', ], }), // Split app and vendor code of app1 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor-app1', chunks: ['app1'], minChunks: ({ resource }) => /node_modules/.test(resource), }), // Split app and vendor code of app2 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor-app2', chunks: ['app2'], minChunks: ({ resource }) => /node_modules/.test(resource), }), // Split app and vendor code of app3 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor-app3', chunks: ['app3'], minChunks: ({ resource }) => /node_modules/.test(resource), }), // Hash assets new WebpackMd5Hash(), // Add manifest to assets after build new ManifestPlugin(), // Enable hash on chunk bundles new ChunkManifestPlugin({ filename: 'chunk-manifest.json', manifestVariable: 'webpackManifest', }), // Separate CSS files from the Javascript files new ExtractTextPlugin({ filename: 'css/[name].[chunkhash].css', allChunks: true, }) ); // Apply optimizing for images on production imageLoader.push( 'file-loader?name=img/[name].[hash].[ext]', { loader: 'image-webpack-loader', query: { optipng: { quality: '65-90', speed: 4, optimizationLevel: 7, interlaced: false, }, gifsicle: { quality: '65-90', speed: 4, optimizationLevel: 7, interlaced: false, }, mozjpeg: { quality: '65-90', speed: 4, optimizationLevel: 7, interlaced: false, progressive: true, }, }, } ); // Use css-loader and sass-loader as an input for ExtractTextPlugin // If CSS files are not extracted, use style-loader instead loaders.push( { test: /\.(css|scss)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader!sass-loader', }), } ); } else { // Enable hot reload on development plugins.push(new webpack.HotModuleReplacementPlugin()); // Standard loading on development imageLoader.push('file-loader?name=img/[name].[ext]'); // Use style-loader, css-loader, and sass-loader on development loaders.push({ test: /\.(css|sass|scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'], }); } // Configuration module.exports = { // source-map: long build, smaller size, production // eval: fast build, bigger size, development devtool: isProd ? 'source-map' : 'eval', // Source directory context: resourcePath, // Source files; relative to context entry: { app1: './js/app1.js', app2: './js/app2.js', app3: './js/app3.js', }, // Output directory output: { path: `${buildPath}/assets/`, filename: isProd ? 'js/[name].[chunkhash].js' : 'js/[name].js', chunkFilename: isProd ? 'js/[name].[chunkhash].js' : 'js/[name].js', publicPath: '/assets/', }, // Loaders used to load modules module: { loaders, }, // Resolve a module name as another module and // directories to lookup when searching for modules resolve: { alias: { joi: 'joi-browser', }, modules: [ resourcePath, nodeModulesPath, ], }, // Plugins used plugins, // webpack-dev-server (more like webpack-dev-middleware) configuration devServer: { // It should be the same as buildPath contentBase: './build', // Fallback to /index.html when not found historyApiFallback: true, port: 3001, // Proxy to a running server proxy: { '**': 'http://localhost:3000/', }, // Enable hot-reload hot: true, // Inline HTML instead of iframe inline: true, // Same as output.publicPath publicPath: '/assets/', compress: false, // Enable "waiting" for file changes watchOptions: { poll: true, }, // Show stats after in-memory bundle has been built stats: { assets: true, children: false, chunks: false, hash: false, modules: false, publicPath: false, timings: true, version: false, warnings: true, colors: { green: '\u001b[32m', }, }, }, };
const dotenv = require('dotenv'); dotenv.config(); module.exports = { secret: String(process.env.SECRET) };
/** * * FUNCTION: resetCols * * * DESCRIPTION: * - Resets chart column elements. * * * NOTES: * [1] * * * TODO: * [1] * * * LICENSE: * MIT * * Copyright (c) 2015. Athan Reines. * * * AUTHOR: * Athan Reines. kgryte@gmail.com. 2015. * */ 'use strict'; /** * FUNCTION: resetCols() * Resets column elements. * * @returns {Object} context */ function resetCols() { /* jslint validthis:true */ var cols, gEnter; cols = this.$.marks.selectAll( '.col' ) .data( this.data.colnames() ) .attr( 'transform', this._x ); // Remove any old columns: cols.exit().remove(); // Add any new columns: gEnter = cols.enter().append( 'svg:g' ) .attr( 'class', 'col' ) .attr( 'transform', this._x ) .on( 'mouseover', this._onColHover ) .on( 'mouseout', this._onColHoverEnd ); gEnter.append( 'svg:line' ) .attr( 'class', 'grid y' ) .attr( 'x1', -this.graphHeight() ); gEnter.append( 'svg:text' ) .attr( 'class', 'noselect name' ) .attr( 'x', 6 ) .attr( 'y', this._xScale.rangeBand() / 2 ) .attr( 'dy', '.32em' ) .attr( 'text-anchor', 'start' ) .attr( 'font-size', this.fontSize() ) .text( this._getColName ) .on( 'click', this._onColClick ); // Cache a reference to the columns: this.$.cols = cols; this.$.colGridlines = cols.selectAll( '.grid.y' ); this.$.colnames = cols.selectAll( '.name' ); return this; } // end FUNCTION resetCols() // EXPORTS // module.exports = resetCols;
import React, { Component, PropTypes } from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import CarsList from '../../components/CarsList/CarsList' import * as Actions from '../../actions/cars' import './Cars.scss' class Cars extends Component { constructor (props){ super(props) } static propTypes = { }; render (){ return ( <div className='Cars'> <h2>Cars</h2> <CarsList cars={ this.props.cars } onCarAddClick={ this.props.addCar }/> </div> ) } } //Place state of redux store into props of component function mapStateToProps (state) { return { cars: state.cars, router: state.router } } //Place action methods into props function mapDispatchToProps (dispatch) { return bindActionCreators(Actions, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(Cars)
var logger = require("loggero").create("service/linker"); var inherit = require("../inherit"); var Module = require("../module"); var Service = require("../service"); function Link(context) { Service.call(this, context); } inherit.base(Link).extends(Service); Link.prototype.canProcess = function(moduleMeta) { return Module.isCompiled(moduleMeta) || Module.hasFactory(moduleMeta); }; /** * The linker step is where we take the evaluated source, build all the dependencies * and call the factory method on the module if available. * * This is the step where the Module instance is finally created. * * @returns {Module} */ Link.prototype.runSync = function(moduleMeta) { this._logger && this._logger.log(moduleMeta.name, moduleMeta); if (!this.validate(moduleMeta)) { throw new TypeError("Module " + moduleMeta.name + " cannot be linked"); } var context = this.context; function traverseDependencies(mod) { logger.log(mod.name, mod); // Build all the dependecies in the dependency graph. var depsGraph = mod.deps.map(function resolveDependency(modDep) { if (context.controllers.registry.getModuleState(modDep.id) === Module.State.READY) { return context.controllers.registry.getModule(modDep.id).exports; } return traverseDependencies(context.controllers.builder.build(modDep.id)).exports; }); // If the module itself is not yet built, then build it if there is a factory // method that can be called. if (mod.factory && !mod.hasOwnProperty("exports")) { mod.exports = mod.factory.apply(undefined, depsGraph); } return mod; } // Link it return traverseDependencies(moduleMeta.merge({ meta: moduleMeta })); }; module.exports = Link;
Polymer({ is: 'moi-send-client-request-button', properties: { text: String, loadingText: String, sendRequestApi: String, ids: { type: Array, value: function() { return []; } } }, onClick: function() { this.prevText = this.text; this.text = this.loadingText; $(this.$.btnsend).addClass('disabled'); $.ajax({ url: this.sendRequestApi, type: 'POST', data: { user_ids: this.ids }, success: function(res) { this.text = this.prevText; $(this.$.btnsend).removeClass('disabled'); this.fire('success', res); }.bind(this), error: function(res) { this.text = this.prevText; $(this.$.btnsend).removeClass('disabled'); this.fire('error', res); }.bind(this) }); } });
/* eslint-env mocha */ import React from 'react'; import chai, { expect } from 'chai'; import chaiEnzyme from 'chai-enzyme'; import { shallow, mount } from 'enzyme'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import TextArea from './'; chai.use(sinonChai); chai.use(chaiEnzyme()); describe('TextArea', () => { it('is a textarea', () => { const textarea = shallow(<TextArea/>); expect(textarea.is('textarea')).to.be.true; expect(textarea).to.have.className('textarea'); }); it('accepts name prop', () => { const wrapper = mount(<TextArea name="foo"/>); expect(wrapper.find('textarea')).to.have.attr('name', 'foo'); }); it('accepts placeholder prop', () => { const wrapper = mount(<TextArea placeholder="Something"/>); expect(wrapper.find('textarea')).to.have.prop('placeholder', 'Something'); }); it('accepts value prop', () => { const wrapper = mount(<TextArea value="hello"/>); expect(wrapper.find('textarea')).to.have.prop('value', 'hello'); }); it('accepts theme prop', () => { const textarea = shallow(<TextArea theme="foo"/>); expect(textarea.hasClass('textarea_theme_foo')).to.be.true; }); it('accepts size prop', () => { const textarea = shallow(<TextArea size="l"/>); expect(textarea.hasClass('textarea_size_l')).to.be.true; }); it('accepts id prop', () => { const textarea = shallow(<TextArea id="my-textarea"/>); expect(textarea).to.have.id('my-textarea'); }); it('accepts className prop', () => { const textarea = shallow(<TextArea className="my-textarea not-my-textarea"/>); expect(textarea.hasClass('my-textarea')).to.be.true; expect(textarea.hasClass('not-my-textarea')).to.be.true; }); it('accepts disabled prop', () => { const textarea = shallow(<TextArea disabled/>); expect(textarea.hasClass('textarea_disabled')).to.be.true; expect(textarea.find('textarea')).to.have.attr('disabled'); textarea.setProps({ disabled: false }); expect(textarea.hasClass('textarea_disabled')).to.be.false; expect(textarea.find('textarea')).to.not.have.attr('disabled'); }); it('accepts minLength prop', () => { const textarea = shallow(<TextArea minLength={3}/>); expect(textarea.find('textarea')).to.have.attr('minlength', '3'); }); it('accepts maxLength prop', () => { const textarea = shallow(<TextArea maxLength={3}/>); expect(textarea.find('textarea')).to.have.attr('maxlength', '3'); }); it('accepts focused prop', () => { const textarea = shallow(<TextArea focused/>); expect(textarea.hasClass('textarea_focused')).to.be.true; }); it('accepts DOM focus', () => { const textarea = shallow(<TextArea/>); expect(textarea.hasClass('textarea_focused')).to.be.false; textarea.find('textarea').simulate('focus'); expect(textarea.hasClass('textarea_focused')).to.be.true; }); it('removes focused if receives disabled', () => { const textarea = shallow(<TextArea focused/>); textarea.setProps({ disabled: true }); expect(textarea.hasClass('textarea_focused')).to.be.false; }); it('is hovered on mouseenter/mouseleave', () => { const textarea = shallow(<TextArea/>); textarea.find('textarea').simulate('mouseenter'); expect(textarea.state('hovered')).to.be.true; expect(textarea.hasClass('textarea_hovered')).to.be.true; textarea.find('textarea').simulate('mouseleave'); expect(textarea.state('hovered')).to.not.be.ok; expect(textarea.hasClass('textarea_hovered')).to.be.false; }); it('can not be hovered if disabled', () => { const textarea = shallow(<TextArea disabled/>); textarea.find('textarea').simulate('mouseenter'); expect(textarea.state('hovered')).to.not.be.ok; }); it('calls onChange on textarea change', () => { const spy = sinon.spy(); const textarea = mount(<TextArea name="foo" onChange={spy}/>); textarea.find('textarea').simulate('change', { target: { value: 'hello' } }); expect(spy).to.have.been.called; expect(spy.lastCall).to.have.been.calledWithMatch('hello', { name: 'foo' }); }); it('does not call onChange on textarea change if disabled', () => { const spy = sinon.spy(); const textarea = mount(<TextArea disabled onChange={spy}/>); const control = textarea.find('textarea'); control.node.setAttribute('value', 'hello'); control.simulate('change'); expect(spy).to.not.have.been.called; }); });
0X04;
import React from 'react'; import { render } from '@testing-library/react'; import ConnectedHome from '.'; import { Provider } from 'react-redux'; import configureStore from 'store'; import { toggleWindowFocus, toggleNotificationEnabled, toggleSoundEnabled } from 'actions/app'; import { receiveEncryptedMessage } from 'actions/encrypted_messages'; import { notify, beep } from 'utils/notifications'; import Tinycon from 'tinycon'; import Modal from 'react-modal'; const store = configureStore(); jest.useFakeTimers(); // We don't test activity list here jest.mock('./ActivityList', () => { return jest.fn().mockReturnValue(null); }); jest.mock('react-modal'); // Cant load modal without root app element jest.mock('utils/socket', () => { // Avoid exception return { connect: jest.fn().mockImplementation(() => { return { on: jest.fn(), emit: jest.fn(), }; }), getSocket: jest.fn().mockImplementation(() => { return { on: jest.fn(), emit: jest.fn(), }; }), }; }); jest.mock('shortid', () => { // Avoid exception return { generate: jest.fn().mockImplementation(() => { return 'shortidgenerated'; }), }; }); jest.mock('utils/crypto', () => { // Need window.crytpo.subtle return jest.fn().mockImplementation(() => { return { createEncryptDecryptKeys: () => { return { privateKey: { n: 'private' }, publicKey: { n: 'public' }, }; }, exportKey: () => { return { n: 'exportedKey' }; }, }; }); }); jest.mock('utils/message', () => { return { process: jest.fn(async (payload, state) => ({ ...payload, payload: { payload: 'text', username: 'sender', text: 'new message' }, })), }; }); jest.mock('utils/notifications', () => { return { notify: jest.fn(), beep: { play: jest.fn() }, }; }); jest.mock('tinycon', () => { return { setBubble: jest.fn(), }; }); describe('Connected Home component', () => { beforeEach(() => { global.Notification = { permission: 'granted', }; }); afterEach(() => { delete global.Notification; }); it('should display', () => { const { asFragment } = render( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" /> </Provider>, ); expect(asFragment()).toMatchSnapshot(); }); it('should set notification', () => { render( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" /> </Provider>, ); expect(store.getState().app.notificationIsAllowed).toBe(true); expect(store.getState().app.notificationIsEnabled).toBe(true); global.Notification = { permission: 'denied', }; render( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" /> </Provider>, ); expect(store.getState().app.notificationIsAllowed).toBe(false); global.Notification = { permission: 'default', }; render( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" /> </Provider>, ); expect(store.getState().app.notificationIsAllowed).toBe(null); }); it('should send notifications', async () => { Modal.prototype.getSnapshotBeforeUpdate = jest.fn().mockReturnValue(null); const { rerender } = render( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" roomId={'testId'} /> </Provider>, ); // Test with window focused await receiveEncryptedMessage({ type: 'TEXT_MESSAGE', payload: {}, })(store.dispatch, store.getState); rerender( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" roomId={'testId'} /> </Provider>, ); expect(store.getState().app.unreadMessageCount).toBe(0); expect(notify).not.toHaveBeenCalled(); expect(beep.play).not.toHaveBeenCalled(); expect(Tinycon.setBubble).not.toHaveBeenCalled(); // Test with window unfocused await toggleWindowFocus(false)(store.dispatch); await receiveEncryptedMessage({ type: 'TEXT_MESSAGE', payload: {}, })(store.dispatch, store.getState); rerender( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" roomId={'testId'} /> </Provider>, ); expect(store.getState().app.unreadMessageCount).toBe(1); expect(notify).toHaveBeenLastCalledWith('sender said:', 'new message'); expect(beep.play).toHaveBeenLastCalledWith(); expect(Tinycon.setBubble).toHaveBeenLastCalledWith(1); // Test with sound and notification disabled await toggleNotificationEnabled(false)(store.dispatch); await toggleSoundEnabled(false)(store.dispatch); await receiveEncryptedMessage({ type: 'TEXT_MESSAGE', payload: {}, })(store.dispatch, store.getState); rerender( <Provider store={store}> <ConnectedHome match={{ params: { roomId: 'roomTest' } }} userId="testUserId" roomId={'testId'} /> </Provider>, ); expect(store.getState().app.unreadMessageCount).toBe(2); expect(notify).toHaveBeenCalledTimes(1); expect(beep.play).toHaveBeenCalledTimes(1); expect(Tinycon.setBubble).toHaveBeenLastCalledWith(2); }); });
// DESCRIPTION: Virtual services REST & SOAP // MAINTAINER: Didier Kimès <didier.kimes@gmail.com> var debug = require('debug')('imock:server:models:groups') var util = require('../models/util') /** * * List of groups * * @param {object} req * @param {function} callback */ module.exports.list = function (req, done) { var client = req.app.locals.redis var hash = '/api/groups' // Sort in ascending order client.sort(hash, 'ALPHA', function (err, list) { if (err) { done(util.getMessage(500, 'Internal Server Error')) } else if (list.length > 0) { // Return groups list done(util.getMessage(200, JSON.stringify(list))) } else { done(util.getMessage(404, 'Empty list')) } }) }
/*global require:true */ var bowler = require('../lib/bowler.js'); exports['awesome'] = { setUp: function(done) { // setup here done(); }, 'no args': function(test) { // test.expect(1); // // tests here // test.equal(bowler.awesome(), 'awesome', 'should be awesome.'); test.done(); } };
'use strict'; /** * @ngdoc service * @name tagsInputConfig * @module ngTagsInput * * @description * Sets global configuration settings for both tagsInput and autoComplete directives. It's also used internally to parse and * initialize options from HTML attributes. */ tagsInput.provider('tagsInputConfig', function() { var globalDefaults = {}, interpolationStatus = {}, autosizeThreshold = 3; /** * @ngdoc method * @name setDefaults * @description Sets the default configuration option for a directive. * @methodOf tagsInputConfig * * @param {string} directive Name of the directive to be configured. Must be either 'tagsInput' or 'autoComplete'. * @param {object} defaults Object containing options and their values. * * @returns {object} The service itself for chaining purposes. */ this.setDefaults = function(directive, defaults) { globalDefaults[directive] = defaults; return this; }; /*** * @ngdoc method * @name setActiveInterpolation * @description Sets active interpolation for a set of options. * @methodOf tagsInputConfig * * @param {string} directive Name of the directive to be configured. Must be either 'tagsInput' or 'autoComplete'. * @param {object} options Object containing which options should have interpolation turned on at all times. * * @returns {object} The service itself for chaining purposes. */ this.setActiveInterpolation = function(directive, options) { interpolationStatus[directive] = options; return this; }; /*** * @ngdoc method * @name setTextAutosizeThreshold * @methodOf tagsInputConfig * * @param {number} threshold Threshold to be used by the tagsInput directive to re-size the input element based on its contents. * * @returns {object} The service itself for chaining purposes. */ this.setTextAutosizeThreshold = function(threshold) { autosizeThreshold = threshold; return this; }; this.$get = function($interpolate) { var converters = {}; converters[String] = function(value) { return value; }; converters[Number] = function(value) { return parseInt(value, 10); }; converters[Boolean] = function(value) { return value.toLowerCase() === 'true'; }; converters[RegExp] = function(value) { return new RegExp(value); }; return { load: function(directive, scope, attrs, options) { var defaultValidator = function() { return true; }; scope.options = {}; angular.forEach(options, function(value, key) { var type, localDefault, validator, converter, getDefault, updateValue; type = value[0]; localDefault = value[1]; validator = value[2] || defaultValidator; converter = converters[type]; getDefault = function() { var globalValue = globalDefaults[directive] && globalDefaults[directive][key]; return angular.isDefined(globalValue) ? globalValue : localDefault; }; updateValue = function(value) { scope.options[key] = value && validator(value) ? converter(value) : getDefault(); }; if (interpolationStatus[directive] && interpolationStatus[directive][key]) { attrs.$observe(key, function(value) { updateValue(value); scope.events.trigger('option-change', { name: key, newValue: value }); }); } else { updateValue(attrs[key] && $interpolate(attrs[key])(scope.$parent)); } }); }, getTextAutosizeThreshold: function() { return autosizeThreshold; } }; }; });
var spec = function () { return jasmine.getEnv().currentSpec; }; var handsontable = function (options) { var currentSpec = spec(); currentSpec.$container.handsontable(options); currentSpec.$container[0].focus(); //otherwise TextEditor tests do not pass in IE8 return currentSpec.$container.data('handsontable'); }; /** * As for v. 0.11 the only scrolling method is native scroll, which creates copies of main htCore table inside of the container. * Therefore, simple $(".htCore") will return more than one object. Most of the time, you're interested in the original * htCore, not the copies made by native scroll. * * This method returns the original htCore object * * @returns {jqObject} reference to the original htCore */ var getHtCore = function () { return spec().$container.find('.htCore').first(); }; var getTopClone = function () { return spec().$container.find('.ht_clone_top'); }; var getLeftClone = function () { return spec().$container.find('.ht_clone_left'); }; var countRows = function () { return getHtCore().find('tbody tr').length; }; var countCols = function () { return getHtCore().find('tbody tr:eq(0) td').length; }; var countCells = function () { return getHtCore().find('tbody td').length; }; var isEditorVisible = function () { return !!(keyProxy().is(':visible') && keyProxy().parent().is(':visible') && !keyProxy().parent().is('.htHidden')); }; var isFillHandleVisible = function () { return !!spec().$container.find('.wtBorder.corner:visible').length; }; /** * Shows context menu */ var contextMenu = function () { var hot = spec().$container.data('handsontable'); var selected = hot.getSelected(); if (!selected) { hot.selectCell(0, 0); selected = hot.getSelected(); } var cell = getCell(selected[0], selected[1]); var cellOffset = $(cell).offset(); var ev = $.Event('contextmenu', { pageX: cellOffset.left, pageY: cellOffset.top }); $(cell).trigger(ev); }; var closeContextMenu = function () { $(document).trigger('mousedown'); }; /** * Returns a function that triggers a mouse event * @param {String} type Event type * @return {Function} */ var handsontableMouseTriggerFactory = function (type, button) { return function (element) { if (!(element instanceof jQuery)) { element = $(element); } var ev = $.Event(type); ev.which = button || 1; //left click by default element.trigger(ev); } }; var mouseDown = handsontableMouseTriggerFactory('mousedown'); var mouseUp = handsontableMouseTriggerFactory('mouseup'); var mouseDoubleClick = function (element) { mouseDown(element); mouseUp(element); mouseDown(element); mouseUp(element); }; var mouseRightDown = handsontableMouseTriggerFactory('mousedown', 3); var mouseRightUp = handsontableMouseTriggerFactory('mouseup', 3); /** * Returns a function that triggers a key event * @param {String} type Event type * @return {Function} */ var handsontableKeyTriggerFactory = function (type) { return function (key, extend) { var ev = $.Event(type); if (typeof key === 'string') { if (key.indexOf('shift+') > -1) { key = key.substring(6); ev.shiftKey = true; } switch (key) { case 'tab': ev.keyCode = 9; break; case 'enter': ev.keyCode = 13; break; case 'esc': ev.keyCode = 27; break; case 'f2': ev.keyCode = 113; break; case 'arrow_left': ev.keyCode = 37; break; case 'arrow_up': ev.keyCode = 38; break; case 'arrow_right': ev.keyCode = 39; break; case 'arrow_down': ev.keyCode = 40; break; case 'ctrl': ev.keyCode = 17; break; case 'shift': ev.keyCode = 16; break; case 'backspace': ev.keyCode = 8; break; case 'space': ev.keyCode = 32; break; default: throw new Error('Unrecognised key name: ' + key); } } else if (typeof key === 'number') { ev.keyCode = key; } ev.originalEvent = {}; //needed as long Handsontable searches for event.originalEvent $.extend(ev, extend); $(document.activeElement).trigger(ev); } }; var keyDown = handsontableKeyTriggerFactory('keydown'); var keyUp = handsontableKeyTriggerFactory('keyup'); /** * Presses keyDown, then keyUp */ var keyDownUp = function (key, extend) { if (typeof key === 'string' && key.indexOf('shift+') > -1) { keyDown('shift'); } keyDown(key, extend); keyUp(key, extend); if (typeof key === 'string' && key.indexOf('shift+') > -1) { keyUp('shift'); } }; /** * Returns current value of the keyboard proxy textarea * @return {String} */ var keyProxy = function () { return spec().$container.find('textarea.handsontableInput'); }; var autocompleteEditor = function () { return spec().$container.find('.handsontableInput'); }; /** * Sets text cursor inside keyboard proxy */ var setCaretPosition = function (pos) { var el = keyProxy()[0]; if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, pos); } else if (el.createTextRange) { var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }; /** * Returns autocomplete instance */ var autocomplete = function () { return spec().$container.find('.autocompleteEditor'); }; /** * Triggers paste string on current selection */ var triggerPaste = function (str) { spec().$container.data('handsontable').copyPaste.triggerPaste(null, str); }; /** * Calls a method in current Handsontable instance, returns its output * @param method * @return {Function} */ var handsontableMethodFactory = function (method) { return function () { var instance = spec().$container.handsontable('getInstance'); if (!instance) { if (method === 'destroy') { return; //we can forgive this... maybe it was destroyed in the test } throw new Error('Something wrong with the test spec: Handsontable instance not found'); } return instance[method].apply(instance, arguments); } }; var getInstance = handsontableMethodFactory('getInstance'); var selectCell = handsontableMethodFactory('selectCell'); var deselectCell = handsontableMethodFactory('deselectCell'); var getSelected = handsontableMethodFactory('getSelected'); var setDataAtCell = handsontableMethodFactory('setDataAtCell'); var setDataAtRowProp = handsontableMethodFactory('setDataAtRowProp'); var getCell = handsontableMethodFactory('getCell'); var getCellMeta = handsontableMethodFactory('getCellMeta'); var setCellMeta = handsontableMethodFactory('setCellMeta'); var removeCellMeta = handsontableMethodFactory('removeCellMeta'); var getCellRenderer = handsontableMethodFactory('getCellRenderer'); var getCellEditor = handsontableMethodFactory('getCellEditor'); var getCellValidator = handsontableMethodFactory('getCellValidator'); var getData = handsontableMethodFactory('getData'); var getCopyableData = handsontableMethodFactory('getCopyableData'); var getDataAtCell = handsontableMethodFactory('getDataAtCell'); var getDataAtRowProp = handsontableMethodFactory('getDataAtRowProp'); var getDataAtRow = handsontableMethodFactory('getDataAtRow'); var getDataAtCol = handsontableMethodFactory('getDataAtCol'); var getSourceDataAtCol = handsontableMethodFactory('getSourceDataAtCol'); var getSourceDataAtRow = handsontableMethodFactory('getSourceDataAtRow'); var getRowHeader = handsontableMethodFactory('getRowHeader'); var getColHeader = handsontableMethodFactory('getColHeader'); var alter = handsontableMethodFactory('alter'); var spliceCol = handsontableMethodFactory('spliceCol'); var spliceRow = handsontableMethodFactory('spliceRow'); var populateFromArray = handsontableMethodFactory('populateFromArray'); var loadData = handsontableMethodFactory('loadData'); var destroyEditor = handsontableMethodFactory('destroyEditor'); var render = handsontableMethodFactory('render'); var updateSettings = handsontableMethodFactory('updateSettings'); var destroy = handsontableMethodFactory('destroy'); var addHook = handsontableMethodFactory('addHook'); /** * Creates 2D array of Excel-like values "A0", "A1", ... * @param rowCount * @param colCount * @returns {Array} */ function createSpreadsheetData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [] , i , j; for (i = 0; i < rowCount; i++) { var row = []; for (j = 0; j < colCount; j++) { row.push(Handsontable.helper.spreadsheetColumnLabel(j) + i); } rows.push(row); } return rows; } function createSpreadsheetObjectData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [] , i , j; for (i = 0; i < rowCount; i++) { var row = {}; for (j = 0; j < colCount; j++) { row['prop' + j] = Handsontable.helper.spreadsheetColumnLabel(j) + i } rows.push(row); } return rows; } /** * Returns column width for HOT container * @param $elem * @param col * @returns {Number} */ function colWidth($elem, col) { var TD = $elem[0].querySelector('TBODY TR').querySelectorAll('TD')[col]; if (!TD) { throw new Error("Cannot find table column of index '" + col + "'"); } return TD.offsetWidth; } /** * Returns row height for HOT container * @param $elem * @param row * @returns {Number} */ function rowHeight($elem, row) { var TD = $elem[0].querySelector('tbody tr:nth-child(' + (row + 1) +') td'); if (!TD) { throw new Error("Cannot find table row of index '" + row + "'"); } var height = Handsontable.Dom.outerHeight(TD); if(row == 0) { height = height - 2; } else { height = height - 1; } return height; } /** * Returns value that has been rendered in table cell * @param {Number} trIndex * @param {Number} tdIndex * @returns {String} */ function getRenderedValue(trIndex, tdIndex) { return spec().$container.find('tbody tr').eq(trIndex).find('td').eq(tdIndex).html(); } /** * Returns nodes that have been rendered in table cell * @param {Number} trIndex * @param {Number} tdIndex * @returns {String} */ function getRenderedContent(trIndex, tdIndex) { return spec().$container.find('tbody tr').eq(trIndex).find('td').eq(tdIndex).children() } /** * Model factory, which creates object with private properties, accessible by setters and getters. * Created for the purpose of testing HOT with Backbone-like Models * @param opts * @returns {{}} * @constructor */ function Model(opts) { var obj = {}; var _data = $.extend({ id: undefined, name: undefined, address: undefined }, opts); obj.attr = function (name, value) { if (typeof value == 'undefined') { return this.get(name); } else { return this.set(name, value); } }; obj.get = function (name) { return _data[name]; }; obj.set = function (name, value) { _data[name] = value; return this; } return obj; } /** * Factory which produces an accessor for objects of type "Model" (see above). * This function should be used to create accessor for a given property name and pass it as `data` option in column * configuration. * * @param name - name of the property for which an accessor function will be created * @returns {Function} */ function createAccessorForProperty(name) { return function (obj, value) { return obj.attr(name, value); } }
"use strict"; const favicon = require("serve-favicon"); const bodyParser = require("body-parser"); const express = require("express"); const path = require("path"); const cors = require("cors")({ origin: "*", methods: "GET,POST,OPTIONS", allowedHeaders: "X-Requested-With, Content-Type, Accept, Origin" }); module.exports = (app, config) => { app.enable("trust proxy"); app.disable("x-powered-by"); app.set("views", path.join(config.root, "app/views")); app.set("view engine", "ejs"); // Should be handled by webserver in production if (config.env !== "production") { app.use(favicon("public/favicon.ico")); app.use(express.static(path.join(config.root, "/public"))); } app.use(cors); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); };
/* globals console, Mustache */ let _nails_forms = function() { var base = this; // -------------------------------------------------------------------------- base.__construct = function() { // @todo: move into CDN module base.initMultiFiles(); base.initCharCounters(); }; // -------------------------------------------------------------------------- base.initMultiFiles = function() { // Add new rows to the picker $(document) .on('click', '.js-cdn-multi-action-add', function() { base.log('MultiFile: Adding Row'); var _parent = $(this).closest('.field'); var _existing = _parent.data('items') || []; var newItem = { 'id': null, 'object_id': null, }; newItem[_parent.data('label-key')] = null; _existing.push(newItem); _parent.data('items', _existing); base.renderMultFiles(_parent, _existing); return false; }); // Remove a row from the picker $(document) .on('click', '.js-cdn-multi-action-remove', function() { base.log('MultiFile: Removing Row'); var _removeIndex = $(this).data('index'); var _parent = $(this).closest('.field'); var _existing = _parent.data('items') || []; var _newItems = []; for (var i = 0; i < _existing.length; i++) { if (i !== _removeIndex) { _newItems.push(_existing[i]); } } base.renderMultFiles(_parent, _newItems); _parent.data('items', _newItems); return false; }); // Apply listeners to any existing multifile $('.field.cdn-multi').each(function() { var _defaults = $(this).data('defaults'); var _labelKey = $(this).data('label-key'); $(this) .data('items', _defaults) .data('label-key', _labelKey); // CDN Picker $(this).find('.cdn-object-picker') .on('picked', function() { base.multiCdnPicked($(this)); }); // Label $(this).find('.js-label') .on('keyup', function() { base.multiLabelChanged($(this)); }); }); }; base.renderMultFiles = function(element, items) { base.log('MultiFile: Rendering', items); var _target = element.find('.js-row-target'); var _tpl = element.children('.js-row-tpl').html(); var _render = ''; _target.empty(); for (var i = 0; i < items.length; i++) { // Prepare the object items[i].index = i; // Render the HTML _render = Mustache.render(_tpl, items[i]); // Apply listeners _render = $(_render); _render.find('.cdn-object-picker') .on('picked', function() { base.multiCdnPicked($(this)); }); _render.find('.js-label') .on('keyup', function() { base.multiLabelChanged($(this)); }); // Add to the target _target.append(_render); } // Init the CDN Pickers window.NAILS.ADMIN.getInstance('ObjectPicker', 'nails/module-cdn').initPickers(); }; // -------------------------------------------------------------------------- base.multiCdnPicked = function(element) { var _updateIndex = element.data('index'); var _parent = element.closest('.field'); var _existing = _parent.data('items') || []; for (var i = 0; i < _existing.length; i++) { if (i === _updateIndex) { base.log('Updating object ID to ' + element.find('.cdn-object-picker__input').val()); base.log('At index: ' + _updateIndex); _existing[i].object_id = parseInt(element.find('.cdn-object-picker__input').val(), 10) || null; break; } } _parent.data('items', _existing); }; // -------------------------------------------------------------------------- base.multiLabelChanged = function(element) { var _updateIndex = element.data('index'); var _parent = element.closest('.field'); var _existing = _parent.data('items') || []; for (var i = 0; i < _existing.length; i++) { if (i === _updateIndex) { base.log('Updating label'); _existing[i][_parent.data('label-key')] = element.val(); break; } } _parent.data('items', _existing); }; // -------------------------------------------------------------------------- base.initCharCounters = function() { $('.field .char-count:not(.counting)').each(function() { var counter = $(this); var maxLength = counter.data('max-length'); var field = $(this).closest('.field'); var input = $(this).closest('.input').find('.field-input'); if (input.length) { input.on('keyup', function() { var length = $(this).val().length; if (length > maxLength) { field.addClass('max-length-exceeded'); } else { field.removeClass('max-length-exceeded'); } counter.html(length + ' of ' + maxLength + ' characters'); }).trigger('keyup'); } counter.addClass('counting'); }); }; // -------------------------------------------------------------------------- /** * Write a log to the console * @param {String} message The message to log * @param {mixed} payload Any additional data to display in the console * @return {void} */ base.log = function(message, payload) { if (typeof (console.log) === 'function') { if (payload !== undefined) { console.log('Nails Forms:', message, payload); } else { console.log('Nails Forms:', message); } } }; // -------------------------------------------------------------------------- /** * Write a warning to the console * @param {String} message The message to warn * @param {mixed} payload Any additional data to display in the console * @return {void} */ base.warn = function(message, payload) { if (typeof (console.warn) === 'function') { if (payload !== undefined) { console.warn('Nails Forms:', message, payload); } else { console.warn('Nails Forms:', message); } } }; // -------------------------------------------------------------------------- return base.__construct(); }();
'use strict'; var browserSync = require('browser-sync'); var gulp = require('gulp'); gulp.task('serve:stage', ['build:prod'], function () { browserSync.init(['./build/app/**'], { server: { baseDir: './build/app' }, injectChanges: false, files: ['./build/app/js/**/*.js', './build/app/css/*.css', './build/app/*.html'] }); });
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { /** * Created by YU on 2015/7/30. */ document.write('<h1>hello world!</h1>'); /***/ } /******/ ]);
/** * @module scroll-spec * @author yiminghe@gmail.com */ KISSY.use("dd/base,dd/plugin/constrain", function (S, DD, Constrain) { var Draggable = DD.Draggable, Gesture= S.Event.Gesture, $ = S.all; window.scrollTo(0, 0); var ie = document['documentMode'] || S.UA['ie']; describe("constrain", function () { var node = $("<div style='width:100px;height:200px;" + "position: absolute;left:0;top:0;'>" + "</div>") .appendTo("body"); var container = $("<div style='width:300px;height:500px;" + "position: absolute;left:0;top:0;'>" + "</div>") .prependTo("body"); var draggable = new Draggable({ node: node, move: 1, groups:false }); var constrain = new Constrain({ constrain: container }); draggable.plug(constrain); it("works for node", function () { node.css({ left: 0, top: 0 }); constrain.set("constrain", container); jasmine.simulateForDrag(node[0], Gesture.start, { clientX: 10, clientY: 10 }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 30, clientY: 30 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 500, clientY: 500 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.end, { clientX: 500, clientY: 500 }); }); waits(100); runs(function () { expect(node.css("left")).toBe("200px"); expect(node.css("top")).toBe("300px"); }); }); it("works for window", function () { node.css({ left: 0, top: 0 }); constrain.set("constrain", window); var win = $(window); jasmine.simulateForDrag(node[0], Gesture.start, { clientX: 10, clientY: 10 }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 30, clientY: 30 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.end, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { expect(parseInt(node.css("left"))).toBe(win.width() - 100); expect(parseInt(node.css("top"))).toBe(win.height() - 200); }); }); it("works for window (true constrain)", function () { node.css({ left: 0, top: 0 }); constrain.set("constrain", true); var win = $(window); jasmine.simulateForDrag(node[0], Gesture.start, { clientX: 10, clientY: 10 }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 30, clientY: 30 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.end, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { expect(parseInt(node.css("left"))).toBe(win.width() - 100); expect(parseInt(node.css("top"))).toBe(win.height() - 200); }); }); it("can be freed (false constrain)", function () { node.css({ left: 0, top: 0 }); constrain.set("constrain", false); jasmine.simulateForDrag(node[0], Gesture.start, { clientX: 10, clientY: 10 }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 30, clientY: 30 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.end, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { expect(parseInt(node.css("left"))).toBe(5490); expect(parseInt(node.css("top"))).toBe(5490); }); }); it("can be freed (detach)", function () { node.css({ left: 0, top: 0 }); constrain.set("constrain", true); draggable.unplug(constrain); jasmine.simulateForDrag(node[0], Gesture.start, { clientX: 10, clientY: 10 }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 30, clientY: 30 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.move, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { jasmine.simulateForDrag(document, Gesture.end, { clientX: 5500, clientY: 5500 }); }); waits(100); runs(function () { expect(parseInt(node.css("left"))).toBe(5490); expect(parseInt(node.css("top"))).toBe(5490); }); }); }); });
import * as React from 'react'; import PropTypes from 'prop-types'; import NextLink from 'next/link'; import { useRouter } from 'next/router'; import Button from '@mui/material/Button'; import Divider from '@mui/material/Divider'; import { styled, alpha } from '@mui/material/styles'; import List from '@mui/material/List'; import Drawer from '@mui/material/Drawer'; import Menu from '@mui/material/Menu'; import MenuItem from '@mui/material/MenuItem'; import Typography from '@mui/material/Typography'; import SwipeableDrawer from '@mui/material/SwipeableDrawer'; import useMediaQuery from '@mui/material/useMediaQuery'; import Box from '@mui/material/Box'; import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils'; import SvgMuiLogo from 'docs/src/icons/SvgMuiLogo'; import DiamondSponsors from 'docs/src/modules/components/DiamondSponsors'; import AppNavDrawerItem from 'docs/src/modules/components/AppNavDrawerItem'; import { pageToTitleI18n } from 'docs/src/modules/utils/helpers'; import PageContext from 'docs/src/modules/components/PageContext'; import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n'; import ArrowDropDownRoundedIcon from '@mui/icons-material/ArrowDropDownRounded'; import DoneRounded from '@mui/icons-material/DoneRounded'; import FEATURE_TOGGLE from 'docs/src/featureToggle'; import IconImage from 'docs/src/components/icon/IconImage'; import Link from 'docs/src/modules/components/Link'; import ROUTES from 'docs/src/route'; import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'; import materialPkgJson from '../../../../packages/mui-material/package.json'; import basePkgJson from '../../../../packages/mui-base/package.json'; import systemPkgJson from '../../../../packages/mui-system/package.json'; const savedScrollTop = {}; const LinksWrapper = styled('div')(({ theme }) => { return { paddingLeft: theme.spacing(5.5), paddingTop: theme.spacing(1), display: 'flex', flexDirection: 'column', '& > a': { display: 'flex', justifyContent: 'space-between', paddingTop: theme.spacing(0.5), paddingBottom: theme.spacing(0.5), paddingLeft: theme.spacing(1), paddingRight: theme.spacing(1), borderRadius: theme.shape.borderRadius, fontWeight: 500, fontSize: theme.typography.pxToRem(14), color: theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600], '&:hover': { backgroundColor: theme.palette.mode === 'dark' ? alpha(theme.palette.primaryDark[700], 0.4) : theme.palette.grey[50], }, '& svg': { width: 18, height: 18, }, }, }; }); function ProductSubMenu(props) { return ( <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2, }} > <Box sx={{ '& circle': { fill: (theme) => theme.palette.mode === 'dark' ? theme.palette.primaryDark[700] : theme.palette.grey[100], }, }} > {props.icon} </Box> <div> <Typography color="text.primary" variant="body2" fontWeight="700"> {props.name} </Typography> <Typography color="text.secondary" variant="body2"> {props.description} </Typography> </div> </Box> ); } ProductSubMenu.propTypes = { description: PropTypes.string, icon: PropTypes.element, name: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), }; function ProductDrawerButton(props) { const [anchorEl, setAnchorEl] = React.useState(null); const open = Boolean(anchorEl); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; return ( <React.Fragment> <Button id="mui-product-selector" aria-controls="drawer-open-button" aria-haspopup="true" aria-expanded={open ? 'true' : undefined} onClick={handleClick} endIcon={<ArrowDropDownRoundedIcon fontSize="small" sx={{ ml: -0.5 }} />} sx={(theme) => ({ py: 0.1, minWidth: 0, fontSize: theme.typography.pxToRem(13), fontWeight: 500, color: theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600], '& svg': { ml: -0.6, width: 18, height: 18, }, })} > {props.productName} </Button> <Menu id="mui-product-menu" anchorEl={anchorEl} open={open} onClose={handleClose} MenuListProps={{ 'aria-labelledby': 'mui-product-selector', }} PaperProps={{ sx: { width: { xs: 310, sm: 360 }, overflow: 'hidden', borderRadius: '10px', borderColor: (theme) => theme.palette.mode === 'dark' ? 'primaryDark.700' : 'grey.200', bgcolor: (theme) => theme.palette.mode === 'dark' ? 'primaryDark.900' : 'background.paper', boxShadow: (theme) => `0px 4px 20px ${ theme.palette.mode === 'dark' ? 'rgba(0, 0, 0, 0.5)' : 'rgba(170, 180, 190, 0.3)' }`, '& ul': { margin: 0, padding: 0, listStyle: 'none', }, '& li:not(:last-of-type)': { borderBottom: '1px solid', borderColor: (theme) => theme.palette.mode === 'dark' ? alpha(theme.palette.primary[100], 0.08) : theme.palette.grey[100], }, '& a': { textDecoration: 'none' }, '& li': { p: 2, }, }, }} > <li role="none"> <ProductSubMenu role="menuitem" icon={<IconImage name="product-core" />} name="MUI Core" description="Ready-to-use foundational components, free forever." /> <LinksWrapper> <Link href={ROUTES.baseDocs} // eslint-disable-next-line material-ui/no-hardcoded-labels > MUI Base <KeyboardArrowRight fontSize="small" /> </Link> <Link href={ROUTES.materialDocs} // eslint-disable-next-line material-ui/no-hardcoded-labels > Material UI <KeyboardArrowRight fontSize="small" /> </Link> <Link href={ROUTES.systemDocs} // eslint-disable-next-line material-ui/no-hardcoded-labels > MUI System <KeyboardArrowRight fontSize="small" /> </Link> </LinksWrapper> </li> <li role="none"> <ProductSubMenu role="menuitem" icon={<IconImage name="product-advanced" />} name={ <Box component="span" display="inline-flex" alignItems="center" // eslint-disable-next-line material-ui/no-hardcoded-labels > MUI&nbsp;X </Box> } description="Advanced and powerful components for complex use-cases." /> <LinksWrapper> <Link href={ROUTES.dataGridDocs} // eslint-disable-next-line material-ui/no-hardcoded-labels > Data Grid <KeyboardArrowRight fontSize="small" /> </Link> </LinksWrapper> </li> </Menu> </React.Fragment> ); } ProductDrawerButton.propTypes = { productName: PropTypes.string, }; const ProductIdentifier = ({ name, metadata, versionSelector }) => ( <Box sx={{ flexGrow: 1 }}> <Typography sx={(theme) => ({ ml: 1, color: theme.palette.grey[600], fontSize: theme.typography.pxToRem(11), fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08rem', })} > {metadata} </Typography> <Box sx={{ display: 'flex' }}> <ProductDrawerButton productName={name} /> {versionSelector} </Box> </Box> ); ProductIdentifier.propTypes = { metadata: PropTypes.string, name: PropTypes.string, versionSelector: PropTypes.element, }; function PersistScroll(props) { const { slot, children, enabled } = props; const rootRef = React.useRef(); useEnhancedEffect(() => { const parent = rootRef.current ? rootRef.current.parentElement : null; const activeElement = parent.querySelector('.app-drawer-active'); if (!enabled || !parent || !activeElement || !activeElement.scrollIntoView) { return undefined; } parent.scrollTop = savedScrollTop[slot]; const activeBox = activeElement.getBoundingClientRect(); if (activeBox.top < 0 || activeBox.top > window.innerHeight) { parent.scrollTop += activeBox.top - 8 - 32; } return () => { savedScrollTop[slot] = parent.scrollTop; }; }, [enabled, slot]); return <div ref={rootRef}>{children}</div>; } PersistScroll.propTypes = { children: PropTypes.node.isRequired, enabled: PropTypes.bool.isRequired, slot: PropTypes.string.isRequired, }; // https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items const ToolbarIE11 = styled('div')({ display: 'flex' }); const ToolbarDiv = styled('div')(({ theme }) => { return { padding: theme.spacing(1.45, 2), paddingRight: 0, height: 'var(--MuiDocs-header-height)', display: 'flex', flexGrow: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }; }); const StyledDrawer = styled(Drawer)(({ theme }) => { return { [theme.breakpoints.up('xs')]: { display: 'none', }, [theme.breakpoints.up('lg')]: { display: 'block', }, }; }); const SwipeableDrawerPaperComponent = styled('div')(({ theme }) => { return { width: 'var(--MuiDocs-navDrawer-width)', boxShadow: 'none', [theme.breakpoints.up('xs')]: { borderRadius: '0px 10px 10px 0px', }, [theme.breakpoints.up('sm')]: { borderRadius: '0px', }, }; }); function renderNavItems(options) { const { pages, ...params } = options; return ( <List disablePadding> {pages.reduce( // eslint-disable-next-line @typescript-eslint/no-use-before-define (items, page) => reduceChildRoutes({ items, page, ...params }), [], )} </List> ); } /** * @param {object} context * @param {import('docs/src/pages').MuiPage} context.page */ function reduceChildRoutes(context) { const { onClose, activePage, items, depth, t } = context; let { page } = context; if (page.ordered === false) { return items; } if (page.children && page.children.length >= 1) { const title = pageToTitleI18n(page, t); const topLevel = activePage ? activePage.pathname.indexOf(`${page.pathname}`) === 0 || page.scopePathnames?.some((pathname) => activePage.pathname.includes(pathname)) : false; items.push( <AppNavDrawerItem linkProps={page.linkProps} depth={depth} key={title} topLevel={topLevel && !page.subheader} openImmediately={topLevel || Boolean(page.subheader)} title={title} legacy={page.legacy} icon={page.icon} > {renderNavItems({ onClose, pages: page.children, activePage, depth: depth + 1, t })} </AppNavDrawerItem>, ); } else { const title = pageToTitleI18n(page, t); page = page.children && page.children.length === 1 ? page.children[0] : page; items.push( <AppNavDrawerItem linkProps={page.linkProps} depth={depth} key={title} title={title} href={page.pathname} legacy={page.legacy} onClick={onClose} icon={page.icon} />, ); } return items; } // iOS is hosted on high-end devices. We can enable the backdrop transition without // dropping frames. The performance will be good enough. // So: <SwipeableDrawer disableBackdropTransition={false} /> const iOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent); function AppNavDrawer(props) { const { className, disablePermanent, mobileOpen, onClose, onOpen } = props; const { activePage, pages } = React.useContext(PageContext); const router = useRouter(); const [anchorEl, setAnchorEl] = React.useState(null); const userLanguage = useUserLanguage(); const languagePrefix = userLanguage === 'en' ? '' : `/${userLanguage}`; const t = useTranslate(); const mobile = useMediaQuery((theme) => theme.breakpoints.down('lg')); const drawer = React.useMemo(() => { const isProductScoped = router.asPath.startsWith('/x') || router.asPath.startsWith('/material') || (router.asPath.startsWith('/system') && FEATURE_TOGGLE.enable_system_scope) || router.asPath.startsWith('/base'); const navItems = renderNavItems({ onClose, pages, activePage, depth: 0, t }); const renderVersionSelector = (versions = [], sx) => { if (!versions?.length) { return null; } return ( <React.Fragment> <Button id="mui-version-selector" onClick={(event) => { setAnchorEl(event.currentTarget); }} endIcon={ versions.length > 1 ? ( <ArrowDropDownRoundedIcon fontSize="small" sx={{ ml: -0.5 }} /> ) : null } sx={[ (theme) => ({ py: 0.1, minWidth: 0, fontSize: theme.typography.pxToRem(13), fontWeight: 500, color: theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600], '& svg': { ml: -0.6, width: 18, height: 18, }, ...(!isProductScoped && { px: 1, py: 0.4, border: `1px solid ${ theme.palette.mode === 'dark' ? theme.palette.primaryDark[700] : theme.palette.grey[200] }`, '&:hover': { borderColor: theme.palette.mode === 'dark' ? theme.palette.primaryDark[600] : theme.palette.grey[300], background: theme.palette.mode === 'dark' ? alpha(theme.palette.primaryDark[700], 0.4) : theme.palette.grey[50], }, }), }), ...(Array.isArray(sx) ? sx : [sx]), ]} > {versions[0].text} </Button> <Menu id="mui-version-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={() => setAnchorEl(null)} > {versions.map((item) => ( <MenuItem key={item.text} {...(item.current ? { selected: true, onClick: () => setAnchorEl(null), } : { component: 'a', href: item.href, onClick: onClose, })} > {item.text} {item.current && <DoneRounded sx={{ fontSize: 16, ml: 0.25 }} />} </MenuItem> ))} {versions.length > 1 && [ <Divider key="divider" />, <MenuItem key="all-versions" component="a" href={`https://mui.com${languagePrefix}/versions/`} onClick={onClose} > {/* eslint-disable-next-line material-ui/no-hardcoded-labels -- version string is untranslatable */} {`View all versions`} </MenuItem>, ]} </Menu> </React.Fragment> ); }; return ( <React.Fragment> <ToolbarIE11> <ToolbarDiv> <NextLink href="/" passHref onClick={onClose}> <Box component="a" aria-label={t('goToHome')} sx={{ pr: 2, mr: 1, borderRight: isProductScoped ? '1px solid' : '0px', borderColor: (theme) => theme.palette.mode === 'dark' ? alpha(theme.palette.primary[100], 0.08) : theme.palette.grey[200], }} > <SvgMuiLogo width={30} /> </Box> </NextLink> {!isProductScoped && renderVersionSelector( [ { text: `v${process.env.LIB_VERSION}`, current: true }, { text: 'v4', href: `https://v4.mui.com${languagePrefix}/` }, ], { mr: 2 }, )} {router.asPath.startsWith('/material/') && ( <ProductIdentifier name="Material UI" metadata="MUI Core" versionSelector={renderVersionSelector([ { text: `v${materialPkgJson.version}`, current: true }, { text: 'v4', href: `https://v4.mui.com${languagePrefix}/getting-started/installation/`, }, ])} /> )} {router.asPath.startsWith('/system/') && FEATURE_TOGGLE.enable_system_scope && ( <ProductIdentifier name="MUI System" metadata="MUI Core" versionSelector={renderVersionSelector([ { text: `v${systemPkgJson.version}`, current: true }, { text: 'v4', href: `https://v4.mui.com${languagePrefix}/system/basics/` }, ])} /> )} {router.asPath.startsWith('/base/') && ( <ProductIdentifier name="MUI Base" metadata="MUI Core" versionSelector={renderVersionSelector([ { text: `v${basePkgJson.version}`, current: true }, ])} /> )} {(router.asPath.startsWith('/x/react-data-grid') || router.asPath.startsWith('/x/api/data-grid')) && ( <ProductIdentifier name="Data Grid" metadata="MUI X" versionSelector={renderVersionSelector([ // LIB_VERSION is set from the X repo { text: `v${process.env.LIB_VERSION}`, current: true }, { text: 'v4', href: `https://v4.mui.com${languagePrefix}/components/data-grid/` }, ])} /> )} </ToolbarDiv> </ToolbarIE11> <Divider sx={{ borderColor: (theme) => theme.palette.mode === 'dark' ? alpha(theme.palette.primary[100], 0.08) : theme.palette.grey[100], }} /> <DiamondSponsors spot="drawer" /> {navItems} <Box sx={{ height: 40 }} /> </React.Fragment> ); }, [activePage, pages, onClose, languagePrefix, t, anchorEl, setAnchorEl, router.asPath]); return ( <nav className={className} aria-label={t('mainNavigation')}> {disablePermanent || mobile ? ( <SwipeableDrawer disableBackdropTransition={!iOS} variant="temporary" open={mobileOpen} onOpen={onOpen} onClose={onClose} ModalProps={{ keepMounted: true, }} PaperProps={{ className: 'algolia-drawer', component: SwipeableDrawerPaperComponent, sx: { background: (theme) => theme.palette.mode === 'dark' ? theme.palette.primaryDark[900] : '#FFF', }, }} > <PersistScroll slot="swipeable" enabled={mobileOpen}> {drawer} </PersistScroll> </SwipeableDrawer> ) : null} {disablePermanent || mobile ? null : ( <StyledDrawer variant="permanent" PaperProps={{ component: SwipeableDrawerPaperComponent, sx: { background: (theme) => theme.palette.mode === 'dark' ? theme.palette.primaryDark[900] : '#fff', borderColor: (theme) => theme.palette.mode === 'dark' ? alpha(theme.palette.primary[100], 0.08) : theme.palette.grey[100], }, }} open > <PersistScroll slot="side" enabled> {drawer} </PersistScroll> </StyledDrawer> )} </nav> ); } AppNavDrawer.propTypes = { className: PropTypes.string, disablePermanent: PropTypes.bool.isRequired, mobileOpen: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, onOpen: PropTypes.func.isRequired, }; export default AppNavDrawer;
{ switch (B.length) { case 1: return encloseBasis1(B[0]); case 2: return encloseBasis2(B[0], B[1]); case 3: return encloseBasis3(B[0], B[1], B[2]); } }
'use strict'; var express = require('express'), path = require('path'), fs = require('fs'), mongoose = require('mongoose'), passport = require('passport'); /** * Main application file */ // Default node environment to development process.env.NODE_ENV = process.env.NODE_ENV || 'development'; // Application Config var config = require('./lib/config/config'); // Connect to database var db = mongoose.connect(config.mongo.uri, config.mongo.options); // Bootstrap models var modelsPath = path.join(__dirname, 'lib/models'); fs.readdirSync(modelsPath).forEach(function (file) { require(modelsPath + '/' + file); }); // Populate empty DB with sample data //require('./lib/config/dummydata'); var app = express(); //Passport settings require('./lib/config/passport')(passport, config); // Express settings require('./lib/config/express')(app); // Routing require('./lib/routes')(app, passport); // Start server app.listen(config.port, function () { console.log('Express server listening on port %d in %s mode', config.port, app.get('env')); }); // Pusher //var pusher = require('./lib/config/pusher'); // Expose app exports = module.exports = app;
export default target => typeof target === "object" && target !== null && target.cheerio && "length" in target;
import { inject as service } from '@ember/service'; import fetch from 'fetch'; import Component from '@ember/component'; import { isPresent } from '@ember/utils'; import vkbeautify from 'vkbeautify'; import ENV from 'bracco/config/environment'; import FileReader from 'ember-file-upload/system/file-reader'; export default Component.extend({ currentUser: service(), tagName: 'div', hasMetadata: false, metadata: null, output: null, summary: true, didReceiveAttrs() { this._super(...arguments); // show metadata if at least one of these attributes is set if (isPresent(this.get('model.publicationYear')) || isPresent(this.get('model.titles')) || isPresent(this.get('model.publisher')) || isPresent(this.get('model.creators')) || this.get('model.types') instanceof Object && !!this.get('model.types.resourceTypeGeneral') || this.get('model.types') instanceof Object && !!this.get('model.types.resourceType')) { this.set('hasMetadata', true); } let formats = { 'summary': 'Summary View', 'datacite': 'DataCite XML', 'datacite_json': 'DataCite JSON', 'schema_org': 'Schema.org JSON-LD', 'citeproc': 'Citeproc JSON', 'codemeta': 'Codemeta JSON', 'bibtex': 'BibTeX', 'ris': 'RIS', 'jats': 'JATS XML' }; this.set('formats', formats); }, showMetadata(metadata) { if (metadata === 'summary') { this.set('output', false); } else { this.set('output', null); let self = this; let url = ENV.API_URL + '/dois/' + this.model.get('doi'); let acceptHeaders = { 'datacite': 'application/vnd.datacite.datacite+xml', 'datacite_json': 'application/vnd.datacite.datacite+json', 'schema_org': 'application/vnd.schemaorg.ld+json', 'citeproc': 'application/vnd.citationstyles.csl+json', 'codemeta': 'application/vnd.codemeta.ld+json', 'bibtex': 'application/x-bibtex', 'ris': 'application/x-research-info-systems', 'jats': 'application/vnd.jats+xml' }; let headers = { 'Accept': acceptHeaders[metadata] }; if (this.currentUser.get('jwt')) { headers = { 'Authorization': 'Bearer ' + this.currentUser.get('jwt'), 'Accept': acceptHeaders[metadata], }; } let result = fetch(url, { headers, }).then(function(response) { if (response.ok) { return response.blob(); } else { return response.statusText; } }); result.then(function(response) { if (typeof response === 'string') { self.set('output', vkbeautify.json(JSON.stringify(response))); } else { let reader = new FileReader(); reader.readAsText(response).then((result) => { self.set('output', vkbeautify.xml(result)); }, (err) => { console.error(err); }); } }); } // this.get('router').transitionTo({ queryParams: { metadata: metadata } }); }, actions: { selectMetadata(metadata) { this.showMetadata(metadata); }, }, });
'use strict'; const Command = require('../../Command.js'); const ConclaveChallengeEmbed = require('../../embeds/ConclaveChallengeEmbed.js'); const values = ['all', 'day', 'week']; /** * Displays the currently active Invasions */ class ConclaveChallenges extends Command { /** * Constructs a callable command * @param {Genesis} bot The bot object */ constructor(bot) { super(bot, 'warframe.worldstate.conclaveChallenges', 'conclave', 'Gets the current conclave challenges for a category of challenge, or all.'); this.regex = new RegExp(`^${this.call}(?:\\s+(${values.join('|')}))?(?:\\s+on\\s+([pcsxb14]{2,3}))?$`, 'i'); this.usages = [ { description: 'Display conclave challenges for a challenge type.', parameters: ['conclave category'], }, ]; } async run(message) { const matches = message.strippedContent.match(this.regex); const param1 = (matches[1] || '').toLowerCase(); const param2 = (matches[2] || '').toLowerCase(); const category = values.indexOf(param1) > -1 ? param1 : 'all'; let platformParam; if (this.platforms.indexOf(param2) > -1) { platformParam = param2; } else if (this.platforms.indexOf(param1) > -1) { platformParam = param1; } const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.worldStates[platform].getData(); const conclaveChallenges = ws.conclaveChallenges; const embed = new ConclaveChallengeEmbed(this.bot, conclaveChallenges, category, platform); await this.messageManager.embed(message, embed, true, false); return this.messageManager.statuses.SUCCESS; } } module.exports = ConclaveChallenges;
var BEM = require('bem'), Q = BEM.require('q'), PATH = require('path'), FS = require('fs'), shmakowiki = require('shmakowiki'), MD = require('marked'), HL = require('highlight.js'), mkdirp = require('mkdirp'); process.env.YENV = 'production'; process.env.BEM_I18N_LANGS = 'en ru'; process.env.SHMAKOWIKI_HL = 'server'; function processMarkdown(src) { var langs = {}; return MD(src, { gfm: true, pedantic: false, sanitize: false, highlight: function(code, lang) { if (!lang) return code; var res = HL.highlight(translateAlias(lang), code); langs[lang] = res.language; return res.value; } }) .replace(/<pre><code class="lang-(.+?)">([\s\S]+?)<\/code><\/pre>/gm, function(m, lang, code) { return '<pre class="highlight"><code class="highlight__code ' + langs[lang] + '">' + code + '</code></pre>'; }); } function translateAlias(alias) { var lang = alias; switch (alias) { case 'js': lang = 'javascript'; break; case 'patch': lang = 'diff'; break; case 'md': lang = 'markdown'; break; case 'html': lang = 'xml'; break; case 'HTML': lang = 'xml'; break; case 'sh': lang = 'bash'; break; } return lang; } /** @name MAKE */ MAKE.decl('BundleNode', { getTechs: function() { var techs = [ 'bemjson.js', 'bemdecl.js', 'deps.js' ]; if (PATH.basename(this.level.dir) === 'bundles-desktop') { return techs.concat([ 'css', 'ie.css', 'js' ]); } return techs.concat([ 'bemhtml', 'html' ]); } }); MAKE.decl('Arch', { getLibraries: function() { return { 'bem-bl': { type: 'git', url: 'git://github.com/bem/bem-bl.git', treeish: '0.3' }, 'content/bem-core': { type: 'git', url: 'git://github.com/bem/bem-core.git', branch: 'v1', npmPackages: false }, 'content/bem-method': { type: 'git', url: 'git://github.com/bem/bem-method.git', npmPackages: false }, 'content/bem-tools': { type: 'git', url: 'git://github.com/bem/bem-tools.git', treeish: 'dev', npmPackages: false }, 'content/csso': { type: 'git', url: 'git://github.com/css/csso.git', npmPackages: false }, 'content/borschik': { type: 'git', url: 'git://github.com/bem/borschik.git', npmPackages: false }, 'content/borschik-server': { type: 'git', url: 'git://github.com/bem/borschik-server.git', treeish: 'bem.info' }, 'content/articles/bem-articles': { type: 'git', url: 'git://github.com/bem/bem-articles.git', npmPackages: false }, 'content/articles/firm-card-story': { type: 'git', url: 'git://github.com/AndreyGeonya/firmCardStory.git', npmPackages: false }, 'content/blog/bem-news': { type: 'git', url: 'git://github.com/mursya/bem-news.git', npmPackages: false } }; }, createCustomNodes: function(common, libs, blocks, bundles) { var node = new (MAKE.getNodeClass('PagesGeneratorNode'))({ id: 'pages-generator', root: this.root, sources: ['bem-method', 'tools', 'bem-tools/docs', 'csso/docs', 'borschik/docs', 'borschik-server/docs', 'articles/bem-articles', 'articles/firm-card-story/docs', 'blog', 'blog/bem-news', 'bem-core/common.docs', 'pages', 'jobs'] }); this.arch.setNode(node, bundles, libs); return node.getId(); } }); MAKE.decl('PagesGeneratorNode', 'Node', { __constructor: function(o) { this.root = o.root; this.sources = o.sources; this.__base(o); }, make: function() { // skip rebuild if this was already done in the same process // TODO: this will not with `bem server` if (this.done) return; var bundlesLevel = BEM.createLevel(PATH.resolve(this.root, 'pages-desktop')), _this = this, ctx = this.ctx, promises; promises = this.sources.reduce(function(res, source) { var level = BEM.createLevel(PATH.resolve(_this.root, 'content', source)); return res.concat(level.getItemsByIntrospection() .filter(function(item) { return BEM.util.bemType(item) === 'block' && ~['md', 'wiki'].indexOf(item.tech); }) //.reduce(BEM.util.uniq(BEM.util.bemKey), []) .map(function(item) { var suffix = item.suffix.substr(1), lang = suffix.split('.').shift(), page = { block: source.split('/').shift() + '-' + item.block + '-' + lang }, srcPath = PATH.join(level.getPathByObj(item, suffix)), outPath = PATH.join(bundlesLevel.getPathByObj(page, 'bemjson.js')); // return BEM.util.isFileValid(outPath, srcPath) // .then(function(valid) { // if (valid && !ctx.force) return; return BEM.util.readFile(srcPath) .then(function(src) { var pageContent = _this.getTemplateBemJson(item.block, source, lang), content = item.tech === 'wiki'? shmakowiki.shmakowikiToBemjson(src) : { block: 'b-text', mods: { 'type': 'global' }, content: processMarkdown(src) }; pageContent.content[1].content.push(content); mkdirp.sync('pages-desktop/' + page.block); var outContent = '(' + JSON.stringify(pageContent, null, 1) + ')'; return BEM.util.writeFile(outPath, outContent); }); // }); }, _this)); }, []); return Q.all(promises) .then(function() { _this.done = true; }); }, pagesConfig: function() { return JSON.parse(FS.readFileSync(PATH.resolve(this.root, 'content/pages-config.json'), 'utf8')); }, _navLevelIdx: 0, structureConfig: function() { return JSON.parse(FS.readFileSync(PATH.resolve(this.root, 'content/site-structure-config.json'), 'utf8')); }, getPageUrl: function(sourceDir, cfg) { cfg = cfg || this.structureConfig(); var children; for (var dir in cfg) { if (sourceDir == dir) return cfg[dir].url; children = (cfg[dir].children && this.getPageUrl(sourceDir, cfg[dir].children)); if (children) return children; } }, getCurrentPageInfo: function(sourceDir, lang) { lang = lang || 'en'; return this.pagesConfig()[lang][sourceDir] || { title: 'BEM: block, element, modificator', description: 'BEM is abbreviation for Block-Element-Modifier. It\'s a way to write code which is easy to support and develop.', keywords: 'bem, block, element, modifier, bemjson, bemhtml, i-bem, i-bem.js, borschik, bem tools, csso', menu: sourceDir.split('/').pop() }; }, getNavBemJson: function(cfg, sourceDir, lang) { var _this = this, navBemJson = [], currentDir, sub, level = ['first', 'second', 'third', 'fourth'], getMenuBemJson = function(mods) { _this._navLevelIdx++; return { block: 'b-menu-horiz', mods: { layout: 'normal' }, mix: [{ block: 'nav' , mods: mods }], js: false, content: [] }; }, currentNavLevelResult = getMenuBemJson({ level: level[_this._navLevelIdx] }), checkParent = function(dir, currentStructureLevel) { if (dir == sourceDir) return true; var children = currentStructureLevel[dir].children; if (!children) return false; for (var child in children) { if (child == sourceDir || checkParent(child, children)) return true; } return false; }; for (var dir in cfg) { var isParent = checkParent(dir, cfg), isCurrent = dir == sourceDir, title = this.getCurrentPageInfo(dir, lang).menu; isParent && (currentDir = dir); currentNavLevelResult.content.push({ elem: 'item', elemMods: isCurrent ? { state: 'current' } : isParent ? { state: 'parent' } : undefined, content: isCurrent ? title : { block: 'b-link', url: '/' + cfg[dir].url + '/', content: title } }); } navBemJson.push(currentNavLevelResult); sub = cfg[currentDir] ? cfg[currentDir].children : null; sub && navBemJson.push(this.getNavBemJson(sub, sourceDir, lang)); _this._navLevelIdx = 0; return navBemJson; }, getTemplateBemJson: function(pagename, source, lang) { /* * upyachka: * this.getNavBemJson returns array with two elements: * first element is first level menu * second element consists of second and third level menues */ var sourceDir = source + '/' + pagename, pageInfo = this.getCurrentPageInfo(sourceDir, lang), resourceFileName = '_' + source.split('/').shift() + '-' + pagename + '-' + lang, nav = this.getNavBemJson(this.structureConfig(), sourceDir, lang), mainNav = [], subNav = nav[1] ? nav[1][1] : '', langSwitcherContent = lang == 'ru' ? [{ block: 'b-link', url: '//bem.info/' + this.getPageUrl(sourceDir) + '/', content: 'English' }, ' | Русский' ] : [ 'English | ', { block: 'b-link', url: '//ru.bem.info/' + this.getPageUrl(sourceDir) + '/', content: 'Русский' } ]; mainNav.push(nav[0], nav[1] ? nav[1][0] : ''); return { block: 'b-page', title: pageInfo.title, favicon: '/favicon.ico', head: [ { elem: 'css', url: '/_inner.css' }, // { elem: 'css', url: '/bundles-desktop/inner/_inner.css', ie: false }, // { elem: 'css', url: '/bundles-desktop/inner/_inner', ie: true }, // { block: 'i-jquery', elem: 'core' }, // { elem: 'js', url: '/bundles-desktop/inner/_inner.js' }, { elem: 'meta', attrs: { name: 'description', content: pageInfo.description }}, { elem: 'meta', attrs: { name: 'keywords', content: pageInfo.keywords }} ], content: [ { block: 'header', content: [ { block: 'b-link', mix: [{ block: 'header', elem: 'logo' }], url: '/' }, { block: 'lang-switcher', content: langSwitcherContent }, mainNav ] }, { block: 'content', content: [subNav] }, { block: 'footer' }, { block: 'metrika' } ] }; } }, { createId: function(o) { return o.id; } });
var text_area_f_s = '\t' var text_area_s_s = '\n' text_area_bis = []; $(document).ready(function () { $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); // $('body').off('.data-api'); $("#messageButton").click(function () { $("#messageModal").modal('show'); getMessage("in", 0); readMessage(); }); $('#messageButton').popover({ html: true, placement: 'bottom', content: '<div>Новые сообщения</div>', trigger: 'manual' }); $('#messageModal').on('hidden', function () { $('#messageButton').popover('hide'); messCountTest(); }); messCountTest(); $('.back-btn').click(function () { window.history.back(); }); castPage(); $("#load_book_list").click(function () { $.ajax({ type: "POST", url: "/loadTextFormatBooks", dataType: "json", success: function (data) { printStickers(data.books); }, error: function () { serverError(); } }); }); $("#printStickers").click(function () { var node=$("#booksFormText .printable-div").clone(); node.find('.close').remove(); popup_print($('<div/>').append(node).html()); }); $(".slider").change(function () { $(".sticker").css(this.name, this.value + "px"); }); $(".slider-page").change(function () { $(".printable-div").css(this.name, this.value + "px"); }); $("#b-group-f-s button").click(function () { text_area_f_s = separatorConverter(this.value); $("#b-group-f-s input").val(""); setTextAreaBooks(); }); $("#b-group-f-s input").keyup(function () { text_area_f_s = this.value; $("#b-group-f-s button").removeClass("active"); setTextAreaBooks(); }); $("#b-group-s-s button").click(function () { text_area_s_s = separatorConverter(this.value); $("#b-group-s-s input").val(""); setTextAreaBooks(); }); $("#b-group-s-s input").keyup(function () { text_area_s_s = this.value; $("#b-group-s-s button").removeClass("active"); setTextAreaBooks(); }); $('#searchButton').click(function () { if ($("#searchInput").val().length > 0) { var testId = parseInt($("#searchInput").val()); if (!isNaN(testId)) { $.ajax({ url: "/searchById", type: "post", dataType: "json", data: JSON.stringify({"id": testId}), success: function (data) { if (data.info == 1) { window.location = data.location; } else { standardSearch(); } }, error: function () { serverError(); }, crossDomain: false }); } else { standardSearch(); } } else { search.word = ""; page.num = 1; tableReq(); } }); }); function standardSearch() { if (typeof local == "undefined"){ window.location="/#?" + $.param({'sew': $("#searchInput").val(), 'sep': "all", 'sot': 0, 'sof': "isbn", 'pan': 1}); } if (local!="home"){ window.location="/#?" + $.param({'sew': $("#searchInput").val(), 'sep': "all", 'sot': 0, 'sof': "isbn", 'pan': 1}); } search.word = $("#searchInput").val(); page.num = 1; tableReq(); } function separatorConverter(val) { var sep = " "; switch (val) { case "1": sep = "\t"; break; case "2": sep = "\n"; break; case "3": sep = ","; break; case "4": sep = "."; break; case "5": sep = " "; break; } return sep; } function messCountTest() { $.ajax({ type: "POST", url: "/countInMessage", dataType: "json", success: function (data) { if (data.count > 0) { $('#messageButton').popover('show'); } }, error: function () { serverError(); } }); } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function displayAlert(text, alert_class) { $(".alert-place").html('<div id="main-alert" class="alert"></div>'); $("#main-alert").addClass(alert_class); $("#main-alert").html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + text); } function notSignIn() { displayAlert("Войдите в систему", "alert-danger") } function serverError() { displayAlert("Проблемы соединения с сервером", "alert-danger") } function markGood(cg, text) { $(cg).removeClass("error"); $(cg).addClass("success"); $(cg + " .help-inline").html(text); } function markBad(cg, text) { $(cg).removeClass("success"); $(cg).addClass("error"); $(cg + " .help-inline").html(text); } function removeMark(cg) { $(cg).removeClass("success"); $(cg).removeClass("error"); $(cg + " .help-inline").html(''); } function getMessage(mType, isRead) { $.ajax({ type: "POST", url: "/getMessages", data: JSON.stringify({ 'mType': mType, 'isRead': isRead}), dataType: "json", success: function (data) { if (parseInt(data.info) == 1) { switch (mType) { case "in": addInMessage(data.messages); break; default: break; } } else if (parseInt(data.info) == 4) { notSignIn(); } }, error: function () { serverError(); } }); } function addInMessage(messages) { $("#table-msg .table-body").html(""); var k = messages.length; for (i = 0; i < k; i++) { $("#table-msg .table-body").prepend(formatMessage(messages[i], "in")); } } function formatMessage(mess) { listed = '<tr id="message_' + mess.id + '">'; listed += '<td>' + mess.book; if (mess.isRead==0){ listed += ' <span class="label label-info">new</span>'; } listed += '</td>'; listed += '<td>' + mess.personFrom + '</td>'; listed += '<td>' + mess.item_id + '</td>'; listed += '<td>' + (new Date(Date.parse(mess.date))).toLocaleString() + '</td>'; listed += '</td></tr>'; return listed; } function readMessage(){ $.ajax({ type: "POST", url: "/readMessage", data: JSON.stringify({ 'info': 1}), dataType: "json", success: function (data) { }, error: function () { serverError(); } }); } function popup_print(data) { var w = window.open(); w.document.write('<html><head>'); // w.document.write('<link rel="stylesheet" href="' + static_path + 'css/base.css" type="text/css" />'); w.document.write('</head><body >'); w.document.write(data); w.document.write('</body></html>'); w.print(); if (navigator.appName != 'Microsoft Internet Explorer') w.close(); return true; } function getUrlParams() { var url = document.URL.split('?')[1]; if (!url) { return null; } var url_params = {}; params = url.split('&'); for (var param in params) { url_params[params[param].split('=')[0]] = params[param].split('=')[1]; } return url_params; } function Sticker(lib_name, book_title, bi_id, person) { Sticker.width = 200; Sticker.height = 100; Sticker.margin_right = 0; Sticker.margin_bottom = 0; this.lib_name = lib_name; this.book_title = book_title; this.bi_id = bi_id; this.person = person; this.getHTML = function () { html_sticker = '<div class="sticker" style="font-family:sans-serif;display: inline-block;border:2px ' + 'solid #aaaaaa;border-radius: 4px;padding: 5px;">'; html_sticker +='<button type="button" class="close" data-dismiss="alert">&times;</button>'; html_sticker += '<div class="libname" style="font-weight: bold;text-align:' + ' center; font-style: italic;">' + this.lib_name + '</div>'; html_sticker += '<div style="font-size: 12px; white-space: nowrap; overflow:hidden; text-overflow: ellipsis;">' + this.book_title + '</div>'; html_sticker += '<div><span>id:&nbsp;&nbsp;</span><span class="biid" style="font-weight: bold; font-size: 19px">' + this.bi_id + '</span></div>'; html_sticker += '<div class="username">' + this.person + '</div>'; html_sticker += '</div>'; return html_sticker; } } function Person(id, name, email, phone_ext, mobile) { this.id = id; this.name = name; this.email = email; this.mobile = mobile; this.phone_ext = phone_ext; this.getHTML = function () { html_person = '<a class="Person" data-toggle="popover" data-placement="right"' + 'data-trigger="hover" data-content="' + '<table ' + '<tr>' + '<td style=\'border-top: none;\'>email:</td>' + '<td style=\'border-top: none;\'><a href=\'mailto:' + this.email + '\'>' + this.email + '</a></td>' + '</tr>' + '<tr>' + '<td style=\'border-top: none;\'>ext:</td>' + '<td style=\'border-top: none;\'>' + this.phone_ext + '</td>' + '</tr>' + '<tr>' + '<td style=\'border-top: none;\'>mobile:</td>' + '<td style=\'border-top: none;\'>' + this.mobile + '</td>' + '</tr>' + '</table>' + '">' + this.name + '</a>'; return html_person; } } function printStickers(books) { text_area_bis = books; setTextAreaBooks(); $(".printable-div").html(''); for (var i in books) { var sticker = new Sticker(books[i].libname, books[i].book_title, books[i].biid, books[i].owner); $("#booksFormText .printable-div").append(sticker.getHTML()); } updateSliders(); $("#booksFormText").modal('show'); } function setTextAreaBooks() { f_s = text_area_f_s; s_s = text_area_s_s; text_area = 'library' + f_s + 'id' + f_s + 'book' + f_s + 'owner' + s_s; for (var i in text_area_bis) { text_area += text_area_bis[i].libname + f_s + text_area_bis[i].book_title + f_s + text_area_bis[i].biid + f_s + text_area_bis[i].owner + s_s; } $("#text_format_books").html(text_area); } function updateSliders() { $('.slider[name="height"]').attr('value', Sticker.height); $('.slider[name="width"]').attr('value', Sticker.width); $('.slider[name="margin-right"]').attr('value', Sticker.margin_right); $('.slider[name="margin-bottom"]').attr('value', Sticker.margin_bottom); $('.slider-page[name="margin-top"]').attr('value', '0'); $('.slider-page[name="margin-left"]').attr('value', '0'); $(".slider").change(); $(".slider-page").change(); text_area_f_s = '\t' text_area_s_s = '\n' setTextAreaBooks(); }
/** * Módulo secundario donacionesApp.nuevoDonante. * Dependencias: ninguna. * @author Roberto Sottini <robysottini@gmail.com> */ (function() { 'use strict'; angular .module('donacionesApp.nuevoDonante', []); })();
const affairGroups = { "Wahlen": "1", "Geschäft des Bundesrates": "1", "Geschäft des Parlaments": "1", "Parlamentarische Initiative": "1", "Motion": "1", "Postulat": "2", "Dringliche Interpellation": "2", "Interpellation": "2", "Anfrage": "3", "Dringliche Anfrage": "3", "Dringliche Einfache Anfrage": "3", "Einfache Anfrage": "3", "Standesinitiative": "3", "Für die Galerie": "3", "Fragestunde. Frage": "3", "Petition": "3" } export class Search { attached() { this.init(); this.query = 'Burka'; this.search(); } init() { this.hits = [] this.hitsByYear = {} this.yearsSpanned = [] } executeSuggestedQuery(query) { this.query = query; this.search(); } search() { this.init(); fetch(`https://policy-papertrails-api.eu-gb.mybluemix.net/affairs?q=${this.query}`) .then(response => { if (!response.ok) { throw response; } return response.json() }) .then(data => { return data.hits.hits; }) .then(hits => { return hits .sort((a, b) => { return (Date.parse(a._source.deposit.date) - Date.parse(b._source.deposit.date)) }) }) .then(hits => { return hits .map(hit => { if (affairGroups.hasOwnProperty(hit._source.affairType.name)) { hit._source.group = affairGroups[hit._source.affairType.name] } else { hit._source.group = 1; } return hit; }) }) .then(hits => { this.hits = hits; let hitsByYear = {}; hits .map(hit => { let depositDate = new Date(hit._source.deposit.date) let year = parseInt(depositDate.getFullYear()) if (!hitsByYear.hasOwnProperty(year)) { hitsByYear[year] = [] } hitsByYear[year].push(hit) }) let firstYear = parseInt(Object.keys(hitsByYear).shift()) let lastYear = parseInt(Object.keys(hitsByYear).pop()) let currentYear = firstYear; while (currentYear <= lastYear) { this.yearsSpanned.push(currentYear); currentYear++; } this.hitsByYear = hitsByYear; }) .catch(err => { console.log(err) this.init(); }) } }
import * as constants from './constants'; import { jday, invjday, } from './ext'; import twoline2satrec from './io'; import { propagate, sgp4, gstime, } from './propagation'; import dopplerFactor from './dopplerFactor'; import { degreesLat, degreesLong, geodeticToEcf, eciToGeodetic, eciToEcf, ecfToEci, ecfToLookAngles, } from './transforms'; export default { version: '1.4.0', constants, // Propagation propagate, sgp4, twoline2satrec, gstime, gstimeFromJday: gstime, // TODO: deprecate gstimeFromDate: gstime, // TODO: deprecate jday, invjday, dopplerFactor, // Coordinate transforms degreesLat, degreesLong, geodeticToEcf, eciToGeodetic, eciToEcf, ecfToEci, ecfToLookAngles, };
(function($) { /** * Auto-growing textareas; technique ripped from Facebook * * http://github.com/jaz303/jquery-grab-bag/tree/master/javascripts/jquery.autogrow-textarea.js */ $.fn.autogrow = function(options) { return this.filter('textarea').each(function() { var self = this; var $self = $(self); var minHeight = $self.height(); var noFlickerPad = $self.hasClass('autogrow-short') ? 0 : parseInt($self.css('lineHeight')); var shadow = $('<div></div>').css({ position: 'absolute', top: -10000, left: -10000, width: $self.width(), fontSize: $self.css('fontSize'), fontFamily: $self.css('fontFamily'), fontWeight: $self.css('fontWeight'), lineHeight: $self.css('lineHeight'), resize: 'none' }).appendTo(document.body); var update = function() { var times = function(string, number) { for (var i=0, r=''; i<number; i++) r += string; return r; }; var val = self.value.replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/&/g, '&amp;') .replace(/\n$/, '<br/>&nbsp;') .replace(/\n/g, '<br/>') .replace(/ {2,}/g, function(space){ return times('&nbsp;', space.length - 1) + ' ' }); shadow.css('width', $self.width()); shadow.html(val); $self.css('height', Math.max(shadow.height() + noFlickerPad, minHeight)); } $self.change(update).keyup(update).keydown(update); $(window).resize(update); update(); }); }; })(jQuery); //auto grow textarea $('textarea.autogrow').autogrow();
import React, { Component, PropTypes } from 'react' import classNames from 'classnames' import {Nav, NavItem, Grid, Row, Col, Table, Glyphicon, Button} from 'react-bootstrap' export default class DataTools extends Component { render(){ return ( <Grid> {this.props.children} </Grid> ); } }
/** * Created by Jeng on 2016/1/8. */ define(function () { return ["$scope", "OrderAPI", "$modal", "$ugDialog","ExpressAPI","$filter", function($scope, OrderAPI, $modal, $ugDialog,ExpressAPI,$filter){ $scope.orderList = []; $scope.pageInfoSetting = { pageSize:10, pageNum:1 }; $scope.datepickerSetting = { datepickerPopupConfig:{ "current-text":"今天", "clear-text":"清除", "close-text":"关闭" }, appointmentTimeStart:{ opened:false }, appointmentTimeEnd:{ opened:false } }; $scope.openDate = function($event, index) { $event.preventDefault(); $event.stopPropagation(); if(index == 0){ $scope.datepickerSetting.appointmentTimeStart.opened = true; }else if(index == 1){ $scope.datepickerSetting.appointmentTimeEnd.opened = true; } }; $scope.queryParam = { appointmentTimeStart :$filter('date')(new Date(new Date().getTime()), 'yyyy-MM-dd'), appointmentTimeEnd :$filter('date')(new Date(new Date().getTime()+86400000), 'yyyy-MM-dd') }; $scope.getOrderList = function(){ //查询待配送的订单 OrderAPI.query({ limit:$scope.pageInfoSetting.pageSize, offset:$scope.pageInfoSetting.pageNum, keyword:$scope.queryParam.keyword, appointmentTimeStart:$scope.queryParam.appointmentTimeStart, appointmentTimeEnd:$scope.queryParam.appointmentTimeEnd, hasNoShowCancel:true, hasShowDespatch:false //不显示已分配的 }, function(data){ $scope.orderList = data.data; $scope.pageInfoSetting = data.pageInfo; $scope.pageInfoSetting.loadData = $scope.getOrderList; }); }; $scope.pageSetting = { pageSize:10, pageNum:1 }; //查询快递商 $scope.expressList = []; $scope.getExpressList = function(){ ExpressAPI.query({ limit:$scope.pageSetting.pageSize, offset:$scope.pageSetting.pageNum, keyword:$scope.queryParam.keyword },function(data){ $scope.expressList = data.data; }); } //选择快递商 $scope.choseExpressUser = function(index){ $scope.currentCustomer = $scope.expressList[index]; }; $scope.getOrderList(); $scope.getExpressList(); $scope.bindExpress = function(index){ if(!$scope.currentCustomer){ $ugDialog.warn("请选择运输的快递商"); return; } var orderNos = []; orderNos.push($scope.orderList[index].orderNo); ExpressAPI.bindExpress({ expressId:$scope.currentCustomer.id, orderNos:orderNos }, function(){ $scope.getOrderList(); $scope.getExpressList(); }) }; $scope.unbindExpress = function(index){ var orderNos = []; orderNos.push($scope.orderList[index].orderNo); ExpressAPI.unbindExpress({ orderNos:orderNos }, function(){ $scope.getOrderList(); $scope.getExpressList(); }) } //批量分配 $scope.chooseOrder = []; $scope.chooseAllCheck = {}; $scope.checkedAllOrder = function() { if($scope.chooseAllCheck.isCheckOrder == 0){ $scope.chooseOrder.splice(0, $scope.chooseOrder.length); for (var i = 0; i < $scope.orderList.length; i++) { var obj = $scope.orderList[i]; if(obj.expressName == null){ $scope.chooseOrder.push(obj); } } }else{ $scope.chooseOrder.splice(0, $scope.chooseOrder.length); } }; $scope.changeOrderList = function(){ if($scope.chooseOrder.length == $scope.orderList.length){ $scope.isCheckCombine = 0; }else{ $scope.isCheckCombine = 1; } }; $scope.saveBtnLoading = false; $scope.batchBindExpress = function(){ if(!$scope.currentCustomer){ $ugDialog.warn("请选择运输的快递商"); return; } $scope.saveBtnLoading = true; var orderNos = []; for(var i in $scope.chooseOrder){ orderNos.push($scope.chooseOrder[i].orderNo); } ExpressAPI.bindExpress({ expressId:$scope.currentCustomer.id, orderNos:orderNos }, function(){ $scope.getOrderList(); $scope.getExpressList(); }).$promise.finally(function(){ $scope.saveBtnLoading = false; }); }; }]; });
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function(A, w) { function ma() { if (!c.isReady) { try { s.documentElement.doScroll("left") } catch (a) { setTimeout(ma, 1); return } c.ready() } } function Qa(a, b) { b.src ? c.ajax({ url: b.src, async: false, dataType: "script" }) : c.globalEval(b.text || b.textContent || b.innerHTML || ""); b.parentNode && b.parentNode.removeChild(b) } function X(a, b, d, f, e, j) { var i = a.length; if (typeof b === "object") { for (var o in b) X(a, o, b[o], f, e, d); return a } if (d !== w) { f = !j && f && c.isFunction(d); for (o = 0; o < i; o++) e(a[o], b, f ? d.call(a[o], o, e(a[o], b)) : d, j); return a } return i ? e(a[0], b) : w } function J() { return (new Date).getTime() } function Y() { return false } function Z() { return true } function na(a, b, d) { d[0].type = a; return c.event.handle.apply(b, d) } function oa(a) { var b, d = [], f = [], e = arguments, j, i, o, k, n, r; i = c.data(this, "events"); if (!(a.liveFired === this || !i || !i.live || a.button && a.type === "click")) { a.liveFired = this; var u = i.live.slice(0); for (k = 0; k < u.length; k++) { i = u[k]; i.origType.replace(O, "") === a.type ? f.push(i.selector) : u.splice(k--, 1) } j = c(a.target).closest(f, a.currentTarget); n = 0; for (r = j.length; n < r; n++) for (k = 0; k < u.length; k++) { i = u[k]; if (j[n].selector === i.selector) { o = j[n].elem; f = null; if (i.preType === "mouseenter" || i.preType === "mouseleave") f = c(a.relatedTarget).closest(i.selector)[0]; if (!f || f !== o) d.push({ elem: o, handleObj: i }) } } n = 0; for (r = d.length; n < r; n++) { j = d[n]; a.currentTarget = j.elem; a.data = j.handleObj.data; a.handleObj = j.handleObj; if (j.handleObj.origHandler.apply(j.elem, e) === false) { b = false; break } } return b } } function pa(a, b) { return "live." + (a && a !== "*" ? a + "." : "") + b.replace(/\./g, "`").replace(/ /g, "&") } function qa(a) { return !a || !a.parentNode || a.parentNode.nodeType === 11 } function ra(a, b) { var d = 0; b.each(function() { if (this.nodeName === (a[d] && a[d].nodeName)) { var f = c.data(a[d++]), e = c.data(this, f); if (f = f && f.events) { delete e.handle; e.events = {}; for (var j in f) for (var i in f[j]) c.event.add(this, j, f[j][i], f[j][i].data) } } }) } function sa(a, b, d) { var f, e, j; b = b && b[0] ? b[0].ownerDocument || b[0] : s; if (a.length === 1 && typeof a[0] === "string" && a[0].length < 512 && b === s && !ta.test(a[0]) && (c.support.checkClone || !ua.test(a[0]))) { e = true; if (j = c.fragments[a[0]]) if (j !== 1) f = j } if (!f) { f = b.createDocumentFragment(); c.clean(a, b, f, d) } if (e) c.fragments[a[0]] = j ? f : 1; return { fragment: f, cacheable: e } } function K(a, b) { var d = {}; c.each(va.concat.apply([], va.slice(0, b)), function() { d[this] = a }); return d } function wa(a) { return "scrollTo" in a && a.document ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : false } var c = function(a, b) { return new c.fn.init(a, b) }, Ra = A.jQuery, Sa = A.$, s = A.document, T, Ta = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, Ua = /^.[^:#\[\.,]*$/, Va = /\S/, Wa = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, Xa = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, P = navigator.userAgent, xa = false, Q = [], L, $ = Object.prototype.toString, aa = Object.prototype.hasOwnProperty, ba = Array.prototype.push, R = Array.prototype.slice, ya = Array.prototype.indexOf; c.fn = c.prototype = { init: function(a, b) { var d, f; if (!a) return this; if (a.nodeType) { this.context = this[0] = a; this.length = 1; return this } if (a === "body" && !b) { this.context = s; this[0] = s.body; this.selector = "body"; this.length = 1; return this } if (typeof a === "string") if ((d = Ta.exec(a)) && (d[1] || !b)) if (d[1]) { f = b ? b.ownerDocument || b : s; if (a = Xa.exec(a)) if (c.isPlainObject(b)) { a = [s.createElement(a[1])]; c.fn.attr.call(a, b, true) } else a = [f.createElement(a[1])]; else { a = sa([d[1]], [f]); a = (a.cacheable ? a.fragment.cloneNode(true) : a.fragment).childNodes } return c.merge(this, a) } else { if (b = s.getElementById(d[2])) { if (b.id !== d[2]) return T.find(a); this.length = 1; this[0] = b } this.context = s; this.selector = a; return this } else if (!b && /^\w+$/.test(a)) { this.selector = a; this.context = s; a = s.getElementsByTagName(a); return c.merge(this, a) } else return !b || b.jquery ? (b || T).find(a) : c(b).find(a); else if (c.isFunction(a)) return T.ready(a); if (a.selector !== w) { this.selector = a.selector; this.context = a.context } return c.makeArray(a, this) }, selector: "", jquery: "1.4.2", length: 0, size: function() { return this.length }, toArray: function() { return R.call(this, 0) }, get: function(a) { return a == null ? this.toArray() : a < 0 ? this.slice(a)[0] : this[a] }, pushStack: function(a, b, d) { var f = c(); c.isArray(a) ? ba.apply(f, a) : c.merge(f, a); f.prevObject = this; f.context = this.context; if (b === "find") f.selector = this.selector + (this.selector ? " " : "") + d; else if (b) f.selector = this.selector + "." + b + "(" + d + ")"; return f }, each: function(a, b) { return c.each(this, a, b) }, ready: function(a) { c.bindReady(); if (c.isReady) a.call(s, c); else Q && Q.push(a); return this }, eq: function(a) { return a === -1 ? this.slice(a) : this.slice(a, +a + 1) }, first: function() { return this.eq(0) }, last: function() { return this.eq(-1) }, slice: function() { return this.pushStack(R.apply(this, arguments), "slice", R.call(arguments).join(",")) }, map: function(a) { return this.pushStack(c.map(this, function(b, d) { return a.call(b, d, b) })) }, end: function() { return this.prevObject || c(null) }, push: ba, sort: [].sort, splice: [].splice }; c.fn.init.prototype = c.fn; c.extend = c.fn.extend = function() { var a = arguments[0] || {}, b = 1, d = arguments.length, f = false, e, j, i, o; if (typeof a === "boolean") { f = a; a = arguments[1] || {}; b = 2 } if (typeof a !== "object" && !c.isFunction(a)) a = {}; if (d === b) { a = this; --b } for (; b < d; b++) if ((e = arguments[b]) != null) for (j in e) { i = a[j]; o = e[j]; if (a !== o) if (f && o && (c.isPlainObject(o) || c.isArray(o))) { i = i && (c.isPlainObject(i) || c.isArray(i)) ? i : c.isArray(o) ? [] : {}; a[j] = c.extend(f, i, o) } else if (o !== w) a[j] = o } return a }; c.extend({ noConflict: function(a) { A.$ = Sa; if (a) A.jQuery = Ra; return c }, isReady: false, ready: function() { if (!c.isReady) { if (!s.body) return setTimeout(c.ready, 13); c.isReady = true; if (Q) { for (var a, b = 0; a = Q[b++];) a.call(s, c); Q = null } c.fn.triggerHandler && c(s).triggerHandler("ready") } }, bindReady: function() { if (!xa) { xa = true; if (s.readyState === "complete") return c.ready(); if (s.addEventListener) { s.addEventListener("DOMContentLoaded", L, false); A.addEventListener("load", c.ready, false) } else if (s.attachEvent) { s.attachEvent("onreadystatechange", L); A.attachEvent("onload", c.ready); var a = false; try { a = A.frameElement == null } catch (b) {} s.documentElement.doScroll && a && ma() } } }, isFunction: function(a) { return $.call(a) === "[object Function]" }, isArray: function(a) { return $.call(a) === "[object Array]" }, isPlainObject: function(a) { if (!a || $.call(a) !== "[object Object]" || a.nodeType || a.setInterval) return false; if (a.constructor && !aa.call(a, "constructor") && !aa.call(a.constructor.prototype, "isPrototypeOf")) return false; var b; for (b in a); return b === w || aa.call(a, b) }, isEmptyObject: function(a) { for (var b in a) return false; return true }, error: function(a) { throw a; }, parseJSON: function(a) { if (typeof a !== "string" || !a) return null; a = c.trim(a); if (/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return A.JSON && A.JSON.parse ? A.JSON.parse(a) : (new Function("return " + a))(); else c.error("Invalid JSON: " + a) }, noop: function() {}, globalEval: function(a) { if (a && Va.test(a)) { var b = s.getElementsByTagName("head")[0] || s.documentElement, d = s.createElement("script"); d.type = "text/javascript"; if (c.support.scriptEval) d.appendChild(s.createTextNode(a)); else d.text = a; b.insertBefore(d, b.firstChild); b.removeChild(d) } }, nodeName: function(a, b) { return a.nodeName && a.nodeName.toUpperCase() === b.toUpperCase() }, each: function(a, b, d) { var f, e = 0, j = a.length, i = j === w || c.isFunction(a); if (d) if (i) for (f in a) { if (b.apply(a[f], d) === false) break } else for (; e < j;) { if (b.apply(a[e++], d) === false) break } else if (i) for (f in a) { if (b.call(a[f], f, a[f]) === false) break } else for (d = a[0]; e < j && b.call(d, e, d) !== false; d = a[++e]); return a }, trim: function(a) { return (a || "").replace(Wa, "") }, makeArray: function(a, b) { b = b || []; if (a != null) a.length == null || typeof a === "string" || c.isFunction(a) || typeof a !== "function" && a.setInterval ? ba.call(b, a) : c.merge(b, a); return b }, inArray: function(a, b) { if (b.indexOf) return b.indexOf(a); for (var d = 0, f = b.length; d < f; d++) if (b[d] === a) return d; return -1 }, merge: function(a, b) { var d = a.length, f = 0; if (typeof b.length === "number") for (var e = b.length; f < e; f++) a[d++] = b[f]; else for (; b[f] !== w;) a[d++] = b[f++]; a.length = d; return a }, grep: function(a, b, d) { for (var f = [], e = 0, j = a.length; e < j; e++) !d !== !b(a[e], e) && f.push(a[e]); return f }, map: function(a, b, d) { for (var f = [], e, j = 0, i = a.length; j < i; j++) { e = b(a[j], j, d); if (e != null) f[f.length] = e } return f.concat.apply([], f) }, guid: 1, proxy: function(a, b, d) { if (arguments.length === 2) if (typeof b === "string") { d = a; a = d[b]; b = w } else if (b && !c.isFunction(b)) { d = b; b = w } if (!b && a) b = function() { return a.apply(d || this, arguments) }; if (a) b.guid = a.guid = a.guid || b.guid || c.guid++; return b }, uaMatch: function(a) { a = a.toLowerCase(); a = /(webkit)[ \/]([\w.]+)/.exec(a) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a) || /(msie) ([\w.]+)/.exec(a) || !/compatible/.test(a) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(a) || []; return { browser: a[1] || "", version: a[2] || "0" } }, browser: {} }); P = c.uaMatch(P); if (P.browser) { c.browser[P.browser] = true; c.browser.version = P.version } if (c.browser.webkit) c.browser.safari = true; if (ya) c.inArray = function(a, b) { return ya.call(b, a) }; T = c(s); if (s.addEventListener) L = function() { s.removeEventListener("DOMContentLoaded", L, false); c.ready() }; else if (s.attachEvent) L = function() { if (s.readyState === "complete") { s.detachEvent("onreadystatechange", L); c.ready() } }; (function() { c.support = {}; var a = s.documentElement, b = s.createElement("script"), d = s.createElement("div"), f = "script" + J(); d.style.display = "none"; d.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var e = d.getElementsByTagName("*"), j = d.getElementsByTagName("a")[0]; if (!(!e || !e.length || !j)) { c.support = { leadingWhitespace: d.firstChild.nodeType === 3, tbody: !d.getElementsByTagName("tbody").length, htmlSerialize: !!d.getElementsByTagName("link").length, style: /red/.test(j.getAttribute("style")), hrefNormalized: j.getAttribute("href") === "/a", opacity: /^0.55$/.test(j.style.opacity), cssFloat: !!j.style.cssFloat, checkOn: d.getElementsByTagName("input")[0].value === "on", optSelected: s.createElement("select").appendChild(s.createElement("option")).selected, parentNode: d.removeChild(d.appendChild(s.createElement("div"))).parentNode === null, deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; b.type = "text/javascript"; try { b.appendChild(s.createTextNode("window." + f + "=1;")) } catch (i) {} a.insertBefore(b, a.firstChild); if (A[f]) { c.support.scriptEval = true; delete A[f] } try { delete b.test } catch (o) { c.support.deleteExpando = false } a.removeChild(b); if (d.attachEvent && d.fireEvent) { d.attachEvent("onclick", function k() { c.support.noCloneEvent = false; d.detachEvent("onclick", k) }); d.cloneNode(true).fireEvent("onclick") } d = s.createElement("div"); d.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; a = s.createDocumentFragment(); a.appendChild(d.firstChild); c.support.checkClone = a.cloneNode(true).cloneNode(true).lastChild.checked; c(function() { var k = s.createElement("div"); k.style.width = k.style.paddingLeft = "1px"; s.body.appendChild(k); c.boxModel = c.support.boxModel = k.offsetWidth === 2; s.body.removeChild(k).style.display = "none" }); a = function(k) { var n = s.createElement("div"); k = "on" + k; var r = k in n; if (!r) { n.setAttribute(k, "return;"); r = typeof n[k] === "function" } return r }; c.support.submitBubbles = a("submit"); c.support.changeBubbles = a("change"); a = b = d = e = j = null } })(); c.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var G = "jQuery" + J(), Ya = 0, za = {}; c.extend({ cache: {}, expando: G, noData: { embed: true, object: true, applet: true }, data: function(a, b, d) { if (!(a.nodeName && c.noData[a.nodeName.toLowerCase()])) { a = a == A ? za : a; var f = a[G], e = c.cache; if (!f && typeof b === "string" && d === w) return null; f || (f = ++Ya); if (typeof b === "object") { a[G] = f; e[f] = c.extend(true, {}, b) } else if (!e[f]) { a[G] = f; e[f] = {} } a = e[f]; if (d !== w) a[b] = d; return typeof b === "string" ? a[b] : a } }, removeData: function(a, b) { if (!(a.nodeName && c.noData[a.nodeName.toLowerCase()])) { a = a == A ? za : a; var d = a[G], f = c.cache, e = f[d]; if (b) { if (e) { delete e[b]; c.isEmptyObject(e) && c.removeData(a) } } else { if (c.support.deleteExpando) delete a[c.expando]; else a.removeAttribute && a.removeAttribute(c.expando); delete f[d] } } } }); c.fn.extend({ data: function(a, b) { if (typeof a === "undefined" && this.length) return c.data(this[0]); else if (typeof a === "object") return this.each(function() { c.data(this, a) }); var d = a.split("."); d[1] = d[1] ? "." + d[1] : ""; if (b === w) { var f = this.triggerHandler("getData" + d[1] + "!", [d[0]]); if (f === w && this.length) f = c.data(this[0], a); return f === w && d[1] ? this.data(d[0]) : f } else return this.trigger("setData" + d[1] + "!", [d[0], b]).each(function() { c.data(this, a, b) }) }, removeData: function(a) { return this.each(function() { c.removeData(this, a) }) } }); c.extend({ queue: function(a, b, d) { if (a) { b = (b || "fx") + "queue"; var f = c.data(a, b); if (!d) return f || []; if (!f || c.isArray(d)) f = c.data(a, b, c.makeArray(d)); else f.push(d); return f } }, dequeue: function(a, b) { b = b || "fx"; var d = c.queue(a, b), f = d.shift(); if (f === "inprogress") f = d.shift(); if (f) { b === "fx" && d.unshift("inprogress"); f.call(a, function() { c.dequeue(a, b) }) } } }); c.fn.extend({ queue: function(a, b) { if (typeof a !== "string") { b = a; a = "fx" } if (b === w) return c.queue(this[0], a); return this.each(function() { var d = c.queue(this, a, b); a === "fx" && d[0] !== "inprogress" && 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; b = b || "fx"; return this.queue(b, function() { var d = this; setTimeout(function() { c.dequeue(d, b) }, a) }) }, clearQueue: function(a) { return this.queue(a || "fx", []) } }); var Aa = /[\n\t]/g, ca = /\s+/, Za = /\r/g, $a = /href|src|style/, ab = /(button|input)/i, bb = /(button|input|object|select|textarea)/i, cb = /^(a|area)$/i, Ba = /radio|checkbox/; c.fn.extend({ attr: function(a, b) { return X(this, a, b, true, c.attr) }, removeAttr: function(a) { return this.each(function() { c.attr(this, a, ""); this.nodeType === 1 && this.removeAttribute(a) }) }, addClass: function(a) { if (c.isFunction(a)) return this.each(function(n) { var r = c(this); r.addClass(a.call(this, n, r.attr("class"))) }); if (a && typeof a === "string") for (var b = (a || "").split(ca), d = 0, f = this.length; d < f; d++) { var e = this[d]; if (e.nodeType === 1) if (e.className) { for (var j = " " + e.className + " ", i = e.className, o = 0, k = b.length; o < k; o++) if (j.indexOf(" " + b[o] + " ") < 0) i += " " + b[o]; e.className = c.trim(i) } else e.className = a } return this }, removeClass: function(a) { if (c.isFunction(a)) return this.each(function(k) { var n = c(this); n.removeClass(a.call(this, k, n.attr("class"))) }); if (a && typeof a === "string" || a === w) for (var b = (a || "").split(ca), d = 0, f = this.length; d < f; d++) { var e = this[d]; if (e.nodeType === 1 && e.className) if (a) { for (var j = (" " + e.className + " ").replace(Aa, " "), i = 0, o = b.length; i < o; i++) j = j.replace(" " + b[i] + " ", " "); e.className = c.trim(j) } else e.className = "" } return this }, toggleClass: function(a, b) { var d = typeof a, f = typeof b === "boolean"; if (c.isFunction(a)) return this.each(function(e) { var j = c(this); j.toggleClass(a.call(this, e, j.attr("class"), b), b) }); return this.each(function() { if (d === "string") for (var e, j = 0, i = c(this), o = b, k = a.split(ca); e = k[j++];) { o = f ? o : !i.hasClass(e); i[o ? "addClass" : "removeClass"](e) } else if (d === "undefined" || d === "boolean") { this.className && c.data(this, "__className__", this.className); this.className = this.className || a === false ? "" : c.data(this, "__className__") || "" } }) }, hasClass: function(a) { a = " " + a + " "; for (var b = 0, d = this.length; b < d; b++) if ((" " + this[b].className + " ").replace(Aa, " ").indexOf(a) > -1) return true; return false }, val: function(a) { if (a === w) { var b = this[0]; if (b) { if (c.nodeName(b, "option")) return (b.attributes.value || {}).specified ? b.value : b.text; if (c.nodeName(b, "select")) { var d = b.selectedIndex, f = [], e = b.options; b = b.type === "select-one"; if (d < 0) return null; var j = b ? d : 0; for (d = b ? d + 1 : e.length; j < d; j++) { var i = e[j]; if (i.selected) { a = c(i).val(); if (b) return a; f.push(a) } } return f } if (Ba.test(b.type) && !c.support.checkOn) return b.getAttribute("value") === null ? "on" : b.value; return (b.value || "").replace(Za, "") } return w } var o = c.isFunction(a); return this.each(function(k) { var n = c(this), r = a; if (this.nodeType === 1) { if (o) r = a.call(this, k, n.val()); if (typeof r === "number") r += ""; if (c.isArray(r) && Ba.test(this.type)) this.checked = c.inArray(n.val(), r) >= 0; else if (c.nodeName(this, "select")) { var u = c.makeArray(r); c("option", this).each(function() { this.selected = c.inArray(c(this).val(), u) >= 0 }); if (!u.length) this.selectedIndex = -1 } else this.value = r } }) } }); c.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function(a, b, d, f) { if (!a || a.nodeType === 3 || a.nodeType === 8) return w; if (f && b in c.attrFn) return c(a)[b](d); f = a.nodeType !== 1 || !c.isXMLDoc(a); var e = d !== w; b = f && c.props[b] || b; if (a.nodeType === 1) { var j = $a.test(b); if (b in a && f && !j) { if (e) { b === "type" && ab.test(a.nodeName) && a.parentNode && c.error("type property can't be changed"); a[b] = d } if (c.nodeName(a, "form") && a.getAttributeNode(b)) return a.getAttributeNode(b).nodeValue; if (b === "tabIndex") return (b = a.getAttributeNode("tabIndex")) && b.specified ? b.value : bb.test(a.nodeName) || cb.test(a.nodeName) && a.href ? 0 : w; return a[b] } if (!c.support.style && f && b === "style") { if (e) a.style.cssText = "" + d; return a.style.cssText } e && a.setAttribute(b, "" + d); a = !c.support.hrefNormalized && f && j ? a.getAttribute(b, 2) : a.getAttribute(b); return a === null ? w : a } return c.style(a, b, d) } }); var O = /\.(.*)$/, db = function(a) { return a.replace(/[^\w\s\.\|`]/g, function(b) { return "\\" + b }) }; c.event = { add: function(a, b, d, f) { if (!(a.nodeType === 3 || a.nodeType === 8)) { if (a.setInterval && a !== A && !a.frameElement) a = A; var e, j; if (d.handler) { e = d; d = e.handler } if (!d.guid) d.guid = c.guid++; if (j = c.data(a)) { var i = j.events = j.events || {}, o = j.handle; if (!o) j.handle = o = function() { return typeof c !== "undefined" && !c.event.triggered ? c.event.handle.apply(o.elem, arguments) : w }; o.elem = a; b = b.split(" "); for (var k, n = 0, r; k = b[n++];) { j = e ? c.extend({}, e) : { handler: d, data: f }; if (k.indexOf(".") > -1) { r = k.split("."); k = r.shift(); j.namespace = r.slice(0).sort().join(".") } else { r = []; j.namespace = "" } j.type = k; j.guid = d.guid; var u = i[k], z = c.event.special[k] || {}; if (!u) { u = i[k] = []; if (!z.setup || z.setup.call(a, f, r, o) === false) if (a.addEventListener) a.addEventListener(k, o, false); else a.attachEvent && a.attachEvent("on" + k, o) } if (z.add) { z.add.call(a, j); if (!j.handler.guid) j.handler.guid = d.guid } u.push(j); c.event.global[k] = true } a = null } } }, global: {}, remove: function(a, b, d, f) { if (!(a.nodeType === 3 || a.nodeType === 8)) { var e, j = 0, i, o, k, n, r, u, z = c.data(a), C = z && z.events; if (z && C) { if (b && b.type) { d = b.handler; b = b.type } if (!b || typeof b === "string" && b.charAt(0) === ".") { b = b || ""; for (e in C) c.event.remove(a, e + b) } else { for (b = b.split(" "); e = b[j++];) { n = e; i = e.indexOf(".") < 0; o = []; if (!i) { o = e.split("."); e = o.shift(); k = new RegExp("(^|\\.)" + c.map(o.slice(0).sort(), db).join("\\.(?:.*\\.)?") + "(\\.|$)") } if (r = C[e]) if (d) { n = c.event.special[e] || {}; for (B = f || 0; B < r.length; B++) { u = r[B]; if (d.guid === u.guid) { if (i || k.test(u.namespace)) { f == null && r.splice(B--, 1); n.remove && n.remove.call(a, u) } if (f != null) break } } if (r.length === 0 || f != null && r.length === 1) { if (!n.teardown || n.teardown.call(a, o) === false) Ca(a, e, z.handle); delete C[e] } } else for (var B = 0; B < r.length; B++) { u = r[B]; if (i || k.test(u.namespace)) { c.event.remove(a, n, u.handler, B); r.splice(B--, 1) } } } if (c.isEmptyObject(C)) { if (b = z.handle) b.elem = null; delete z.events; delete z.handle; c.isEmptyObject(z) && c.removeData(a) } } } } }, trigger: function(a, b, d, f) { var e = a.type || a; if (!f) { a = typeof a === "object" ? a[G] ? a : c.extend(c.Event(e), a) : c.Event(e); if (e.indexOf("!") >= 0) { a.type = e = e.slice(0, -1); a.exclusive = true } if (!d) { a.stopPropagation(); c.event.global[e] && c.each(c.cache, function() { this.events && this.events[e] && c.event.trigger(a, b, this.handle.elem) }) } if (!d || d.nodeType === 3 || d.nodeType === 8) return w; a.result = w; a.target = d; b = c.makeArray(b); b.unshift(a) } a.currentTarget = d; (f = c.data(d, "handle")) && f.apply(d, b); f = d.parentNode || d.ownerDocument; try { if (!(d && d.nodeName && c.noData[d.nodeName.toLowerCase()])) if (d["on" + e] && d["on" + e].apply(d, b) === false) a.result = false } catch (j) {} if (!a.isPropagationStopped() && f) c.event.trigger(a, b, f, true); else if (!a.isDefaultPrevented()) { f = a.target; var i, o = c.nodeName(f, "a") && e === "click", k = c.event.special[e] || {}; if ((!k._default || k._default.call(d, a) === false) && !o && !(f && f.nodeName && c.noData[f.nodeName.toLowerCase()])) { try { if (f[e]) { if (i = f["on" + e]) f["on" + e] = null; c.event.triggered = true; f[e]() } } catch (n) {} if (i) f["on" + e] = i; c.event.triggered = false } } }, handle: function(a) { var b, d, f, e; a = arguments[0] = c.event.fix(a || A.event); a.currentTarget = this; b = a.type.indexOf(".") < 0 && !a.exclusive; if (!b) { d = a.type.split("."); a.type = d.shift(); f = new RegExp("(^|\\.)" + d.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)") } e = c.data(this, "events"); d = e[a.type]; if (e && d) { d = d.slice(0); e = 0; for (var j = d.length; e < j; e++) { var i = d[e]; if (b || f.test(i.namespace)) { a.handler = i.handler; a.data = i.data; a.handleObj = i; i = i.handler.apply(this, arguments); if (i !== w) { a.result = i; if (i === false) { a.preventDefault(); a.stopPropagation() } } if (a.isImmediatePropagationStopped()) break } } } return a.result }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function(a) { if (a[G]) return a; var b = a; a = c.Event(b); for (var d = this.props.length, f; d;) { f = this.props[--d]; a[f] = b[f] } if (!a.target) a.target = a.srcElement || s; if (a.target.nodeType === 3) a.target = a.target.parentNode; if (!a.relatedTarget && a.fromElement) a.relatedTarget = a.fromElement === a.target ? a.toElement : a.fromElement; if (a.pageX == null && a.clientX != null) { b = s.documentElement; d = s.body; a.pageX = a.clientX + (b && b.scrollLeft || d && d.scrollLeft || 0) - (b && b.clientLeft || d && d.clientLeft || 0); a.pageY = a.clientY + (b && b.scrollTop || d && d.scrollTop || 0) - (b && b.clientTop || d && d.clientTop || 0) } if (!a.which && (a.charCode || a.charCode === 0 ? a.charCode : a.keyCode)) a.which = a.charCode || a.keyCode; if (!a.metaKey && a.ctrlKey) a.metaKey = a.ctrlKey; if (!a.which && a.button !== w) a.which = a.button & 1 ? 1 : a.button & 2 ? 3 : a.button & 4 ? 2 : 0; return a }, guid: 1E8, proxy: c.proxy, special: { ready: { setup: c.bindReady, teardown: c.noop }, live: { add: function(a) { c.event.add(this, a.origType, c.extend({}, a, { handler: oa })) }, remove: function(a) { var b = true, d = a.origType.replace(O, ""); c.each(c.data(this, "events").live || [], function() { if (d === this.origType.replace(O, "")) return b = false }); b && c.event.remove(this, a.origType, oa) } }, beforeunload: { setup: function(a, b, d) { if (this.setInterval) this.onbeforeunload = d; return false }, teardown: function(a, b) { if (this.onbeforeunload === b) this.onbeforeunload = null } } } }; var Ca = s.removeEventListener ? function(a, b, d) { a.removeEventListener(b, d, false) } : function(a, b, d) { a.detachEvent("on" + b, d) }; c.Event = function(a) { if (!this.preventDefault) return new c.Event(a); if (a && a.type) { this.originalEvent = a; this.type = a.type } else this.type = a; this.timeStamp = J(); this[G] = true }; c.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = Z; var a = this.originalEvent; if (a) { a.preventDefault && a.preventDefault(); a.returnValue = false } }, stopPropagation: function() { this.isPropagationStopped = Z; var a = this.originalEvent; if (a) { a.stopPropagation && a.stopPropagation(); a.cancelBubble = true } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = Z; this.stopPropagation() }, isDefaultPrevented: Y, isPropagationStopped: Y, isImmediatePropagationStopped: Y }; var Da = function(a) { var b = a.relatedTarget; try { for (; b && b !== this;) b = b.parentNode; if (b !== this) { a.type = a.data; c.event.handle.apply(this, arguments) } } catch (d) {} }, Ea = function(a) { a.type = a.data; c.event.handle.apply(this, arguments) }; c.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function(a, b) { c.event.special[a] = { setup: function(d) { c.event.add(this, b, d && d.selector ? Ea : Da, a) }, teardown: function(d) { c.event.remove(this, b, d && d.selector ? Ea : Da) } } }); if (!c.support.submitBubbles) c.event.special.submit = { setup: function() { if (this.nodeName.toLowerCase() !== "form") { c.event.add(this, "click.specialSubmit", function(a) { var b = a.target, d = b.type; if ((d === "submit" || d === "image") && c(b).closest("form").length) return na("submit", this, arguments) }); c.event.add(this, "keypress.specialSubmit", function(a) { var b = a.target, d = b.type; if ((d === "text" || d === "password") && c(b).closest("form").length && a.keyCode === 13) return na("submit", this, arguments) }) } else return false }, teardown: function() { c.event.remove(this, ".specialSubmit") } }; if (!c.support.changeBubbles) { var da = /textarea|input|select/i, ea, Fa = function(a) { var b = a.type, d = a.value; if (b === "radio" || b === "checkbox") d = a.checked; else if (b === "select-multiple") d = a.selectedIndex > -1 ? c.map(a.options, function(f) { return f.selected }).join("-") : ""; else if (a.nodeName.toLowerCase() === "select") d = a.selectedIndex; return d }, fa = function(a, b) { var d = a.target, f, e; if (!(!da.test(d.nodeName) || d.readOnly)) { f = c.data(d, "_change_data"); e = Fa(d); if (a.type !== "focusout" || d.type !== "radio") c.data(d, "_change_data", e); if (!(f === w || e === f)) if (f != null || e) { a.type = "change"; return c.event.trigger(a, b, d) } } }; c.event.special.change = { filters: { focusout: fa, click: function(a) { var b = a.target, d = b.type; if (d === "radio" || d === "checkbox" || b.nodeName.toLowerCase() === "select") return fa.call(this, a) }, keydown: function(a) { var b = a.target, d = b.type; if (a.keyCode === 13 && b.nodeName.toLowerCase() !== "textarea" || a.keyCode === 32 && (d === "checkbox" || d === "radio") || d === "select-multiple") return fa.call(this, a) }, beforeactivate: function(a) { a = a.target; c.data(a, "_change_data", Fa(a)) } }, setup: function() { if (this.type === "file") return false; for (var a in ea) c.event.add(this, a + ".specialChange", ea[a]); return da.test(this.nodeName) }, teardown: function() { c.event.remove(this, ".specialChange"); return da.test(this.nodeName) } }; ea = c.event.special.change.filters } s.addEventListener && c.each({ focus: "focusin", blur: "focusout" }, function(a, b) { function d(f) { f = c.event.fix(f); f.type = b; return c.event.handle.call(this, f) } c.event.special[b] = { setup: function() { this.addEventListener(a, d, true) }, teardown: function() { this.removeEventListener(a, d, true) } } }); c.each(["bind", "one"], function(a, b) { c.fn[b] = function(d, f, e) { if (typeof d === "object") { for (var j in d) this[b](j, f, d[j], e); return this } if (c.isFunction(f)) { e = f; f = w } var i = b === "one" ? c.proxy(e, function(k) { c(this).unbind(k, i); return e.apply(this, arguments) }) : e; if (d === "unload" && b !== "one") this.one(d, f, e); else { j = 0; for (var o = this.length; j < o; j++) c.event.add(this[j], d, i, f) } return this } }); c.fn.extend({ unbind: function(a, b) { if (typeof a === "object" && !a.preventDefault) for (var d in a) this.unbind(d, a[d]); else { d = 0; for (var f = this.length; d < f; d++) c.event.remove(this[d], a, b) } return this }, delegate: function(a, b, d, f) { return this.live(b, d, f, a) }, undelegate: function(a, b, d) { return arguments.length === 0 ? this.unbind("live") : this.die(b, null, d, a) }, trigger: function(a, b) { return this.each(function() { c.event.trigger(a, b, this) }) }, triggerHandler: function(a, b) { if (this[0]) { a = c.Event(a); a.preventDefault(); a.stopPropagation(); c.event.trigger(a, b, this[0]); return a.result } }, toggle: function(a) { for (var b = arguments, d = 1; d < b.length;) c.proxy(a, b[d++]); return this.click(c.proxy(a, function(f) { var e = (c.data(this, "lastToggle" + a.guid) || 0) % d; c.data(this, "lastToggle" + a.guid, e + 1); f.preventDefault(); return b[e].apply(this, arguments) || false })) }, hover: function(a, b) { return this.mouseenter(a).mouseleave(b || a) } }); var Ga = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; c.each(["live", "die"], function(a, b) { c.fn[b] = function(d, f, e, j) { var i, o = 0, k, n, r = j || this.selector, u = j ? this : c(this.context); if (c.isFunction(f)) { e = f; f = w } for (d = (d || "").split(" "); (i = d[o++]) != null;) { j = O.exec(i); k = ""; if (j) { k = j[0]; i = i.replace(O, "") } if (i === "hover") d.push("mouseenter" + k, "mouseleave" + k); else { n = i; if (i === "focus" || i === "blur") { d.push(Ga[i] + k); i += k } else i = (Ga[i] || i) + k; b === "live" ? u.each(function() { c.event.add(this, pa(i, r), { data: f, selector: r, handler: e, origType: i, origHandler: e, preType: n }) }) : u.unbind(pa(i, r), e) } } return this } }); 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".split(" "), function(a, b) { c.fn[b] = function(d) { return d ? this.bind(b, d) : this.trigger(b) }; if (c.attrFn) c.attrFn[b] = true }); A.attachEvent && !A.addEventListener && A.attachEvent("onunload", function() { for (var a in c.cache) if (c.cache[a].handle) try { c.event.remove(c.cache[a].handle.elem) } catch (b) {} }); (function() { function a(g) { for (var h = "", l, m = 0; g[m]; m++) { l = g[m]; if (l.nodeType === 3 || l.nodeType === 4) h += l.nodeValue; else if (l.nodeType !== 8) h += a(l.childNodes) } return h } function b(g, h, l, m, q, p) { q = 0; for (var v = m.length; q < v; q++) { var t = m[q]; if (t) { t = t[g]; for (var y = false; t;) { if (t.sizcache === l) { y = m[t.sizset]; break } if (t.nodeType === 1 && !p) { t.sizcache = l; t.sizset = q } if (t.nodeName.toLowerCase() === h) { y = t; break } t = t[g] } m[q] = y } } } function d(g, h, l, m, q, p) { q = 0; for (var v = m.length; q < v; q++) { var t = m[q]; if (t) { t = t[g]; for (var y = false; t;) { if (t.sizcache === l) { y = m[t.sizset]; break } if (t.nodeType === 1) { if (!p) { t.sizcache = l; t.sizset = q } if (typeof h !== "string") { if (t === h) { y = true; break } } else if (k.filter(h, [t]).length > 0) { y = t; break } } t = t[g] } m[q] = y } } } var f = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e = 0, j = Object.prototype.toString, i = false, o = true; [0, 0].sort(function() { o = false; return 0 }); var k = function(g, h, l, m) { l = l || []; var q = h = h || s; if (h.nodeType !== 1 && h.nodeType !== 9) return []; if (!g || typeof g !== "string") return l; for (var p = [], v, t, y, S, H = true, M = x(h), I = g; (f.exec(""), v = f.exec(I)) !== null;) { I = v[3]; p.push(v[1]); if (v[2]) { S = v[3]; break } } if (p.length > 1 && r.exec(g)) if (p.length === 2 && n.relative[p[0]]) t = ga(p[0] + p[1], h); else for (t = n.relative[p[0]] ? [h] : k(p.shift(), h); p.length;) { g = p.shift(); if (n.relative[g]) g += p.shift(); t = ga(g, t) } else { if (!m && p.length > 1 && h.nodeType === 9 && !M && n.match.ID.test(p[0]) && !n.match.ID.test(p[p.length - 1])) { v = k.find(p.shift(), h, M); h = v.expr ? k.filter(v.expr, v.set)[0] : v.set[0] } if (h) { v = m ? { expr: p.pop(), set: z(m) } : k.find(p.pop(), p.length === 1 && (p[0] === "~" || p[0] === "+") && h.parentNode ? h.parentNode : h, M); t = v.expr ? k.filter(v.expr, v.set) : v.set; if (p.length > 0) y = z(t); else H = false; for (; p.length;) { var D = p.pop(); v = D; if (n.relative[D]) v = p.pop(); else D = ""; if (v == null) v = h; n.relative[D](y, v, M) } } else y = [] } y || (y = t); y || k.error(D || g); if (j.call(y) === "[object Array]") if (H) if (h && h.nodeType === 1) for (g = 0; y[g] != null; g++) { if (y[g] && (y[g] === true || y[g].nodeType === 1 && E(h, y[g]))) l.push(t[g]) } else for (g = 0; y[g] != null; g++) y[g] && y[g].nodeType === 1 && l.push(t[g]); else l.push.apply(l, y); else z(y, l); if (S) { k(S, q, l, m); k.uniqueSort(l) } return l }; k.uniqueSort = function(g) { if (B) { i = o; g.sort(B); if (i) for (var h = 1; h < g.length; h++) g[h] === g[h - 1] && g.splice(h--, 1) } return g }; k.matches = function(g, h) { return k(g, null, null, h) }; k.find = function(g, h, l) { var m, q; if (!g) return []; for (var p = 0, v = n.order.length; p < v; p++) { var t = n.order[p]; if (q = n.leftMatch[t].exec(g)) { var y = q[1]; q.splice(1, 1); if (y.substr(y.length - 1) !== "\\") { q[1] = (q[1] || "").replace(/\\/g, ""); m = n.find[t](q, h, l); if (m != null) { g = g.replace(n.match[t], ""); break } } } } m || (m = h.getElementsByTagName("*")); return { set: m, expr: g } }; k.filter = function(g, h, l, m) { for (var q = g, p = [], v = h, t, y, S = h && h[0] && x(h[0]); g && h.length;) { for (var H in n.filter) if ((t = n.leftMatch[H].exec(g)) != null && t[2]) { var M = n.filter[H], I, D; D = t[1]; y = false; t.splice(1, 1); if (D.substr(D.length - 1) !== "\\") { if (v === p) p = []; if (n.preFilter[H]) if (t = n.preFilter[H](t, v, l, p, m, S)) { if (t === true) continue } else y = I = true; if (t) for (var U = 0; (D = v[U]) != null; U++) if (D) { I = M(D, t, U, v); var Ha = m ^ !!I; if (l && I != null) if (Ha) y = true; else v[U] = false; else if (Ha) { p.push(D); y = true } } if (I !== w) { l || (v = p); g = g.replace(n.match[H], ""); if (!y) return []; break } } } if (g === q) if (y == null) k.error(g); else break; q = g } return v }; k.error = function(g) { throw "Syntax error, unrecognized expression: " + g; }; var n = k.selectors = { order: ["ID", "NAME", "TAG"], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(g) { return g.getAttribute("href") } }, relative: { "+": function(g, h) { var l = typeof h === "string", m = l && !/\W/.test(h); l = l && !m; if (m) h = h.toLowerCase(); m = 0; for (var q = g.length, p; m < q; m++) if (p = g[m]) { for (; (p = p.previousSibling) && p.nodeType !== 1;); g[m] = l || p && p.nodeName.toLowerCase() === h ? p || false : p === h } l && k.filter(h, g, true) }, ">": function(g, h) { var l = typeof h === "string"; if (l && !/\W/.test(h)) { h = h.toLowerCase(); for (var m = 0, q = g.length; m < q; m++) { var p = g[m]; if (p) { l = p.parentNode; g[m] = l.nodeName.toLowerCase() === h ? l : false } } } else { m = 0; for (q = g.length; m < q; m++) if (p = g[m]) g[m] = l ? p.parentNode : p.parentNode === h; l && k.filter(h, g, true) } }, "": function(g, h, l) { var m = e++, q = d; if (typeof h === "string" && !/\W/.test(h)) { var p = h = h.toLowerCase(); q = b } q("parentNode", h, m, g, p, l) }, "~": function(g, h, l) { var m = e++, q = d; if (typeof h === "string" && !/\W/.test(h)) { var p = h = h.toLowerCase(); q = b } q("previousSibling", h, m, g, p, l) } }, find: { ID: function(g, h, l) { if (typeof h.getElementById !== "undefined" && !l) return (g = h.getElementById(g[1])) ? [g] : [] }, NAME: function(g, h) { if (typeof h.getElementsByName !== "undefined") { var l = []; h = h.getElementsByName(g[1]); for (var m = 0, q = h.length; m < q; m++) h[m].getAttribute("name") === g[1] && l.push(h[m]); return l.length === 0 ? null : l } }, TAG: function(g, h) { return h.getElementsByTagName(g[1]) } }, preFilter: { CLASS: function(g, h, l, m, q, p) { g = " " + g[1].replace(/\\/g, "") + " "; if (p) return g; p = 0; for (var v; (v = h[p]) != null; p++) if (v) if (q ^ (v.className && (" " + v.className + " ").replace(/[\t\n]/g, " ").indexOf(g) >= 0)) l || m.push(v); else if (l) h[p] = false; return false }, ID: function(g) { return g[1].replace(/\\/g, "") }, TAG: function(g) { return g[1].toLowerCase() }, CHILD: function(g) { if (g[1] === "nth") { var h = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2] === "even" && "2n" || g[2] === "odd" && "2n+1" || !/\D/.test(g[2]) && "0n+" + g[2] || g[2]); g[2] = h[1] + (h[2] || 1) - 0; g[3] = h[3] - 0 } g[0] = e++; return g }, ATTR: function(g, h, l, m, q, p) { h = g[1].replace(/\\/g, ""); if (!p && n.attrMap[h]) g[1] = n.attrMap[h]; if (g[2] === "~=") g[4] = " " + g[4] + " "; return g }, PSEUDO: function(g, h, l, m, q) { if (g[1] === "not") if ((f.exec(g[3]) || "").length > 1 || /^\w/.test(g[3])) g[3] = k(g[3], null, null, h); else { g = k.filter(g[3], h, l, true ^ q); l || m.push.apply(m, g); return false } else if (n.match.POS.test(g[0]) || n.match.CHILD.test(g[0])) return true; return g }, POS: function(g) { g.unshift(true); return g } }, filters: { enabled: function(g) { return g.disabled === false && g.type !== "hidden" }, disabled: function(g) { return g.disabled === true }, checked: function(g) { return g.checked === true }, selected: function(g) { return g.selected === true }, parent: function(g) { return !!g.firstChild }, empty: function(g) { return !g.firstChild }, has: function(g, h, l) { return !!k(l[3], g).length }, header: function(g) { return /h\d/i.test(g.nodeName) }, text: function(g) { return "text" === g.type }, radio: function(g) { return "radio" === g.type }, checkbox: function(g) { return "checkbox" === g.type }, file: function(g) { return "file" === g.type }, password: function(g) { return "password" === g.type }, submit: function(g) { return "submit" === g.type }, image: function(g) { return "image" === g.type }, reset: function(g) { return "reset" === g.type }, button: function(g) { return "button" === g.type || g.nodeName.toLowerCase() === "button" }, input: function(g) { return /input|select|textarea|button/i.test(g.nodeName) } }, setFilters: { first: function(g, h) { return h === 0 }, last: function(g, h, l, m) { return h === m.length - 1 }, even: function(g, h) { return h % 2 === 0 }, odd: function(g, h) { return h % 2 === 1 }, lt: function(g, h, l) { return h < l[3] - 0 }, gt: function(g, h, l) { return h > l[3] - 0 }, nth: function(g, h, l) { return l[3] - 0 === h }, eq: function(g, h, l) { return l[3] - 0 === h } }, filter: { PSEUDO: function(g, h, l, m) { var q = h[1], p = n.filters[q]; if (p) return p(g, l, h, m); else if (q === "contains") return (g.textContent || g.innerText || a([g]) || "").indexOf(h[3]) >= 0; else if (q === "not") { h = h[3]; l = 0; for (m = h.length; l < m; l++) if (h[l] === g) return false; return true } else k.error("Syntax error, unrecognized expression: " + q) }, CHILD: function(g, h) { var l = h[1], m = g; switch (l) { case "only": case "first": for (; m = m.previousSibling;) if (m.nodeType === 1) return false; if (l === "first") return true; m = g; case "last": for (; m = m.nextSibling;) if (m.nodeType === 1) return false; return true; case "nth": l = h[2]; var q = h[3]; if (l === 1 && q === 0) return true; h = h[0]; var p = g.parentNode; if (p && (p.sizcache !== h || !g.nodeIndex)) { var v = 0; for (m = p.firstChild; m; m = m.nextSibling) if (m.nodeType === 1) m.nodeIndex = ++v; p.sizcache = h } g = g.nodeIndex - q; return l === 0 ? g === 0 : g % l === 0 && g / l >= 0 } }, ID: function(g, h) { return g.nodeType === 1 && g.getAttribute("id") === h }, TAG: function(g, h) { return h === "*" && g.nodeType === 1 || g.nodeName.toLowerCase() === h }, CLASS: function(g, h) { return (" " + (g.className || g.getAttribute("class")) + " ").indexOf(h) > -1 }, ATTR: function(g, h) { var l = h[1]; g = n.attrHandle[l] ? n.attrHandle[l](g) : g[l] != null ? g[l] : g.getAttribute(l); l = g + ""; var m = h[2]; h = h[4]; return g == null ? m === "!=" : m === "=" ? l === h : m === "*=" ? l.indexOf(h) >= 0 : m === "~=" ? (" " + l + " ").indexOf(h) >= 0 : !h ? l && g !== false : m === "!=" ? l !== h : m === "^=" ? l.indexOf(h) === 0 : m === "$=" ? l.substr(l.length - h.length) === h : m === "|=" ? l === h || l.substr(0, h.length + 1) === h + "-" : false }, POS: function(g, h, l, m) { var q = n.setFilters[h[2]]; if (q) return q(g, l, h, m) } } }, r = n.match.POS; for (var u in n.match) { n.match[u] = new RegExp(n.match[u].source + /(?![^\[]*\])(?![^\(]*\))/.source); n.leftMatch[u] = new RegExp(/(^(?:.|\r|\n)*?)/.source + n.match[u].source.replace(/\\(\d+)/g, function(g, h) { return "\\" + (h - 0 + 1) })) } var z = function(g, h) { g = Array.prototype.slice.call(g, 0); if (h) { h.push.apply(h, g); return h } return g }; try { Array.prototype.slice.call(s.documentElement.childNodes, 0) } catch (C) { z = function(g, h) { h = h || []; if (j.call(g) === "[object Array]") Array.prototype.push.apply(h, g); else if (typeof g.length === "number") for (var l = 0, m = g.length; l < m; l++) h.push(g[l]); else for (l = 0; g[l]; l++) h.push(g[l]); return h } } var B; if (s.documentElement.compareDocumentPosition) B = function(g, h) { if (!g.compareDocumentPosition || !h.compareDocumentPosition) { if (g == h) i = true; return g.compareDocumentPosition ? -1 : 1 } g = g.compareDocumentPosition(h) & 4 ? -1 : g === h ? 0 : 1; if (g === 0) i = true; return g }; else if ("sourceIndex" in s.documentElement) B = function(g, h) { if (!g.sourceIndex || !h.sourceIndex) { if (g == h) i = true; return g.sourceIndex ? -1 : 1 } g = g.sourceIndex - h.sourceIndex; if (g === 0) i = true; return g }; else if (s.createRange) B = function(g, h) { if (!g.ownerDocument || !h.ownerDocument) { if (g == h) i = true; return g.ownerDocument ? -1 : 1 } var l = g.ownerDocument.createRange(), m = h.ownerDocument.createRange(); l.setStart(g, 0); l.setEnd(g, 0); m.setStart(h, 0); m.setEnd(h, 0); g = l.compareBoundaryPoints(Range.START_TO_END, m); if (g === 0) i = true; return g }; (function() { var g = s.createElement("div"), h = "script" + (new Date).getTime(); g.innerHTML = "<a name='" + h + "'/>"; var l = s.documentElement; l.insertBefore(g, l.firstChild); if (s.getElementById(h)) { n.find.ID = function(m, q, p) { if (typeof q.getElementById !== "undefined" && !p) return (q = q.getElementById(m[1])) ? q.id === m[1] || typeof q.getAttributeNode !== "undefined" && q.getAttributeNode("id").nodeValue === m[1] ? [q] : w : [] }; n.filter.ID = function(m, q) { var p = typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id"); return m.nodeType === 1 && p && p.nodeValue === q } } l.removeChild(g); l = g = null })(); (function() { var g = s.createElement("div"); g.appendChild(s.createComment("")); if (g.getElementsByTagName("*").length > 0) n.find.TAG = function(h, l) { l = l.getElementsByTagName(h[1]); if (h[1] === "*") { h = []; for (var m = 0; l[m]; m++) l[m].nodeType === 1 && h.push(l[m]); l = h } return l }; g.innerHTML = "<a href='#'></a>"; if (g.firstChild && typeof g.firstChild.getAttribute !== "undefined" && g.firstChild.getAttribute("href") !== "#") n.attrHandle.href = function(h) { return h.getAttribute("href", 2) }; g = null })(); s.querySelectorAll && function() { var g = k, h = s.createElement("div"); h.innerHTML = "<p class='TEST'></p>"; if (!(h.querySelectorAll && h.querySelectorAll(".TEST").length === 0)) { k = function(m, q, p, v) { q = q || s; if (!v && q.nodeType === 9 && !x(q)) try { return z(q.querySelectorAll(m), p) } catch (t) {} return g(m, q, p, v) }; for (var l in g) k[l] = g[l]; h = null } }(); (function() { var g = s.createElement("div"); g.innerHTML = "<div class='test e'></div><div class='test'></div>"; if (!(!g.getElementsByClassName || g.getElementsByClassName("e").length === 0)) { g.lastChild.className = "e"; if (g.getElementsByClassName("e").length !== 1) { n.order.splice(1, 0, "CLASS"); n.find.CLASS = function(h, l, m) { if (typeof l.getElementsByClassName !== "undefined" && !m) return l.getElementsByClassName(h[1]) }; g = null } } })(); var E = s.compareDocumentPosition ? function(g, h) { return !!(g.compareDocumentPosition(h) & 16) } : function(g, h) { return g !== h && (g.contains ? g.contains(h) : true) }, x = function(g) { return (g = (g ? g.ownerDocument || g : 0).documentElement) ? g.nodeName !== "HTML" : false }, ga = function(g, h) { var l = [], m = "", q; for (h = h.nodeType ? [h] : h; q = n.match.PSEUDO.exec(g);) { m += q[0]; g = g.replace(n.match.PSEUDO, "") } g = n.relative[g] ? g + "*" : g; q = 0; for (var p = h.length; q < p; q++) k(g, h[q], l); return k.filter(m, l) }; c.find = k; c.expr = k.selectors; c.expr[":"] = c.expr.filters; c.unique = k.uniqueSort; c.text = a; c.isXMLDoc = x; c.contains = E })(); var eb = /Until$/, fb = /^(?:parents|prevUntil|prevAll)/, gb = /,/; R = Array.prototype.slice; var Ia = function(a, b, d) { if (c.isFunction(b)) return c.grep(a, function(e, j) { return !!b.call(e, j, e) === d }); else if (b.nodeType) return c.grep(a, function(e) { return e === b === d }); else if (typeof b === "string") { var f = c.grep(a, function(e) { return e.nodeType === 1 }); if (Ua.test(b)) return c.filter(b, f, !d); else b = c.filter(b, f) } return c.grep(a, function(e) { return c.inArray(e, b) >= 0 === d }) }; c.fn.extend({ find: function(a) { for (var b = this.pushStack("", "find", a), d = 0, f = 0, e = this.length; f < e; f++) { d = b.length; c.find(a, this[f], b); if (f > 0) for (var j = d; j < b.length; j++) for (var i = 0; i < d; i++) if (b[i] === b[j]) { b.splice(j--, 1); break } } return b }, has: function(a) { var b = c(a); return this.filter(function() { for (var d = 0, f = b.length; d < f; d++) if (c.contains(this, b[d])) return true }) }, not: function(a) { return this.pushStack(Ia(this, a, false), "not", a) }, filter: function(a) { return this.pushStack(Ia(this, a, true), "filter", a) }, is: function(a) { return !!a && c.filter(a, this).length > 0 }, closest: function(a, b) { if (c.isArray(a)) { var d = [], f = this[0], e, j = {}, i; if (f && a.length) { e = 0; for (var o = a.length; e < o; e++) { i = a[e]; j[i] || (j[i] = c.expr.match.POS.test(i) ? c(i, b || this.context) : i) } for (; f && f.ownerDocument && f !== b;) { for (i in j) { e = j[i]; if (e.jquery ? e.index(f) > -1 : c(f).is(e)) { d.push({ selector: i, elem: f }); delete j[i] } } f = f.parentNode } } return d } var k = c.expr.match.POS.test(a) ? c(a, b || this.context) : null; return this.map(function(n, r) { for (; r && r.ownerDocument && r !== b;) { if (k ? k.index(r) > -1 : c(r).is(a)) return r; r = r.parentNode } return null }) }, index: function(a) { if (!a || typeof a === "string") return c.inArray(this[0], a ? c(a) : this.parent().children()); return c.inArray(a.jquery ? a[0] : a, this) }, add: function(a, b) { a = typeof a === "string" ? c(a, b || this.context) : c.makeArray(a); b = c.merge(this.get(), a); return this.pushStack(qa(a[0]) || qa(b[0]) ? b : c.unique(b)) }, andSelf: function() { return this.add(this.prevObject) } }); c.each({ parent: function(a) { return (a = a.parentNode) && a.nodeType !== 11 ? 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 c.nth(a, 2, "nextSibling") }, prev: function(a) { return c.nth(a, 2, "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.makeArray(a.childNodes) } }, function(a, b) { c.fn[a] = function(d, f) { var e = c.map(this, b, d); eb.test(a) || (f = d); if (f && typeof f === "string") e = c.filter(f, e); e = this.length > 1 ? c.unique(e) : e; if ((this.length > 1 || gb.test(f)) && fb.test(a)) e = e.reverse(); return this.pushStack(e, a, R.call(arguments).join(",")) } }); c.extend({ filter: function(a, b, d) { if (d) a = ":not(" + a + ")"; return c.find.matches(a, b) }, dir: function(a, b, d) { var f = []; for (a = a[b]; a && a.nodeType !== 9 && (d === w || a.nodeType !== 1 || !c(a).is(d));) { a.nodeType === 1 && f.push(a); a = a[b] } return f }, nth: function(a, b, d) { b = b || 1; for (var f = 0; a; a = a[d]) if (a.nodeType === 1 && ++f === b) break; return a }, sibling: function(a, b) { for (var d = []; a; a = a.nextSibling) a.nodeType === 1 && a !== b && d.push(a); return d } }); var Ja = / jQuery\d+="(?:\d+|null)"/g, V = /^\s+/, Ka = /(<([\w:]+)[^>]*?)\/>/g, hb = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, La = /<([\w:]+)/, ib = /<tbody/i, jb = /<|&#?\w+;/, ta = /<script|<object|<embed|<option|<style/i, ua = /checked\s*(?:[^=]|=\s*.checked.)/i, Ma = function(a, b, d) { return hb.test(d) ? a : b + "></" + d + ">" }, F = { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], area: [1, "<map>", "</map>"], _default: [0, "", ""] }; F.optgroup = F.option; F.tbody = F.tfoot = F.colgroup = F.caption = F.thead; F.th = F.td; if (!c.support.htmlSerialize) F._default = [1, "div<div>", "</div>"]; c.fn.extend({ text: function(a) { if (c.isFunction(a)) return this.each(function(b) { var d = c(this); d.text(a.call(this, b, d.text())) }); if (typeof a !== "object" && a !== w) return this.empty().append((this[0] && this[0].ownerDocument || s).createTextNode(a)); return c.text(this) }, wrapAll: function(a) { if (c.isFunction(a)) return this.each(function(d) { c(this).wrapAll(a.call(this, d)) }); if (this[0]) { var b = c(a, this[0].ownerDocument).eq(0).clone(true); this[0].parentNode && b.insertBefore(this[0]); b.map(function() { for (var d = this; d.firstChild && d.firstChild.nodeType === 1;) d = d.firstChild; return d }).append(this) } return this }, wrapInner: function(a) { if (c.isFunction(a)) return this.each(function(b) { c(this).wrapInner(a.call(this, b)) }); return this.each(function() { var b = c(this), d = b.contents(); d.length ? d.wrapAll(a) : b.append(a) }) }, wrap: function(a) { return this.each(function() { c(this).wrapAll(a) }) }, unwrap: function() { return this.parent().each(function() { c.nodeName(this, "body") || c(this).replaceWith(this.childNodes) }).end() }, append: function() { return this.domManip(arguments, true, function(a) { this.nodeType === 1 && this.appendChild(a) }) }, prepend: function() { return this.domManip(arguments, true, function(a) { this.nodeType === 1 && this.insertBefore(a, this.firstChild) }) }, before: function() { if (this[0] && this[0].parentNode) return this.domManip(arguments, false, function(b) { this.parentNode.insertBefore(b, this) }); else if (arguments.length) { var a = c(arguments[0]); a.push.apply(a, this.toArray()); return this.pushStack(a, "before", arguments) } }, after: function() { if (this[0] && this[0].parentNode) return this.domManip(arguments, false, function(b) { this.parentNode.insertBefore(b, this.nextSibling) }); else if (arguments.length) { var a = this.pushStack(this, "after", arguments); a.push.apply(a, c(arguments[0]).toArray()); return a } }, remove: function(a, b) { for (var d = 0, f; (f = this[d]) != null; d++) if (!a || c.filter(a, [f]).length) { if (!b && f.nodeType === 1) { c.cleanData(f.getElementsByTagName("*")); c.cleanData([f]) } f.parentNode && f.parentNode.removeChild(f) } return this }, empty: function() { for (var a = 0, b; (b = this[a]) != null; a++) for (b.nodeType === 1 && c.cleanData(b.getElementsByTagName("*")); b.firstChild;) b.removeChild(b.firstChild); return this }, clone: function(a) { var b = this.map(function() { if (!c.support.noCloneEvent && !c.isXMLDoc(this)) { var d = this.outerHTML, f = this.ownerDocument; if (!d) { d = f.createElement("div"); d.appendChild(this.cloneNode(true)); d = d.innerHTML } return c.clean([d.replace(Ja, "").replace(/=([^="'>\s]+\/)>/g, '="$1">').replace(V, "")], f)[0] } else return this.cloneNode(true) }); if (a === true) { ra(this, b); ra(this.find("*"), b.find("*")) } return b }, html: function(a) { if (a === w) return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(Ja, "") : null; else if (typeof a === "string" && !ta.test(a) && (c.support.leadingWhitespace || !V.test(a)) && !F[(La.exec(a) || ["", ""])[1].toLowerCase()]) { a = a.replace(Ka, Ma); try { for (var b = 0, d = this.length; b < d; b++) if (this[b].nodeType === 1) { c.cleanData(this[b].getElementsByTagName("*")); this[b].innerHTML = a } } catch (f) { this.empty().append(a) } } else c.isFunction(a) ? this.each(function(e) { var j = c(this), i = j.html(); j.empty().append(function() { return a.call(this, e, i) }) }) : this.empty().append(a); return this }, replaceWith: function(a) { if (this[0] && this[0].parentNode) { if (c.isFunction(a)) return this.each(function(b) { var d = c(this), f = d.html(); d.replaceWith(a.call(this, b, f)) }); if (typeof a !== "string") a = c(a).detach(); return this.each(function() { var b = this.nextSibling, d = this.parentNode; c(this).remove(); b ? c(b).before(a) : c(d).append(a) }) } else return this.pushStack(c(c.isFunction(a) ? a() : a), "replaceWith", a) }, detach: function(a) { return this.remove(a, true) }, domManip: function(a, b, d) { function f(u) { return c.nodeName(u, "table") ? u.getElementsByTagName("tbody")[0] || u.appendChild(u.ownerDocument.createElement("tbody")) : u } var e, j, i = a[0], o = [], k; if (!c.support.checkClone && arguments.length === 3 && typeof i === "string" && ua.test(i)) return this.each(function() { c(this).domManip(a, b, d, true) }); if (c.isFunction(i)) return this.each(function(u) { var z = c(this); a[0] = i.call(this, u, b ? z.html() : w); z.domManip(a, b, d) }); if (this[0]) { e = i && i.parentNode; e = c.support.parentNode && e && e.nodeType === 11 && e.childNodes.length === this.length ? { fragment: e } : sa(a, this, o); k = e.fragment; if (j = k.childNodes.length === 1 ? (k = k.firstChild) : k.firstChild) { b = b && c.nodeName(j, "tr"); for (var n = 0, r = this.length; n < r; n++) d.call(b ? f(this[n], j) : this[n], n > 0 || e.cacheable || this.length > 1 ? k.cloneNode(true) : k) } o.length && c.each(o, Qa) } return this } }); c.fragments = {}; c.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(a, b) { c.fn[a] = function(d) { var f = []; d = c(d); var e = this.length === 1 && this[0].parentNode; if (e && e.nodeType === 11 && e.childNodes.length === 1 && d.length === 1) { d[b](this[0]); return this } else { e = 0; for (var j = d.length; e < j; e++) { var i = (e > 0 ? this.clone(true) : this).get(); c.fn[b].apply(c(d[e]), i); f = f.concat(i) } return this.pushStack(f, a, d.selector) } } }); c.extend({ clean: function(a, b, d, f) { b = b || s; if (typeof b.createElement === "undefined") b = b.ownerDocument || b[0] && b[0].ownerDocument || s; for (var e = [], j = 0, i; (i = a[j]) != null; j++) { if (typeof i === "number") i += ""; if (i) { if (typeof i === "string" && !jb.test(i)) i = b.createTextNode(i); else if (typeof i === "string") { i = i.replace(Ka, Ma); var o = (La.exec(i) || ["", "" ])[1].toLowerCase(), k = F[o] || F._default, n = k[0], r = b.createElement("div"); for (r.innerHTML = k[1] + i + k[2]; n--;) r = r.lastChild; if (!c.support.tbody) { n = ib.test(i); o = o === "table" && !n ? r.firstChild && r.firstChild.childNodes : k[1] === "<table>" && !n ? r.childNodes : []; for (k = o.length - 1; k >= 0; --k) c.nodeName(o[k], "tbody") && !o[k].childNodes.length && o[k].parentNode.removeChild(o[k]) }!c.support.leadingWhitespace && V.test(i) && r.insertBefore(b.createTextNode(V.exec(i)[0]), r.firstChild); i = r.childNodes } if (i.nodeType) e.push(i); else e = c.merge(e, i) } } if (d) for (j = 0; e[j]; j++) if (f && c.nodeName(e[j], "script") && (!e[j].type || e[j].type.toLowerCase() === "text/javascript")) f.push(e[j].parentNode ? e[j].parentNode.removeChild(e[j]) : e[j]); else { e[j].nodeType === 1 && e.splice.apply(e, [j + 1, 0].concat(c.makeArray(e[j].getElementsByTagName("script")))); d.appendChild(e[j]) } return e }, cleanData: function(a) { for (var b, d, f = c.cache, e = c.event.special, j = c.support.deleteExpando, i = 0, o; (o = a[i]) != null; i++) if (d = o[c.expando]) { b = f[d]; if (b.events) for (var k in b.events) e[k] ? c.event.remove(o, k) : Ca(o, k, b.handle); if (j) delete o[c.expando]; else o.removeAttribute && o.removeAttribute(c.expando); delete f[d] } } }); var kb = /z-?index|font-?weight|opacity|zoom|line-?height/i, Na = /alpha\([^)]*\)/, Oa = /opacity=([^)]*)/, ha = /float/i, ia = /-([a-z])/ig, lb = /([A-Z])/g, mb = /^-?\d+(?:px)?$/i, nb = /^-?\d/, ob = { position: "absolute", visibility: "hidden", display: "block" }, pb = ["Left", "Right"], qb = ["Top", "Bottom"], rb = s.defaultView && s.defaultView.getComputedStyle, Pa = c.support.cssFloat ? "cssFloat" : "styleFloat", ja = function(a, b) { return b.toUpperCase() }; c.fn.css = function(a, b) { return X(this, a, b, true, function(d, f, e) { if (e === w) return c.curCSS(d, f); if (typeof e === "number" && !kb.test(f)) e += "px"; c.style(d, f, e) }) }; c.extend({ style: function(a, b, d) { if (!a || a.nodeType === 3 || a.nodeType === 8) return w; if ((b === "width" || b === "height") && parseFloat(d) < 0) d = w; var f = a.style || a, e = d !== w; if (!c.support.opacity && b === "opacity") { if (e) { f.zoom = 1; b = parseInt(d, 10) + "" === "NaN" ? "" : "alpha(opacity=" + d * 100 + ")"; a = f.filter || c.curCSS(a, "filter") || ""; f.filter = Na.test(a) ? a.replace(Na, b) : b } return f.filter && f.filter.indexOf("opacity=") >= 0 ? parseFloat(Oa.exec(f.filter)[1]) / 100 + "" : "" } if (ha.test(b)) b = Pa; b = b.replace(ia, ja); if (e) f[b] = d; return f[b] }, css: function(a, b, d, f) { if (b === "width" || b === "height") { var e, j = b === "width" ? pb : qb; function i() { e = b === "width" ? a.offsetWidth : a.offsetHeight; f !== "border" && c.each(j, function() { f || (e -= parseFloat(c.curCSS(a, "padding" + this, true)) || 0); if (f === "margin") e += parseFloat(c.curCSS(a, "margin" + this, true)) || 0; else e -= parseFloat(c.curCSS(a, "border" + this + "Width", true)) || 0 }) } a.offsetWidth !== 0 ? i() : c.swap(a, ob, i); return Math.max(0, Math.round(e)) } return c.curCSS(a, b, d) }, curCSS: function(a, b, d) { var f, e = a.style; if (!c.support.opacity && b === "opacity" && a.currentStyle) { f = Oa.test(a.currentStyle.filter || "") ? parseFloat(RegExp.$1) / 100 + "" : ""; return f === "" ? "1" : f } if (ha.test(b)) b = Pa; if (!d && e && e[b]) f = e[b]; else if (rb) { if (ha.test(b)) b = "float"; b = b.replace(lb, "-$1").toLowerCase(); e = a.ownerDocument.defaultView; if (!e) return null; if (a = e.getComputedStyle(a, null)) f = a.getPropertyValue(b); if (b === "opacity" && f === "") f = "1" } else if (a.currentStyle) { d = b.replace(ia, ja); f = a.currentStyle[b] || a.currentStyle[d]; if (!mb.test(f) && nb.test(f)) { b = e.left; var j = a.runtimeStyle.left; a.runtimeStyle.left = a.currentStyle.left; e.left = d === "fontSize" ? "1em" : f || 0; f = e.pixelLeft + "px"; e.left = b; a.runtimeStyle.left = j } } return f }, swap: function(a, b, d) { var f = {}; for (var e in b) { f[e] = a.style[e]; a.style[e] = b[e] } d.call(a); for (e in b) a.style[e] = f[e] } }); if (c.expr && c.expr.filters) { c.expr.filters.hidden = function(a) { var b = a.offsetWidth, d = a.offsetHeight, f = a.nodeName.toLowerCase() === "tr"; return b === 0 && d === 0 && !f ? true : b > 0 && d > 0 && !f ? false : c.curCSS(a, "display") === "none" }; c.expr.filters.visible = function(a) { return !c.expr.filters.hidden(a) } } var sb = J(), tb = /<script(.|\s)*?\/script>/gi, ub = /select|textarea/i, vb = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, N = /=\?(&|$)/, ka = /\?/, wb = /(\?|&)_=.*?(&|$)/, xb = /^(\w+:)?\/\/([^\/?#]+)/, yb = /%20/g, zb = c.fn.load; c.fn.extend({ load: function(a, b, d) { if (typeof a !== "string") return zb.call(this, a); else if (!this.length) return this; var f = a.indexOf(" "); if (f >= 0) { var e = a.slice(f, a.length); a = a.slice(0, f) } f = "GET"; if (b) if (c.isFunction(b)) { d = b; b = null } else if (typeof b === "object") { b = c.param(b, c.ajaxSettings.traditional); f = "POST" } var j = this; c.ajax({ url: a, type: f, dataType: "html", data: b, complete: function(i, o) { if (o === "success" || o === "notmodified") j.html(e ? c("<div />").append(i.responseText.replace(tb, "")).find(e) : i.responseText); d && j.each(d, [i.responseText, o, i]) } }); return this }, serialize: function() { return c.param(this.serializeArray()) }, serializeArray: function() { return this.map(function() { return this.elements ? c.makeArray(this.elements) : this }).filter(function() { return this.name && !this.disabled && (this.checked || ub.test(this.nodeName) || vb.test(this.type)) }).map(function(a, b) { a = c(this).val(); return a == null ? null : c.isArray(a) ? c.map(a, function(d) { return { name: b.name, value: d } }) : { name: b.name, value: a } }).get() } }); c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a, b) { c.fn[b] = function(d) { return this.bind(b, d) } }); c.extend({ get: function(a, b, d, f) { if (c.isFunction(b)) { f = f || d; d = b; b = null } return c.ajax({ type: "GET", url: a, data: b, success: d, dataType: f }) }, getScript: function(a, b) { return c.get(a, null, b, "script") }, getJSON: function(a, b, d) { return c.get(a, b, d, "json") }, post: function(a, b, d, f) { if (c.isFunction(b)) { f = f || d; d = b; b = {} } return c.ajax({ type: "POST", url: a, data: b, success: d, dataType: f }) }, ajaxSetup: function(a) { c.extend(c.ajaxSettings, a) }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, xhr: A.XMLHttpRequest && (A.location.protocol !== "file:" || !A.ActiveXObject) ? function() { return new A.XMLHttpRequest } : function() { try { return new A.ActiveXObject("Microsoft.XMLHTTP") } catch (a) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, lastModified: {}, etag: {}, ajax: function(a) { function b() { e.success && e.success.call(k, o, i, x); e.global && f("ajaxSuccess", [x, e]) } function d() { e.complete && e.complete.call(k, x, i); e.global && f("ajaxComplete", [x, e]); e.global && !--c.active && c.event.trigger("ajaxStop") } function f(q, p) { (e.context ? c(e.context) : c.event).trigger(q, p) } var e = c.extend(true, {}, c.ajaxSettings, a), j, i, o, k = a && a.context || e, n = e.type.toUpperCase(); if (e.data && e.processData && typeof e.data !== "string") e.data = c.param(e.data, e.traditional); if (e.dataType === "jsonp") { if (n === "GET") N.test(e.url) || (e.url += (ka.test(e.url) ? "&" : "?") + (e.jsonp || "callback") + "=?"); else if (!e.data || !N.test(e.data)) e.data = (e.data ? e.data + "&" : "") + (e.jsonp || "callback") + "=?"; e.dataType = "json" } if (e.dataType === "json" && (e.data && N.test(e.data) || N.test(e.url))) { j = e.jsonpCallback || "jsonp" + sb++; if (e.data) e.data = (e.data + "").replace(N, "=" + j + "$1"); e.url = e.url.replace(N, "=" + j + "$1"); e.dataType = "script"; A[j] = A[j] || function(q) { o = q; b(); d(); A[j] = w; try { delete A[j] } catch (p) {} z && z.removeChild(C) } } if (e.dataType === "script" && e.cache === null) e.cache = false; if (e.cache === false && n === "GET") { var r = J(), u = e.url.replace(wb, "$1_=" + r + "$2"); e.url = u + (u === e.url ? (ka.test(e.url) ? "&" : "?") + "_=" + r : "") } if (e.data && n === "GET") e.url += (ka.test(e.url) ? "&" : "?") + e.data; e.global && !c.active++ && c.event.trigger("ajaxStart"); r = (r = xb.exec(e.url)) && (r[1] && r[1] !== location.protocol || r[2] !== location.host); if (e.dataType === "script" && n === "GET" && r) { var z = s.getElementsByTagName("head")[0] || s.documentElement, C = s.createElement("script"); C.src = e.url; if (e.scriptCharset) C.charset = e.scriptCharset; if (!j) { var B = false; C.onload = C.onreadystatechange = function() { if (!B && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { B = true; b(); d(); C.onload = C.onreadystatechange = null; z && C.parentNode && z.removeChild(C) } } } z.insertBefore(C, z.firstChild); return w } var E = false, x = e.xhr(); if (x) { e.username ? x.open(n, e.url, e.async, e.username, e.password) : x.open(n, e.url, e.async); try { if (e.data || a && a.contentType) x.setRequestHeader("Content-Type", e.contentType); if (e.ifModified) { c.lastModified[e.url] && x.setRequestHeader("If-Modified-Since", c.lastModified[e.url]); c.etag[e.url] && x.setRequestHeader("If-None-Match", c.etag[e.url]) } r || x.setRequestHeader("X-Requested-With", "XMLHttpRequest"); x.setRequestHeader("Accept", e.dataType && e.accepts[e.dataType] ? e.accepts[e.dataType] + ", */*" : e.accepts._default) } catch (ga) {} if (e.beforeSend && e.beforeSend.call(k, x, e) === false) { e.global && !--c.active && c.event.trigger("ajaxStop"); x.abort(); return false } e.global && f("ajaxSend", [x, e]); var g = x.onreadystatechange = function(q) { if (!x || x.readyState === 0 || q === "abort") { E || d(); E = true; if (x) x.onreadystatechange = c.noop } else if (!E && x && (x.readyState === 4 || q === "timeout")) { E = true; x.onreadystatechange = c.noop; i = q === "timeout" ? "timeout" : !c.httpSuccess(x) ? "error" : e.ifModified && c.httpNotModified(x, e.url) ? "notmodified" : "success"; var p; if (i === "success") try { o = c.httpData(x, e.dataType, e) } catch (v) { i = "parsererror"; p = v } if (i === "success" || i === "notmodified") j || b(); else c.handleError(e, x, i, p); d(); q === "timeout" && x.abort(); if (e.async) x = null } }; try { var h = x.abort; x.abort = function() { x && h.call(x); g("abort") } } catch (l) {} e.async && e.timeout > 0 && setTimeout(function() { x && !E && g("timeout") }, e.timeout); try { x.send(n === "POST" || n === "PUT" || n === "DELETE" ? e.data : null) } catch (m) { c.handleError(e, x, null, m); d() } e.async || g(); return x } }, handleError: function(a, b, d, f) { if (a.error) a.error.call(a.context || a, b, d, f); if (a.global)(a.context ? c(a.context) : c.event).trigger("ajaxError", [b, a, f]) }, active: 0, httpSuccess: function(a) { try { return !a.status && location.protocol === "file:" || a.status >= 200 && a.status < 300 || a.status === 304 || a.status === 1223 || a.status === 0 } catch (b) {} return false }, httpNotModified: function(a, b) { var d = a.getResponseHeader("Last-Modified"), f = a.getResponseHeader("Etag"); if (d) c.lastModified[b] = d; if (f) c.etag[b] = f; return a.status === 304 || a.status === 0 }, httpData: function(a, b, d) { var f = a.getResponseHeader("content-type") || "", e = b === "xml" || !b && f.indexOf("xml") >= 0; a = e ? a.responseXML : a.responseText; e && a.documentElement.nodeName === "parsererror" && c.error("parsererror"); if (d && d.dataFilter) a = d.dataFilter(a, b); if (typeof a === "string") if (b === "json" || !b && f.indexOf("json") >= 0) a = c.parseJSON(a); else if (b === "script" || !b && f.indexOf("javascript") >= 0) c.globalEval(a); return a }, param: function(a, b) { function d(i, o) { if (c.isArray(o)) c.each(o, function(k, n) { b || /\[\]$/.test(i) ? f(i, n) : d(i + "[" + (typeof n === "object" || c.isArray(n) ? k : "") + "]", n) }); else !b && o != null && typeof o === "object" ? c.each(o, function(k, n) { d(i + "[" + k + "]", n) }) : f(i, o) } function f(i, o) { o = c.isFunction(o) ? o() : o; e[e.length] = encodeURIComponent(i) + "=" + encodeURIComponent(o) } var e = []; if (b === w) b = c.ajaxSettings.traditional; if (c.isArray(a) || a.jquery) c.each(a, function() { f(this.name, this.value) }); else for (var j in a) d(j, a[j]); return e.join("&").replace(yb, "+") } }); var la = {}, Ab = /toggle|show|hide/, Bb = /^([+-]=)?([\d+-.]+)(.*)$/, W, va = [ ["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"], ["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"], ["opacity"] ]; c.fn.extend({ show: function(a, b) { if (a || a === 0) return this.animate(K("show", 3), a, b); else { a = 0; for (b = this.length; a < b; a++) { var d = c.data(this[a], "olddisplay"); this[a].style.display = d || ""; if (c.css(this[a], "display") === "none") { d = this[a].nodeName; var f; if (la[d]) f = la[d]; else { var e = c("<" + d + " />").appendTo("body"); f = e.css("display"); if (f === "none") f = "block"; e.remove(); la[d] = f } c.data(this[a], "olddisplay", f) } } a = 0; for (b = this.length; a < b; a++) this[a].style.display = c.data(this[a], "olddisplay") || ""; return this } }, hide: function(a, b) { if (a || a === 0) return this.animate(K("hide", 3), a, b); else { a = 0; for (b = this.length; a < b; a++) { var d = c.data(this[a], "olddisplay"); !d && d !== "none" && c.data(this[a], "olddisplay", c.css(this[a], "display")) } a = 0; for (b = this.length; a < b; a++) this[a].style.display = "none"; return this } }, _toggle: c.fn.toggle, toggle: function(a, b) { var d = typeof a === "boolean"; if (c.isFunction(a) && c.isFunction(b)) this._toggle.apply(this, arguments); else a == null || d ? this.each(function() { var f = d ? a : c(this).is(":hidden"); c(this)[f ? "show" : "hide"]() }) : this.animate(K("toggle", 3), a, b); return this }, fadeTo: function(a, b, d) { return this.filter(":hidden").css("opacity", 0).show().end().animate({ opacity: b }, a, d) }, animate: function(a, b, d, f) { var e = c.speed(b, d, f); if (c.isEmptyObject(a)) return this.each(e.complete); return this[e.queue === false ? "each" : "queue"](function() { var j = c.extend({}, e), i, o = this.nodeType === 1 && c(this).is(":hidden"), k = this; for (i in a) { var n = i.replace(ia, ja); if (i !== n) { a[n] = a[i]; delete a[i]; i = n } if (a[i] === "hide" && o || a[i] === "show" && !o) return j.complete.call(this); if ((i === "height" || i === "width") && this.style) { j.display = c.css(this, "display"); j.overflow = this.style.overflow } if (c.isArray(a[i])) { (j.specialEasing = j.specialEasing || {})[i] = a[i][1]; a[i] = a[i][0] } } if (j.overflow != null) this.style.overflow = "hidden"; j.curAnim = c.extend({}, a); c.each(a, function(r, u) { var z = new c.fx(k, j, r); if (Ab.test(u)) z[u === "toggle" ? o ? "show" : "hide" : u](a); else { var C = Bb.exec(u), B = z.cur(true) || 0; if (C) { u = parseFloat(C[2]); var E = C[3] || "px"; if (E !== "px") { k.style[r] = (u || 1) + E; B = (u || 1) / z.cur(true) * B; k.style[r] = B + E } if (C[1]) u = (C[1] === "-=" ? -1 : 1) * u + B; z.custom(B, u, E) } else z.custom(B, u, "") } }); return true }) }, stop: function(a, b) { var d = c.timers; a && this.queue([]); this.each(function() { for (var f = d.length - 1; f >= 0; f--) if (d[f].elem === this) { b && d[f](true); d.splice(f, 1) } }); b || this.dequeue(); return this } }); c.each({ slideDown: K("show", 1), slideUp: K("hide", 1), slideToggle: K("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function(a, b) { c.fn[a] = function(d, f) { return this.animate(b, d, f) } }); c.extend({ speed: function(a, b, d) { var f = a && typeof a === "object" ? a : { complete: d || !d && b || c.isFunction(a) && a, duration: a, easing: d && b || b && !c.isFunction(b) && b }; f.duration = c.fx.off ? 0 : typeof f.duration === "number" ? f.duration : c.fx.speeds[f.duration] || c.fx.speeds._default; f.old = f.complete; f.complete = function() { f.queue !== false && c(this).dequeue(); c.isFunction(f.old) && f.old.call(this) }; return f }, easing: { linear: function(a, b, d, f) { return d + f * a }, swing: function(a, b, d, f) { return (-Math.cos(a * Math.PI) / 2 + 0.5) * f + d } }, timers: [], fx: function(a, b, d) { this.options = b; this.elem = a; this.prop = d; if (!b.orig) b.orig = {} } }); c.fx.prototype = { update: function() { this.options.step && this.options.step.call(this.elem, this.now, this); (c.fx.step[this.prop] || c.fx.step._default)(this); if ((this.prop === "height" || this.prop === "width") && this.elem.style) this.elem.style.display = "block" }, cur: function(a) { if (this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null)) return this.elem[this.prop]; return (a = parseFloat(c.css(this.elem, this.prop, a))) && a > -10000 ? a : parseFloat(c.curCSS(this.elem, this.prop)) || 0 }, custom: function(a, b, d) { function f(j) { return e.step(j) } this.startTime = J(); this.start = a; this.end = b; this.unit = d || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var e = this; f.elem = this.elem; if (f() && c.timers.push(f) && !W) W = setInterval(c.fx.tick, 13) }, show: function() { this.options.orig[this.prop] = c.style(this.elem, this.prop); this.options.show = true; this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); c(this.elem).show() }, hide: function() { this.options.orig[this.prop] = c.style(this.elem, this.prop); this.options.hide = true; this.custom(this.cur(), 0) }, step: function(a) { var b = J(), d = true; if (a || b >= this.options.duration + this.startTime) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[this.prop] = true; for (var f in this.options.curAnim) if (this.options.curAnim[f] !== true) d = false; if (d) { if (this.options.display != null) { this.elem.style.overflow = this.options.overflow; a = c.data(this.elem, "olddisplay"); this.elem.style.display = a ? a : this.options.display; if (c.css(this.elem, "display") === "none") this.elem.style.display = "block" } this.options.hide && c(this.elem).hide(); if (this.options.hide || this.options.show) for (var e in this.options.curAnim) c.style(this.elem, e, this.options.orig[e]); this.options.complete.call(this.elem) } return false } else { e = b - this.startTime; this.state = e / this.options.duration; a = this.options.easing || (c.easing.swing ? "swing" : "linear"); this.pos = c.easing[this.options.specialEasing && this.options.specialEasing[this.prop] || a](this.state, e, 0, 1, this.options.duration); this.now = this.start + (this.end - this.start) * this.pos; this.update() } return true } }; c.extend(c.fx, { tick: function() { for (var a = c.timers, b = 0; b < a.length; b++) a[b]() || a.splice(b--, 1); a.length || c.fx.stop() }, stop: function() { clearInterval(W); W = null }, speeds: { slow: 600, fast: 200, _default: 400 }, step: { opacity: function(a) { c.style(a.elem, "opacity", a.now) }, _default: function(a) { if (a.elem.style && a.elem.style[a.prop] != null) a.elem.style[a.prop] = (a.prop === "width" || a.prop === "height" ? Math.max(0, a.now) : a.now) + a.unit; else a.elem[a.prop] = a.now } } }); if (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 = "getBoundingClientRect" in s.documentElement ? function(a) { var b = this[0]; if (a) return this.each(function(e) { c.offset.setOffset(this, a, e) }); if (!b || !b.ownerDocument) return null; if (b === b.ownerDocument.body) return c.offset.bodyOffset(b); var d = b.getBoundingClientRect(), f = b.ownerDocument; b = f.body; f = f.documentElement; return { top: d.top + (self.pageYOffset || c.support.boxModel && f.scrollTop || b.scrollTop) - (f.clientTop || b.clientTop || 0), left: d.left + (self.pageXOffset || c.support.boxModel && f.scrollLeft || b.scrollLeft) - (f.clientLeft || b.clientLeft || 0) } } : function(a) { var b = this[0]; if (a) return this.each(function(r) { c.offset.setOffset(this, a, r) }); if (!b || !b.ownerDocument) return null; if (b === b.ownerDocument.body) return c.offset.bodyOffset(b); c.offset.initialize(); var d = b.offsetParent, f = b, e = b.ownerDocument, j, i = e.documentElement, o = e.body; f = (e = e.defaultView) ? e.getComputedStyle(b, null) : b.currentStyle; for (var k = b.offsetTop, n = b.offsetLeft; (b = b.parentNode) && b !== o && b !== i;) { if (c.offset.supportsFixedPosition && f.position === "fixed") break; j = e ? e.getComputedStyle(b, null) : b.currentStyle; k -= b.scrollTop; n -= b.scrollLeft; if (b === d) { k += b.offsetTop; n += b.offsetLeft; if (c.offset.doesNotAddBorder && !(c.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(b.nodeName))) { k += parseFloat(j.borderTopWidth) || 0; n += parseFloat(j.borderLeftWidth) || 0 } f = d; d = b.offsetParent } if (c.offset.subtractsBorderForOverflowNotVisible && j.overflow !== "visible") { k += parseFloat(j.borderTopWidth) || 0; n += parseFloat(j.borderLeftWidth) || 0 } f = j } if (f.position === "relative" || f.position === "static") { k += o.offsetTop; n += o.offsetLeft } if (c.offset.supportsFixedPosition && f.position === "fixed") { k += Math.max(i.scrollTop, o.scrollTop); n += Math.max(i.scrollLeft, o.scrollLeft) } return { top: k, left: n } }; c.offset = { initialize: function() { var a = s.body, b = s.createElement("div"), d, f, e, j = parseFloat(c.curCSS(a, "marginTop", true)) || 0; c.extend(b.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" }); b.innerHTML = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; a.insertBefore(b, a.firstChild); d = b.firstChild; f = d.firstChild; e = d.nextSibling.firstChild.firstChild; this.doesNotAddBorder = f.offsetTop !== 5; this.doesAddBorderForTableAndCells = e.offsetTop === 5; f.style.position = "fixed"; f.style.top = "20px"; this.supportsFixedPosition = f.offsetTop === 20 || f.offsetTop === 15; f.style.position = f.style.top = ""; d.style.overflow = "hidden"; d.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = f.offsetTop === -5; this.doesNotIncludeMarginInBodyOffset = a.offsetTop !== j; a.removeChild(b); c.offset.initialize = c.noop }, bodyOffset: function(a) { var b = a.offsetTop, d = a.offsetLeft; c.offset.initialize(); if (c.offset.doesNotIncludeMarginInBodyOffset) { b += parseFloat(c.curCSS(a, "marginTop", true)) || 0; d += parseFloat(c.curCSS(a, "marginLeft", true)) || 0 } return { top: b, left: d } }, setOffset: function(a, b, d) { if (/static/.test(c.curCSS(a, "position"))) a.style.position = "relative"; var f = c(a), e = f.offset(), j = parseInt(c.curCSS(a, "top", true), 10) || 0, i = parseInt(c.curCSS(a, "left", true), 10) || 0; if (c.isFunction(b)) b = b.call(a, d, e); d = { top: b.top - e.top + j, left: b.left - e.left + i }; "using" in b ? b.using.call(a, d) : f.css(d) } }; c.fn.extend({ position: function() { if (!this[0]) return null; var a = this[0], b = this.offsetParent(), d = this.offset(), f = /^body|html$/i.test(b[0].nodeName) ? { top: 0, left: 0 } : b.offset(); d.top -= parseFloat(c.curCSS(a, "marginTop", true)) || 0; d.left -= parseFloat(c.curCSS(a, "marginLeft", true)) || 0; f.top += parseFloat(c.curCSS(b[0], "borderTopWidth", true)) || 0; f.left += parseFloat(c.curCSS(b[0], "borderLeftWidth", true)) || 0; return { top: d.top - f.top, left: d.left - f.left } }, offsetParent: function() { return this.map(function() { for (var a = this.offsetParent || s.body; a && !/^body|html$/i.test(a.nodeName) && c.css(a, "position") === "static";) a = a.offsetParent; return a }) } }); c.each(["Left", "Top"], function(a, b) { var d = "scroll" + b; c.fn[d] = function(f) { var e = this[0], j; if (!e) return null; if (f !== w) return this.each(function() { if (j = wa(this)) j.scrollTo(!a ? f : c(j).scrollLeft(), a ? f : c(j).scrollTop()); else this[d] = f }); else return (j = wa(e)) ? "pageXOffset" in j ? j[a ? "pageYOffset" : "pageXOffset"] : c.support.boxModel && j.document.documentElement[d] || j.document.body[d] : e[d] } }); c.each(["Height", "Width"], function(a, b) { var d = b.toLowerCase(); c.fn["inner" + b] = function() { return this[0] ? c.css(this[0], d, false, "padding") : null }; c.fn["outer" + b] = function(f) { return this[0] ? c.css(this[0], d, false, f ? "margin" : "border") : null }; c.fn[d] = function(f) { var e = this[0]; if (!e) return f == null ? null : this; if (c.isFunction(f)) return this.each(function(j) { var i = c(this); i[d](f.call(this, j, i[d]())) }); return "scrollTo" in e && e.document ? e.document.compatMode === "CSS1Compat" && e.document.documentElement["client" + b] || e.document.body["client" + b] : e.nodeType === 9 ? Math.max(e.documentElement["client" + b], e.body["scroll" + b], e.documentElement["scroll" + b], e.body["offset" + b], e.documentElement["offset" + b]) : f === w ? c.css(e, d) : this.css(d, typeof f === "string" ? f : f + "px") } }); A.jQuery = A.$ = c })(window);
import d3 from 'd3'; export default function update(el, data, isMain){ console.warn('update'); var width = el.clientWidth; var height = el.clientHeight; var count = data.length; var barWidth = width/count; var barColor = 'rgba(25, 183, 226, 0.1)'; var barBorderColor = '#01afde'; var meanColor = '#ff5454'; var meanY = d3.mean(data, d => { return d.y }); var meanValue = meanY < 10 ? Number(meanY.toFixed(2)) : Math.round(meanY); var duration = 400; var y = d3.scale.linear() .domain([0, d3.max(data, d => { return +d.y })]) .range([0, height]); // var yAxis = d3.svg.axis() // .scale(y) // .tickSize(width) // .tickFormat(d3.format('')) // .orient('right'); // // var gy = d3.select('.y.axis'); // gy // .transition() // .duration(duration) // .call(yAxis); // gy.selectAll('g').filter(d => { return d}) // .classed('minor', true); // // gy.selectAll('g').filter(d => { return !d}) // .classed('hidden', true); // // gy.selectAll('text') // .attr('font-family', 'helvetica') // .attr('font-size', 10) // .attr('fill', '#a6a6a6') // .attr('x', 4) // .attr('dy', -4); // if (isMain) { // var tooltip = d3.select('.chart-tooltip'); // } var bars = d3.select(el).selectAll('rect.bar-body') .data(data); bars .transition() .duration(duration) .attr('height', d => { return y(d.y) }) .attr('y', d => { return height-y(d.y) }) // .on('mousemove', showTooltip) // .on('mouseover', hideTooltip); if (isMain) { // tooltip.html(`=))<br/>ЧИсло: ${d.y}`); // bar.on('mousemove', d => { // tooltip // // .transition() // // .duration(150) // .style('opacity', 1); // tooltip.html(`=))<br/>ЧИсло: ${d.y}`) // .style('left', (d3.event.pageX-50)+"px") // .style('top', (d3.event.pageY+10)+"px"); // }) // bar.on('mouseout', d => { // tooltip // // .transition() // // .duration(150) // .style('opacity', 0); // }) } d3.select(el).selectAll('rect.bar-border') .data(data) .transition() .duration(duration) .attr('y', d => { return height-y(d.y) }); d3.select(el).selectAll('line.mean-line') .data(data) .transition() .duration(duration) .attr('y1', height - y(meanY)) .attr('y2', height - y(meanY)); d3.select(el).selectAll('rect.mean-counter') .data(data) .transition() .duration(duration) .attr('y', height - y(meanY) - 9); d3.select(el).selectAll('text.mean-text') .data(data) .transition() .duration(duration) .attr('y', height - y(meanY) + 3) .text(meanValue); }
var passport = require('passport'), BasicStrategy = require('passport-http').BasicStrategy, config = require('../config'); passport.use(new BasicStrategy(function (username, password, done){ if (username === config.username && password === config.password) return done(null, {auth: true}); return done(true); })); module.exports = passport.authenticate('basic', {session: false});
var Person = (function () { function Person(firstName, lastName, age) { var self = this; self.firstname = firstName; self.lastname = lastName; self.fullname = self.firstname + ' ' + self.lastname; self.age = age; } // validations: function validateName(name) { var i, len; if (name.length < 3 || name.length > 20) { return false; } for (i = 0, len = name.length; i < len; i += 1) { if (name[i] < 'A' || name[i] > 'z') { return false; } } return true } function validateAge(age) { if (isFinite(age)) { age = age | 0; if (age < 0 || age > 150) { return false; } } else { return false; } return true; } // Getters and setters: Object.defineProperty(Person.prototype, 'firstname', { get: function () { return this._firstName; }, set: function (name) { if (!validateName(name)) { throw new Error('Invalid first name') } this._firstName = name; } }); Object.defineProperty(Person.prototype, 'lastname', { get: function () { return this._lastName; }, set: function (name) { if (!validateName(name)) { throw new Error('Invalid last name') } this._lastName = name; } }); Object.defineProperty(Person.prototype, 'age', { get: function () { return this._age; }, set: function (age) { if (!validateAge(age)) { throw new Error('Invalid age') } this._age = age | 0; } }); Object.defineProperty(Person.prototype, 'fullname', { get: function () { return this._fullname; }, set: function (name) { var splittedName = name.split(' '); if (!validateName(splittedName[0]) || !validateName(splittedName[1])) { throw new Error('Invalid full name') } this._firstName = splittedName[0]; this._lastName = splittedName[1]; this._fullname = name; } }); return Person; }()); Person.prototype.introduce = function () { return 'Hello! My name is ' + this.fullname + ' and I am ' + this.age + '-years-old'; }; var firstPerson = new Person('John', 'Doe', 15); console.log(firstPerson.firstname); console.log(firstPerson.lastname); console.log(firstPerson.age); console.log(firstPerson.introduce());
module.exports = [ "Piazza", "Strada", "Via", "Borgo", "Contrada", "Rotonda", "Incrocio" ];
import i18n from '../../managers/i18n' i18n.register( 'zh-Hans', { uploader: '文件上传', selectFile: '选择文件', fileTypeInvalid: '文件的类型不符合要求', fileSizeInvalid: '文件的大小不符合要求', tooManyFiles: '文件的数量超过限制', uploadSuccess: '上传成功!', uploadFailure: '上传失败', remove: '移除', retry: '重试', replace: '重新上传', cancel: '取消', complete: '完成', error: '错误!', uploading: '上传中…', separator: ';' }, { ns: 'uploader' } )
var Update = function (model, version) { this.model = model; this.previous_version = version; }; Update.from = function (model, version) { return new Update(model, version); }; Update.prototype.to = function (version, migration) { return this.model.find({schema_version: this.previous_version}).exec(function (err, objects) { objects.forEach(function (obj) { obj.update(migration).exec(function (err2, res) { if (res) { console.log('Object Updated to Version {}'.format(version)); } else { console.log('Error while trying to update Object to Version {}'.format(version)) } }); }); }) }; module.exports = Update;
export default function setSelectionRange (containerEl, start, end) { var charIndex = 0 var range = document.createRange() range.setStart(containerEl, 0) range.collapse(true) var nodeStack = [containerEl] var node var foundStart = false var stop = false while (!stop && (node = nodeStack.pop())) { if (node.nodeType === 3) { var nextCharIndex = charIndex + node.length if (!foundStart && start >= charIndex && start <= nextCharIndex) { range.setStart(node, start - charIndex) foundStart = true } if (foundStart && end >= charIndex && end <= nextCharIndex) { range.setEnd(node, end - charIndex) stop = true } charIndex = nextCharIndex } else { var i = node.childNodes.length while (i--) { nodeStack.push(node.childNodes[i]) } } } var sel = window.getSelection() sel.removeAllRanges() sel.addRange(range) }
var express = require('express'); var path = require('path'); var logger = require('morgan'); var bodyParser = require('body-parser'); var cors = require('cors') var index = require('./routes/index'); var auth = require('./routes/auth'); var app = express() app.use(logger('dev')); app.use(bodyParser.json()); app.use(cors()); app.options('*', cors()) app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,Authorization, Accept"); next(); }); app.use('/auth',auth); //TODO uncomment this app.use(auth.jwtverify) //Middleware to verify jwt token app.use('/api', index); // 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 handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.send('error'); }); module.exports = app;
import React, { PropTypes, Component } from 'react'; import Gravatar from 'react-gravatar'; import { Link, browserHistory } from 'react-router'; class ScheduleItem extends Component { constructor() { super(); this.onClickAcceptAction = this.onClickAcceptAction.bind(this); this.onClickRejectAction = this.onClickRejectAction.bind(this); this.onClickSendMessageAction = this.onClickSendMessageAction.bind(this); this.onClickUsePromo = this.onClickUsePromo.bind(this); this.onClickRescheduleAction = this.onClickRescheduleAction.bind(this); this.onEnterRoom = this.onEnterRoom.bind(this); } onClickAcceptAction() { const { schedule, schedule: { modality }, onSetScheduleAction } = this.props; const action = modality === 'paid' ? 'accepted_awaiting_payment' : 'confirmed'; onSetScheduleAction({ action, scheduleId: schedule.id, receiverId: '' }); } onClickRejectAction() { const { schedule, onSetScheduleAction, userInfo } = this.props; const receiverId = userInfo === schedule.student_id ? schedule.teacher_id : schedule.student_id; onSetScheduleAction({ action: 'rejected', scheduleId: schedule.id, receiverId}); } onClickSendMessageAction() { const { schedule, onSetScheduleAction, userInfo } = this.props; const receiverId = userInfo === schedule.student_id ? schedule.teacher_id : schedule.student_id; onSetScheduleAction({ action: 'message', scheduleId: schedule.id, receiverId}); } onClickUsePromo() { const { schedule, onSetScheduleAction, userInfo } = this.props; const receiverId = userInfo === schedule.student_id ? schedule.teacher_id : schedule.student_id; onSetScheduleAction({ action: 'promo', scheduleId: schedule.id, receiverId}); } onClickRescheduleAction() { const { schedule, onSetAppointmenteType } = this.props; onSetAppointmenteType(schedule.modality); browserHistory.push(`/estudiantes/agendar-tutoria/${schedule.id}`); } onEnterRoom() { const { onGetSessionStatus, role, schedule } = this.props; onGetSessionStatus(role, schedule.id); } render() { const { role, schedule, pathname, couponsList } = this.props; const columnTableClass = pathname === '/tutores/tutorias-agendadas' ? 'schedule-list__row--teacher--large' : ''; return ( <tr> <td className={`schedule-list__row ${role === 'student' ? '' : 'schedule-list__row--teacher' }`}> <Gravatar className="schedule-list__photo" email={role === 'student' ? schedule.teacher_email||schedule.email : schedule.student_email||schedule.email} size={50} /> <div className="schedule-list__description"> <p className="schedule-list__description-txt">{schedule.start_at} <span className="schedule-list__duration">{`(${schedule.duration} min)`}</span></p> <p className="schedule-list__description-txt"><Link className="schedule-list__link">{role === 'student' ? schedule.teacher_name||`${schedule.first_name} ${schedule.last_name}` : schedule.student_name||`${schedule.first_name} ${schedule.last_name}`}</Link></p> </div> </td> <td className={`schedule-list__row ${role === 'student' ? '' : `schedule-list__row--teacher ${columnTableClass}` }`}> <p className="schedule-list__description-txt">{ schedule.modality === 'free' ? 'Entrevista Gratuita' : 'Tutoria'}</p> <p className="schedule-list__description-txt">Cálculo Diferencial</p> </td> <td className={`schedule-list__row ${role === 'student' ? '' : 'schedule-list__row--teacher' }`}> <img className="schedule-list__icon" src={require('../assets/images/calendar-icon.png')} /> <span className="schedule-list__description-highlight">{ role === 'student' ? schedule.status === 'awaiting_tutor' ? 'Esperando confirmación del tutor' : schedule.status === 'accepted_awaiting_payment' ? 'Esperando tu pago' : schedule.status === 'rejected' ? 'Tutoría Rechazada' : 'Tutoría confirmada' : role === 'teacher' ? schedule.status === 'awaiting_tutor' ? 'Esperando tu confirmación' : schedule.status === 'accepted_awaiting_payment' ? 'Esperando el pago del estudiante' : schedule.status === 'rejected' ? 'Tutoría Rechazada' : 'Tutoría confirmada' : '' }</span> </td> { role === 'student' ? <td className={`schedule-list__row ${role === 'student' ? '' : 'schedule-list__row--teacher' }`}> {schedule.status === 'accepted_awaiting_payment' ? <span> <a className="button button--light-green push-half--right" target="_blank" href={`https://brainsapi.herokuapp.com/order/${schedule.order&&schedule.order.number}`}>Pagar Tutoria</a> {couponsList && couponsList.length > 0 ? <a className="button button--transparent-blue" onClick={this.onClickUsePromo}>Usar Promo</a> : null} </span> : schedule.status !== 'confirmed' ? <button className="button button--blue" onClick={this.onClickRescheduleAction} >Volver a Agendar</button> : <button className="button button--dark-green" onClick={this.onEnterRoom} >Entrar al salón de clases</button> } </td> : <td className={`schedule-list__row ${role === 'student' ? '' : 'schedule-list__row--teacher' }`}> {schedule.status === 'awaiting_tutor' ? <div> <button className="button button--blue push-half--right" onClick={this.onClickAcceptAction} >Aceptar</button> <button className="button button--light-green push-half--right" onClick={this.onClickRejectAction} >Rechazar</button> <button className={`button button--transparent-blue ${pathname !== '/tutores/tutorias-agendadas' ? 'push-half--top' : ''}`} onClick={this.onClickSendMessageAction} >Enviar mensaje</button> </div> : schedule.status === 'confirmed' ? <button className="button button--dark-green" onClick={this.onEnterRoom} >Entrar al salón de clases</button> : <button className={`button button--transparent-blue ${pathname !== '/tutores/tutorias-agendadas' ? 'push-half--top' : ''}`} onClick={this.onClickSendMessageAction} >Enviar mensaje</button> } </td> } </tr> ); } } ScheduleItem.propTypes = { schedule: PropTypes.object, role: PropTypes.string, pathname: PropTypes.string, userInfo: PropTypes.object, onSetScheduleAction: PropTypes.func, onSetAppointmenteType: PropTypes.func, onGetSessionStatus: PropTypes.func, couponsList: PropTypes.array, }; export default ScheduleItem;
class Title extends React.Component { render() { return <h1>{this.props.title}</h1>; } } ReactDOM.render(<Title title="Hello world" />, document.getElementById("root"));
(function () { const themeStorage = new Proxy(localStorage, { get: function (target, prop) { return function (...args) { return target[prop + "Item"]("dark-mode", ...args); }; }, }); const skin_dir = "/assets/css/skins/"; const themes = { dark: "dark.css", light: "default.css", }; const systemColorDark = window.matchMedia("(prefers-color-scheme: dark)"); systemColorDark.addEventListener('change', function (e) { if (!themeStorage.get()) { changeTheme(e.matches, false); } }); let toggleButton; document.addEventListener("DOMContentLoaded", function () { const theme = themeStorage.get(); toggleButton = document.getElementById("theme-toggle"); toggleButton.checked = theme ? theme == "dark" : systemColorDark.matches; toggleButton.addEventListener("change", function (e) { changeTheme(e.target.checked, true); }); }); window.addEventListener("storage", function (e) { if (e.storageArea == localStorage && e.key == "dark-mode") { changeTheme(e.newValue || systemColorDark.matches, !!e.newValue); } }); function changeTheme(theme, persistent) { if (typeof theme == "boolean") { theme = theme ? "dark" : "light"; } document.querySelector(`link[rel="stylesheet"][href^="${skin_dir}"]`).href = skin_dir + themes[theme]; if (persistent) { themeStorage.set(theme); } if (toggleButton != null) { toggleButton.checked = theme == "dark"; } } changeTheme( themeStorage.get() || systemColorDark.matches, !!themeStorage.get() ); })();
/* global $, APP, config, Strophe*/ var Moderator = require("./moderator"); var EventEmitter = require("events"); var Recording = require("./recording"); var SDP = require("./SDP"); var Settings = require("../settings/Settings"); var Pako = require("pako"); var StreamEventTypes = require("../../service/RTC/StreamEventTypes"); var RTCEvents = require("../../service/RTC/RTCEvents"); var UIEvents = require("../../service/UI/UIEvents"); var XMPPEvents = require("../../service/xmpp/XMPPEvents"); var eventEmitter = new EventEmitter(); var connection = null; var authenticatedUser = false; function connect(jid, password) { connection = XMPP.createConnection(); Moderator.setConnection(connection); if (connection.disco) { // for chrome, add multistream cap } connection.jingle.pc_constraints = APP.RTC.getPCConstraints(); if (config.useIPv6) { // https://code.google.com/p/webrtc/issues/detail?id=2828 if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = []; connection.jingle.pc_constraints.optional.push({googIPv6: true}); } // Include user info in MUC presence var settings = Settings.getSettings(); if (settings.email) { connection.emuc.addEmailToPresence(settings.email); } if (settings.uid) { connection.emuc.addUserIdToPresence(settings.uid); } if (settings.displayName) { connection.emuc.addDisplayNameToPresence(settings.displayName); } var anonymousConnectionFailed = false; connection.connect(jid, password, function (status, msg) { console.log('Strophe status changed to', Strophe.getStatusString(status)); if (status === Strophe.Status.CONNECTED) { if (config.useStunTurn) { connection.jingle.getStunAndTurnCredentials(); } console.info("My Jabber ID: " + connection.jid); if(password) authenticatedUser = true; maybeDoJoin(); } else if (status === Strophe.Status.CONNFAIL) { if(msg === 'x-strophe-bad-non-anon-jid') { anonymousConnectionFailed = true; } } else if (status === Strophe.Status.DISCONNECTED) { if(anonymousConnectionFailed) { // prompt user for username and password XMPP.promptLogin(); } } else if (status === Strophe.Status.AUTHFAIL) { // wrong password or username, prompt user XMPP.promptLogin(); } }); } function maybeDoJoin() { if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) && (APP.RTC.localAudio || APP.RTC.localVideo)) { // .connected is true while connecting? doJoin(); } } function doJoin() { var roomName = APP.UI.generateRoomName(); Moderator.allocateConferenceFocus( roomName, APP.UI.checkForNicknameAndJoin); } function initStrophePlugins() { require("./strophe.emuc")(XMPP, eventEmitter); require("./strophe.jingle")(XMPP, eventEmitter); require("./strophe.moderate")(XMPP); require("./strophe.util")(); require("./strophe.rayo")(); require("./strophe.logger")(); } function registerListeners() { APP.RTC.addStreamListener(maybeDoJoin, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED); APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) { XMPP.addToPresence("devices", devices); }) APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) { XMPP.addToPresence("displayName", nickname); }); } function setupEvents() { $(window).bind('beforeunload', function () { if (connection && connection.connected) { // ensure signout $.ajax({ type: 'POST', url: config.bosh, async: false, cache: false, contentType: 'application/xml', data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'>" + "<presence xmlns='jabber:client' type='unavailable'/>" + "</body>", success: function (data) { console.log('signed out'); console.log(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log('signout error', textStatus + ' (' + errorThrown + ')'); } }); } XMPP.disposeConference(true); }); } var XMPP = { sessionTerminated: false, /** * XMPP connection status */ Status: Strophe.Status, XMPPEvents: XMPPEvents, /** * Remembers if we were muted by the focus. * @type {boolean} */ forceMuted: false, start: function () { setupEvents(); initStrophePlugins(); registerListeners(); Moderator.init(this, eventEmitter); var configDomain = config.hosts.anonymousdomain || config.hosts.domain; // Force authenticated domain if room is appended with '?login=true' if (config.hosts.anonymousdomain && window.location.search.indexOf("login=true") !== -1) { configDomain = config.hosts.domain; } var jid = configDomain || window.location.hostname; connect(jid, null); }, createConnection: function () { var bosh = config.bosh || '/http-bind'; return new Strophe.Connection(bosh); }, getStatusString: function (status) { return Strophe.getStatusString(status); }, promptLogin: function () { // FIXME: re-use LoginDialog which supports retries APP.UI.showLoginPopup(connect); }, joinRoom: function(roomName, useNicks, nick) { var roomjid; roomjid = roomName; if (useNicks) { if (nick) { roomjid += '/' + nick; } else { roomjid += '/' + Strophe.getNodeFromJid(connection.jid); } } else { var tmpJid = Strophe.getNodeFromJid(connection.jid); if(!authenticatedUser) tmpJid = tmpJid.substr(0, 8); roomjid += '/' + tmpJid; } connection.emuc.doJoin(roomjid); window.$injector.get("$rootScope").$apply(function() { window.$injector.get("meetingService").addSelf(roomjid); }); }, myJid: function () { if(!connection) return null; return connection.emuc.myroomjid; }, myResource: function () { if(!connection || ! connection.emuc.myroomjid) return null; return Strophe.getResourceFromJid(connection.emuc.myroomjid); }, disposeConference: function (onUnload) { eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload); var handler = connection.jingle.activecall; if (handler && handler.peerconnection) { // FIXME: probably removing streams is not required and close() should // be enough if (APP.RTC.localAudio) { handler.peerconnection.removeStream( APP.RTC.localAudio.getOriginalStream(), onUnload); } if (APP.RTC.localVideo) { handler.peerconnection.removeStream( APP.RTC.localVideo.getOriginalStream(), onUnload); } handler.peerconnection.close(); } connection.jingle.activecall = null; if(!onUnload) { this.sessionTerminated = true; connection.emuc.doLeave(); } }, addListener: function(type, listener) { eventEmitter.on(type, listener); }, removeListener: function (type, listener) { eventEmitter.removeListener(type, listener); }, allocateConferenceFocus: function(roomName, callback) { Moderator.allocateConferenceFocus(roomName, callback); }, getLoginUrl: function (roomName, callback) { Moderator.getLoginUrl(roomName, callback); }, getPopupLoginUrl: function (roomName, callback) { Moderator.getPopupLoginUrl(roomName, callback); }, isModerator: function () { return Moderator.isModerator(); }, isSipGatewayEnabled: function () { return Moderator.isSipGatewayEnabled(); }, isExternalAuthEnabled: function () { return Moderator.isExternalAuthEnabled(); }, switchStreams: function (stream, oldStream, callback) { if (connection && connection.jingle.activecall) { // FIXME: will block switchInProgress on true value in case of exception connection.jingle.activecall.switchStreams(stream, oldStream, callback); } else { // We are done immediately console.warn("No conference handler or conference not started yet"); callback(); } }, sendVideoInfoPresence: function (mute) { connection.emuc.addVideoInfoToPresence(mute); connection.emuc.sendPresence(); }, setVideoMute: function (mute, callback, options) { if(!connection) return; var self = this; var localCallback = function (mute) { self.sendVideoInfoPresence(mute); return callback(mute); }; if(connection.jingle.activecall) { connection.jingle.activecall.setVideoMute( mute, localCallback, options); } else { localCallback(mute); } }, setAudioMute: function (mute, callback) { if (!(connection && APP.RTC.localAudio)) { return false; } if (this.forceMuted && !mute) { console.info("Asking focus for unmute"); connection.moderate.setMute(connection.emuc.myroomjid, mute); // FIXME: wait for result before resetting muted status this.forceMuted = false; } if (mute == APP.RTC.localAudio.isMuted()) { // Nothing to do return true; } // It is not clear what is the right way to handle multiple tracks. // So at least make sure that they are all muted or all unmuted and // that we send presence just once. APP.RTC.localAudio.mute(); // isMuted is the opposite of audioEnabled connection.emuc.addAudioInfoToPresence(mute); connection.emuc.sendPresence(); callback(); return true; }, // Really mute video, i.e. dont even send black frames muteVideo: function (pc, unmute) { // FIXME: this probably needs another of those lovely state safeguards... // which checks for iceconn == connected and sigstate == stable pc.setRemoteDescription(pc.remoteDescription, function () { pc.createAnswer( function (answer) { var sdp = new SDP(answer.sdp); if (sdp.media.length > 1) { if (unmute) sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv'); else sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly'); sdp.raw = sdp.session + sdp.media.join(''); answer.sdp = sdp.raw; } pc.setLocalDescription(answer, function () { console.log('mute SLD ok'); }, function (error) { console.log('mute SLD error'); APP.UI.messageHandler.showError("dialog.error", "dialog.SLDFailure"); } ); }, function (error) { console.log(error); APP.UI.messageHandler.showError(); } ); }, function (error) { console.log('muteVideo SRD error'); APP.UI.messageHandler.showError("dialog.error", "dialog.SRDFailure"); } ); }, toggleRecording: function (tokenEmptyCallback, startingCallback, startedCallback) { Recording.toggleRecording(tokenEmptyCallback, startingCallback, startedCallback, connection); }, addToPresence: function (name, value, dontSend) { switch (name) { case "displayName": connection.emuc.addDisplayNameToPresence(value); break; case "etherpad": connection.emuc.addEtherpadToPresence(value); break; case "prezi": connection.emuc.addPreziToPresence(value, 0); break; case "preziSlide": connection.emuc.addCurrentSlideToPresence(value); break; case "connectionQuality": connection.emuc.addConnectionInfoToPresence(value); break; case "email": connection.emuc.addEmailToPresence(value); break; case "devices": connection.emuc.addDevicesToPresence(value); break; default : console.log("Unknown tag for presence: " + name); return; } if (!dontSend) connection.emuc.sendPresence(); }, /** * Sends 'data' as a log message to the focus. Returns true iff a message * was sent. * @param data * @returns {boolean} true iff a message was sent. */ sendLogs: function (data) { if(!connection.emuc.focusMucJid) return false; var deflate = true; var content = JSON.stringify(data); if (deflate) { content = String.fromCharCode.apply(null, Pako.deflateRaw(content)); } content = Base64.encode(content); // XEP-0337-ish var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'}); message.c('log', { xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'}); message.c('message').t(content).up(); if (deflate) { message.c('tag', {name: "deflated", value: "true"}).up(); } message.up(); connection.send(message); return true; }, populateData: function () { var data = {}; if (connection.jingle) { data = connection.jingle.populateData(); } return data; }, getLogger: function () { if(connection.logger) return connection.logger.log; return null; }, getPrezi: function () { return connection.emuc.getPrezi(this.myJid()); }, removePreziFromPresence: function () { connection.emuc.removePreziFromPresence(); connection.emuc.sendPresence(); }, sendChatMessage: function (message, nickname) { connection.emuc.sendMessage(message, nickname); }, setSubject: function (topic) { connection.emuc.setSubject(topic); }, lockRoom: function (key, onSuccess, onError, onNotSupported) { connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported); }, dial: function (to, from, roomName,roomPass) { connection.rayo.dial(to, from, roomName,roomPass); }, setMute: function (jid, mute) { connection.moderate.setMute(jid, mute); }, eject: function (jid) { connection.moderate.eject(jid); }, logout: function (callback) { Moderator.logout(callback); }, findJidFromResource: function (resource) { return connection.emuc.findJidFromResource(resource); }, getMembers: function () { return connection.emuc.members; }, getJidFromSSRC: function (ssrc) { if(!connection) return null; return connection.emuc.ssrc2jid[ssrc]; }, getMUCJoined: function () { return connection.emuc.joined; }, getSessions: function () { return connection.jingle.sessions; }, removeStream: function (stream) { if(!connection || !connection.jingle.activecall || !connection.jingle.activecall.peerconnection) return; connection.jingle.activecall.peerconnection.removeStream(stream); } }; module.exports = XMPP;
import { actions } from '../constants/actions'; import { statuses } from '../constants/statuses'; import fetch from 'isomorphic-fetch'; export function loginStarted() { return { type: actions.LOGIN, status: statuses.PENDING }; } export function loginFailed(errorMsg) { return { type: actions.LOGIN, status: statuses.ERROR, error: errorMsg }; } export function loginSucceeded(username) { return { type: actions.LOGIN, status: statuses.LOGGED_IN, username: username }; } export function login() { return dispatch => { dispatch(loginStarted()); return fetch('http://localhost:3000/login') .then(response => response.json()) .then(tokenJson => { if (tokenJson.params) { window.location = `http://en.wikipedia.org/w/index.php?title=Special:OAuth/authorize&${tokenJson.params}`; } }); }; } export function verify(token, verifier) { debugger; return dispatch => { return fetch('http://localhost:3000/verify', { method: 'POST', body: { token: token, verifier: verifier } }) .then(response => response.json()) .then(tokenJson => { console.log(tokenJson) }); }; }
'use strict'; module.exports = require('../showcase').extend({ data: { ref: 'services', title: 'Services' } });
'use strict'; var log = require('debug')('temply:cms-render-customer-list'); var moment = require('moment'); module.exports = function(data, $element, callback) { if (!data) { callback(); return; } var customers = data[0].clients; var $option = $element.find('option'); customers.forEach(function(customer){ var $row = $option.clone(); $row.text(customer.email).attr('value', customer.email); $element.append($row); }); callback(data); };
import $ from 'jquery'; import d3 from 'd3'; import Tools from 'components/tools/tools'; import React, { Component } from 'react'; import './timeBattery.scss'; class TimeBattery extends Component { constructor(props) { super(props); } componentDidMount() { let year = new Date().getFullYear(); let days = Tools.isLeapYear(year) ? 366 : 365; let container = this.refs.battery; let outter = this.refs.batteryBody; let timeTip = this.refs.timeTip; $(outter).css("width", days + 4 + "px"); $(container).css("width", days); let svg = d3.select(container) .append("svg") .attr("width", () => { return $(container).width(); }) .attr("height", () => { return $(container).height(); }) .style({ "background-color": "grey" }) let dayCount = d3.range(days).map((i) => { return i; }); let thisColor; let rects = svg.selectAll("rect") .data(dayCount) .enter() .append("rect") .attr({ "x": (d, i) => { return d; }, "y": (d, i) => { return 0; }, "width": "1px", "height": $(outter).height(), "fill": function (d, i) { if (d + 1 >= Tools.getDayOfYear()) { return "limegreen"; } else { return 'grey'; } } }) .style({ "cursor": "pointer" }) .on({ "mouseover": function (d, i) { thisColor = d3.select(this).attr("fill"); d3.select(this).attr("fill", "yellow"); let x = d3.event.x; let y = d3.event.y; let info = Tools.getDateOfYear(d + 1); d3.select(timeTip).style({ "left": x + 10 + "px", "top": y + 20 + "px", "display": "block" }) .text(info); }, "mouseout": function (d, i) { d3.select(this).attr("fill", thisColor); d3.select(timeTip).style({ "left": 0, "top": 0, "display": "none" }); } }); svg.selectAll('rect').each(function (index) { if (index + 1 == Tools.getDayOfYear()) { d3.select(this) .transition() .attr({ "height": 0, "fill": "limegreen" }) .transition() .duration(5000) .ease("cubic") .attr({ "height": $(outter).height(), "fill": "grey" }); } }); setInterval(function () { svg.selectAll('rect').each(function (index) { if (index + 1 == Tools.getDayOfYear()) { d3.select(this) .transition() .attr({ "height": 0, "fill": "limegreen" }) .transition() .duration(5000) .ease("cubic") .attr({ "height": $(outter).height(), "fill": "grey" }); } }); }, 5500); } render() { let batteryHeaderProps = { className: "batteryHeader", onMouseOver: this.batteryHeaderOnMouseOver, onMouseOut: this.batteryHeaderOnMouseOut, onMouseMove: this.batteryHeaderOnMouseMove } return ( <div className={"timeBattery"}> <div {...batteryHeaderProps} ></div> <div ref="batteryBody" className={"batteryBody"}> <div ref="battery" className={"batteryBodyInner"}></div> </div> <div ref="timeTip" className={"timeTip"}></div> </div> ) } batteryHeaderOnMouseOver = (e) => { let x = e.nativeEvent.clientX; let y = e.nativeEvent.clientY; let year = new Date().getFullYear(); let days = Tools.isLeapYear(year) ? 366 : 365; let reminder = `今天是${Tools.getDate()},距离今年结束还有${days-Tools.getDayOfYear()}天.`; d3.select(this.refs.timeTip) .style({ "display": "block", }) .text(reminder); } batteryHeaderOnMouseMove = (e) => { let x = e.nativeEvent.clientX; let y = e.nativeEvent.clientY; d3.select(this.refs.timeTip) .style({ "top": y + 10 + "px", "left": x + 20 + "px" }); } batteryHeaderOnMouseOut = (e) => { d3.select(this.refs.timeTip) .style({ "display": "none", }) .text(""); } } export default TimeBattery
define(["app/api/review/participants"], function (participants) { return { Participants: participants } });
/** * @fileoverview Blog utilities for routing. * @author Jak Wings * @license The MIT License (MIT) * @preserve Copyright (c) 2013 Jak Wings */ 'use strict'; (function (window) { // only available for browser which supports specified history APIs var isBrowser = typeof window !== 'undefined' && window.document; if (!isBrowser || !window.history || !window.history.replaceState) { define('blog', function () { return {init: function () {}}; }); return; } /** * @constructor * @return {Object} */ var Blog = function () { // sets constants this.window = window; this.document = window.document; this.BASE_URL = this.window.location.origin + this.window.location.pathname.replace(/\/*$/, '/'); this.HASH_CAP = '#!/'; // prefix for pages hash tags }; /** * Initiates and starts rendering. It can be called only once. * @public * @param {boolean=} opt_debug opens debug mode? * @return {void} */ Blog.prototype.init = function (opt_debug) { /** * Opens debug mode? * @private * @type {boolean} */ this.DEBUG = !!opt_debug; /** * Configurations * @public * @constant {Object.<string, *>} */ this.config = require('blog.config'); [].slice.call(this.document.querySelectorAll('#-article-list li')). forEach((function (li) { var item = { url: li.getAttribute('data-url').trim(), file: li.getAttribute('data-file').trim(), title: li.getAttribute('data-title').trim(), summary: li.textContent.trim(), }; this.push(item); }).bind(this.config.articles)); /** * Templates * @private * @constant {Object.<string, string>} */ this.templates_ = require('blog.templates'); /** * Render function (needs blog.templates) * @private * @type {function(this:Blog, string, string)} */ this.render_ = require('blog.render'); // registers router on HashChangeEvent this.window.addEventListener('hashchange', this.route_.bind(this), false); this.route_(this.window.location.hash); // destroys the initiator this.init = function () {}; }; /** * Listens and routes URLs (with hash tags). * @private * @param {(Object|string)} evt HashChangeEvent or hash tag * @return {void} */ Blog.prototype.route_ = function (evt) { var oldHash; var newHash; // gets old hash tag and new hash tag if (typeof evt !== 'undefined' && evt instanceof Event) { var newMatch = evt.newURL.match(/#.*$/); var oldMatch = evt.oldURL.match(/#.*$/); // empty hash '' will be mapped to HASH_CAP newHash = newMatch ? newMatch[0] : this.HASH_CAP; oldHash = oldMatch ? oldMatch[0] : this.HASH_CAP; } else { var window = this.window; var queryTag = (window.location.search.match(/\bhtag=([^&\/]+)/) || [])[1]; if (queryTag) { // with query string // for compatibility with some comment systems oldHash = newHash = this.HASH_CAP + decodeURIComponent(queryTag); window.history.replaceState(window.history.state, window.document.title, this.BASE_URL + newHash); } else { newHash = evt || this.HASH_CAP; oldHash = window.location.hash || this.HASH_CAP; } } this.DEBUG && console.log(queryTag, oldHash, newHash); // wraps the environment (not cloning) var env = {}; for (var k in this) { if (!(this[k] instanceof Function)) { env[k] = this[k]; } } // routes url by hash tags to collect information for rendering this.render_.call(env, oldHash, newHash); }; define('blog', function () { return new Blog(); }); })(this);
var Chaplin = require('chaplin') class Application extends Chaplin.Application { initialize(options) { this.initRouter(options.routes, options) this.initDispatcher(options) this.initLayout(options) this.start() } initLayout(options) { this.layout = new Chaplin.Layout({title: options.title || this.title}) } } module.exports = Application
Model.articleModel = function(exports){ exports.config = { fields : [ {name:'title',type:'string',validation:'unique'}, {name: 'time', type: 'datatime',defaultValue: 'now()'}, {name:'desc',type:'string',defaultValue:''}, {name:'content',type:'string',defaultValue:''}, {name:'username',type:'string',defaultValue:''}, {name:'pic',type:'string',defaultValue:'/assets/pic/logo.jpg'} ] }; };
/** * Ternific Copyright (c) 2014 Miguel Castillo. * * Licensed under MIT */ define(function(require, exports, module) { "use strict"; var _ = brackets.getModule("thirdparty/lodash"); var extensionUtils = brackets.getModule("utils/ExtensionUtils"); var Promise = require("node_modules/spromise/dist/spromise.min"); var workerFactory = require("workerFactory"); var TernApi = require("TernApi"); var Settings = require("Settings"); var globalSettings = Settings.create(".tern-project", false); var projectSettings = Settings.create(".tern-project"); var TERN_ROOT = "node_modules/tern/"; var TERN_DEFINITIONS = TERN_ROOT + "defs/"; var WORKER_SCRIPT = extensionUtils.getModulePath(module, "TernWorker.js"); // Initialize global settings globalSettings.load(extensionUtils.getModulePath(module)); function parseJSON(data) { try { return JSON.parse(data); } catch(ex) { return undefined; } } /** * Bridge to communicate into tern worker thread. */ function LocalServer(documenProvider) { this.settings = {}; this.documenProvider = documenProvider; this.worker = workerFactory.create(this, WORKER_SCRIPT); // Call tern api to set the rest of the stuff up. TernApi.call(this); var processSettings = createSettingsProcessor(this, globalSettings, projectSettings); globalSettings.on("change", processSettings); projectSettings.on("change", processSettings); processSettings(); } LocalServer.prototype = new TernApi(); LocalServer.prototype.constructor = LocalServer; LocalServer.prototype.request = function(body) { return this.worker.deferredSend({ type: "request", body: body }, true); }; LocalServer.prototype.clear = function() { this.worker.send({ type: "clear" }); }; LocalServer.prototype.addFile = function(name, text) { this.worker.send({ type: "addFile", name: name, text: text }); }; LocalServer.prototype.deleteFile = function(name) { this.worker.send({ type: "deleteFile", name: name }); }; LocalServer.prototype.loadSettings = function(fullPath) { projectSettings.load(fullPath); }; LocalServer.create = function(provider) { return new Promise(function(resolve) { var localServer = new LocalServer(provider); initialize(localServer); resolve(localServer); }); }; function initialize(localServer, settings) { localServer.worker.send({ type: "init", body: settings }); } function createSettingsProcessor(localServer, global, project) { return function() { var settings = _.assign({}, global.data || {}, project.data || {}); getDefinitions(settings.libs).then(function(defs) { settings.defs = defs; initialize(localServer, settings); }); }; } function getDefinitions(libs) { libs = _.toArray(libs).map(function(item) { if (item.indexOf("/") !== -1 || item.indexOf("\\") !== -1) { return "text!" + item + ".json"; } return "text!" + TERN_DEFINITIONS + item + ".json"; }); return new Promise(function(resolve) { require(libs, function() { var defs = _.toArray(arguments).reduce(function(result, item) { item = parseJSON(item); if (item) { result.push(item); } return result; }, []); resolve(defs); }); }); } return LocalServer; });
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('login', { title: 'VelvetSpider' }); }); module.exports = router;
+(function($admin, $) { var self = $admin.Validator = this; var private = {}, protected = {}, pages = {}; var $HB, $DM; var _construct = function() { console.log('Admin.Validator constructor'); $HB = $admin._parent; $DM = $HB.DataManager; }; var _init = function() { // Our parent already listens for DOM ready console.log('Admin.Validator initialized'); }; $admin.module.register({ name: 'Validator', instance: this },function(_unsealed) { // Initialize module $admin = _unsealed(_init); // fire initializer when DOM ready _construct(); // run constructor now }); this.source = {}; this.source.validate = function(src) { var src = {}, type = $('#sourcetype').val(); switch (type) { case "RETS": src.uri = $('#sourceuri').val(); src.type = type; src.auth = { username: $('#sourceuser').val(), password: $('#sourcepassword').val(), userAgentHeader: $('#sourceua').val(), userAgentPassword: $('#sourceuapw').val() }; break; case "FTP": src.uri = $('#ftphost').val(); src.type = type; src.port = 21; src.auth = { username: $('#ftpuser').val(), password: $('#ftpauth').val() }; break; } $('#sourceValidationStatus').removeClass('ok-sign exclamation-sign').addClass('asterisk'); // $('#validateBtn').attr('disabled','disabled'); $DM.validateSource(src,function(e) { $('#validateBtn').removeClass('btn-danger btn-success').addClass('btn-primary'); if (!e.err) { $('#validateBtn').removeClass('btn-primary').addClass('btn-success') $('#sourceValidationStatus').removeClass('asterisk').addClass('ok-sign'); $('#sourceEditor [am-Button~=next]').hide(); $('#sourceEditor [am-Button~=finish]').show().prop("disabled", false); } else { $('#validateBtn').removeAttr('disabled').removeClass('btn-primary').addClass('btn-danger') $('#sourceValidationStatus').removeClass('asterisk').addClass('exclamation-sign'); $('#sourceEditor [am-Button~=finish]').prop('disabled', true); } }); }; this.source.save = function() { if (!$('#sourcename').val()) return false; var type = $('#sourcetype').val(), src = { name: $('#sourcename').val() }, src_id = $('#sourceEditor').attr('data-id'), src_rev = $('#sourceEditor').attr('data-rev'); if (src_id) { src._id = src_id; } if (src_rev) { src._rev = src_rev; } src.status = $('#sourceEditor .modal-header [am-Button~=switch].status').attr('data-state-value'); switch (type) { case "RETS": src.source = { uri: $('#sourceuri').val(), type: type, version: '1.5', auth: { username: $('#sourceuser').val(), password: $('#sourcepassword').val(), userAgentHeader: $('#sourceua').val(), userAgentPassword: $('#sourceuapw').val() } }; break; case "FTP": src.source = { uri: $('#ftphost').val(), type: type, auth: { username: $('#ftpuser').val(), password: $('#ftpauth').val() } }; break; case "SOAP": break; case "REST": break; case "XML": break; } $DM.saveSource(src, function(e) { $DM.loadSources(); }); $admin.UI.Controllers.Source.ModalReset(); $('#sourceEditor').modal('hide'); }; }(HoneyBadger.Admin, jQuery));
function demo() { cam ( 90, 20, 100 ); world = new OIMO.World({ timestep: 1/60, iterations: 8, broadphase: 2, // 1: brute force, 2: sweep & prune, 3: volume tree worldscale: 1, random: true, info:true // display statistique }); var i, x, y, z, s, b; var mx = 150; var r = 50; var a = (360/mx) * Math.torad; var spring = [2, 0.3];// soften the joint ex: 100, 0.2 for( i = 0; i < mx; i++){ x = Math.sin(i*a) * r; y = 60 + Math.sin(i*0.5) * 2; z = Math.cos(i*a) * r; add({ type:'sphere', size:[1], pos:[x, y, z], move:1 }); if( i > 0 ) world.add({ type:'jointHinge', body1:(i-1), body2:i, pos1:[0,-1,0], pos2:[0,1,0], collision:true, spring:spring }); if( i === mx-1 ) world.add({ type:'jointHinge', body1:mx-1, body2:0, pos1:[0,-1,0], pos2:[0,1,0], collision:true, spring:spring }); } var ground = world.add({size:[1000, 10, 1000], pos:[0,-5,0], density:1 }); for( i = 0; i<40; i++ ){ x = rand(-50, 50); z = rand(-50, 50); s = rand(5, 15); add({ type:'box', geometry:geo.dice, size:[s,s,s], pos:[x,s*0.5,z], move:true }); } // world internal loop world.postLoop = postLoop; world.play(); }; function postLoop () { var m; bodys.forEach( function ( b, id ) { if(b.type===1){ m = b.mesh; if( b.sleeping ) switchMat( m, 'sleep'); else switchMat( m, 'move'); if(m.position.y<-10){ b.resetPosition(rand(-5,5),rand(10,20),rand(-5,5)); } } }); editor.tell( world.getInfo() ); }
import PropTypes from 'prop-types' import React from 'react' import enhanceClickOutside from 'react-click-outside' import Menu from 'part:@lyra/components/menus/default' import styles from './styles/SpaceSwitcher.css' import {CONFIGURED_SPACES} from '../util/spaces' import {state as urlState} from '../datastores/urlState' import {withRouterHOC} from 'part:@lyra/base/router' import ArrowDropDown from 'part:@lyra/base/arrow-drop-down' import {map} from 'rxjs/operators' const currentSpace$ = urlState.pipe( map(event => event.state && event.state.space), map(spaceName => CONFIGURED_SPACES.find(sp => sp.name === spaceName)) ) class SpaceSwitcher extends React.PureComponent { static propTypes = { router: PropTypes.shape({navigate: PropTypes.func}) } state = { menuOpen: false, currentSpace: null } componentDidMount() { this.currentSpaceSubscription = currentSpace$.subscribe(space => { this.setState({currentSpace: space}) }) } componentWillUnmount() { this.currentSpaceSubscription.unsubscribe() } handleClickOutside = () => { if (this.state.menuOpen) { this.setState({menuOpen: false}) } } handleMenuToggle = () => { this.setState({menuOpen: !this.state.menuOpen}) } handleMenuItemClick = item => { this.props.router.navigate({space: item.name}) this.setState({menuOpen: false}) } render() { const {menuOpen, currentSpace} = this.state const title = currentSpace && currentSpace.title return ( <div className={styles.root}> <div title={title} onClick={this.handleMenuToggle} className={styles.currentSpace} > {title && `${title}`} <span className={styles.arrow}> <ArrowDropDown /> </span> </div> {menuOpen && ( <div className={styles.menu}> <Menu onAction={this.handleMenuItemClick} items={CONFIGURED_SPACES} opened origin="top-right" onClickOutside={this.handleMenuClose} /> </div> )} </div> ) } } export default withRouterHOC(enhanceClickOutside(SpaceSwitcher))
(function (exports) { 'use strict'; var Syntax = { AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement' }; // Executes visitor on the object and its children (recursively). function traverse(object, visitor, master) { var key, child, parent, path; parent = (typeof master === 'undefined') ? [] : master; if (visitor.call(null, object, parent) === false) { return; } for (key in object) { if (object.hasOwnProperty(key)) { child = object[key]; path = [ object ]; path.push(parent); if (typeof child === 'object' && child !== null) { traverse(child, visitor, path); } } } } function traverseFunctionTree(object, visitor, master) { var key, child, parent, path, i, children, childrenLength; parent = (typeof master === 'undefined') ? [] : master; if (visitor.call(null, object, parent) === false) { return; } children = object.myChildren || object.children; childrenLength = children.length; for(i = 0; i < childrenLength; i++) { child = children[i]; path = [object]; path.push(parent); if (typeof child === 'object' && child !== null) { traverseFunctionTree(child, visitor, path); } } } function createFunctionTree (object, code, functionTree, master, masterFunction) { var key, child, parent, parentFunction, path, i, functionObject; parent = (typeof master === 'undefined') ? [] : master; parentFunction = (masterFunction && !isEmpty(masterFunction)) ? masterFunction : functionTree; functionObject = createFunctionObject(object, parent[0], code); for (key in object) { if (object.hasOwnProperty(key)) { child = object[key]; path = [ object ]; path.push(parent); if (typeof child === 'object' && child !== null) { if (!isEmpty(functionObject)) { if (getNodeScope(parentFunction).concat(parentFunction.myChildren).indexOf(functionObject) < 0) { functionObject.parent = parentFunction; parentFunction.myChildren.push(functionObject); } createFunctionTree(child, code, functionTree, path, functionObject); } else { createFunctionTree(child, code, functionTree, path, parentFunction); } } } } } function isEmpty(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) { return false; } } return true; } function init (code) { var tree, functionList, functionTree, param, signature, pos, i, formattedList; tree = esprima.parse(code, { range: true, loc: true}); console.log("esprima tree: ", tree); functionTree = getFunctionTree(tree, code); functionTree = setFunctionTreeDependencies(functionTree); functionTree = addHiddenChildren(functionTree); console.log("functionTree!!!, ", functionTree); // // BUBBLE functionTree = convertToChildren(functionTree); makeBubbleChart(functionTree, code); return code; } function convertToChildren (functionTree) { var parent = functionTree; function traverseChild (parent) { var i, childLength, child; //convert myChildren to children parent.children = parent.myChildren; //parent.size = parent.dependencies.length * 2 + 1; parent.size = parent.sourceCode ? (parent.sourceCode.length * 2 + 1) : 1; delete parent.myChildren; childLength = parent.children.length; for(i = 0; i < childLength; i++) { child = parent.children[i]; traverseChild(child); } } traverseChild(parent); return functionTree; } function getSankeyData (functionTree) { var nodes = [], links = []; traverseFunctionTree(functionTree, function(node, path) { nodes.push(node); if (node && node.parent) { links.push({ source: node.parent, target: node, value: node.dependencies.length * 2 + 1 }); } }); return { nodes: nodes, links: links } } function createFunctionObject(node, parent, code) { var functionObject = {}; if (node.type === Syntax.FunctionDeclaration) { functionObject = { name: node.id.name }; } else if (parent && node.type === Syntax.FunctionExpression) { if (parent.type === Syntax.AssignmentExpression) { if (typeof parent.left.range !== 'undefined') { functionObject = { name: code.slice(parent.left.range[0], parent.left.range[1]).replace(/"/g, '\\"') }; } } else if (parent.type === Syntax.VariableDeclarator) { functionObject = { name: parent.id.name }; } else if (parent.type === Syntax.CallExpression) { functionObject = { name: parent.id ? parent.id.name : '[Anonymous]' }; } else if (parent.type === Syntax.Property) { functionObject = { name: parent.key ? parent.key.name : '[Anonymous]' }; } else if (parent.type === Syntax.ConditionalExpression && parent.tmpName) { functionObject = { name: parent.tmpName || '[Anonymous]' }; } else if (typeof parent.length === 'number') { functionObject = { name: parent.id ? parent.id.name : '[Anonymous]' }; } else if (typeof parent.key !== 'undefined') { if (parent.key.type === 'Identifier') { if (parent.value === node && parent.key.name) { functionObject = { name: parent.key.name }; } } } else { functionObject = { name: '[Anonymous]' }; } //setup for conditional functions } else if (node.type === Syntax.ConditionalExpression && ((node.alternate && node.alternate.type === Syntax.FunctionExpression) || (node.conditional && node.conditional.type === Syntax.FunctionExpression))) { if (parent.type === Syntax.VariableDeclarator && parent.id) { node.tmpName = parent.id.name; } else if (parent.type === Syntax.AssignmentExpression && parent.left) { node.tmpName = parent.left.name; } } if (!isEmpty(functionObject)) { functionObject.range = node.range; functionObject.loc = node.loc; functionObject.blockStart = node.body.range[0]; functionObject.treeNode = node; functionObject.dependencies = []; functionObject.myChildren = []; functionObject.scopedList = []; } return functionObject; } //create tree of scoped functions function getFunctionTree (node, code, sourceCode) { //console.log("sourceCode in getFunctionTree: ", sourceCode); var functionTree = { name: sourceCode.name || 'noName', parent: null, myChildren: [], treeNode: node, type: sourceCode.type, sourceCode: sourceCode.code }; createFunctionTree(node, code, functionTree); return functionTree; } //NOTE: node.scopedList will be a 2d array of nodes function setScopedList (functionTree) { traverseFunctionTree(functionTree, function(node, path) { if (!node.scopedList) { node.scopedList = []; } if (node.parent && node.parent.scopedList.length) { //TODO: should exclude anonymous functions from the lastscopedList block node.scopedList = node.parent.scopedList.concat([node.scopedList]); } node.scopedList.push(node.myChildren); }); return functionTree; } function setFunctionTreeDependencies (functionTree){ traverseFunctionTree(functionTree, function (node, path) { var scopedList = [], parent = node, func, i, childLength = node.myChildren.length, flatScopedList; flatScopedList = node.scopedList.reduce(function(a, b) { return b.concat(a); }); node.dependencies = getDependencies(node.treeNode, flatScopedList); for (i = 0; i < childLength; i++) { func = node.myChildren[i]; if (func.name === "[Anonymous]"){ node.dependencies.push(func); } } }); return functionTree; } //walk up the parents and add all their children function getNodeScope (node, scopeList) { scopeList = scopeList ? scopeList : []; if (node && node.parent) { scopeList = scopeList.concat(node.parent.myChildren); getNodeScope(node.parent, scopeList); } return scopeList; } function getDependencies (node, scopedList) { var children = []; traverse(node, function (element, path) { var funcIndex, existingIndex, parent = path[0], isAFunction = false; if (parent === node) { return; } if (parent && parent.type === Syntax.CallExpression) { isAFunction = true; } else if (parent && parent.property === element) { isAFunction = true; } if (isAFunction && element.name) { funcIndex = scopedList.map(function (funcObject) { return UTILS.getBaseName(funcObject); }).indexOf(UTILS.getBaseName(element)); if (funcIndex >= 0) { existingIndex = children.map(function (funcObject) { return UTILS.getBaseName(funcObject); }).indexOf(UTILS.getBaseName(element)); if (existingIndex === -1) { children.push(scopedList[funcIndex]); } } } }); return children; } function addHiddenChildren (functionTree) { traverseFunctionTree(functionTree, function(node, path) { if (node && node.myChildren && node.myChildren.length === 1 && (node.type !== 'file' || node.type !== 'inlineScript') && node.myChildren[0].name !== '[Anonymous]' ) { node.myChildren.push({ name: '', parent: node, myChildren:[], dependencies:[], treeNode: null, type: "hidden" }); } }); return functionTree; } function setUniqueIds (functionTree) { traverseFunctionTree(functionTree, function(node, path) { node.uniqueId = node.uniqueId || UTILS.getId(node.treeNode); }); return functionTree; } function functionExists (name, functionList) { var index = functionList.map(function (node) {return node.name}).indexOf(name); if (index === -1 ) { return false; } else { return true; } } function initFunctionTree (sourceCode) { var tree, functionTree, code = sourceCode.code; tree = esprima.parse(code, { range: true, loc: true}); functionTree = getFunctionTree(tree, code, sourceCode); functionTree = setFunctionTreeDependencies(functionTree); functionTree = addHiddenChildren(functionTree); functionTree = setUniqueIds(functionTree); functionTree = convertToChildren(functionTree); return functionTree; } function addFunctionTrace (code, codeTree) { var offset = 0, //adjust range to account for upstream insertions traceStartInsert; traverseFunctionTree(codeTree, function(node, path) { var start; if (node.type === 'file' || node.type === 'inlineScript') { return; } start = code.slice(node.treeNode.range[0] + offset).indexOf('{') + node.treeNode.range[0] + offset + 1; node.uniqueId = UTILS.getId(node.treeNode); traceStartInsert = ' postMessage({ type: "TARGET_PAGE", uniqueId: "'+ node.uniqueId +'", direction: "start"}, "*"); '; code = UTILS.spliceSlice(code, start, 0, traceStartInsert); offset += traceStartInsert.length; }); //remove google api loading header if (code.slice(0, 50).indexOf('gapi.loaded') > -1) { console.log("removing google api loading header"); code = code.replace(/gapi\.loaded(_\d+)?/, ''); } //TODO: insert the traceEndInsert return code; } exports.Tracer = { init: init, functionTree: initFunctionTree, getFunctionTree: getFunctionTree, setScopedList: setScopedList, setFunctionTreeDependencies: setFunctionTreeDependencies, addHiddenChildren: addHiddenChildren, setUniqueIds: setUniqueIds, convertToChildren: convertToChildren, addFunctionTrace: addFunctionTrace }; }(typeof exports === 'undefined' ? (esmorph = {}) : exports));
import React from "react"; import { LgMeats, MdSearch } from "@crave/farmblocks-icon"; import { FULLSCREEN } from "../../constants/variants"; import useToggle from "../../utils/useToggle"; import NavItem from "./NavItem"; export default { title: "SideNav/NavItem", component: NavItem }; export const NavItems = () => { const NavItemWithToggle = (props) => { const [active, { toggle }] = useToggle(false); return <NavItem active={active} onClick={toggle} {...props} />; }; return ( <div> <NavItemWithToggle>Simple Item</NavItemWithToggle> <NavItemWithToggle image="https://picsum.photos/640/?image=234"> Item with Image </NavItemWithToggle> <NavItemWithToggle icon={<LgMeats />}>Item with Icon</NavItemWithToggle> <NavItemWithToggle variant={FULLSCREEN} icon={<MdSearch />}> Item with fullScreen variant and Icon </NavItemWithToggle> </div> ); };
'use strict'; /* * Layout Header: Member * * Used to control the member layout header and top navigtion. */ angular.module('app.elements.memberHeader', []) .controller('MemberHeaderCtrl', ['$scope', 'UserSession', 'AuthService', 'siteSystemVariables', function ($scope, UserSession, AuthService, siteSystemVariables) { /* Site configuration variables are pre loaded within the * state resolve method in the app.router */ $scope.siteOptions = siteSystemVariables; /* User display name for logged in indicator. */ $scope.userDisplayName = UserSession.displayName(); /* Logout function in the auth service. */ $scope.logout = AuthService.logout; /* ui.bootstrap navbar collapse flag. */ $scope.navbarCollapsed = true; /* ui.bootstrap logged in user menu drop down. */ $scope.userNavDropdownIsOpen = false; /* Trigger the outtermost navbar to collapse (the hamburger button) * when a link is selected. */ $(".navbar-nav li.trigger-collapse a").click(function (event) { $scope.navbarCollapsed = true; }); }]);
import React from "react" import $ from 'jquery' import {List, ListItem, Heading} from "spectacle" import {esNext} from '../data/' const getListItem = ({ name, spec }) => <ListItem textColor='tertiary' key={name + spec}>{name}</ListItem> export default class NewFeatures extends React.Component { componentDidMount() { const parent = $(this.ref).parent() parent.css('overflowY', 'scroll') } render() { return ( <div ref={elem => this.ref = elem}> <Heading size={1} textColor='primary'> ESNext </Heading> <Heading size={4} textColor='primary'> non-standard </Heading> <List> {esNext.map(getListItem)} </List> </div> ) } }
var path = require('path'), argv = require('yargs').argv, _ = require('lodash'), webpack = require('webpack'); var playgroundPath = __dirname, rootPath = path.join(playgroundPath, '..'), modulesPath = path.join(rootPath, 'node_modules'), cwd = process.cwd(); var resolvePath = function(userPath) { return path.resolve(cwd, userPath); }; var config = {}, userConfig; try { userConfig = require( resolvePath(argv.configPath || 'component-playground.config')); } catch (e) { if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') { userConfig = {}; } else { throw e; } } config.server = _.extend({ port: 8989, hostname: 'localhost' }, userConfig.server); config.webpack = { context: playgroundPath, entry: [ 'webpack-dev-server/client?http://' + config.server.hostname + ':' + config.server.port, 'webpack/hot/dev-server', './entry' ], resolve: { alias: { components: resolvePath(argv.componentsPath || 'components'), fixtures: resolvePath(argv.fixturesPath || 'components') }, extensions: ['', '.js', '.jsx'] }, resolveLoader: { root: modulesPath }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader'] }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }] }, output: { libraryTarget: 'umd', library: 'cosmosRouter', path: path.join(playgroundPath, 'public', 'build'), filename: 'bundle.js', publicPath: '/build/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] }; if (userConfig.webpack) { config.webpack = userConfig.webpack(config.webpack); } module.exports = config;
import React from 'react' import { Image } from 'shengnian-ui-react' const ImageExampleAvatar = () => ( <div> <Image src='/assets/images/wireframe/square-image.png' avatar /> <span>Username</span> </div> ) export default ImageExampleAvatar
IntlMessageFormat.__addLocaleData({locale:"ebu",pluralRuleFunction:function(a,e){return"other"}});
/* * Copyright (c) 2015-2017 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const ejs = require('ejs') const express = require('express') const middleware = require('./middleware') const path = require('path') function configureLocals (app, options) { app.locals.privateKey = options.privateKey app.locals.publicKey = options.publicKey } function configureViewEngine (app) { app.set('views', path.join(__dirname, 'views')) app.engine('html', ejs.renderFile) app.set('view engine', 'html') } module.exports = (options = {}) => { const app = express() configureLocals(app, options) configureViewEngine(app) middleware(app) return app }
import DomainResourceSerializer from 'ember-fhir/serializers/domain-resource'; export default DomainResourceSerializer.extend({ attrs: { identifier: { embedded: 'always' }, effectivePeriod: { embedded: 'always' }, useContext: { embedded: 'always' }, jurisdiction: { embedded: 'always' }, contact: { embedded: 'always' }, code: { embedded: 'always' }, item: { embedded: 'always' } } });
/* @flow */ /* eslint-disable import/no-duplicates */ import { Emitter, CompositeDisposable } from 'atom' import type { TextEditor, Disposable, Notification } from 'atom' import * as Helpers from './helpers' import * as Validate from './validate' import { $version, $activated, $requestLatest, $requestLastReceived } from './helpers' import type { Linter } from './types' class LinterRegistry { emitter: Emitter linters: Set<Linter> lintOnChange: boolean ignoreVCS: boolean ignoreGlob: string lintPreviewTabs: boolean subscriptions: CompositeDisposable disabledProviders: Array<string> activeNotifications: Set<Notification> constructor() { this.emitter = new Emitter() this.linters = new Set() this.subscriptions = new CompositeDisposable() this.activeNotifications = new Set() this.subscriptions.add( atom.config.observe('linter.lintOnChange', lintOnChange => { this.lintOnChange = lintOnChange }), ) this.subscriptions.add( atom.config.observe('core.excludeVcsIgnoredPaths', ignoreVCS => { this.ignoreVCS = ignoreVCS }), ) this.subscriptions.add( atom.config.observe('linter.ignoreGlob', ignoreGlob => { this.ignoreGlob = ignoreGlob }), ) this.subscriptions.add( atom.config.observe('linter.lintPreviewTabs', lintPreviewTabs => { this.lintPreviewTabs = lintPreviewTabs }), ) this.subscriptions.add( atom.config.observe('linter.disabledProviders', disabledProviders => { this.disabledProviders = disabledProviders }), ) this.subscriptions.add(this.emitter) } hasLinter(linter: Linter): boolean { return this.linters.has(linter) } addLinter(linter: Linter) { if (!Validate.linter(linter)) { return } linter[$activated] = true if (typeof linter[$requestLatest] === 'undefined') { linter[$requestLatest] = 0 } if (typeof linter[$requestLastReceived] === 'undefined') { linter[$requestLastReceived] = 0 } linter[$version] = 2 this.linters.add(linter) } getProviders(): Array<Linter> { return Array.from(this.linters) } deleteLinter(linter: Linter) { if (!this.linters.has(linter)) { return } linter[$activated] = false this.linters.delete(linter) } async lint({ onChange, editor }: { onChange: boolean, editor: TextEditor }): Promise<boolean> { const filePath = editor.getPath() if ( (onChange && !this.lintOnChange) || // Lint-on-change mismatch // Ignored by VCS, Glob, or simply not saved anywhere yet Helpers.isPathIgnored(editor.getPath(), this.ignoreGlob, this.ignoreVCS) || (!this.lintPreviewTabs && atom.workspace.getActivePane().getPendingItem() === editor) // Ignore Preview tabs ) { return false } const scopes = Helpers.getEditorCursorScopes(editor) const promises = [] for (const linter of this.linters) { if (!Helpers.shouldTriggerLinter(linter, onChange, scopes)) { continue } if (this.disabledProviders.includes(linter.name)) { continue } const number = ++linter[$requestLatest] const statusBuffer = linter.scope === 'file' ? editor.getBuffer() : null const statusFilePath = linter.scope === 'file' ? filePath : null this.emitter.emit('did-begin-linting', { number, linter, filePath: statusFilePath }) promises.push( new Promise(function(resolve) { // $FlowIgnore: Type too complex, duh resolve(linter.lint(editor)) }).then( messages => { this.emitter.emit('did-finish-linting', { number, linter, filePath: statusFilePath }) if (linter[$requestLastReceived] >= number || !linter[$activated] || (statusBuffer && !statusBuffer.isAlive())) { return } linter[$requestLastReceived] = number if (statusBuffer && !statusBuffer.isAlive()) { return } if (messages === null) { // NOTE: Do NOT update the messages when providers return null return } let validity = true // NOTE: We are calling it when results are not an array to show a nice notification if (atom.inDevMode() || !Array.isArray(messages)) { validity = Validate.messages(linter.name, messages) } if (!validity) { return } Helpers.normalizeMessages(linter.name, messages) this.emitter.emit('did-update-messages', { messages, linter, buffer: statusBuffer }) }, error => { this.emitter.emit('did-finish-linting', { number, linter, filePath: statusFilePath }) console.error(`[Linter] Error running ${linter.name}`, error) const notificationMessage = `[Linter] Error running ${linter.name}` if (Array.from(this.activeNotifications).some(item => item.getOptions().detail === notificationMessage)) { // This message is still showing to the user! return } const notification = atom.notifications.addError(notificationMessage, { detail: 'See Console for more info.', dismissable: true, buttons: [ { text: 'Open Console', onDidClick: () => { atom.openDevTools() notification.dismiss() }, }, { text: 'Cancel', onDidClick: () => { notification.dismiss() }, }, ], }) }, ), ) } await Promise.all(promises) return true } onDidUpdateMessages(callback: Function): Disposable { return this.emitter.on('did-update-messages', callback) } onDidBeginLinting(callback: Function): Disposable { return this.emitter.on('did-begin-linting', callback) } onDidFinishLinting(callback: Function): Disposable { return this.emitter.on('did-finish-linting', callback) } dispose() { this.activeNotifications.forEach(notification => notification.dismiss()) this.activeNotifications.clear() this.linters.clear() this.subscriptions.dispose() } } export default LinterRegistry
/* 把指定的字符串翻译成 pig latin。 Pig Latin 把一个英文单词的第一个辅音或辅音丛(consonant cluster)移到词尾,然后加上后缀 "ay"。 如果单词以元音开始,你只需要在词尾添加 "way" 就可以了。 */ function translate(str) { var consonant_array = ["c","p","gl"]; var new_str = ""; if(consonant_array.indexOf(str.substr(0,2)) !== -1){ new_str = str.substr(2) + str.substr(0,2) +"ay"; } else if(consonant_array.indexOf(str.substr(0,1)) !== -1){ new_str = str.substr(1) + str.substr(0,1) +"ay"; } else{ new_str = str + "way"; } return new_str; } translate("eight");
/*! unwrapped.js ~ v0.1.0-alpha ~ created by Dylan Waits ~ https://github.com/waits/unwrapped */ (function() { 'use strict'; window.typeOf = function(object) { return Object.prototype.toString.call(object).slice(8, -1); }; })(); (function() { 'use strict'; window.id = function(str) {return document.getElementById(str);}; window.classes = function(str) {return document.getElementsByClassName(str);}; window.names = function(str) {return document.getElementsByName(str);}; window.tags = function(str) {return document.getElementsByTagName(str);}; Element.create = function(type, child, options) { var el = document.createElement(type); if (options) { for (var k in options) { if (options.hasOwnProperty(k)) { if (k === 'style') { for (var s in options.style) { if (options.hasOwnProperty(k)) {el.style[s] = options.style[s];} } } else if (k === 'data') { for (var d in options.data) { if (options.hasOwnProperty(k)) {el.dataset[d] = options.data[d];} } } else { el.setAttribute(k, options[k]); } } } } switch (typeOf(child)) { case "Null": case "Undefined": break; case "String": el.appendChild(document.createTextNode(child)); break; case "NodeList": child = Array.prototype.slice.call(child); case "Array": for (var c in child) {if (child.hasOwnProperty(c)) {el.appendChild(child[c]);}} break; default: el.appendChild(child); } return el; }; Element.prototype.classes = function(name) { return this.getElementsByClassName(name); }; Element.prototype.names = function(arg) { var returnList = []; (function loop(start) { for (var child in start) { if (start.hasOwnProperty(child) && start[child].nodeType === 1) { if (start[child].name === arg) {returnList.push(start[child]);} if (start[child].childNodes.length > 0) { loop(start[child].childNodes); } } } })(this.childNodes); return returnList; }; Element.prototype.tags = function(name) { return this.getElementsByTagName(name); }; Document.prototype.on = Element.prototype.on = function(event, callback) { this.addEventListener(event, function(e) { callback.call(this, e); }); }; HTMLCollection.prototype.on = NodeList.prototype.on = function(event, callback) { for (var i in this) { if (this.hasOwnProperty(i)) { var node = this[i]; if (node.nodeType === 1) { node.on(event, callback); } } } }; HTMLCollection.prototype.each = NodeList.prototype.each = function(callback) { Array.prototype.forEach.call(this, function(el, i) { callback.call(el, i); }); }; HTMLCollection.prototype.first = NodeList.prototype.first = function() { return this[0] || null; }; HTMLCollection.prototype.last = NodeList.prototype.last = function() { return this[this.length-1] || null; }; HTMLCollection.prototype.remove = NodeList.prototype.remove = function() { var arr = Array.prototype.slice.call(this); for (var i in arr) { if (this.hasOwnProperty(i)) { var el = arr[i]; if (el.nodeType === 1) { el.remove(); } } } }; Element.prototype.closest = function(options) { if (options.class && !this.classList.contains(options.class) || options.name && this.name !== options.name || options.tag && this.tagName !== options.tag.toUpperCase()) { if (this.parentNode.nodeType === 1) {return this.parentNode.closest(options);} else {return null;} } else { return this; } }; Element.prototype.next = function() {return this.nextElementSibling;}; Element.prototype.prev = function() {return this.previousElementSibling;}; Element.prototype.siblings = function() { var el = this; return Array.prototype.filter.call(this.parentNode.children, function(child) { return child !== el; }); }; Element.prototype.index = function() { return [].slice.call(this.parentNode.children).indexOf(this); }; })(); (function() { 'use strict'; HTMLFormElement.prototype.stringify = function() { var values = []; var tags = ['input', 'select', 'textarea']; for (var t=0; t<tags.length; t++) { var inputs = this.tags(tags[t]); for (var i in inputs) { if (inputs.hasOwnProperty(i) && inputs[i].nodeType === 1) { if (inputs[i].type === 'checkbox') { if (inputs[i].checked) {values.push(inputs[i].name + '=' + encodeURIComponent(inputs[i].value));} } else if (inputs[i].type === 'radio') { if (inputs[i].checked) {values.push(inputs[i].name + '=' + encodeURIComponent(inputs[i].value));} } else {values.push(inputs[i].name + '=' + encodeURIComponent(inputs[i].value));} } } } return values.join('&'); }; })(); window.HTTP = (function() { 'use strict'; var HTTP = {}; function sendEmptyRequest(method, url, callback) { var request = new XMLHttpRequest(); request.open(method, url, true); if (callback) {request.onload = callback;} request.send(); } function sendDataRequest(method, url, data, callback) { var request = new XMLHttpRequest(); request.open(method, url, true); if (callback) {request.onload = callback;} if (typeOf(data) === 'Object') { request.setRequestHeader("Content-Type", "application/json"); request.send(JSON.stringify(data)); } else { request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send(data); } } HTTP.get = function(url, data, callback) { if (data) { url += '?'; for (var p in data) { if (data.hasOwnProperty(p)) {url += p + '=' + encodeURIComponent(data[p]) + '&';} } } sendEmptyRequest('GET', url, data, callback); }; HTTP.post = function(url, data, callback) { sendDataRequest('POST', url, data, callback); }; HTTP.patch = function(url, data, callback) { sendDataRequest('PATCH', url, data, callback); }; HTTP.put = function(url, data, callback) { sendDataRequest('PUT', url, data, callback); }; HTTP.delete = function(url, callback) { sendEmptyRequest('DELETE', url, callback); }; return HTTP; })();
/* * mobile buttonMarkup tests */ (function($){ module("jquery.mobile.buttonMarkup.js"); test( "header buttons should have the header class", function() { var headerButton1 = $("#header-button-1"), headerButton2 = $("#header-button-2"); ok((headerButton1.hasClass("ui-btn-left") && headerButton2.hasClass("ui-btn-right")), "first header button should have class 'ui-btn-left' and the second one should have 'ui-btn-right'"); }); test( "control group buttons should be enhanced inside a footer", function(){ var group, linkCount; group = $("#control-group-footer"); linkCount = group.find( "a" ).length; same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons"); same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button"); same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button"); same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered"); }); test( "control group buttons should respect theme-related data attributes", function(){ var group = $("#control-group-content"); ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"), "buttons with data-shadow=false should not have the ui-shadow class"); ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"), "buttons with data-corners=false should not have the ui-btn-corner-all class"); ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"), "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons"); }); // Test for issue #3046 and #3054: test( "mousedown on SVG elements should not throw an exception", function(){ var svg = $("#embedded-svg"), success = true, rect; ok(svg.length > 0, "found embedded svg document" ); if ( svg.length > 0 ) { rect = $( "rect", svg ); ok(rect.length > 0, "found rect" ); try { rect.trigger("mousedown"); } catch ( ex ) { success = false; } ok( success, "mousedown executed without exception"); } }); test( "Elements with “data-mini='true'” should have “ui-mini” class attached to enhanced element.", function(){ var $mini = $("#mini"), $full = $("#full"), $minicontrol = $('#mini-control'); ok( $full.not('.ui-mini'), "Original element does not have data attribute, enhanced version does not recieve .ui-mini."); ok( $mini.is('.ui-mini'), "Original element has data attribute, enhanced version recieves .ui-mini." ); ok( $minicontrol.is('.ui-mini'), "Controlgroup has data attribute and recieves .ui-mini."); }); })(jQuery);
define(['jsonUtils'], /** * Set to "backwards compatibility mode" (for pre version 2.0) for CommonUtils. * * This function re-adds deprecated and removed functions and * properties to the CommonUtils instance. * * NOTE that once set to compatibility mode, it cannot be reset to * non-compatibility mode. * * <p> * In addition, the following functions of CommonUtils are made accessible * on the <code>mmir.CommonUtils</code> instance with these additional names * <ul> * <li> {@link mmir.CommonUtils#regexHTMLComment} as * <b><u>html_comment_regex : RegExpr</u></b> * </li><li> * {@link mmir.CommonUtils#resizeFitToSourroundingBox} as * <b><u>html_resize_font_to_fit_surrounding_box()</u></b> * </li><li> * {@link mmir.CommonUtils#toJSONStringValue} as * <b><u>to_json_string_value(String: theObjectValue) : String</u></b> * </li><li> * {@link mmir.CommonUtils#convertJSONStringValueToHTML} as * <b><u>convert_to_json_value_HTML_string(String: str) : String</u></b> * </li><li> * {@link mmir.CommonUtils#convertJSONStringToHTML} as * <b><u>convert_json_to_HTML_string(String: str) : String</u></b> * </li><li> * {@link mmir.CommonUtils#parseParamsToDictionary} as * <b><u>get_params_as_dict(String: str) : Object</u></b> * </li> * </ul> * * Also, the functions of {@link mmir.extensions.JsonUtils} will be made available. * * @requires document (DOM element) * * @param {mmir.CommonUtils} compatibilitySelf * the instance of mmir.CommonUtils to which the compatibility functions etc. * will be attached * * @class * @name mmir.CommonUtils.setToCompatibilityModeExtension * @static * * @example * require(['commonUtilsCompatibility'], function(setCompatibility){ * setCompatibility(mmir.CommonUtils); * }); * * @requires document (DOM element) * * @public */ function(jsonUtils ) { /** * Set to "backwards compatibility mode" (for pre version 2.0). * * This function re-adds deprecated and removed functions and * properties to the CommonUtils instance. * * NOTE that once set to compatibility mode, it cannot be reset to * non-compatibility mode. * * @requires document (DOM element) * * @param {mmir.CommonUtils} compatibilitySelf * the instance of mmir.CommonUtils to which the compatibility functions etc. * will be attached * * @constructs mmir.CommonUtils.setToCompatibilityModeExtension * * @borrows mmir.CommonUtils#regexHTMLComment as * html_comment_regex * @borrows mmir.CommonUtils#resizeFitToSourroundingBox as * this.html_resize_font_to_fit_surrounding_box * @borrows mmir.CommonUtils#toJSONStringValue as * this.to_json_string_value * @borrows mmir.CommonUtils#convertJSONStringValueToHTML as * this.convert_to_json_value_HTML_string * @borrows mmir.CommonUtils#convertJSONStringToHTML as * this.convert_json_to_HTML_string * @borrows mmir.CommonUtils#parseParamsToDictionary as * this.get_params_as_dict */ return setToCompatibilityMode = function(compatibilitySelf) { /** @scope mmir.CommonUtils.setToCompatibilityModeExtension.prototype *///for jsdoc2 //add functions from jsonUtils for(var p in jsonUtils){ if(jsonUtils.hasOwnProperty(p)){ compatibilitySelf[p] = jsonUtils[p]; } } /** * Array of strings for the conversion of month represented by integers * to strings Default Language for months is english, 'en' * * @type Object * @private */ compatibilitySelf.months = { '01': 'January', '02': 'February', '03': 'March', '04': 'April', '05': 'May', '06': 'June', '07': 'July', '08': 'August', '09': 'September', '10': 'October', '11': 'November', '12': 'December' }; /** * @private */ compatibilitySelf.months.de = { '01': 'Januar', '02': 'Februar', '03': 'M\u00E4rz',//'M&auml;rz', '04': 'April', '05': 'Mai', '06': 'Juni', '07': 'Juli', '08': 'August', '09': 'September', '10': 'Oktober', '11': 'November', '12': 'Dezember' }; // /** // * The instance that holds the extensions for compatibility // * mode, which really is the CommonUtils instance. // * // * @type // * @private // */ // var compatibilitySelf = this; /** * HTML-Dom-Element for logging directly on the main HTML-Page * as of now there is no element with the id "log" in the * index.html * * @type Element * @private * @deprecated unused */ var debugNode = document.getElementById("log"); /** * Regular Expression to identify a styleSheet-tag for the * transformation of ehtml to html * * @type String|RegExp * @private * @deprecated unused */ var styleSheetRegExp = /<(%=\s*stylesheet_link_tag)\s* (\"(.*)\" %)>/; /** * Regular Expression to identify a javascript for the * transformation of ehtml to html * * @type String|RegExp * @private * @deprecated unused */ var javaScriptRegExp = /<(%=\s*javascript_include_tag)\s* (\"(.*)\" %)>/; /** * Regular Expression to identify content for a view-element:<br> * either _header_, _footer_, _dialogs_ or _content_ * * @deprecated old template syntax format * * @type String|RegExp * @private */ var contentForRegExp = /<%\s*content_for\s*:([^\s]*)\s*do\s*%>(([\s|\n]*.*[\s|\n]*)*)<%\s*end\s*%>/i; /** * Regular Expression to identify if a partial should be * rendered inside a view (ehtml-String) * * @deprecated old template syntax format * * @type String|RegExp * @private */ var renderPartialRegExp = /<%\s*render\s*([^\s]*)\s*\{\}\s*%>/i; /** * Regular Expression for matching a translation-tag for the * localization of view content (ehtml-String) * * @deprecated old template syntax format * * @type String|RegExp * @private */ var translationRegExpString = '<%t\\s*:([^\\s]*)\\s*%>'; // /** // * The Prefix for the names of view-files - currently unused // and deprecated. // * // * @type String // * @private // * @deprecated has no further value // */ // var viewsPrefix = '#'; /** * See Property: * {@link #setToCompatibilityModeExtension-render_partial_regex} * <br> * This regular expression is an extension for the parsing of * the parameters of the partial (for customization) to get the * name of the corresponding controller of the partial.<br> * * Regular Expression to identify if a partial is to be inserted * in a view. <br> * Partials are in principle customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * @deprecated old template syntax format * * @example <% render googlemap/poi_details {:curr_poi_data_jpath => new JPath(mmir.ControllerManager.getInstance().getController("googlemap").script['current_poi_meta_data'])} %> * @type String|RegExp * @public */ var partial_name_regex = /^([^\/]+)\/(.+)$/i; compatibilitySelf.partial_name_regex = partial_name_regex; /** * Regular expression for the parsing of partial-files.<br> * This expression detects all variables and data-instructions * for the customization of the partial. There are 3 types of * variables or instructions: * + <b>if-else-statement</b>, controls which part of the * partial will be displayed - depending on the condition + * <b>data-instruction</b>, which is evaluated, but not * displayed + <b>variable</b> or <b>javascript-code</b>, * which are evaluated and displayed in the view * * Partials are principally customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * @deprecated old template syntax format * * @example {::address = address + " " + {:curr_poi_data}.query('addressBean/housenumber')} * @type String|RegExp * @public */ var partial_var_pattern_regex = /(\{[^\}\{]+\})|(\{[^\{]*(\{(?=[^\}]*\}).*)\})/gmi; compatibilitySelf.partial_var_pattern_regex = partial_var_pattern_regex; /** * Regular expression for the parsing of partial-files.<br> * This expression detects all simple variables for the * customization of the partial in the form of * <b>{:curr_poi_data}</b>.<br> * Form of <b>simple object</b>: <b>{:SIMPLE_OBJECT}</b><br> * * Partials are principally customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * * @deprecated old template syntax format * * @example {:curr_poi_data} * @type String|RegExp * @public */ var partial_var_pattern_simpleobject_regex = /\{:([^\}]+)\}/; compatibilitySelf.partial_var_pattern_simpleobject_regex = partial_var_pattern_simpleobject_regex; /** * Regular expression for the parsing of partial-files.<br> * This expression detects all <b>data objects</b> for the * customization of the partial in the form of * <b>{::curr_poi_data={:curr_poi_data_jpath}}</b>.<br> * Form of <b>data object</b>: <b>{::DATA_OBJECT}</b><br> * * Partials are principally customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * * @deprecated old template syntax format * * @example {::address = address + "&lt;br/&gt;"} * @type String|RegExp * @public */ var partial_var_pattern_dataobject_regex = /\{::([^\}\{]+)\}|\{::([^\{]*(?:\{(?:[^\}]*\}).*))\}/ig; compatibilitySelf.partial_var_pattern_dataobject_regex = partial_var_pattern_dataobject_regex; /** * Regular expression for detecting an assignment expression in * templates, e.g. <code>{::theVariable=... }</code>. * * * @deprecated old template syntax format * * @example {::address = address + "&lt;br/&gt;"} * or * <code>{::address = {:anotherVariable} + "&lt;br/&gt;"}</code> * @type String|RegExp * @public */ var partial_var_pattern_assignment_regex = /\{::([^\}\{=]+)=([^\}\{]+)\}|\{::([^\}\{=]+)=([^\{]*(?:\{(?:[^\}]*\}).*))\}/ig; compatibilitySelf.partial_var_pattern_assignment_regex = partial_var_pattern_assignment_regex; // /** // * Deprecated regular expression for partials. // * @type String|RegExp // * @public // * @deprecated unused // */ // var partial_var_pattern_object_with_function_regex = // /\{?([^\.]+)([\.\[])([^\s\}]+)()/ig // compatibilitySelf.partial_var_pattern_object_with_function_regex // = partial_var_pattern_object_with_function_regex; /** * Regular Expression to identify content in a view that will be * inserted.<br> * The content is generated by a helper function of the * controller and usually saved as a JSON-Object with a _helper_ * and _content_ part.<br> * If the string is escaped and must be unescaped a second * parameter can be given to ensure that the string will be * unescaped before the insertion in the view. * * @deprecated old template syntax format * * @example <%= value_of(languageMenu::header, true) %> * @type String|RegExp * @public */ var value_of_regex = /<%=\s*value_of\s*\(([^\)]*)\)\s*%>/igm; compatibilitySelf.value_of_regex = value_of_regex; /** * See Property: * {@link #setToCompatibilityModeExtension-value_of_regex} * <br> * This regular expression is an extension to parse the * parameters of the <b>value_of</b>-function.<br> * * Regular Expression to identify content in a view that will be * inserted.<br> * The content is generated by a helper function of the * controller and usually saved as a JSON-Object with a _helper_ * and _content_ part.<br> * If the string is escaped and must be unescaped a second * parameter can be given to ensure that the string will be * unescaped before the insertion in the view. * * @deprecated old template syntax format * * @example <%= value_of(languageMenu::header, true) %> * @type String|RegExp * @public */ var value_of_path_regex = /\(\s*([^\),]*),?\s*([^\)]*)\s*\)/i; compatibilitySelf.value_of_path_regex = value_of_path_regex; /** * Regular Expression to identify if a partial is to be inserted * in a view. <br> * Partials are in principle customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * @deprecated old template syntax format * * @example <% render googlemap/poi_details {:curr_poi_data_jpath => new JPath(mmir.ControllerManager.getInstance().getController("googlemap").script['current_poi_meta_data'])} %> * @type String|RegExp * @public */ var render_partial_regex = /<%\s*render\s*([^\s]*)\s*\{([^\}]*)\}\s*%>/igm; compatibilitySelf.render_partial_regex = render_partial_regex; /** * See Property: * {@link #setToCompatibilityModeExtension-render_partial_regex} * <br> * This regular expression is an extension for the parsing of * the parameters of the partial (for customization).<br> * * Regular Expression to identify if a partial is to be inserted * in a view. <br> * Partials are in principle customizable views, which can be * used independently from a controller and furthermore accept * parameters to customize the partial.<br> * A partial is first processed and then integrated into the * view. * * @deprecated old template syntax format * * @example <% render googlemap/poi_details {:curr_poi_data_jpath => new JPath(mmir.ControllerManager.getInstance().getController("googlemap").script['current_poi_meta_data'])} %> * @type String|RegExp * @public */ var partial_parameter_regex = /\s*:(\S*)\s*=>\s*(("([\S ]+)")|([^,]+))/i; compatibilitySelf.partial_parameter_regex = partial_parameter_regex; /** * Appends a log-message to the main document (index.html) and * prints it in the console * * @function * @param {String} * clazz A prefix for the output of the log message * in the console * @param {String} * logMessage The log message which should be printed * @public * @deprecated */ var log = function(clazz, logMessage) { debugNode = document.getElementById("log"); if (debugNode) { debugNode.innerHTML += "<pre>\n" + logMessage + "\n</pre>\n"; } console.log(clazz + ":" + logMessage); }; compatibilitySelf.log = log; /** * Function which transforms a ehtml string (while parsing * views) into html by replacing stylesheet-, javascript- and * content_for-tags with corresponding contents. * * * @deprecated used for parsing/rendering old template syntax * format * * @function * @param {String} * eHtmlTag A string that should be transformed from * ehtml to html * @public * @returns {String} From ehtml into html transformed string */ var ehtml2Html = function(eHtmlTag) { var result; if (eHtmlTag.match(styleSheetRegExp)) { var group = eHtmlTag.match(styleSheetRegExp); result = eHtmlTag.replace(group[1], "link rel=\"stylesheet\" ").replace(group[2], "href=\"content/stylesheets/" + group[3] + ".css\"/"); }else if (eHtmlTag.match(javaScriptRegExp)) { var group = eHtmlTag.match(javaScriptRegExp); result = eHtmlTag.replace(group[1], "script type=\"text/javascript\" charset=\"utf-8\" ").replace(group[2], "src=\"" + group[3] + ".js\"></script"); }else if (eHtmlTag.match(contentForRegExp)) { var group = eHtmlTag.match(contentForRegExp); return group; } else { return eHtmlTag; } return result; }; compatibilitySelf.ehtml2Html = ehtml2Html; /** * Similar to the jQuery.getScript() function - appending a url * of a javascript-source to the header of the main document. * * @function * @param {String} * scriptSrc source of javascript-file * @public * @deprecated superseded by getLocalScript */ var appendJsSrcToHeader = function(scriptSrc) { // appends '<script src=scriptSrc type = // "text/javascript"></script>' to header // thus loading it dynamically var newScript = document.createElement('script'); newScript.type = "text/javascript"; newScript.src = scriptSrc; document.head.appendChild(newScript); }; compatibilitySelf.appendJsSrcToHeader = appendJsSrcToHeader; // /** // * Get the prefix for views. // * @function // * @public // * @returns {String} The Prefix for the file names of views // * @deprecated This function is unused and superfluous // */ // var compatibilitySelf.getViewsPrefix= function(){ // return viewsPrefix; // }; // compatibilitySelf.getViewsPrefix = getViewsPrefix; /** * Gets the Regular Expression for translation tags. * * @function * @public * @returns {String} The regular expression for matching a * translation-tag - used inside a ehtml-String */ var getTranslationRegExp = function() { return new RegExp(translationRegExpString, 'gi'); }; compatibilitySelf.getTranslationRegExp = getTranslationRegExp; /** * Reformat the String representation of a date. * * @example converts <code>2012-07-23 16:37:33.0</code> into * &rarr; <code>23. July 2012</code> * * @function * @param {String} * the date String in format * <code>yyyy-mm-dd HH:mm:ss.S</code> * @param {String} * <em>[Optional]</em> the language code (currently * used to format the name of the month). Currently * supported languages: <code>en, de</code>. If * unkown or omitted, default <code>en</code> is * used. * @return {String} a new String representation for the date * @public */ var get_date_as_string = function(date, languageCode) { var self = this; var day, month, year; var date_time = date.split(" "); var splited_date = date_time[0].split("-"); year = splited_date[0]; month = splited_date[1]; // add leading zero if necessary if (month.length == 1) { month = '0' + month; } day = splited_date[2]; var theLanguage = typeof languageCode === 'string'? languageCode.toLowerCase() : null; var monthName; if(theLanguage !== null && languageCode !== 'en' && self.months[theLanguage]){ //get language specific name for month, if possible monthName = self.months[theLanguage][month]; } else { //get default name for month monthName = self.months[month]; } return day +". "+monthName+" "+year; }; compatibilitySelf.get_date_as_string = get_date_as_string; /** * Convert a duration (in seconds) into a String representation. * * @example * 2:09:19 h * 12:05 min * * @function * @param {Integer} * the duration in seconds * @return {String} a String representation for the duration * @public */ var get_duration_as_string = function(duration) { var sec = duration % 60; var min = (duration - sec) / 60; var hour = 0; if (min > 59) { min = min % 60; hour = ((duration - (min * 60)) - sec) / 3600; } if (sec < 10) { sec = "0" + sec; } if (min < 10) { min = "0" + min; } if (hour > 0) { return hour + ":" + min + ":" + sec + " h"; } else { return min + ":" + sec + " min"; } }; compatibilitySelf.get_duration_as_string = get_duration_as_string; // //////////////////////////////////////////////////////////////////////////// // comp: make renamed functions available under their old name again: compatibilitySelf.html_comment_regex = compatibilitySelf.regexHTMLComment; compatibilitySelf.html_resize_font_to_fit_surrounding_box = compatibilitySelf.resizeFitToSourroundingBox; compatibilitySelf.to_json_string_value = compatibilitySelf.toJSONStringValue; compatibilitySelf.convert_to_json_value_HTML_string = compatibilitySelf.convertJSONStringValueToHTML; compatibilitySelf.convert_json_to_HTML_string = compatibilitySelf.convertJSONStringToHTML; compatibilitySelf.get_params_as_dict = compatibilitySelf.parseParamsToDictionary; };// END: setToCompatibilityModeExtension });
// LICENSE : MIT "use strict"; const EventEmitter = require("events"); const REPOSITORY_CHANGE = "REPOSITORY_CHANGE"; import MemoryDB from "./adpter/MemoryDB"; import Video from "../domain/Video"; export class VideoRepository extends EventEmitter { constructor(database = new MemoryDB()) { super(); /** * @type {MemoryDB} */ this._database = database; } /** * get instance * @param id * @private */ _get(id) { // Domain.<id> return this._database.get(`${Video.name}.${id}`); } findById(id) { return this._get(id); } /** * @returns {Video|undefined} */ lastUsed() { console.log(`${Video.name}.lastUsed`); const video = this._database.get(`${Video.name}.lastUsed`); if (!video) { return new Video(); } return this._get(video.id); } /** * @param {Video} video */ save(video) { this._database.set(`${Video.name}.lastUsed`, video); this._database.set(`${Video.name}.${video.id}`, video); this.emit(REPOSITORY_CHANGE); } /** * @param {Video} video */ remove(video) { this._database.delete(`${Video.name}.${video.id}`); this.emit(REPOSITORY_CHANGE); } onChange(handler) { this.on(REPOSITORY_CHANGE, handler); } } // singleton export default new VideoRepository();
// All code points in the `Kannada` script as per Unicode v5.1.0: [ 0xC82, 0xC83, 0xC85, 0xC86, 0xC87, 0xC88, 0xC89, 0xC8A, 0xC8B, 0xC8C, 0xC8E, 0xC8F, 0xC90, 0xC92, 0xC93, 0xC94, 0xC95, 0xC96, 0xC97, 0xC98, 0xC99, 0xC9A, 0xC9B, 0xC9C, 0xC9D, 0xC9E, 0xC9F, 0xCA0, 0xCA1, 0xCA2, 0xCA3, 0xCA4, 0xCA5, 0xCA6, 0xCA7, 0xCA8, 0xCAA, 0xCAB, 0xCAC, 0xCAD, 0xCAE, 0xCAF, 0xCB0, 0xCB1, 0xCB2, 0xCB3, 0xCB5, 0xCB6, 0xCB7, 0xCB8, 0xCB9, 0xCBC, 0xCBD, 0xCBE, 0xCBF, 0xCC0, 0xCC1, 0xCC2, 0xCC3, 0xCC4, 0xCC6, 0xCC7, 0xCC8, 0xCCA, 0xCCB, 0xCCC, 0xCCD, 0xCD5, 0xCD6, 0xCDE, 0xCE0, 0xCE1, 0xCE2, 0xCE3, 0xCE6, 0xCE7, 0xCE8, 0xCE9, 0xCEA, 0xCEB, 0xCEC, 0xCED, 0xCEE, 0xCEF ];
import React, { Component } from 'react' import { StyleSheet, Text, View, ToolbarAndroid, ToastAndroid, TouchableOpacity, Image, BackHandler, Clipboard, ListView, Animated, Easing, Vibration } from 'react-native' import {rvDB} from '../rvAPI' import ParsedText from 'react-native-parsed-text' import { SwipeListView } from 'react-native-swipe-list-view' export default class PracticeScene extends Component { constructor (props) { super(props) const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => { return r1.item !== r2.item }}) this.db = null this.lastYLocation = 0 this.checkBookmarkReadyTimeoutID = null this.deviceWidth = 360 this.state = { buttonSize: new Animated.Value(0), textSize: new Animated.Value(30), toggle: true, state: 'init', dataSource: ds.cloneWithRows([{item: '加载中...'}]) } this._exitPracticeScene = this._exitPracticeScene.bind(this) this._checkDeviceWidth = this._checkDeviceWidth.bind(this) this._practiceSceneBackPressHandler = this._practiceSceneBackPressHandler.bind(this) } static navigationOptions = { header: null } componentWillMount () { rvDB.showDataItemRows(this.props.navigation.state.params.db).then(([results, lastYLocation]) => { if (results === null) { ToastAndroid.show('没有要背的东西', ToastAndroid.SHORT) // this.props.navigator.pop() this.props.navigation.goBack() } else { this.db = results this.lastYLocation = lastYLocation if (lastYLocation !== 0) { this.checkBookmarkReadyTimeoutID = setInterval(() => { // check whether list view reach the record Y location every second if (this.swipteListViewRef._listView.scrollProperties.contentLength >= this.lastYLocation) { Animated.parallel([ // occur button Animated.timing(this.state.buttonSize, { toValue: 70, easing: Easing.in(Easing.circle), duration: 500 } ), // remove text Animated.timing(this.state.textSize, { toValue: 0, easing: Easing.in(Easing.circle), duration: 500 } ) ]).start() clearInterval(this.checkBookmarkReadyTimeoutID) this.checkBookmarkReadyTimeoutID = null } }, 1000) } setTimeout(() => { this.setState({ state: 'initDone', dataSource: this.state.dataSource.cloneWithRows(this.db) }) }, 500) } }).catch((e) => { ToastAndroid.show('' + e, ToastAndroid.SHORT) // this.props.navigator.pop() this.props.navigation.goBack() }) } componentDidMount () { BackHandler.addEventListener('PracticeSceneBackPress', this._practiceSceneBackPressHandler) } componentWillUnmount () { BackHandler.removeEventListener('PracticeSceneBackPress', this._practiceSceneBackPressHandler) } render () { return ( <View style={{flex: 1}} onLayout = {this._checkDeviceWidth}> <ToolbarAndroid navIcon={{uri: 'ic_arrow_back_white_36dp'}} title={this.props.navigation.state.params.db} titleColor="white" style={styles.toolBar} onIconClicked={this._exitPracticeScene} /> <View style={{flex: 1, backgroundColor: '#FAFAFA'}}> <SwipeListView dataSource={this.state.dataSource} ref={(swipteListViewRef) => { this.swipteListViewRef = swipteListViewRef }} renderRow={ (rowData, secdId, rowId) => ( <View style={styles.rowFront}> { this.state.state !== 'initDone' ? ( <Text style={[styles.textShow, {textAlign: 'center'}]}>{rowData.item}</Text> ) : ( <ParsedText style={styles.textShow} parse={[ // ParsedText not support LongPress {pattern: /\w+/, onPress: this._handleWordPress} ]} > {rowData.item} </ParsedText> ) } </View> )} renderHiddenRow={(rowData, secdId, rowId, rowMap) => ( <TouchableOpacity style={styles.rowBack} onPress={this._delete.bind(this, secdId, rowId, rowMap)} > <View style={{width: 66}}> <Image source={{uri: 'ic_delete_forever_white_36dp'}} style={{width: 36, height: 36, marginLeft: 15}} /> </View> </TouchableOpacity> )} closeOnRowPress={false} rightOpenValue={-66} recalculateHiddenLayout={true} disableRightSwipe={true} disableLeftSwipe={this.state.state !== 'initDone'} initialListSize={5} // 默认值是10 scrollRenderAheadDistance={this.lastYLocation + 800} // 这个是row离屏幕还有某像素时就渲染 /> { this.lastYLocation !== 0 && this.state.state === 'initDone' && ( <View style={styles.overlay}> <Animated.Text style={{ color: '#448AFF', fontSize: this.state.textSize }} >加载上次退出点</Animated.Text> {/* cancel button whic use to cancel loading record Y location */} <TouchableOpacity onPress={() => { if (this.checkBookmarkReadyTimeoutID !== null) { clearInterval(this.checkBookmarkReadyTimeoutID) this.checkBookmarkReadyTimeoutID = null } this.lastYLocation = 0 this.setState({toggle: !this.state.toggle}) }}> <View style={styles.cancelBookmarkButton}> <Image source={{uri: 'ic_cancel_white_36dp'}} style={{width: 36, height: 36}}/> </View> </TouchableOpacity> {/* button use to go to the record Y location */} <TouchableOpacity onPress={() => { this.swipteListViewRef._listView.scrollTo({y: this.lastYLocation}) this.lastYLocation = 0 this.setState({toggle: !this.state.toggle}) }}> <Animated.View style={{ width: this.state.buttonSize, height: this.state.buttonSize, borderRadius: this.state.buttonSize.interpolate({ inputRange: [0, 70], outputRange: [0, 35] }), backgroundColor: '#E040FB', justifyContent: 'center', alignItems: 'center' }} > <Image source={{uri: 'ic_bookmark_border_white_36dp'}} style={{width: 36, height: 36}} /> </Animated.View> </TouchableOpacity> </View> ) } </View> </View> ) } _handleWordPress (word) { ToastAndroid.show('复制' + word + '到剪贴板', ToastAndroid.SHORT) Clipboard.setString(word) } _delete (secdId, rowId, rowMap) { let data = this.db.slice() rvDB.deleteDataItem(this.props.navigation.state.params.db, rowId).then(() => { data.splice(rowId, 1) if (data.length === 0) { // 唯一的一个删除 // this.props.navigator.pop() this.props.navigation.goBack() } else { Animated.timing( rowMap[`${secdId}${rowId}`]._translateX, { duration: 100, toValue: -this.deviceWidth } ).start() Vibration.vibrate([0, 50]) this.db = data // should wait above delete animition finish, so wait 150 ms to update db setTimeout(() => { this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.db) }) }, 150) } }).catch((e) => { ToastAndroid.show('remove occur wrong: ' + e, ToastAndroid.SHORT) }) } _exitPracticeScene () { let leaveLocation = this.swipteListViewRef._listView.scrollProperties.offset if (this.checkBookmarkReadyTimeoutID !== null) { clearInterval(this.checkBookmarkReadyTimeoutID) } rvDB.saveDataItemBookmark(this.props.navigation.state.params.db, leaveLocation).then(() => { // this.props.navigator.pop() this.props.navigation.goBack() }).catch((e) => { ToastAndroid.show('' + e, ToastAndroid.SHORT) }) } _checkDeviceWidth (e) { // ToastAndroid.show('width: '+e.nativeEvent.layout.width, ToastAndroid.SHORT); this.deviceWidth = e.nativeEvent.layout.width } _practiceSceneBackPressHandler () { let currentRoute = this.props.navigation.state.routeName if (currentRoute === 'PracticeScene') { this._exitPracticeScene() return true } } } const styles = StyleSheet.create({ textShow: { fontSize: 21, marginHorizontal: 20, marginVertical: 25, lineHeight: 28 }, rowBack: { alignItems: 'flex-end', backgroundColor: '#FF5252', justifyContent: 'center', flex: 1 }, rowFront: { borderBottomColor: '#F0F0F0', backgroundColor: 'white', borderBottomWidth: 1 }, toolBar: { height: 56, backgroundColor: '#2196F3' }, overlay: { position: 'absolute', bottom: 0, left: 0, right: 0, top: 0, backgroundColor: 'rgba(189, 189, 189, 0.8)', justifyContent: 'center', alignItems: 'center' }, cancelBookmarkButton: { width: 70, height: 70, borderRadius: 35, backgroundColor: '#FF5252', justifyContent: 'center', alignItems: 'center', marginVertical: 20 } })