text
stringlengths
2
6.14k
var http = require('http'); function jsonHttpRequest(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', 'Accept': 'application/json' } }; var req = http.request(options, function(res){ var replyData = ''; res.setEncoding('utf8'); res.on('data', function(chunk){ replyData += chunk; }); res.on('end', function(){ var replyJson; try{ replyJson = JSON.parse(replyData); } catch(e){ callback(e); return; } callback(null, replyJson); }); }); req.on('error', function(e){ callback(e); }); req.end(data); } function rpc(host, port, method, params, callback){ var data = JSON.stringify({ id: "0", jsonrpc: "2.0", method: method, params: params }); jsonHttpRequest(host, port, data, function(error, replyJson){ if (error){ callback(error); return; } callback(replyJson.error, replyJson.result) }); } function batchRpc(host, port, array, callback){ var rpcArray = []; for (var i = 0; i < array.length; i++){ rpcArray.push({ id: i.toString(), jsonrpc: "2.0", method: array[i][0], params: array[i][1] }); } var data = JSON.stringify(rpcArray); jsonHttpRequest(host, port, data, callback); } module.exports = function(daemonConfig, walletConfig){ return { batchRpcDaemon: function(batchArray, callback){ batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback); }, rpcDaemon: function(method, params, callback){ rpc(daemonConfig.host, daemonConfig.port, method, params, callback); }, rpcWallet: function(method, params, callback){ rpc(walletConfig.host, walletConfig.port, method, params, callback); } } };
/** * Module dependencies */ var XMLHttpRequest = require('xmlhttprequest-ssl'); var XHR = require('./polling-xhr'); var JSONP = require('./polling-jsonp'); var websocket = require('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } }
describe('Application controller', function(){ beforeEach(module('mpk')); var scope, applicationController, kanbanRepositoryMock, themesProviderMock, window; var renamer, saver; beforeEach(inject(function($rootScope, $controller, $window){ renamer = jasmine.createSpy('Kanban Rename Function'); saver = jasmine.createSpy('Kanban Saver'); kanbanRepositoryMock = { load: function(){ return validSampleKanban.kanbans;}, getLastUsed: function(){ return validSampleKanban.kanbans['Stuff to do at home']}, all: function() { return validSampleKanban.kanbans;}, getTheme: function() { return 'default-dark'; }, renameLastUsedTo: renamer, save: saver, get: function(name) { return validSampleKanban.kanbans[name]; }, setLastUsed: function(kanban) { return kanban; }, }; window = $window; themesProviderMock = {setCurrentTheme: function(){}}; scope = $rootScope.$new(); applicationController = $controller('ApplicationController', {$scope: scope, kanbanRepository: kanbanRepositoryMock, themesProvider: themesProviderMock, $window: window, $routeParams: {}}); })); it("should change name of the Kanban to new name", function(){ scope.newName = 'foobarboo'; scope.allKanbans = []; scope.rename(); expect(renamer).toHaveBeenCalledWith(scope.newName); expect(saver).toHaveBeenCalled(); expect(scope.allKanbans).not.toEqual([]); }); it("should set the Text field variable of the name", function(){ expect(scope.newName).toBe('Stuff to do at home'); }); it("should switch to editing when clicking Kanban Name editing", function(){ expect(scope.editingName).toBeFalsy(); scope.editingKanbanName(); expect(scope.editingName).toBeTruthy(); }); it("should add switch to option to Switch Menu", function(){ expect(scope.switchToList.length).toBe(scope.allKanbans.length+1); }); var validSampleKanban = {"kanbans": {"Stuff to do at home":{"name":"Stuff to do at home","numberOfColumns":3, "columns":[ {"name":"Not started","cards":[{"name":"This little piggy went to lunch","color":"CCD0FC"},{"name":"Foo bar","color":"FCE4D4"}]}, {"name":"In progress","cards":[{"name":"another on a bit longer text this time","color":"FAFFA1"},{"name":"And another one","color":"94D6FF"}]}, {"name":"Done","cards":[{"name":"bar foo","color":"FCE4D4"},{"name":"Another on","color":"FCC19D"},{"name":"New one","color":"FC9AFB"}]} ] }, "foobarboo":{"name":"foobarboo","numberOfColumns":3, "columns":[ {"name":"Col 1","cards":[]}, {"name":"Col 2","cards":[]}, {"name":"Col 3","cards":[]}, ] }}, "lastUsed":"Stuff to do at home", "theme":"default-dark", "lastUpdated":"1391554268110"}; });
/** * Shopware 4 * Copyright © shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * Shopware UI - Main Backend Application Bootstrap * * This file bootstrapps the complete backend structure. */ //{block name="backend/index/application"} Ext.define('Shopware.apps.Index', { /** * Extends from our special controller, which handles the * sub-application behavior and the event bus * @string */ extend:'Enlight.app.SubApplication', /** * Enables our bulk loading technique. * @booelan */ bulkLoad: true, /** * Sets the loading path for the sub-application. * * Note that you'll need a "loadAction" in your * controller (server-side) * @string */ loadPath: '{url action=load}', /** * Required controllers for module (subapplication) * @array */ controllers:[ 'Main', 'Widgets', 'ErrorReporter' ], /** * Requires class for the module (subapplication) */ requires: [ 'Shopware.container.Viewport' ], /** * Required views for module (subapplication) * @array */ views: [ 'Main', 'Menu', 'Footer', 'Search', 'widgets.Window', 'widgets.Sales', 'widgets.Upload', 'widgets.Visitors', 'widgets.Orders', 'widgets.Notice', 'widgets.Merchant', 'widgets.Base', 'merchant.Window' ], /** * Required models for the module * @array */ models: [ 'Widget', 'WidgetSettings', 'Turnover', 'Batch', 'Customers', 'Visitors', 'Orders', 'Merchant', 'MerchantMail' ], /** * Required stores for the module * @array */ stores: [ 'Widget', 'WidgetSettings' ] }); //{/block}
description( "This test checks that iterating a large array backwards works correctly." ); var bytes = new Array(); function prepare(nbytes) { var i = nbytes - 1; while (i >= 0) { bytes[i] = new Number(i); i -= 1; } } function verify(nbytes) { var i = nbytes - 1; while (i >= 0) { if (bytes[i] != i) return false; i -= 1; } return true; } prepare(32768); shouldBeTrue('verify(32768)'); prepare(65536); shouldBeTrue('verify(65536)'); prepare(120000); shouldBeTrue('verify(120000)');
'use strict'; var ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { entry: { 'index': './index.styl', 'index-no-normalize': './style/index.styl' }, output: { filename: 'index.css' }, module: { loaders: [ { test: /\.styl$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!stylus-loader') } ] }, plugins: [ new ExtractTextPlugin('[name].css') ] }
var NAME = "InvalidDerefInputError"; var MESSAGE = "Deref can only be used with a non-primitive object from get, set, or call."; /** * An invalid deref input is when deref is used with input that is not generated * from a get, set, or a call. * * @param {String} message * @private */ function InvalidDerefInputError() { this.message = MESSAGE; this.stack = (new Error()).stack; } // instanceof will be an error, but stack will be correct because its defined in the constructor. InvalidDerefInputError.prototype = new Error(); InvalidDerefInputError.prototype.name = NAME; InvalidDerefInputError.name = NAME; InvalidDerefInputError.message = MESSAGE; module.exports = InvalidDerefInputError;
// FIXME add some error checking // FIXME check order of async callbacks /** * @see http://mapbox.com/developers/api/ */ goog.provide('ol.source.TileJSON'); goog.provide('ol.tilejson'); goog.require('goog.asserts'); goog.require('goog.net.Jsonp'); goog.require('ol.Attribution'); goog.require('ol.TileRange'); goog.require('ol.TileUrlFunction'); goog.require('ol.extent'); goog.require('ol.proj'); goog.require('ol.source.State'); goog.require('ol.source.TileImage'); /** * @classdesc * Layer source for tile data in TileJSON format. * * @constructor * @extends {ol.source.TileImage} * @param {olx.source.TileJSONOptions} options TileJSON options. * @api stable */ ol.source.TileJSON = function(options) { goog.base(this, { attributions: options.attributions, crossOrigin: options.crossOrigin, projection: ol.proj.get('EPSG:3857'), state: ol.source.State.LOADING, tileLoadFunction: options.tileLoadFunction, wrapX: goog.isDef(options.wrapX) ? options.wrapX : true }); var request = new goog.net.Jsonp(options.url); request.send(undefined, goog.bind(this.handleTileJSONResponse, this)); }; goog.inherits(ol.source.TileJSON, ol.source.TileImage); /** * @protected * @param {TileJSON} tileJSON Tile JSON. */ ol.source.TileJSON.prototype.handleTileJSONResponse = function(tileJSON) { var epsg4326Projection = ol.proj.get('EPSG:4326'); var sourceProjection = this.getProjection(); var extent; if (goog.isDef(tileJSON.bounds)) { var transform = ol.proj.getTransformFromProjections( epsg4326Projection, sourceProjection); extent = ol.extent.applyTransform(tileJSON.bounds, transform); } if (goog.isDef(tileJSON.scheme)) { goog.asserts.assert(tileJSON.scheme == 'xyz', 'tileJSON-scheme is "xyz"'); } var minZoom = tileJSON.minzoom || 0; var maxZoom = tileJSON.maxzoom || 22; var tileGrid = ol.tilegrid.createXYZ({ extent: ol.tilegrid.extentFromProjection(sourceProjection), maxZoom: maxZoom, minZoom: minZoom }); this.tileGrid = tileGrid; this.tileUrlFunction = ol.TileUrlFunction.createFromTemplates(tileJSON.tiles); if (goog.isDef(tileJSON.attribution) && goog.isNull(this.getAttributions())) { var attributionExtent = goog.isDef(extent) ? extent : epsg4326Projection.getExtent(); /** @type {Object.<string, Array.<ol.TileRange>>} */ var tileRanges = {}; var z, zKey; for (z = minZoom; z <= maxZoom; ++z) { zKey = z.toString(); tileRanges[zKey] = [tileGrid.getTileRangeForExtentAndZ(attributionExtent, z)]; } this.setAttributions([ new ol.Attribution({ html: tileJSON.attribution, tileRanges: tileRanges }) ]); } this.setState(ol.source.State.READY); };
module("Director.js", { setup: function() { window.location.hash = ""; shared = {}; }, teardown: function() { window.location.hash = ""; shared = {}; } }); var shared; function createTest(name, config, use, test) { if (typeof use === 'function') { test = use; use = undefined; } asyncTest(name, function() { setTimeout(function() { var router = new Router(config), context; if (use !== undefined) { router.configure(use); } router.init(); test.call(context = { router: router, navigate: function(url, callback) { window.location.hash = url; setTimeout(function() { callback.call(context); }, 14); }, finish: function() { router.destroy(); start(); } }); }, 14); }); };
// @flow // $ExpectError: No negative tests here const skipNegativeTest: string = true; var inquirer = require('inquirer'); var directionsPrompt = { type: 'list', name: 'direction', message: 'Which direction would you like to go?', choices: ['Forward', 'Right', 'Left', 'Back'] }; function main() { console.log('You find youself in a small room, there is a door in front of you.'); exitHouse(); } function exitHouse() { inquirer.prompt(directionsPrompt).then(function (answers) { if (answers.direction === 'Forward') { console.log('You find yourself in a forest'); console.log('There is a wolf in front of you; a friendly looking dwarf to the right and an impasse to the left.'); encounter1(); } else { console.log('You cannot go that way. Try again'); exitHouse(); } }); } function encounter1() { inquirer.prompt(directionsPrompt).then(function (answers) { var direction = answers.direction; if (direction === 'Forward') { console.log('You attempt to fight the wolf'); console.log('Theres a stick and some stones lying around you could use as a weapon'); encounter2b(); } else if (direction === 'Right') { console.log('You befriend the dwarf'); console.log('He helps you kill the wolf. You can now move forward'); encounter2a(); } else { console.log('You cannot go that way'); encounter1(); } }); } function encounter2a() { inquirer.prompt(directionsPrompt).then(function (answers) { var direction = answers.direction; if (direction === 'Forward') { var output = 'You find a painted wooden sign that says:'; output += ' \n'; output += ' ____ _____ ____ _____ \n'; output += '(_ _)( _ )( _ \\( _ ) \n'; output += ' )( )(_)( )(_) ))(_)( \n'; output += ' (__) (_____)(____/(_____) \n'; console.log(output); } else { console.log('You cannot go that way'); encounter2a(); } }); } function encounter2b() { inquirer.prompt({ type: 'list', name: 'weapon', message: 'Pick one', choices: [ 'Use the stick', 'Grab a large rock', 'Try and make a run for it', 'Attack the wolf unarmed' ] }).then(function () { console.log('The wolf mauls you. You die. The end.'); }); } main();
/** * Module dependencies. */ var express = require('../../'); var cookie-parser = require('cookie-parser'); var app = module.exports = express(); // pass a secret to cookieParser() for signed cookies app.use(cookieParser('manny is cool')); // add req.session cookie support app.use(cookieSession()); // do something with the session app.use(count); // custom middleware function count(req, res) { req.session.count = req.session.count || 0; var n = req.session.count++; res.send('viewed ' + n + ' times\n'); } /* istanbul ignore next */ if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); }
import { ElementRef, Input, Component, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Calendar } from '@fullcalendar/core'; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var FullCalendar = /** @class */ (function () { function FullCalendar(el) { this.el = el; } FullCalendar.prototype.ngOnInit = function () { this.config = { theme: true }; if (this.options) { for (var prop in this.options) { this.config[prop] = this.options[prop]; } } }; FullCalendar.prototype.ngAfterViewChecked = function () { if (!this.initialized && this.el.nativeElement.offsetParent) { this.initialize(); } }; Object.defineProperty(FullCalendar.prototype, "events", { get: function () { return this._events; }, set: function (value) { this._events = value; if (this._events && this.calendar) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this._events); } }, enumerable: true, configurable: true }); Object.defineProperty(FullCalendar.prototype, "options", { get: function () { return this._options; }, set: function (value) { this._options = value; if (this._options && this.calendar) { for (var prop in this._options) { var optionValue = this._options[prop]; this.config[prop] = optionValue; this.calendar.setOption(prop, optionValue); } } }, enumerable: true, configurable: true }); FullCalendar.prototype.initialize = function () { this.calendar = new Calendar(this.el.nativeElement.children[0], this.config); this.calendar.render(); this.initialized = true; if (this.events) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this.events); } }; FullCalendar.prototype.getCalendar = function () { return this.calendar; }; FullCalendar.prototype.ngOnDestroy = function () { if (this.calendar) { this.calendar.destroy(); this.initialized = false; this.calendar = null; } }; FullCalendar.ctorParameters = function () { return [ { type: ElementRef } ]; }; __decorate([ Input() ], FullCalendar.prototype, "style", void 0); __decorate([ Input() ], FullCalendar.prototype, "styleClass", void 0); __decorate([ Input() ], FullCalendar.prototype, "events", null); __decorate([ Input() ], FullCalendar.prototype, "options", null); FullCalendar = __decorate([ Component({ selector: 'p-fullCalendar', template: '<div [ngStyle]="style" [class]="styleClass"></div>' }) ], FullCalendar); return FullCalendar; }()); var FullCalendarModule = /** @class */ (function () { function FullCalendarModule() { } FullCalendarModule = __decorate([ NgModule({ imports: [CommonModule], exports: [FullCalendar], declarations: [FullCalendar] }) ], FullCalendarModule); return FullCalendarModule; }()); /** * Generated bundle index. Do not edit. */ export { FullCalendar, FullCalendarModule }; //# sourceMappingURL=primeng-fullcalendar.js.map
/** @module Discourse */ var get = Ember.get, set = Ember.set; var popstateFired = false; var supportsHistoryState = window.history && 'state' in window.history; // Thanks: https://gist.github.com/kares/956897 var re = /([^&=]+)=?([^&]*)/g; var decode = function(str) { return decodeURIComponent(str.replace(/\+/g, ' ')); }; $.parseParams = function(query) { var params = {}, e; if (query) { if (query.substr(0, 1) === '?') { query = query.substr(1); } while (e = re.exec(query)) { var k = decode(e[1]); var v = decode(e[2]); if (params[k] !== undefined) { if (!$.isArray(params[k])) { params[k] = [params[k]]; } params[k].push(v); } else { params[k] = v; } } } return params; }; /** `Ember.DiscourseLocation` implements the location API using the browser's `history.pushState` API. @class DiscourseLocation @namespace Discourse @extends Ember.Object */ Ember.DiscourseLocation = Ember.Object.extend({ init: function() { set(this, 'location', get(this, 'location') || window.location); this.initState(); }, /** @private Used to set state on first call to setURL @method initState */ initState: function() { var location = this.get('location'); if (location && location.search) { this.set('queryParams', $.parseParams(location.search)); } set(this, 'history', get(this, 'history') || window.history); this.replaceState(this.formatURL(this.getURL())); }, /** Will be pre-pended to path upon state change @property rootURL @default '/' */ rootURL: '/', /** @private Returns the current `location.pathname` without rootURL @method getURL */ getURL: function() { var rootURL = (Discourse.BaseUri === undefined ? "/" : Discourse.BaseUri), url = get(this, 'location').pathname; rootURL = rootURL.replace(/\/$/, ''); url = url.replace(rootURL, ''); return url; }, /** @private Uses `history.pushState` to update the url without a page reload. @method setURL @param path {String} */ setURL: function(path) { var state = this.getState(); path = this.formatURL(path); if (state && state.path !== path) { this.pushState(path); } }, /** @private Uses `history.replaceState` to update the url without a page reload or history modification. @method replaceURL @param path {String} */ replaceURL: function(path) { var state = this.getState(); path = this.formatURL(path); if (state && state.path !== path) { this.replaceState(path); } }, /** @private Get the current `history.state` Polyfill checks for native browser support and falls back to retrieving from a private _historyState variable @method getState */ getState: function() { return supportsHistoryState ? get(this, 'history').state : this._historyState; }, /** @private Pushes a new state @method pushState @param path {String} */ pushState: function(path) { var state = { path: path }; // store state if browser doesn't support `history.state` if (!supportsHistoryState) { this._historyState = state; } else { get(this, 'history').pushState(state, null, path); } // used for webkit workaround this._previousURL = this.getURL(); }, /** @private Replaces the current state @method replaceState @param path {String} */ replaceState: function(path) { var state = { path: path }; // store state if browser doesn't support `history.state` if (!supportsHistoryState) { this._historyState = state; } else { get(this, 'history').replaceState(state, null, path); } // used for webkit workaround this._previousURL = this.getURL(); }, queryParamsString: function() { var params = this.get('queryParams'); if (Em.isEmpty(params) || Em.isEmpty(Object.keys(params))) { return ""; } else { return "?" + decodeURIComponent($.param(params, true)); } }.property('queryParams'), // When our query params change, update the URL queryParamsStringChanged: function() { var loc = this; Em.run.next(function () { loc.replaceState(loc.formatURL(loc.getURL())); }); }.observes('queryParamsString'), /** @private Register a callback to be invoked whenever the browser history changes, including using forward and back buttons. @method onUpdateURL @param callback {Function} */ onUpdateURL: function(callback) { var guid = Ember.guidFor(this), self = this; Ember.$(window).on('popstate.ember-location-'+guid, function(e) { // Ignore initial page load popstate event in Chrome if (!popstateFired) { popstateFired = true; if (self.getURL() === self._previousURL) { return; } } callback(self.getURL()); }); }, /** @private Used when using `{{action}}` helper. The url is always appended to the rootURL. @method formatURL @param url {String} */ formatURL: function(url) { var rootURL = get(this, 'rootURL'); if (url !== '') { rootURL = rootURL.replace(/\/$/, ''); } return rootURL + url + this.get('queryParamsString'); }, willDestroy: function() { var guid = Ember.guidFor(this); Ember.$(window).off('popstate.ember-location-'+guid); } }); Ember.Location.registerImplementation('discourse_location', Ember.DiscourseLocation);
class Component { /** * Generic constructor for all components * @constructor * @param {Element} el * @param {Object} options */ constructor(classDef, el, options) { // Display error if el is valid HTML Element if (!(el instanceof Element)) { console.error(Error(el + ' is not an HTML Element')); } // If exists, destroy and reinitialize in child let ins = classDef.getInstance(el); if (!!ins) { ins.destroy(); } this.el = el; this.$el = cash(el); } /** * Initializes components * @param {class} classDef * @param {Element | NodeList | jQuery} els * @param {Object} options */ static init(classDef, els, options) { let instances = null; if (els instanceof Element) { instances = new classDef(els, options); } else if (!!els && (els.jquery || els.cash || els instanceof NodeList)) { let instancesArr = []; for (let i = 0; i < els.length; i++) { instancesArr.push(new classDef(els[i], options)); } instances = instancesArr; } return instances; } }
var searchData= [ ['_7emd_5fmax72xx',['~MD_MAX72XX',['../class_m_d___m_a_x72_x_x.html#afffa5b85187905f713477435187b3759',1,'MD_MAX72XX']]] ];
/* * #%L * ACS AEM Commons Package * %% * Copyright (C) 2014 Adobe * %% * 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. * #L% */ /*global angular: false, ace: false qrCode: false*/ angular.module('acs-commons-instant-package-app', ['acsCoral', 'ACS.Commons.notifications']).controller('MainCtrl', ['$scope', '$http', '$timeout', 'NotificationsService', function ($scope, $http, $timeout, NotificationsService) { $scope.app = { uri: '' }; $scope.form = { enabled: false }; $scope.init = function(appUri) { $scope.app.uri = appUri; $http({ method: 'GET', url: $scope.app.uri + '/config/enabled' }).success(function (data) { $scope.form.enabled = data; }).error(function (data, status) { // Response code 404 will be when configs are not available if (status !== 404) { NotificationsService.add('error', "Error", "Something went wrong while fetching previous configurations"); } }); }; $scope.saveConfig = function () { $http({ method: 'POST', url: $scope.app.uri + '/config', data: 'enabled=' + $scope.form.enabled || 'false', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }). success(function (data, status, headers, config) { if ($scope.form.enabled) { $http({ method: 'POST', url: $scope.app.uri, data: './clientlib-authoring/categories@TypeHint=String[]&./clientlib-authoring/categories=cq.wcm.sites&./clientlib-authoring/categories=dam.gui.admin.coral', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } else { $http({ method: 'POST', url: $scope.app.uri, data: './clientlib-authoring/categories@Delete', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } $scope.app.running = false; NotificationsService.add('success', "Success", "Your configuration has been saved"); NotificationsService.running($scope.app.running); }). error(function (data) { NotificationsService.add('error', 'ERROR', data.title + '. ' + data.message); $scope.app.running = false; NotificationsService.running($scope.app.running); }); }; }]);
class AppFooterCtrl { constructor(AppConstants) { 'ngInject'; this.appName = AppConstants.appName; // Get today's date to generate the year this.date = new Date(); } } let AppFooter = { controller: AppFooterCtrl, templateUrl: 'layout/footer.html' }; export default AppFooter;
export const EXAMPLE_REPOSITORIES = { clock: { repo: 'https://github.com/meteor/clock' }, leaderboard: { repo: 'https://github.com/meteor/leaderboard' }, localmarket: { repo: 'https://github.com/meteor/localmarket' }, 'simple-todos': { repo: 'https://github.com/meteor/simple-todos' }, 'simple-todos-react': { repo: 'https://github.com/meteor/simple-todos-react' }, 'simple-todos-angular': { repo: 'https://github.com/meteor/simple-todos-angular' }, todos: { repo: 'https://github.com/meteor/todos' }, 'todos-react': { 'repo': 'https://github.com/meteor/todos', 'branch': 'react', }, 'angular2-boilerplate': { repo: 'https://github.com/bsliran/angular2-meteor-base' } };
import EmptyObject from 'ember-data/-private/system/empty-object'; import parseResponseHeaders from 'ember-data/-private/utils/parse-response-headers'; import { module, test } from 'qunit'; const CRLF = '\u000d\u000a'; module('unit/adapters/parse-response-headers'); test('returns an EmptyObject when headersString is undefined', function(assert) { let headers = parseResponseHeaders(undefined); assert.deepEqual(headers, new EmptyObject(), 'EmptyObject is returned'); }); test('header parsing', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'content-type: application/json; charset=utf-8', 'date: Fri, 05 Feb 2016 21:47:56 GMT' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(headers['content-type'], 'application/json; charset=utf-8', 'parses header with complex value'); assert.equal(headers['date'], 'Fri, 05 Feb 2016 21:47:56 GMT', 'parses header with date value'); }); test('field-name parsing', function(assert) { let headersString = [ ' name-with-leading-whitespace: some value', 'name-with-whitespace-before-colon : another value' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['name-with-leading-whitespace'], 'some value', 'strips leading whitespace from field-name'); assert.equal(headers['name-with-whitespace-before-colon'], 'another value', 'strips whitespace before colon from field-name'); }); test('field-value parsing', function(assert) { let headersString = [ 'value-with-leading-space: value with leading whitespace', 'value-without-leading-space:value without leading whitespace', 'value-with-colon: value with: a colon', 'value-with-trailing-whitespace: banana ' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['value-with-leading-space'], 'value with leading whitespace', 'strips leading whitespace in field-value'); assert.equal(headers['value-without-leading-space'], 'value without leading whitespace', 'works without leaading whitespace in field-value'); assert.equal(headers['value-with-colon'], 'value with: a colon', 'has correct value when value contains a colon'); assert.equal(headers['value-with-trailing-whitespace'], 'banana', 'strips trailing whitespace from field-value'); }); test('ignores headers that do not contain a colon', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'I am ignored because I do not contain a colon' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.deepEqual(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(Object.keys(headers).length, 1, 'only has the one valid header'); });
/* * Copyright 2012 Amadeus s.a.s. * 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. */ var Aria = require("../Aria"); var ariaTouchEvent = require("./Event"); var ariaCoreBrowser = require("../core/Browser"); /** * Contains delegated handler for a tap event */ module.exports = Aria.classDefinition({ $singleton : true, $classpath : "aria.touch.ClickBuster", $statics : { RADIO : 25, DELAY : 500 }, $constructor : function () { this.isDesktop = ariaCoreBrowser.isDesktopView; this.lastEvt = null; }, $prototype : { registerTap : function (event) { this.lastEvt = { pos : { x : event.detail.currentX, y : event.detail.currentY }, date : new Date() }; }, preventGhostClick : function (event) { if (this._alreadyHandled(event)) { event.preventDefault(); event.stopPropagation(); return false; } return true; }, _alreadyHandled : function (e) { var position = ariaTouchEvent.getPositions(e)[0]; return (this.lastEvt && this._isShortDelay(this.lastEvt.date, new Date()) && this._isSameArea(this.lastEvt.pos, position)); }, _isSameArea : function (pos1, pos2) { return (Math.abs(pos1.x - pos2.x) < this.RADIO && Math.abs(pos1.y - pos2.y) < this.RADIO); }, _isShortDelay : function (date1, date2) { return (date2 - date1 <= this.DELAY); } } });
// Copyright (c) IPython Development Team. // Distributed under the terms of the Modified BSD License. define([ 'base/js/namespace', 'jqueryui', 'base/js/utils', ], function(IPython, $, utils) { "use strict"; var Pager = function (pager_selector, options) { /** * Constructor * * Parameters: * pager_selector: string * options: dictionary * Dictionary of keyword arguments. * events: $(Events) instance */ this.events = options.events; this.pager_element = $(pager_selector); this.pager_button_area = $('#pager-button-area'); this._default_end_space = 100; this.pager_element.resizable({handles: 'n', resize: $.proxy(this._resize, this)}); this.expanded = false; this.create_button_area(); this.bind_events(); }; Pager.prototype.create_button_area = function(){ var that = this; this.pager_button_area.append( $('<a>').attr('role', "button") .attr('title',"Open the pager in an external window") .addClass('ui-button') .click(function(){that.detach();}) .append( $('<span>').addClass("ui-icon ui-icon-extlink") ) ); this.pager_button_area.append( $('<a>').attr('role', "button") .attr('title',"Close the pager") .addClass('ui-button') .click(function(){that.collapse();}) .append( $('<span>').addClass("ui-icon ui-icon-close") ) ); }; Pager.prototype.bind_events = function () { var that = this; this.pager_element.bind('collapse_pager', function (event, extrap) { // Animate hiding of the pager. var time = (extrap && extrap.duration) ? extrap.duration : 'fast'; that.pager_element.animate({ height: 'toggle' }, { duration: time, done: function() { $('.end_space').css('height', that._default_end_space); } }); }); this.pager_element.bind('expand_pager', function (event, extrap) { // Clear the pager's height attr if it's set. This allows the // pager to size itself according to its contents. that.pager_element.height('initial'); // Animate the showing of the pager var time = (extrap && extrap.duration) ? extrap.duration : 'fast'; that.pager_element.show(time, function() { // Explicitly set pager height once the pager has shown itself. // This allows the pager-contents div to use percentage sizing. that.pager_element.height(that.pager_element.height()); that._resize(); }); }); this.events.on('open_with_text.Pager', function (event, payload) { // FIXME: support other mime types if (payload.data['text/plain'] && payload.data['text/plain'] !== "") { that.clear(); that.expand(); that.append_text(payload.data['text/plain']); } }); }; Pager.prototype.collapse = function (extrap) { if (this.expanded === true) { this.expanded = false; this.pager_element.trigger('collapse_pager', extrap); } }; Pager.prototype.expand = function (extrap) { if (this.expanded !== true) { this.expanded = true; this.pager_element.trigger('expand_pager', extrap); } }; Pager.prototype.toggle = function () { if (this.expanded === true) { this.collapse(); } else { this.expand(); } }; Pager.prototype.clear = function (text) { this.pager_element.find(".container").empty(); }; Pager.prototype.detach = function(){ var w = window.open("","_blank"); $(w.document.head) .append( $('<link>') .attr('rel',"stylesheet") .attr('href',"/static/css/notebook.css") .attr('type',"text/css") ) .append( $('<title>').text("Spark Notebook Pager") ); var pager_body = $(w.document.body); pager_body.css('overflow','scroll'); pager_body.append(this.pager_element.clone().children()); w.document.close(); this.collapse(); }; Pager.prototype.append_text = function (text) { /** * The only user content injected with this HTML call is escaped by * the fixConsole() method. */ this.pager_element.find(".container").append($('<pre/>').html(utils.fixCarriageReturn(utils.fixConsole(text)))); }; Pager.prototype._resize = function() { /** * Update document based on pager size. */ // Make sure the padding at the end of the notebook is large // enough that the user can scroll to the bottom of the // notebook. $('.end_space').css('height', Math.max(this.pager_element.height(), this._default_end_space)); }; // Backwards compatability. IPython.Pager = Pager; return {'Pager': Pager}; });
ms.dispatch = function(that) { var types = {}; that.on = function(type, handler) { var listeners = types[type] || (types[type] = []); for (var i = 0; i < listeners.length; i++) { if (listeners[i].handler == handler) return that; // already registered } listeners.push({handler: handler, on: true}); return that; }; that.off = function(type, handler) { var listeners = types[type]; if (listeners) for (var i = 0; i < listeners.length; i++) { var l = listeners[i]; if (l.handler == handler) { l.on = false; listeners.splice(i, 1); break; } } return that; }; return function(event) { var listeners = types[event.type]; if (!listeners) return; listeners = listeners.slice(); // defensive copy for (var i = 0; i < listeners.length; i++) { var l = listeners[i]; if (l.on) l.handler.call(that, event); } }; };
define('b',{}); define('c',{}); define('second',['b', 'c'], function (b, c) { console.log(b.name); console.log(c.name); });
var faker = new function () { function define(obj, name, desc) { } if (something) { define(this, 'base', {}); } define(a, b, c); function other () { define(this, '__proto__', {}); } };
var express = require('../') , request = require('supertest'); describe('app', function(){ describe('.response', function(){ it('should extend the response prototype', function(done){ var app = express(); app.response.shout = function(str){ this.send(str.toUpperCase()); }; app.use(function(req, res){ res.shout('hey'); }); request(app) .get('/') .expect('HEY', done); }) it('should not be influenced by other app protos', function(done){ var app = express() , app2 = express(); app.response.shout = function(str){ this.send(str.toUpperCase()); }; app2.response.shout = function(str){ this.send(str); }; app.use(function(req, res){ res.shout('hey'); }); request(app) .get('/') .expect('HEY', done); }) }) })
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tornado:inner", function() { var keywords = ["and","as","assert","autoescape","block","break","class","comment","context", "continue","datetime","def","del","elif","else","end","escape","except", "exec","extends","false","finally","for","from","global","if","import","in", "include","is","json_encode","lambda","length","linkify","load","module", "none","not","or","pass","print","put","raise","raw","return","self","set", "squeeze","super","true","try","url_escape","while","with","without","xhtml_escape","yield"]; keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); function tokenBase (stream, state) { stream.eatWhile(/[^\{]/); var ch = stream.next(); if (ch == "{") { if (ch = stream.eat(/\{|%|#/)) { state.tokenize = inTag(ch); return "tag"; } } } function inTag (close) { if (close == "{") { close = "}"; } return function (stream, state) { var ch = stream.next(); if ((ch == close) && stream.eat("}")) { state.tokenize = tokenBase; return "tag"; } if (stream.match(keywords)) { return "keyword"; } return close == "#" ? "comment" : "string"; }; } return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { return state.tokenize(stream, state); } }; }); CodeMirror.defineMode("tornado", function(config) { var htmlBase = CodeMirror.getMode(config, "text/html"); var tornadoInner = CodeMirror.getMode(config, "tornado:inner"); return CodeMirror.overlayMode(htmlBase, tornadoInner); }); CodeMirror.defineMIME("text/x-tornado", "tornado"); });
ace.define("ace/theme/kuroir",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { exports.isDark = false; exports.cssClass = "ace-kuroir"; exports.cssText = "\ .ace-kuroir .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ .ace-kuroir .ace_print-margin {\ width: 1px;\ background: #e8e8e8;\ }\ .ace-kuroir {\ background-color: #E8E9E8;\ color: #363636;\ }\ .ace-kuroir .ace_cursor {\ color: #202020;\ }\ .ace-kuroir .ace_marker-layer .ace_selection {\ background: rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir.ace_multiselect .ace_selection.ace_start {\ box-shadow: 0 0 3px 0px #E8E9E8;\ border-radius: 2px;\ }\ .ace-kuroir .ace_marker-layer .ace_step {\ background: rgb(198, 219, 174);\ }\ .ace-kuroir .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(0, 0, 0, 0.29);\ }\ .ace-kuroir .ace_marker-layer .ace_active-line {\ background: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_gutter-active-line {\ background-color: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_marker-layer .ace_selected-word {\ border: 1px solid rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir .ace_invisible {\ color: #BFBFBF\ }\ .ace-kuroir .ace_fold {\ border-color: #363636;\ }\ .ace-kuroir .ace_constant{color:#CD6839;}.ace-kuroir .ace_constant.ace_numeric{color:#9A5925;}.ace-kuroir .ace_support{color:#104E8B;}.ace-kuroir .ace_support.ace_function{color:#005273;}.ace-kuroir .ace_support.ace_constant{color:#CF6A4C;}.ace-kuroir .ace_storage{color:#A52A2A;}.ace-kuroir .ace_invalid.ace_illegal{color:#FD1224;\ background-color:rgba(255, 6, 0, 0.15);}.ace-kuroir .ace_invalid.ace_deprecated{text-decoration:underline;\ font-style:italic;\ color:#FD1732;\ background-color:#E8E9E8;}.ace-kuroir .ace_string{color:#639300;}.ace-kuroir .ace_string.ace_regexp{color:#417E00;\ background-color:#C9D4BE;}.ace-kuroir .ace_comment{color:rgba(148, 148, 148, 0.91);\ background-color:rgba(220, 220, 220, 0.56);}.ace-kuroir .ace_variable{color:#009ACD;}.ace-kuroir .ace_meta.ace_tag{color:#005273;}.ace-kuroir .ace_markup.ace_heading{color:#B8012D;\ background-color:rgba(191, 97, 51, 0.051);}.ace-kuroir .ace_markup.ace_list{color:#8F5B26;}\ "; var dom = acequire("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('blog.services', []). value('version', '0.1');
var AppDispatcher = require('../dispatcher/app-dispatcher'), EventEmitter = require('events').EventEmitter, JPSConstants = require('../constants/jetpack-onboarding-constants'); var CHANGE_EVENT = 'change'; var spinnerEnabled = false, spinnerMessage = null; function show(message) { spinnerEnabled = true; spinnerMessage = message; } function hide() { spinnerEnabled = false; spinnerMessage = null; } var SpinnerStore = _.extend({}, EventEmitter.prototype, { showing: function() { return spinnerEnabled; }, getMessage: function() { return spinnerMessage; }, addChangeListener: function(callback) { this.on( CHANGE_EVENT, callback ); }, removeChangeListener: function(callback) { this.removeListener( CHANGE_EVENT, callback ); }, emitChange: function() { this.emit( CHANGE_EVENT ); }, }); AppDispatcher.register(function(action) { switch(action.actionType) { case JPSConstants.SHOW_SPINNER: show(action.message); SpinnerStore.emitChange(); break; case JPSConstants.HIDE_SPINNER: hide(); SpinnerStore.emitChange(); break; default: // no op } }); module.exports = SpinnerStore;
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'newpage', 'el', { toolbar: 'Νέα Σελίδα' } );
//// [parser509698.ts] /// <style requireSemi="on" /> /// <reference no-default-lib="true"/> declare function foo(): void; declare function bar(): void; //// [parser509698.js]
(function() { define(function() { var AccessibleViewItemView, AccessibleViewsView; AccessibleViewItemView = Backbone.View.extend({ tagName: 'div', events: { "click": "clicked", "mouseover": "mousedover", "mouseout": "mousedout" }, render: function() { this.$el.empty().append("<a href=\"#\" title=\"" + (this.model.getShelleySelector()) + "\">\n <span class=\"viewClass\">" + (this.model.get('class')) + "</span>\n with label\n \"<span class=\"viewLabel\">" + (this.model.get('accessibilityLabel')) + "</span>\"\n</a>"); return this; }, mousedover: function() { return this.model.setActive(); }, mousedout: function() { return this.model.unsetActive(); }, clicked: function() { return this.model.trigger('accessible-selected', this.model); } }); AccessibleViewsView = Backbone.View.extend({ el: $('#accessible-views'), initialize: function() { this.collection = new Backbone.Collection; return this.collection.on('reset', _.bind(this.render, this)); }, render: function() { var _this = this; this.$el.empty(); this.collection.each(function(viewModel) { return _this.$el.append(new AccessibleViewItemView({ model: viewModel }).render().el); }); return this; } }); return AccessibleViewsView; }); }).call(this);
/* * Copyright 2012 Amadeus s.a.s. * 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. */ var Aria = require("../../Aria"); var ariaUtilsData = require("../../utils/Data"); var ariaUtilsDom = require("../../utils/Dom"); /** * Template script for the default ErrorListTemplate */ module.exports = Aria.tplScriptDefinition({ $classpath : "aria.widgets.errorlist.ErrorListTemplateScript", $statics : { /** * Links each type of message with an icon. The order in the array is important as the first entry for which * messages of that type exist in the messages list is used. Since it depends on aria.utils.Data wait for it to * be loaded by the dependency manager * @type Array */ ICONS : [], /** * Icon used if there is no matching icon in ICONS. * @type String */ DEFAULT_ICON : "std:missing" }, $prototype : { /** * Initialize this class building the icons object. It's done here so we are sure that aria.utils.Data is * already loaded * @param {aria.widgets.errorlist.ErrorListTemplateScript} proto Class prototype */ $init : function (proto) { // Using push instead of resetting the reference because items are not copied from proto but from the // parameter of tplScriptDefinition directly proto.ICONS.push({ type : ariaUtilsData.TYPE_ERROR, icon : "std:error" }, { type : ariaUtilsData.TYPE_WARNING, icon : "std:warning" }, { type : ariaUtilsData.TYPE_INFO, icon : "std:info" }, { type : ariaUtilsData.TYPE_FATAL, icon : "std:error" }, { type : ariaUtilsData.TYPE_NOTYPE, icon : "std:info" }, { type : ariaUtilsData.TYPE_CRITICAL_WARNING, icon : "std:warning" }, { type : ariaUtilsData.TYPE_CONFIRMATION, icon : "std:confirm" }); }, /** * React to module events * @param {Event} evt */ onModuleEvent : function (evt) { if (evt.name == "messagesChanged") { if (evt.domRef) { ariaUtilsDom.scrollIntoView(evt.domRef); } this.$refresh(); } }, /** * Click on an error message * @param {Event} evt Not used * @param {Object} msg Error message */ clickOnMessage : function (evt, msg) { this.moduleCtrl.focusField(msg); }, /** * Get the icon name for the current message type * @return {String} Icon name */ getIcon : function () { var messageTypes = this.data.messageTypes; var res = this.DEFAULT_ICON; var icons = this.ICONS; for (var i = 0, l = icons.length; i < l; i++) { var curIcon = icons[i]; if (messageTypes[curIcon.type] > 0) { res = curIcon.icon; break; } } return res; }, /** * Get the message to be displayed as label of the error list item * @param {Object} msg Error message * @return {String} localized message */ getDisplayMessage : function (msg) { if (this.data.displayCodes && (msg.code || msg.code === 0)) { return msg.localizedMessage + " (" + msg.code + ")"; } return msg.localizedMessage; } } });
define( ({ _widgetLabel: "موقعي", title: "العثور على الموقع الخاص بي", browserError: "الموقع الجغرافي غير مدعوم من قبل هذا المستعرض.", failureFinding: "يتعذر إيجاد الموقع. يجرى التحقق من المتصفح للتأكد من أن الموقع قد تم مشاركته." }) );
/** @module ember @submodule ember-htmlbars */ import isEnabled from 'ember-metal/features'; import { keyword } from 'htmlbars-runtime/hooks'; import closureAction from 'ember-routing-htmlbars/keywords/closure-action'; /** The `{{action}}` helper provides a useful shortcut for registering an HTML element within a template for a single DOM event and forwarding that interaction to the template's controller or specified `target` option. If the controller does not implement the specified action, the event is sent to the current route, and it bubbles up the route hierarchy from there. For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html) ### Use Given the following application Handlebars template on the page ```handlebars <div {{action 'anActionName'}}> click me </div> ``` And application code ```javascript App.ApplicationController = Ember.Controller.extend({ actions: { anActionName: function() { } } }); ``` Will result in the following rendered HTML ```html <div class="ember-view"> <div data-ember-action="1"> click me </div> </div> ``` Clicking "click me" will trigger the `anActionName` action of the `App.ApplicationController`. In this case, no additional parameters will be passed. If you provide additional parameters to the helper: ```handlebars <button {{action 'edit' post}}>Edit</button> ``` Those parameters will be passed along as arguments to the JavaScript function implementing the action. ### Event Propagation Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. If you need to allow event propagation (to handle file inputs for example) you can supply the `preventDefault=false` option to the `{{action}}` helper: ```handlebars <div {{action "sayHello" preventDefault=false}}> <input type="file" /> <input type="checkbox" /> </div> ``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html) 'Responding to Browser Events' for more information. ### Specifying DOM event type By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <div {{action "anActionName" on="doubleClick"}}> click me </div> ``` See `Ember.View` 'Responding to Browser Events' for a list of acceptable DOM event names. ### Specifying whitelisted modifier keys By default the `{{action}}` helper will ignore click event with pressed modifier keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. ```handlebars <div {{action "anActionName" allowedKeys="alt"}}> click me </div> ``` This way the `{{action}}` will fire when clicking with the alt key pressed down. Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. ```handlebars <div {{action "anActionName" allowedKeys="any"}}> click me with any key pressed </div> ``` ### Specifying a Target There are several possible target objects for `{{action}}` helpers: In a typical Ember application, where templates are managed through use of the `{{outlet}}` helper, actions will bubble to the current controller, then to the current route, and then up the route hierarchy. Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path to an object, accessible in the current context: ```handlebars {{! the application template }} <div {{action "anActionName" target=view}}> click me </div> ``` ```javascript App.ApplicationView = Ember.View.extend({ actions: { anActionName: function() {} } }); ``` ### Additional Parameters You may specify additional parameters to the `{{action}}` helper. These parameters are passed along as the arguments to the JavaScript function implementing the action. ```handlebars {{#each people as |person|}} <div {{action "edit" person}}> click me </div> {{/each}} ``` Clicking "click me" will trigger the `edit` method on the current controller with the value of `person` as a parameter. @method action @for Ember.Handlebars.helpers @public */ export default function(morph, env, scope, params, hash, template, inverse, visitor) { if (isEnabled('ember-routing-htmlbars-improved-actions')) { if (morph) { keyword('@element_action', morph, env, scope, params, hash, template, inverse, visitor); return true; } return closureAction(morph, env, scope, params, hash, template, inverse, visitor); } else { keyword('@element_action', morph, env, scope, params, hash, template, inverse, visitor); return true; } }
/* * WYMeditor : what you see is What You Mean web-based editor * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/ * Dual licensed under the MIT (MIT-license.txt) * and GPL (GPL-license.txt) licenses. * * For further information visit: * http://www.wymeditor.org/ * * File Name: * jquery.wymeditor.fullscreen.js * Fullscreen plugin for WYMeditor * * File Authors: * Luis Santos (luis.santos a-t openquest dotpt) * Jonatan Lundin (jonatan.lundin a-t gmail dotcom) * Gerd Riesselmann (gerd a-t gyro-php dot org) : Fixed issue with new skin layout * Philipp Cordes (pc a-t irgendware dotnet) */ //Extend WYMeditor WYMeditor.editor.prototype.fullscreen = function() { var wym = this, $box = jQuery(this._box), $iframe = jQuery(this._iframe), $overlay = null, $window = jQuery(window), editorMargin = 15; // Margin from window (without padding) //construct the button's html var html = '' + "<li class='wym_tools_fullscreen'>" + "<a name='Fullscreen' href='#' " + "title='Fullscreen' " + "style='background-image: url(" + wym._options.basePath + "plugins/fullscreen/icon_fullscreen.gif)'>" + "Fullscreen" + "</a>" + "</li>"; //add the button to the tools box $box.find(wym._options.toolsSelector + wym._options.toolsListSelector) .append(html); function resize () { // Calculate margins var uiHeight = $box.outerHeight(true) - $iframe.outerHeight(true); var editorPadding = $box.outerWidth() - $box.width(); // Calculate heights var screenHeight = $window.height(); var iframeHeight = (screenHeight - uiHeight - (editorMargin * 2)) + 'px'; // Calculate witdths var screenWidth = $window.width(); var boxWidth = (screenWidth - editorPadding - (editorMargin * 2)) + 'px'; $box.css('width', boxWidth); $iframe.css('height', iframeHeight); $overlay.css({ 'height': screenHeight + 'px', 'width': screenWidth + 'px' }); } //handle click event $box.find('li.wym_tools_fullscreen a').click(function() { if ($box.css('position') != 'fixed') { // Store previous inline styles $box.data('wym-inline-css', $box.attr('style')); $iframe.data('wym-inline-css', $iframe.attr('style')); // Create overlay $overlay = jQuery('<div id="wym-fullscreen-overlay"></div>') .appendTo('body').css({ 'position': 'fixed', 'background-color': 'rgb(0, 0, 0)', 'opacity': '0.75', 'z-index': '98', 'top': '0px', 'left': '0px' }); // Possition the editor $box.css({ 'position': 'fixed', 'z-index': '99', 'top': editorMargin + 'px', 'left': editorMargin + 'px' }); // Bind event listeners $window.bind('resize', resize); $box.find('li.wym_tools_html a').bind('click', resize); // Force resize resize(); } else { // Unbind event listeners $window.unbind('resize', resize); $box.find('li.wym_tools_html a').unbind('click', resize); // Remove inline styles $box.css({ 'position': 'static', 'z-index': '', 'width': '', 'top': '', 'left': '' }); $iframe.css('height', ''); // Remove overlay $overlay.remove(); $overlay = null; // Retore previous inline styles $box.attr('style', $box.data('wym-inline-css')); $iframe.attr('style', $iframe.data('wym-inline-css')); } return false; }); };
define("ace/snippets/plain_text",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "plain_text"; }); (function() { window.require(["ace/snippets/plain_text"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
define(["dojo/_base/declare", "dojox/app/ViewBase", "dijit/form/Button"], function(declare, ViewBase, Button){ return declare([Button, ViewBase], { postscript: function(){ // we want to avoid kickin the Dijit lifecycle at ctor time so that definition has been mixed into the // widget when it is instanciated. This is only really needed if you need the definition }, _startup: function(){ this.create(); this.inherited(arguments); } }); } );
/* ** Ext.ux.upload.LogPanel.js for Ext.ux.upload ** ** Made by Gary van Woerkens ** Contact <gary@chewam.com> ** ** Started on Fri Jun 4 19:01:47 2010 Gary van Woerkens ** Last update Mon Jun 21 13:48:39 2010 Gary van Woerkens */ Ext.ns('Ext.ux.upload'); /** * @class Ext.ux.upload.LogPanel * @extends Ext.Panel * * @author Gary van Woerkens * @version 1.0 */ Ext.ux.upload.LogPanel = Ext.extend(Ext.Panel, { autoScroll:true ,cls:"x-upload-logpanel-toolbar" /** * @cfg {Ext.Template} progressTpl * The {@link Ext.Template template} used to display file {@link Ext.ProgressBar progress} messages. */ ,progressTpl:new Ext.Template( '<div ext:qtip="{msg}" class="x-progress-text-{type}">{text}</div>' ) /** * @cfg {String} lang * The language to display log panel messages (default to "en"). */ ,lang:"en" /** * @cfg {Object} langs * Available languages to load on init with {@link Ext.ux.upload.LogPanel#lang lang}. * <code><pre> ,langs:{ en:{ emptyListButtonTooltip:"Empty list" ,progressStatus:"Loading..." ,uploadComplete:"Upload complete" ,uploadingStatus:'Uploading {[count > 1 ? "files" : "file"]}' } ,fr:{ emptyListButtonTooltip:"vider la liste des téléchargements" ,progressStatus:"Chargement..." ,uploadComplete:"Envoi terminé " ,uploadingStatus:'Envoi {[count > 1 ? "des fichiers" : "du fichier"]}' } } * </code></pre> */ ,langs:{ en:{ emptyListButtonTooltip:"Empty list" ,progressStatus:"Loading..." ,uploadComplete:"Upload complete" ,uploadingStatus:'Uploading {[values.count > 1 ? "files" : "file"]}' } ,fr:{ emptyListButtonTooltip:"Vider la liste des téléchargements" ,progressStatus:"Chargement..." ,uploadComplete:"Envoi terminé " ,uploadingStatus:'Envoi {[values.count > 1 ? "des fichiers" : "du fichier"]}' } } /** * Array of Files in queue. * @type {Array} * @property queue */ ,initComponent:function() { this.queue = []; this.bodyStyle = "border:1px solid #99BBE8;background-color:#FFFFFF"; this.lang = this.langs[this.lang] || this.langs["en"]; this.uploadingStatus = new Ext.XTemplate(this.lang.uploadingStatus); this.bbar = new Ext.ux.StatusBar({ height:27 // ,style:"border:1px solid #99BBE8;" ,items:[{ iconCls:"icon-eraser" ,tooltip:this.lang.emptyListButtonTooltip ,scope:this ,handler:this.cleanLogPanel }] }); Ext.ux.upload.LogPanel.superclass.initComponent.call(this); this.on({added:this.bindContainer}); } /** * */ ,bindContainer:function(logpanel, ctn, index) { Ext.apply(ctn, { addProgress:this.addProgress.createDelegate(this) ,updateProgress:this.updateProgress.createDelegate(this) ,setStatus:this.setStatus.createDelegate(this) }); } /** * Removes all {@link Ext.ProgressBar progress} bars. */ ,cleanLogPanel:function() { this.removeAll(); } /** * Returns the {@link Ext.ux.StatusBar} where logs are displayed. * @return {Ext.ux.StatusBar} */ ,getStatusBar:function() { return this.getBottomToolbar(); } /** * Adds a {@link Ext.ProgressBar} to log panel. * @param {Object} file */ ,addProgress:function(file) { if (this.getProgress(file.id) === false) { var p = new Ext.ProgressBar({ text:this.progressTpl.apply({type:"loading", text:file.name}) ,isUploading:true ,style:"border-width:0 0 1px 0" // ,height:30 }); this.insert(0, p); this.doLayout(); this.queue.push({ id:file.id ,p:p }); } } /** * Updates a {@link Ext.ProgressBar progress} bar already added to log panel. * @param {Object} config The progress config */ ,updateProgress:function(config) { var toolbar = this.getStatusBar(), p = this.getProgress(config.file.id); p.updateProgress(config.progress, this.progressTpl.apply({ type:config.type ,text:config.file.name ,msg:config.msg })); if (config.type === "loading") { count = this.queue.length - this.getUploadingCount() + 1, msg = this.uploadingStatus.apply({count:this.queue.length}); } else if (config.type === "success" || config.type === "error") { config.type = "info"; p.isUploading = false; var count = this.queue.length - this.getUploadingCount(), msg = this.lang.uploadComplete; } this.setStatus(config.type, msg+" ("+count + "/" + this.queue.length+")"); } /** * Set global upload status. * Logs are displayed in the {@link Ext.ux.StatusBar bottom toolbar}. * @param {String} type Type of log can be "loading", "success" or "error" * @param {String} msg Message to log. */ ,setStatus:function(type, msg) { this.getStatusBar().setStatus({ text:msg ,iconCls:"x-status-"+type }); } /** * Returns the count of files in the {@link Ext.ux.upload.LogPanel#queue queue} * which are not uploaded yet. * @return {Number} */ ,getUploadingCount:function() { var count = 0; Ext.each(this.queue, function(item) { if (item.p.isUploading) count++; }); return count; } /** * Returns the {@link Ext.ProgressBar progress} bar from id. * @param {String} id The progress id */ ,getProgress:function(id) { var index = Ext.each(this.queue, function(item, index) { return !(item.id === id); }); return Ext.isDefined(index) ? this.queue[index].p : false; } }); Ext.reg('uploadlogspanel', Ext.ux.upload.LogPanel);
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import { forkJoin } from 'rxjs/observable/forkJoin'; import { fromPromise } from 'rxjs/observable/fromPromise'; export function resolve(resolver, state) { return resolveNode(resolver, state._root).map(_ => state); } function resolveNode(resolver, node) { if (node.children.length === 0) { return fromPromise(resolveComponent(resolver, node.value).then(factory => { node.value._resolvedComponentFactory = factory; return node.value; })); } else { const c = node.children.map(c => resolveNode(resolver, c).toPromise()); return forkJoin(c).map(_ => resolveComponent(resolver, node.value).then(factory => { node.value._resolvedComponentFactory = factory; return node.value; })); } } function resolveComponent(resolver, snapshot) { if (snapshot.component && snapshot._routeConfig && typeof snapshot.component === 'string') { return resolver.resolveComponent(snapshot.component); } else { return Promise.resolve(null); } } //# sourceMappingURL=resolve.js.map
/* @flow */ // These util functions are split into its own file because Rollup cannot drop // makeMap() due to potential side effects, so these variables end up // bloating the web builds. import { makeMap, noop } from 'shared/util' export const isReservedTag = makeMap( 'template,script,style,element,content,slot,link,meta,svg,view,' + 'a,div,img,image,text,span,input,switch,textarea,spinner,select,' + 'slider,slider-neighbor,indicator,canvas,' + 'list,cell,header,loading,loading-indicator,refresh,scrollable,scroller,' + 'video,web,embed,tabbar,tabheader,datepicker,timepicker,marquee,countdown', true ) // Elements that you can, intentionally, leave open (and which close themselves) // more flexible than web export const canBeLeftOpenTag = makeMap( 'web,spinner,switch,video,textarea,canvas,' + 'indicator,marquee,countdown', true ) export const isRuntimeComponent = makeMap( 'richtext,transition,transition-group', true ) export const isUnaryTag = makeMap( 'embed,img,image,input,link,meta', true ) export function mustUseProp (): boolean { return false } export function getTagNamespace (): void { } export function isUnknownElement (): boolean { return false } export function query (el: string | Element, document: Object) { // document is injected by weex factory wrapper const placeholder = document.createComment('root') placeholder.hasAttribute = placeholder.removeAttribute = noop // hack for patch document.documentElement.appendChild(placeholder) return placeholder }
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ ( function() { CKEDITOR.plugins.add( 'templates', { requires: 'dialog', // jscs:disable maximumLineLength lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% // jscs:enable maximumLineLength icons: 'templates,templates-rtl', // %REMOVE_LINE_CORE% hidpi: true, // %REMOVE_LINE_CORE% init: function( editor ) { CKEDITOR.dialog.add( 'templates', CKEDITOR.getUrl( this.path + 'dialogs/templates.js' ) ); editor.addCommand( 'templates', new CKEDITOR.dialogCommand( 'templates' ) ); editor.ui.addButton && editor.ui.addButton( 'Templates', { label: editor.lang.templates.button, command: 'templates', toolbar: 'doctools,10' } ); } } ); var templates = {}, loadedTemplatesFiles = {}; CKEDITOR.addTemplates = function( name, definition ) { templates[ name ] = definition; }; CKEDITOR.getTemplates = function( name ) { return templates[ name ]; }; CKEDITOR.loadTemplates = function( templateFiles, callback ) { // Holds the templates files to be loaded. var toLoad = []; // Look for pending template files to get loaded. for ( var i = 0, count = templateFiles.length; i < count; i++ ) { if ( !loadedTemplatesFiles[ templateFiles[ i ] ] ) { toLoad.push( templateFiles[ i ] ); loadedTemplatesFiles[ templateFiles[ i ] ] = 1; } } if ( toLoad.length ) CKEDITOR.scriptLoader.load( toLoad, callback ); else setTimeout( callback, 0 ); }; } )(); /** * The templates definition set to use. It accepts a list of names separated by * comma. It must match definitions loaded with the {@link #templates_files} setting. * * config.templates = 'my_templates'; * * @cfg {String} [templates='default'] * @member CKEDITOR.config */ /** * The list of templates definition files to load. * * config.templates_files = [ * '/editor_templates/site_default.js', * 'http://www.example.com/user_templates.js * ]; * * @cfg * @member CKEDITOR.config */ CKEDITOR.config.templates_files = [ CKEDITOR.getUrl( 'plugins/templates/templates/default.js' ) ]; /** * Whether the "Replace actual contents" checkbox is checked by default in the * Templates dialog. * * config.templates_replaceContent = false; * * @cfg * @member CKEDITOR.config */ CKEDITOR.config.templates_replaceContent = true;
(function () { var nonbreaking = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var stringRepeat = function (string, repeats) { var str = ''; for (var index = 0; index < repeats; index++) { str += string; } return str; }; var isVisualCharsEnabled = function (editor) { return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false; }; var insertNbsp = function (editor, times) { var nbsp = isVisualCharsEnabled(editor) ? '<span class="mce-nbsp">&nbsp;</span>' : '&nbsp;'; editor.insertContent(stringRepeat(nbsp, times)); editor.dom.setAttrib(editor.dom.select('span.mce-nbsp'), 'data-mce-bogus', '1'); }; var $_cwy81eh0jfuw8pru = { insertNbsp: insertNbsp }; var register = function (editor) { editor.addCommand('mceNonBreaking', function () { $_cwy81eh0jfuw8pru.insertNbsp(editor, 1); }); }; var $_buxrv5gzjfuw8prt = { register: register }; var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK'); var getKeyboardSpaces = function (editor) { var spaces = editor.getParam('nonbreaking_force_tab', 0); if (typeof spaces === 'boolean') { return spaces === true ? 3 : 0; } else { return spaces; } }; var $_f5rvddh3jfuw8prx = { getKeyboardSpaces: getKeyboardSpaces }; var setup = function (editor) { var spaces = $_f5rvddh3jfuw8prx.getKeyboardSpaces(editor); if (spaces > 0) { editor.on('keydown', function (e) { if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) { if (e.shiftKey) { return; } e.preventDefault(); e.stopImmediatePropagation(); $_cwy81eh0jfuw8pru.insertNbsp(editor, spaces); } }); } }; var $_6lsd92h1jfuw8prv = { setup: setup }; var register$1 = function (editor) { editor.addButton('nonbreaking', { title: 'Nonbreaking space', cmd: 'mceNonBreaking' }); editor.addMenuItem('nonbreaking', { icon: 'nonbreaking', text: 'Nonbreaking space', cmd: 'mceNonBreaking', context: 'insert' }); }; var $_9wbdylh4jfuw8pry = { register: register$1 }; global.add('nonbreaking', function (editor) { $_buxrv5gzjfuw8prt.register(editor); $_9wbdylh4jfuw8pry.register(editor); $_6lsd92h1jfuw8prv.setup(editor); }); function Plugin () { } return Plugin; }()); })();
function main() { // Get the store reference var store = url.templateArgs.store_type + "://" + url.templateArgs.store_id; // Get the details of the tag if (json.has("name") == false || json.get("name").length == 0) { status.setCode(status.STATUS_BAD_REQUEST, "Name missing when creating tag"); return; } var tagName = json.get("name"); // See if the tag already exists var tag = taggingService.getTag(store, tagName), tagExists = (tag != null); if (!tagExists) { tag = taggingService.createTag(store, tagName); if (tag == null) { status.setCode(status.STATUS_INTERNAL_SERVER_ERROR, "error.cannotCreateTag"); return; } } // Put the created tag into the model model.tag = tag; model.tagExists = tagExists; } main();
import { Platform, Dimensions } from "react-native"; import variable from "./../variables/platform"; const deviceHeight = Dimensions.get("window").height; export default (variables = variable) => { const theme = { flex: 1, height: Platform.OS === "ios" ? deviceHeight : deviceHeight - 20 }; return theme; };
var reporter_1 = require('./reporter'); function isTS14(typescript) { return !('findConfigFile' in typescript); } exports.isTS14 = isTS14; function getFileName(thing) { if (thing.filename) return thing.filename; // TS 1.4 return thing.fileName; // TS 1.5 } exports.getFileName = getFileName; function getDiagnosticsAndEmit(program) { var result = reporter_1.emptyCompilationResult(); if (program.getDiagnostics) { var errors = program.getDiagnostics(); result.syntaxErrors = errors.length; if (!errors.length) { // If there are no syntax errors, check types var checker = program.getTypeChecker(true); var semanticErrors = checker.getDiagnostics(); var emitErrors = checker.emitFiles().diagnostics; errors = semanticErrors.concat(emitErrors); result.semanticErrors = errors.length; } else { result.emitSkipped = true; } return [errors, result]; } else { var errors = program.getSyntacticDiagnostics(); result.syntaxErrors = errors.length; if (errors.length === 0) { errors = program.getGlobalDiagnostics(); // Remove error: "File '...' is not under 'rootDir' '...'. 'rootDir' is expected to contain all source files." // This is handled by ICompiler#correctSourceMap, so this error can be muted. errors = errors.filter(function (item) { return item.code !== 6059; }); result.globalErrors = errors.length; } if (errors.length === 0) { errors = program.getSemanticDiagnostics(); result.semanticErrors = errors.length; } var emitOutput = program.emit(); result.emitErrors = emitOutput.diagnostics.length; result.emitSkipped = emitOutput.emitSkipped; return [errors.concat(emitOutput.diagnostics), result]; } } exports.getDiagnosticsAndEmit = getDiagnosticsAndEmit; function getLineAndCharacterOfPosition(typescript, file, position) { if (file.getLineAndCharacterOfPosition) { var lineAndCharacter = file.getLineAndCharacterOfPosition(position); return { line: lineAndCharacter.line + 1, character: lineAndCharacter.character + 1 }; } else { return file.getLineAndCharacterFromPosition(position); } } exports.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; function createSourceFile(typescript, fileName, content, target, version) { if (version === void 0) { version = '0'; } if (typescript.findConfigFile) { return typescript.createSourceFile(fileName, content, target, true); } else { return typescript.createSourceFile(fileName, content, target, version); } } exports.createSourceFile = createSourceFile; function flattenDiagnosticMessageText(typescript, messageText) { if (typeof messageText === 'string') { return messageText; } else { return typescript.flattenDiagnosticMessageText(messageText, "\n"); } } exports.flattenDiagnosticMessageText = flattenDiagnosticMessageText; function transpile(typescript, input, compilerOptions, fileName, diagnostics) { if (!typescript.transpile) { throw new Error('gulp-typescript: Single file compilation is not supported using TypeScript 1.4'); } return typescript.transpile(input, compilerOptions, fileName, diagnostics); } exports.transpile = transpile;
/** * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * `PlatformLocation` encapsulates all calls to DOM apis, which allows the Router to be platform * agnostic. * This means that we can have different implementation of `PlatformLocation` for the different * platforms * that angular supports. For example, the default `PlatformLocation` is {@link * BrowserPlatformLocation}, * however when you run your app in a WebWorker you use {@link WebWorkerPlatformLocation}. * * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy} * when * they need to interact with the DOM apis like pushState, popState, etc... * * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly * by * the {@link Router} in order to navigate between routes. Since all interactions between {@link * Router} / * {@link Location} / {@link LocationStrategy} and DOM apis flow through the `PlatformLocation` * class * they are all platform independent. */ export class PlatformLocation { /* abstract */ get pathname() { return null; } /* abstract */ get search() { return null; } /* abstract */ get hash() { return null; } }
!function ($) { $(function(){ map = new GMaps({ div: '#gmap_geocoding', lat: 40.0000, lng: -100.0000, zoom: 4 }); map.addMarker({ lat: 40.0000, lng: -100.0000, title: 'Marker', infoWindow: { content: 'Info content here...' } }); $('#geocoding_form').submit(function(e){ e.preventDefault(); GMaps.geocode({ address: $('#address').val().trim(), callback: function(results, status){ if(status=='OK'){ var latlng = results[0].geometry.location; map.setCenter(latlng.lat(), latlng.lng()); map.addMarker({ lat: latlng.lat(), lng: latlng.lng() }); } } }); }); }); }(window.jQuery);
odoo.define('iap.CrashManager', function (require) { "use strict"; var ajax = require('web.ajax'); var core = require('web.core'); var CrashManager = require('web.CrashManager'); var Dialog = require('web.Dialog'); var _t = core._t; var QWeb = core.qweb; CrashManager.include({ /** * @override */ rpc_error: function (error) { if (error.data.name === "odoo.addons.iap.models.iap.InsufficientCreditError") { var error_data = JSON.parse(error.data.message); ajax.jsonRpc('/web/dataset/call_kw', 'call', { model: 'iap.account', method: 'get_credits_url', args: [], kwargs: { base_url: error_data.base_url, service_name: error_data.service_name, credit: error_data.credit, } }).then(function (url) { var content = $(QWeb.render('iap.redirect_to_odoo_credit', { data: error_data, })) if (error_data.body) { content.css('padding', 0); } new Dialog(this, { size: 'large', title: error_data.title || _t("Insufficient Balance"), $content: content, buttons: [ {text: _t('Buy credits at Odoo'), classes : "btn-primary", click: function() { window.open(url, '_blank'); }, close:true}, {text: _t("Cancel"), close: true} ], }).open(); }); } else { this._super.apply(this, arguments); } }, }); });
// // Test robustness about JS injection in different place // // This assume malicious document arrive to the frontend. // casper.notebook_test(function () { var messages = []; this.on('remote.alert', function (msg) { messages.push(msg); }); this.evaluate(function () { var cell = IPython.notebook.get_cell(0); var json = cell.toJSON(); json.execution_count = "<script> alert('hello from input prompts !')</script>"; cell.fromJSON(json); }); this.then(function () { this.test.assert(messages.length == 0, "Captured log message from script tag injection !"); }); });
// # Surrounds given text with Markdown syntax /*global $, CodeMirror, Showdown, moment */ (function () { 'use strict'; var Markdown = { init : function (options, elem) { var self = this; self.elem = elem; self.style = (typeof options === 'string') ? options : options.style; self.options = $.extend({}, CodeMirror.prototype.addMarkdown.options, options); self.replace(); }, replace: function () { var text = this.elem.getSelection(), pass = true, cursor = this.elem.getCursor(), line = this.elem.getLine(cursor.line), md, word, letterCount, converter, textIndex, position; switch (this.style) { case 'h1': this.elem.setLine(cursor.line, '# ' + line); this.elem.setCursor(cursor.line, cursor.ch + 2); pass = false; break; case 'h2': this.elem.setLine(cursor.line, '## ' + line); this.elem.setCursor(cursor.line, cursor.ch + 3); pass = false; break; case 'h3': this.elem.setLine(cursor.line, '### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 4); pass = false; break; case 'h4': this.elem.setLine(cursor.line, '#### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 5); pass = false; break; case 'h5': this.elem.setLine(cursor.line, '##### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 6); pass = false; break; case 'h6': this.elem.setLine(cursor.line, '###### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 7); pass = false; break; case 'link': md = this.options.syntax.link.replace('$1', text); this.elem.replaceSelection(md, 'end'); if (!text) { this.elem.setCursor(cursor.line, cursor.ch + 1); } else { textIndex = line.indexOf(text, cursor.ch - text.length); position = textIndex + md.length - 1; this.elem.setSelection({line: cursor.line, ch: position - 7}, {line: cursor.line, ch: position}); } pass = false; break; case 'image': md = this.options.syntax.image.replace('$1', text); if (line !== '') { md = "\n\n" + md; } this.elem.replaceSelection(md, "end"); cursor = this.elem.getCursor(); this.elem.setSelection({line: cursor.line, ch: cursor.ch - 8}, {line: cursor.line, ch: cursor.ch - 1}); pass = false; break; case 'uppercase': md = text.toLocaleUpperCase(); break; case 'lowercase': md = text.toLocaleLowerCase(); break; case 'titlecase': md = text.toTitleCase(); break; case 'selectword': word = this.elem.getTokenAt(cursor); if (!/\w$/g.test(word.string)) { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end - 1}); } else { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end}); } break; case 'copyHTML': converter = new Showdown.converter(); if (text) { md = converter.makeHtml(text); } else { md = converter.makeHtml(this.elem.getValue()); } $(".modal-copyToHTML-content").text(md).selectText(); pass = false; break; case 'list': md = text.replace(/^(\s*)(\w\W*)/gm, '$1* $2'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'currentDate': md = moment(new Date()).format('D MMMM YYYY'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'newLine': if (line !== "") { this.elem.setLine(cursor.line, line + "\n\n"); } pass = false; break; default: if (this.options.syntax[this.style]) { md = this.options.syntax[this.style].replace('$1', text); } } if (pass && md) { this.elem.replaceSelection(md, 'end'); if (!text) { letterCount = md.length; this.elem.setCursor({line: cursor.line, ch: cursor.ch - (letterCount / 2)}); } } } }; CodeMirror.prototype.addMarkdown = function (options) { var markdown = Object.create(Markdown); markdown.init(options, this); }; CodeMirror.prototype.addMarkdown.options = { style: null, syntax: { bold: '**$1**', italic: '*$1*', strike: '~~$1~~', code: '`$1`', link: '[$1](http://)', image: '![$1](http://)', blockquote: '> $1' } }; }());
/* * QtWebKit-powered headless test runner using PhantomJS * * PhantomJS binaries: http://phantomjs.org/download.html * Requires PhantomJS 1.6+ (1.7+ recommended) * * Run with: * phantomjs runner.js [url-of-your-qunit-testsuite] * * e.g. * phantomjs runner.js http://localhost/qunit/test/index.html */ /*global phantom:false, require:false, console:false, window:false, QUnit:false */ (function() { 'use strict'; var url, page, timeout, args = require('system').args; // arg[0]: scriptName, args[1...]: arguments if (args.length < 2 || args.length > 3) { console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite] [timeout-in-seconds]'); phantom.exit(1); } url = args[1]; page = require('webpage').create(); page.settings.clearMemoryCaches = true; if (args[2] !== undefined) { timeout = parseInt(args[2], 10); } // Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`) page.onConsoleMessage = function(msg) { console.log(msg); }; page.onInitialized = function() { page.evaluate(addLogging); }; page.onCallback = function(message) { var result, failed; if (message) { if (message.name === 'QUnit.done') { result = message.data; failed = !result || !result.total || result.failed; if (!result.total) { console.error('No tests were executed. Are you loading tests asynchronously?'); } phantom.exit(failed ? 1 : 0); } } }; page.open(url, function(status) { if (status !== 'success') { console.error('Unable to access network: ' + status); phantom.exit(1); } else { // Cannot do this verification with the 'DOMContentLoaded' handler because it // will be too late to attach it if a page does not have any script tags. var qunitMissing = page.evaluate(function() { return (typeof QUnit === 'undefined' || !QUnit); }); if (qunitMissing) { console.error('The `QUnit` object is not present on this page.'); phantom.exit(1); } // Set a timeout on the test running, otherwise tests with async problems will hang forever if (typeof timeout === 'number') { setTimeout(function() { console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...'); phantom.exit(1); }, timeout * 1000); } // Do nothing... the callback mechanism will handle everything! } }); function addLogging() { window.document.addEventListener('DOMContentLoaded', function() { var currentTestAssertions = []; QUnit.log(function(details) { var response; // Ignore passing assertions if (details.result) { return; } response = details.message || ''; if (typeof details.expected !== 'undefined') { if (response) { response += ', '; } response += 'expected: ' + details.expected + ', but was: ' + details.actual; } if (details.source) { response += "\n" + details.source; } currentTestAssertions.push('Failed assertion: ' + response); }); QUnit.testDone(function(result) { var i, len, name = result.module + ': ' + result.name; if (result.failed) { console.log('Test failed: ' + name); for (i = 0, len = currentTestAssertions.length; i < len; i++) { console.log(' ' + currentTestAssertions[i]); } } currentTestAssertions.length = 0; }); QUnit.done(function(result) { console.log('Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.'); if (typeof window.callPhantom === 'function') { window.callPhantom({ 'name': 'QUnit.done', 'data': result }); } }); }, false); } })();
(function ($) { /*jslint undef: false, browser: true, devel: false, eqeqeq: false, bitwise: false, white: false, plusplus: false, regexp: false, nomen: false */ /*global jQuery,setTimeout,projekktor,location,setInterval,YT,clearInterval,pixelentity */ $.pixelentity = $.pixelentity || {version: '1.0.0'}; $.pixelentity.influxSlider = { conf: { api: false, delay: 3000, fade: false, pause: true } }; function PeInfluxSlider(target, conf) { var self = this; var jthis = $(this); var slides = []; var timer; var slider; var index=0; var master; var haveLinks = false; var locked = true; var paused = false; var enabled = true; var links; var nav = ""; function start() { target.bind("enable.pixelentity ",enable); target.bind("disable.pixelentity ",disable); target.addClass("peActiveWidget"); target.children().each(parseSlide); if (slides.length > 0) { addNavigation(); init(); if (conf.pause) { target.bind("mouseenter mouseleave",evHandler); } } } function parseSlide(idx) { var link = false,img = false,parent; var el = $(this); nav += '<li><a id="'+idx+'" href="#">btn</a></li>'; if (this.tagName.toLowerCase() == "img") { img = el; } else { if (el.attr("href")) { img = el.find("img:eq(0)"); if (img.length > 0) { link = el; //link.replaceWith(img); link.before(img); link.css("position","absolute").css("z-index",100).css("display","block").hide(); if ($.browser.msie && $.browser.version < 9) { link.css("opacity",0).css("background-color","black"); } target.prepend(link); haveLinks = true; } } } if (img.length > 0) { slides.push({ image: img, link: link }); if (idx > 0) { img.detach(); } } } function addNavigation() { nav = '<ul class="sliderNav">'+nav+'</ul>'; target.before(nav); nav = target.parent().find(".sliderNav a"); nav.click(evHandler); } function evHandler(e) { if (enabled) { switch (e.type) { case "click": if (!locked) { rotate(parseInt(e.currentTarget.id,10)); timer.reset(); //timer.start(conf.delay); } break; case "mouseenter": case "mouseleave": paused = (e.type == "mouseenter"); timer[paused ? "pause" : "resume"](); break; } } return e.type == "click" ? false : true; } // used to disable timer function noop() { } function init() { links = target.find("a"); slider = slides[0].image.peTransitionHilight({api:true,boost:1,fallback:conf.fade,disabled:true}); slider.bind("ready.pixelentity change.pixelentity",next); timer = conf.delay > 0 ? new $.pixelentity.Timer(rotate) : { start: noop, pause: noop, resume: noop }; } function next(e) { if (e.type == "ready") { if (haveLinks) { links.width(slider.width()).height(slider.height()); } setLink(); } timer.start(conf.delay); if (paused || !enabled) { timer.pause(); } locked = false; } function setLink() { if (haveLinks) { links.hide(); if (slides[index].link) { slides[index].link.show(); } } nav.removeClass("selected").eq(index).addClass("selected").end(); } function rotate(idx) { locked = true; index = idx >=0 ? idx : (index + 1) % slides.length; slider.load(slides[index].image); setLink(index); } function enable() { if (!enabled) { enabled = true; slider.enable(); timer.resume(); } } function disable() { if (enabled) { enabled = false; slider.disable(); timer.pause(); } } $.extend(self, { bind: function(ev,handler) { jthis.bind(ev,handler); }, one: function(ev,handler) { jthis.one(ev,handler); }, enable: enable, disable: disable, destroy: function() { if (jthis) { jthis.remove(); } jthis = self = undefined; target.data("peInfluxSlider", null); target = undefined; } }); start(); } // jQuery plugin implementation $.fn.peInfluxSlider = function(conf) { // return existing instance var api = this.data("peInfluxSlider"); if (api) { return api; } conf = $.extend(true, {}, $.pixelentity.influxSlider.conf, conf); // install peScroll for each entry in jQuery object this.each(function() { api = new PeInfluxSlider($(this), conf); $(this).data("peInfluxSlider", api); }); return conf.api ? api: this; }; }(jQuery));
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {setStyle} from '../src/style'; import {validateData, writeScript} from '../3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function inmobi(global, data) { validateData(data, ['siteid', 'slotid'], []); const inmobiConf = { siteid: data.siteid, slot: data.slotid, manual: true, onError: code => { if (code == 'nfr') { global.context.noContentAvailable(); setStyle(document.getElementById('my-ad-slot'), 'display', 'none'); } }, onSuccess: () => { global.context.renderStart(); }, }; writeScript(global, 'https://cf.cdn.inmobi.com/ad/inmobi.secure.js', () => { global.document.write("<div id='my-ad-slot'></div>"); global._inmobi.getNewAd(document.getElementById('my-ad-slot'), inmobiConf); }); }
/* * Copyright (C) 2010 Google Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {string} label * @param {string} className * @param {string=} tooltip */ WebInspector.Checkbox = function(label, className, tooltip) { this.element = document.createElementWithClass("label", className); this._inputElement = this.element.createChild("input"); this._inputElement.type = "checkbox"; this.element.createTextChild(label); if (tooltip) this.element.title = tooltip; } WebInspector.Checkbox.prototype = { set checked(checked) { this._inputElement.checked = checked; }, get checked() { return this._inputElement.checked; }, addEventListener: function(listener) { function listenerWrapper(event) { if (listener) listener(event); event.consume(); return true; } this._inputElement.addEventListener("click", listenerWrapper, false); this.element.addEventListener("click", listenerWrapper, false); } }
/** * Template JS for Internet Explorer 8 and lower - mainly workaround for missing selectors */ (function($) { // Standard template setup for IE $.fn.addTemplateSetup(function() { // Clean existing classes this.find('.first-child').removeClass('first-child'); this.find('.last-child').removeClass('last-child'); this.find('.last-of-type').removeClass('last-of-type'); this.find('.even').removeClass('even'); this.find('.odd').removeClass('odd'); // Missing selectors this.find(':first-child').addClass('first-child'); this.find(':last-child').addClass('last-child'); // Specific classes this.find('.head').each(function () { $(this).children('div:last').addClass('last-of-type'); }); this.find('tbody tr:even, .task-dialog > li:even, .planning > li.planning-header > ul > li:even').addClass('even'); this.find('tbody tr:odd, .planning > li:odd').addClass('odd'); this.find('.form fieldset:has(legend)').addClass('fieldset-with-legend').filter(':first-child').addClass('fieldset-with-legend-first-child'); // Disabled buttons this.find('button:disabled').addClass('disabled'); // IE 7 if ($.browser.version < 8) { // Clean existing classes this.find('.after-h1').removeClass('after-h1'); this.find('.block-content h1:first-child, .block-content .h1:first-child').next().addClass('after-h1'); this.find('.calendar .add-event').prepend('<span class="before"></span>'); } // Input switches this.find('input[type=radio].switch:checked + .switch-replace, input[type=checkbox].switch:checked + .switch-replace').addClass('switch-replace-checked'); this.find('input[type=radio].switch:disabled + .switch-replace, input[type=checkbox].switch:disabled + .switch-replace').addClass('switch-replace-disabled'); this.find('input[type=radio].mini-switch:checked + .mini-switch-replace, input[type=checkbox].mini-switch:checked + .mini-switch-replace').addClass('mini-switch-replace-checked'); this.find('input[type=radio].mini-switch:disabled + .mini-switch-replace, input[type=checkbox].mini-switch:disabled + .mini-switch-replace').addClass('mini-switch-replace-disabled'); }); // Document initial setup $(document).ready(function() { // Input switches $('input[type=radio].switch, input[type=checkbox].switch').click(function() { if (!this.checked) { $(this).next('.switch-replace').addClass('switch-replace-checked'); } else { $(this).next('.switch-replace').removeClass('switch-replace-checked'); } }); $('input[type=radio].mini-switch, input[type=checkbox].mini-switch').click(function() { if (!this.checked) { $(this).next('.mini-switch-replace').addClass('mini-switch-replace-checked'); } else { $(this).next('.mini-switch-replace').removeClass('mini-switch-replace-checked'); } }); }); })(jQuery);
import Ember from 'ember'; import MaterializeNavBar from './md-navbar'; export default MaterializeNavBar.extend({ init() { this._super(...arguments); Ember.deprecate("{{materialize-navbar}} has been deprecated. Please use {{md-navbar}} instead", false, {url: "https://github.com/sgasser/ember-cli-materialize/issues/67"}); } });
var _ = require('underscore'); module.exports = { 'passport-number': { labelClassName: 'visuallyhidden', validate: [ 'required' ] }, 'can-sign': { legend: { className: 'visuallyhidden' }, formatter: 'boolean', validate: ['required'], options: [ { value: true, label: 'I understand and will sign my passport', }, { value: false, label: 'I can’t sign my name', toggle: 'no-sign' } ] }, 'no-sign-reason': { className: 'textarea', validate: [ 'required', { type: 'maxlength', arguments: 250 } ], dependent: { field: 'can-sign', value: false } }, 'age-year': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'age-month': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'age-day': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'title':{ legend: { value: 'Your title', className: 'visuallyhidden' }, options: [ {value: 'Mr', label: 'Mr'}, {value: 'Mrs', label: 'Mrs'}, {value: 'Miss', label: 'Miss'}, {value: 'Ms', label: 'Ms'}, {value: 'Other', label: 'Other', toggle: 'other-titles'} ], validate: [ 'required' ] }, 'name': { }, 'lastname': { }, 'previous-name': { formatter: 'boolean', validate: 'required', legend: { className: 'form-label-bold' }, className: 'inline', options: [ { value: true, label: 'Yes', toggle: 'previous-names', child: 'input-text' }, { value: false, label: 'No' } ] }, 'previous-names': { validate: [ 'required', { type: 'maxlength', arguments: 100 } ], dependent: { field: 'previous-name', value: true } }, 'gender': { validate: [ 'required' ], legend: { value: 'Your gender', className: 'visuallyhidden' }, options: [ { value: 'F', label: 'Female' }, { value: 'M', label: 'Male' } ] }, 'town-of-birth': { validate: [ 'required' ] }, 'born-in-uk': { formatter: 'boolean', validate: 'required', legend: { className: 'form-label-bold' }, options: [ { value: true, label: 'Yes' }, { value: false, label: 'No', toggle: 'birth-country' } ], className: 'inline' }, 'country-of-birth': { validate: 'required', dependent: { field: 'born-in-uk', value: false }, }, 'expiry-year': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'expiry-month': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'address1': { validate: [ 'required' ] }, 'address2': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address3': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address4': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address5': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'town': { validate: [ 'required' ] }, 'postcode': { validate: [ 'required' ] }, 'email': { validate: [ 'required' ] }, 'country-code': { labelClassName: 'visuallyhidden', formatter: 'removehyphens', validate: [ 'required' ] }, 'mobile': { validate: [ 'numeric', 'required' ] }, 'passport-options-dps':{ legend: { value: 'Passport size' }, options: [ {value: '32', label: 'Standard adult 32-page passport (£128)'}, {value: '48', label: 'Jumbo adult 48-page passport (£137)'} ], validate: [ 'required' ] }, 'passport-size': { formatter: 'boolean', validate: 'required', legend: { value: 'What size passport would you like?', className: 'form-label' }, options: [ { value: false, label: '32-page passport (free)' }, { value: true, label: '48-page passport ({{#currency}}{{largePassportCost}}{{/currency}})' } ], dependent: { field: 'passport-size-dependent', value: 'true' } }, braille: { formatter: 'boolean-strict', legend: { value: 'Add a Braille sticker' }, }, 'return-passport':{ legend: { value: 'How would you like us to return your ols passport?', className: 'visuallyhidden' }, options: [ {value: 'Special-delivery', label: 'Special delivery (£3 extra)'}, {value: 'Standard', label: 'Standard post (free)'} ], validate: [ 'required' ] }, 'secure-return': { formatter: 'boolean', validate: 'required', legend: { value: 'How would you like us to send your old passport back to you?', className: 'form-label-bold' }, options: [ { value: true, label: 'Special delivery (&#163;3 extra)' }, { value: false, label: 'Standard post (free)' } ] }, };
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'justify', 'nb', { block: 'Blokkjuster', center: 'Midtstill', left: 'Venstrejuster', right: 'Høyrejuster' });
function f() { var x = undefined ? 1 : 4294967295; print(false || x); } f();
/** * jQuery EasyUI 1.5 * * Copyright (c) 2009-2016 www.jeasyui.com. All rights reserved. * * Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php * To use it on other terms please contact us: info@jeasyui.com * */ (function($){ function _1(_2){ var _3=$.data(_2,"datetimebox"); var _4=_3.options; $(_2).datebox($.extend({},_4,{onShowPanel:function(){ var _5=$(this).datetimebox("getValue"); _d(this,_5,true); _4.onShowPanel.call(this); },formatter:$.fn.datebox.defaults.formatter,parser:$.fn.datebox.defaults.parser})); $(_2).removeClass("datebox-f").addClass("datetimebox-f"); $(_2).datebox("calendar").calendar({onSelect:function(_6){ _4.onSelect.call(this.target,_6); }}); if(!_3.spinner){ var _7=$(_2).datebox("panel"); var p=$("<div style=\"padding:2px\"><input></div>").insertAfter(_7.children("div.datebox-calendar-inner")); _3.spinner=p.children("input"); } _3.spinner.timespinner({width:_4.spinnerWidth,showSeconds:_4.showSeconds,separator:_4.timeSeparator}); $(_2).datetimebox("initValue",_4.value); }; function _8(_9){ var c=$(_9).datetimebox("calendar"); var t=$(_9).datetimebox("spinner"); var _a=c.calendar("options").current; return new Date(_a.getFullYear(),_a.getMonth(),_a.getDate(),t.timespinner("getHours"),t.timespinner("getMinutes"),t.timespinner("getSeconds")); }; function _b(_c,q){ _d(_c,q,true); }; function _e(_f){ var _10=$.data(_f,"datetimebox").options; var _11=_8(_f); _d(_f,_10.formatter.call(_f,_11)); $(_f).combo("hidePanel"); }; function _d(_12,_13,_14){ var _15=$.data(_12,"datetimebox").options; $(_12).combo("setValue",_13); if(!_14){ if(_13){ var _16=_15.parser.call(_12,_13); $(_12).combo("setText",_15.formatter.call(_12,_16)); $(_12).combo("setValue",_15.formatter.call(_12,_16)); }else{ $(_12).combo("setText",_13); } } var _16=_15.parser.call(_12,_13); $(_12).datetimebox("calendar").calendar("moveTo",_16); $(_12).datetimebox("spinner").timespinner("setValue",_17(_16)); function _17(_18){ function _19(_1a){ return (_1a<10?"0":"")+_1a; }; var tt=[_19(_18.getHours()),_19(_18.getMinutes())]; if(_15.showSeconds){ tt.push(_19(_18.getSeconds())); } return tt.join($(_12).datetimebox("spinner").timespinner("options").separator); }; }; $.fn.datetimebox=function(_1b,_1c){ if(typeof _1b=="string"){ var _1d=$.fn.datetimebox.methods[_1b]; if(_1d){ return _1d(this,_1c); }else{ return this.datebox(_1b,_1c); } } _1b=_1b||{}; return this.each(function(){ var _1e=$.data(this,"datetimebox"); if(_1e){ $.extend(_1e.options,_1b); }else{ $.data(this,"datetimebox",{options:$.extend({},$.fn.datetimebox.defaults,$.fn.datetimebox.parseOptions(this),_1b)}); } _1(this); }); }; $.fn.datetimebox.methods={options:function(jq){ var _1f=jq.datebox("options"); return $.extend($.data(jq[0],"datetimebox").options,{originalValue:_1f.originalValue,disabled:_1f.disabled,readonly:_1f.readonly}); },cloneFrom:function(jq,_20){ return jq.each(function(){ $(this).datebox("cloneFrom",_20); $.data(this,"datetimebox",{options:$.extend(true,{},$(_20).datetimebox("options")),spinner:$(_20).datetimebox("spinner")}); $(this).removeClass("datebox-f").addClass("datetimebox-f"); }); },spinner:function(jq){ return $.data(jq[0],"datetimebox").spinner; },initValue:function(jq,_21){ return jq.each(function(){ var _22=$(this).datetimebox("options"); var _23=_22.value; if(_23){ _23=_22.formatter.call(this,_22.parser.call(this,_23)); } $(this).combo("initValue",_23).combo("setText",_23); }); },setValue:function(jq,_24){ return jq.each(function(){ _d(this,_24); }); },reset:function(jq){ return jq.each(function(){ var _25=$(this).datetimebox("options"); $(this).datetimebox("setValue",_25.originalValue); }); }}; $.fn.datetimebox.parseOptions=function(_26){ var t=$(_26); return $.extend({},$.fn.datebox.parseOptions(_26),$.parser.parseOptions(_26,["timeSeparator","spinnerWidth",{showSeconds:"boolean"}])); }; $.fn.datetimebox.defaults=$.extend({},$.fn.datebox.defaults,{spinnerWidth:"100%",showSeconds:true,timeSeparator:":",keyHandler:{up:function(e){ },down:function(e){ },left:function(e){ },right:function(e){ },enter:function(e){ _e(this); },query:function(q,e){ _b(this,q); }},buttons:[{text:function(_27){ return $(_27).datetimebox("options").currentText; },handler:function(_28){ var _29=$(_28).datetimebox("options"); _d(_28,_29.formatter.call(_28,new Date())); $(_28).datetimebox("hidePanel"); }},{text:function(_2a){ return $(_2a).datetimebox("options").okText; },handler:function(_2b){ _e(_2b); }},{text:function(_2c){ return $(_2c).datetimebox("options").closeText; },handler:function(_2d){ $(_2d).datetimebox("hidePanel"); }}],formatter:function(_2e){ var h=_2e.getHours(); var M=_2e.getMinutes(); var s=_2e.getSeconds(); function _2f(_30){ return (_30<10?"0":"")+_30; }; var _31=$(this).datetimebox("spinner").timespinner("options").separator; var r=$.fn.datebox.defaults.formatter(_2e)+" "+_2f(h)+_31+_2f(M); if($(this).datetimebox("options").showSeconds){ r+=_31+_2f(s); } return r; },parser:function(s){ if($.trim(s)==""){ return new Date(); } var dt=s.split(" "); var d=$.fn.datebox.defaults.parser(dt[0]); if(dt.length<2){ return d; } var _32=$(this).datetimebox("spinner").timespinner("options").separator; var tt=dt[1].split(_32); var _33=parseInt(tt[0],10)||0; var _34=parseInt(tt[1],10)||0; var _35=parseInt(tt[2],10)||0; return new Date(d.getFullYear(),d.getMonth(),d.getDate(),_33,_34,_35); }}); })(jQuery);
/** * Macedonia translation * By PetarD petar.dimitrijevic@vorteksed.com.mk (utf8 encoding) * 23 April 2007 */ Ext.onReady(function() { if (Ext.Date) { Ext.Date.monthNames = ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"]; Ext.Date.dayNames = ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]; } if (Ext.util && Ext.util.Format) { Ext.apply(Ext.util.Format, { thousandSeparator: '.', decimalSeparator: ',', currencySign: '\u0434\u0435\u043d', // Macedonian Denar dateFormat: 'd.m.Y' }); } }); Ext.define("Ext.locale.mk.view.View", { override: "Ext.view.View", emptyText: "" }); Ext.define("Ext.locale.mk.grid.plugin.DragDrop", { override: "Ext.grid.plugin.DragDrop", dragText: "{0} избрани редици" }); Ext.define("Ext.locale.mk.tab.Tab", { override: "Ext.tab.Tab", closeText: "Затвори tab" }); Ext.define("Ext.locale.mk.form.field.Base", { override: "Ext.form.field.Base", invalidText: "Вредноста во ова поле е невалидна" }); // changing the msg text below will affect the LoadMask Ext.define("Ext.locale.mk.view.AbstractView", { override: "Ext.view.AbstractView", loadingText: "Вчитувам..." }); Ext.define("Ext.locale.mk.picker.Date", { override: "Ext.picker.Date", todayText: "Денеска", minText: "Овој датум е пред најмалиот датум", maxText: "Овој датум е пред најголемиот датум", disabledDaysText: "", disabledDatesText: "", nextText: 'Следен месец (Control+Стрелка десно)', prevText: 'Претходен месец (Control+Стрелка лево)', monthYearText: 'Изберете месец (Control+Стрелка горе/Стрелка десно за менување година)', todayTip: "{0} (Spacebar)", format: "d.m.y" }); Ext.define("Ext.locale.mk.toolbar.Paging", { override: "Ext.PagingToolbar", beforePageText: "Страница", afterPageText: "од {0}", firstText: "Прва Страница", prevText: "Претходна Страница", nextText: "Следна Страница", lastText: "Последна Страница", refreshText: "Освежи", displayMsg: "Прикажувам {0} - {1} од {2}", emptyMsg: 'Нема податоци за приказ' }); Ext.define("Ext.locale.mk.form.field.Text", { override: "Ext.form.field.Text", minLengthText: "Минималната должина за ова поле е {0}", maxLengthText: "Максималната должина за ова поле е {0}", blankText: "Податоците во ова поле се потребни", regexText: "", emptyText: null }); Ext.define("Ext.locale.mk.form.field.Number", { override: "Ext.form.field.Number", minText: "Минималната вредност за ова поле е {0}", maxText: "Максималната вредност за ова поле е {0}", nanText: "{0} не е валиден број" }); Ext.define("Ext.locale.mk.form.field.Date", { override: "Ext.form.field.Date", disabledDaysText: "Неактивно", disabledDatesText: "Неактивно", minText: "Датумот во ова поле мора да биде пред {0}", maxText: "Датумот во ова поле мора да биде по {0}", invalidText: "{0} не е валиден датум - мора да биде во формат {1}", format: "d.m.y" }); Ext.define("Ext.locale.mk.form.field.ComboBox", { override: "Ext.form.field.ComboBox", valueNotFoundText: undefined }, function() { Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, { loadingText: "Вчитувам..." }); }); Ext.define("Ext.locale.mk.form.field.VTypes", { override: "Ext.form.field.VTypes", emailText: 'Ова поле треба да биде e-mail адреса во формат "user@example.com"', urlText: 'Ова поле треба да биде URL во формат "http:/' + '/www.example.com"', alphaText: 'Ова поле треба да содржи само букви и _', alphanumText: 'Ова поле треба да содржи само букви, бројки и _' }); Ext.define("Ext.locale.mk.grid.header.Container", { override: "Ext.grid.header.Container", sortAscText: "Сортирај Растечки", sortDescText: "Сортирај Опаѓачки", lockText: "Заклучи Колона", unlockText: "Отклучи колона", columnsText: "Колони" }); Ext.define("Ext.locale.mk.grid.PropertyColumnModel", { override: "Ext.grid.PropertyColumnModel", nameText: "Име", valueText: "Вредност", dateFormat: "m.d.Y" }); Ext.define("Ext.locale.mk.window.MessageBox", { override: "Ext.window.MessageBox", buttonText: { ok: "Потврди", cancel: "Поништи", yes: "Да", no: "Не" } }); // This is needed until we can refactor all of the locales into individual files Ext.define("Ext.locale.mk.Component", { override: "Ext.Component" });
define(['sinon', 'underscore', 'URI'], function(sinon, _, URI) { 'use strict'; var fakeServer, fakeRequests, expectRequest, expectJsonRequest, expectPostRequest, expectRequestURL, respondWithJson, respondWithError, respondWithTextError, respondWithNoContent; /* These utility methods are used by Jasmine tests to create a mock server or * get reference to mock requests. In either case, the cleanup (restore) is done with * an after function. * * This pattern is being used instead of the more common beforeEach/afterEach pattern * because we were seeing sporadic failures in the afterEach restore call. The cause of the * errors were that one test suite was incorrectly being linked as the parent of an unrelated * test suite (causing both suites' afterEach methods to be called). No solution for the root * cause has been found, but initializing sinon and cleaning it up on a method-by-method * basis seems to work. For more details, see STUD-1264. */ /** * Get a reference to the mocked server, and respond * to all requests with the specified statusCode. */ fakeServer = function (that, response) { var server = sinon.fakeServer.create(); that.after(function() { server.restore(); }); server.respondWith(response); return server; }; /** * Keep track of all requests to a fake server, and * return a reference to the Array. This allows tests * to respond for individual requests. */ fakeRequests = function (that) { var requests = [], xhr = sinon.useFakeXMLHttpRequest(); xhr.onCreate = function(request) { requests.push(request); }; that.after(function() { xhr.restore(); }); return requests; }; expectRequest = function(requests, method, url, body, requestIndex) { var request; if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } request = requests[requestIndex]; expect(request.url).toEqual(url); expect(request.method).toEqual(method); expect(request.requestBody).toEqual(body); }; expectJsonRequest = function(requests, method, url, jsonRequest, requestIndex) { var request; if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } request = requests[requestIndex]; expect(request.url).toEqual(url); expect(request.method).toEqual(method); expect(JSON.parse(request.requestBody)).toEqual(jsonRequest); }; /** * Expect that a JSON request be made with the given URL and parameters. * @param requests The collected requests * @param expectedUrl The expected URL excluding the parameters * @param expectedParameters An object representing the URL parameters * @param requestIndex An optional index for the request (by default, the last request is used) */ expectRequestURL = function(requests, expectedUrl, expectedParameters, requestIndex) { var request, parameters; if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } request = requests[requestIndex]; expect(new URI(request.url).path()).toEqual(expectedUrl); parameters = new URI(request.url).query(true); delete parameters._; // Ignore the cache-busting argument expect(parameters).toEqual(expectedParameters); }; /** * Intended for use with POST requests using application/x-www-form-urlencoded. */ expectPostRequest = function(requests, url, body, requestIndex) { var request; if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } request = requests[requestIndex]; expect(request.url).toEqual(url); expect(request.method).toEqual("POST"); expect(_.difference(request.requestBody.split('&'), body.split('&'))).toEqual([]); }; respondWithJson = function(requests, jsonResponse, requestIndex) { if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } requests[requestIndex].respond(200, { 'Content-Type': 'application/json' }, JSON.stringify(jsonResponse)); }; respondWithError = function(requests, statusCode, jsonResponse, requestIndex) { if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } if (_.isUndefined(statusCode)) { statusCode = 500; } if (_.isUndefined(jsonResponse)) { jsonResponse = {}; } requests[requestIndex].respond(statusCode, { 'Content-Type': 'application/json' }, JSON.stringify(jsonResponse) ); }; respondWithTextError = function(requests, statusCode, textResponse, requestIndex) { if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } if (_.isUndefined(statusCode)) { statusCode = 500; } if (_.isUndefined(textResponse)) { textResponse = ""; } requests[requestIndex].respond(statusCode, { 'Content-Type': 'text/plain' }, textResponse ); }; respondWithNoContent = function(requests, requestIndex) { if (_.isUndefined(requestIndex)) { requestIndex = requests.length - 1; } requests[requestIndex].respond(204, { 'Content-Type': 'application/json' }); }; return { server: fakeServer, requests: fakeRequests, expectRequest: expectRequest, expectJsonRequest: expectJsonRequest, expectPostRequest: expectPostRequest, expectRequestURL: expectRequestURL, respondWithJson: respondWithJson, respondWithError: respondWithError, respondWithTextError: respondWithTextError, respondWithNoContent: respondWithNoContent }; });
/** * @license AngularJS v1.3.0-rc.4 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookiesExample', ['ngCookies']) * .controller('ExampleController', ['$cookies', function($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * }]); * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookieStoreExample', ['ngCookies']) * .controller('ExampleController', ['$cookieStore', function($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * }]); * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unifies the bite.project subsystem within the context of a * background script. The constructor as a the initializer for the subsystem * causes the rest of the system to initialize. * * @author jasonstredwick@google.com (Jason Stredwick) */ goog.provide('bite.project.Background'); /** * Constructs an object that manages the project UX within the background. * @constructor * @export */ bite.project.Background = function() { }; goog.addSingletonGetter(bite.project.Background); /** * Handles messages for the project subsystem and redirects as appropriate. * @param {!Object} request The data sent. * @param {MessageSender} sender An object containing information about the * script context that sent the request. * @param {function(!*): void} response Optional function to call when the * request completes; only call when appropriate. * @private */ bite.project.Background.prototype.onRequest_ = function(request, sender, response) { }; /** * Create the content instance to initialize the project subsystem in the * context of a content script. */ bite.project.Background.getInstance();
defineSuite([ 'Widgets/Animation/Animation', 'Core/defined', 'Specs/pollToPromise', 'Widgets/Animation/AnimationViewModel', 'Widgets/ClockViewModel' ], function( Animation, defined, pollToPromise, AnimationViewModel, ClockViewModel) { 'use strict'; var container; var animation; afterEach(function() { if (defined(animation)) { animation = animation.destroy(); } if (defined(container) && defined(container.parentNode)) { container.parentNode.removeChild(container); } }); it('Can create and destroy', function() { var clockViewModel = new ClockViewModel(); var animationViewModel = new AnimationViewModel(clockViewModel); animation = new Animation(document.body, animationViewModel); }); it('Can create with container not in the DOM', function() { container = document.createElement('div'); var clockViewModel = new ClockViewModel(); var animationViewModel = new AnimationViewModel(clockViewModel); var animation = new Animation(container, animationViewModel); //Verify applyThemeChanges is called when we add the container to the DOM. spyOn(animation, 'applyThemeChanges').and.callThrough(); document.body.appendChild(container); //This is done via polling because we can't control when the DOM decides to //fire the Mutation event. return pollToPromise(function() { return animation.applyThemeChanges.calls.count() === 1; }); }); it('Can destroy without container ever being in the DOM', function() { container = document.createElement('div'); var clockViewModel = new ClockViewModel(); var animationViewModel = new AnimationViewModel(clockViewModel); animation = new Animation(container, animationViewModel); }); });
/************************************************************* * * MathJax/localization/cdo/TeX.js * * Copyright (c) 2009-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.Localization.addTranslation("cdo","TeX",{ version: "2.7.2", isLoaded: true, strings: { } }); MathJax.Ajax.loadComplete("[MathJax]/localization/cdo/TeX.js");
/* * Copyright 2016 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * Tests transpilation of arrow functions. * * @author moz@google.com (Michael Zhou) */ goog.require('goog.testing.jsunit'); function testBasic() { var a = [1, 2, 3]; function map(arr, f) { var result = []; for (var i = 0; i < arr.length; i++) { result.push(f(arr[i])); } return result; } assertArrayEquals([2, 3, 4], map(a, (x) => x + 1)); } function testTemplate() { var f = x => `x is ${x}`; assertEquals('x is foo', f('foo')); } function testArguments() { function getArgs(x) { return ((y) => arguments)(7); } assertEquals(5, getArgs(5)[0]); } function forEach(arr, f) { for (var i = 0; i < arr.length; i++) { f(arr[i]); } } function testTwoArrowFunctionsInSameFunctionScope() { var count = 0; forEach([1, 2], x => count += x); forEach([3, 4], x => count += x); assertEquals(10, count); } function testTwoArrowFunctionsInSameBlockScope() { while (true) { var count = 0; forEach([1, 2], x => count += x); forEach([3, 4], x => count += x); assertEquals(10, count); break; } } // https://github.com/google/closure-compiler/issues/932 function testBug932_this() { var count = 0; class C { log(x) { count++; } f(xs) { forEach(xs, x => this.log(x)); if (xs.length > 1) { forEach(xs, x => this.log(x)); } } } var c = new C(); c.f([1, 2]); assertEquals(4, count); } // https://github.com/google/closure-compiler/issues/932 function testBug932_arguments() { var log = []; class C { log(x) { log.push(x); } f(var_args) { forEach(arguments, x => this.log(arguments[0])); if (arguments.length > 1) { forEach(arguments, x => this.log(arguments[1])); } } } var c = new C(); c.f(3, 4); assertArrayEquals([3, 3, 4, 4], log); } function testBug1907() { class Base { f() { assertTrue(this instanceof Sub); } } class Sub extends Base { f() { (() => super.f())(); } } (new Sub()).f(); }
/* Copyright (c) 2015 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Authors: Cui,Jieqiong <jieqiongx.cui@intel.com> */ var testTarget; $(document).ready(function(){ pause(); }); function play() { testTarget=document.getElementById("MediaPlayback"); testTarget.play(); } function pause() { testTarget=document.getElementById("MediaPlayback"); testTarget.pause(); }
/** PURE_IMPORTS_START .._Subscriber PURE_IMPORTS_END */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; import { Subscriber } from '../Subscriber'; /* tslint:enable:max-line-length */ /** * Applies an accumulator function over the source Observable, and returns each * intermediate result, with an optional seed value. * * <span class="informal">It's like {@link reduce}, but emits the current * accumulation whenever the source emits a value.</span> * * <img src="./img/scan.png" width="100%"> * * Combines together all values emitted on the source, using an accumulator * function that knows how to join a new source value into the accumulation from * the past. Is similar to {@link reduce}, but emits the intermediate * accumulations. * * Returns an Observable that applies a specified `accumulator` function to each * item emitted by the source Observable. If a `seed` value is specified, then * that value will be used as the initial value for the accumulator. If no seed * value is specified, the first item of the source is used as the seed. * * @example <caption>Count the number of click events</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var ones = clicks.mapTo(1); * var seed = 0; * var count = ones.scan((acc, one) => acc + one, seed); * count.subscribe(x => console.log(x)); * * @see {@link expand} * @see {@link mergeScan} * @see {@link reduce} * * @param {function(acc: R, value: T, index: number): R} accumulator * The accumulator function called on each source value. * @param {T|R} [seed] The initial accumulation value. * @return {Observable<R>} An observable of the accumulated values. * @method scan * @owner Observable */ export function scan(accumulator, seed) { var hasSeed = false; // providing a seed of `undefined` *should* be valid and trigger // hasSeed! so don't use `seed !== undefined` checks! // For this reason, we have to check it here at the original call site // otherwise inside Operator/Subscriber we won't know if `undefined` // means they didn't provide anything or if they literally provided `undefined` if (arguments.length >= 2) { hasSeed = true; } return function scanOperatorFunction(source) { return source.lift(new ScanOperator(accumulator, seed, hasSeed)); }; } var ScanOperator = /*@__PURE__*/ (/*@__PURE__*/ function () { function ScanOperator(accumulator, seed, hasSeed) { if (hasSeed === void 0) { hasSeed = false; } this.accumulator = accumulator; this.seed = seed; this.hasSeed = hasSeed; } ScanOperator.prototype.call = function (subscriber, source) { return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); }; return ScanOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ var ScanSubscriber = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { __extends(ScanSubscriber, _super); function ScanSubscriber(destination, accumulator, _seed, hasSeed) { _super.call(this, destination); this.accumulator = accumulator; this._seed = _seed; this.hasSeed = hasSeed; this.index = 0; } Object.defineProperty(ScanSubscriber.prototype, "seed", { get: function () { return this._seed; }, set: function (value) { this.hasSeed = true; this._seed = value; }, enumerable: true, configurable: true }); ScanSubscriber.prototype._next = function (value) { if (!this.hasSeed) { this.seed = value; this.destination.next(value); } else { return this._tryNext(value); } }; ScanSubscriber.prototype._tryNext = function (value) { var index = this.index++; var result; try { result = this.accumulator(this.seed, value, index); } catch (err) { this.destination.error(err); } this.seed = result; this.destination.next(result); }; return ScanSubscriber; }(Subscriber)); //# sourceMappingURL=scan.js.map
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * 15.5.5.2 defines [[GetOwnProperty]] for Strings. It supports using indexing * notation to look up non numeric property names. * * @path ch15/15.5/15.5.5/15.5.5.2/15.5.5.5.2-3-5.js * @description String object indexing returns undefined if the numeric index ( 2^32-1) is not an array index */ function testcase() { var s = new String("hello world"); if (s[Math.pow(2, 32)-1]===undefined) { return true; } } runTestCase(testcase);
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-33.js * @description Object.defineProperty - 'Attributes' is a Function object which implements its own [[Get]] method to access the 'enumerable' property (8.10.5 step 3.a) */ function testcase() { var obj = {}; var accessed = false; var fun = function () { }; fun.enumerable = true; Object.defineProperty(obj, "property", fun); for (var prop in obj) { if (prop === "property") { accessed = true; } } return accessed; } runTestCase(testcase);
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-173.js * @description Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (SyntaxError.prototype.constructor) */ function testcase() { var desc = Object.getOwnPropertyDescriptor(SyntaxError.prototype, "constructor"); if (desc.value === SyntaxError.prototype.constructor && desc.writable === true && desc.enumerable === false && desc.configurable === true) { return true; } } runTestCase(testcase);
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.3/15.4.3.2/15.4.3.2-0-2.js * @description Array.isArray must exist as a function taking 1 parameter */ function testcase() { if (Array.isArray.length === 1) { return true; } } runTestCase(testcase);
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-c-iii-2.js * @description Array.prototype.map - value of returned array element equals to 'mappedValue' */ function testcase() { function callbackfn(val, idx, obj) { return val; } var obj = { 0: 11, 1: 9, length: 2 }; var newArr = Array.prototype.map.call(obj, callbackfn); return newArr[0] === obj[0] && newArr[1] === obj[1]; } runTestCase(testcase);
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastetext', 'el', { button: 'Επικόλληση ως απλό κείμενο', title: 'Επικόλληση ως απλό κείμενο' } );
/** * Prev Rollover * (c) 2013 Bill, BunKat LLC. * * Determines if a value will cause a particualr constraint to rollover to the * previous largest time period. Used primarily when a constraint has a * variable extent. * * Later is freely distributable under the MIT license. * For all details and documentation: * http://github.com/bunkat/later */ later.date.prevRollover = function(d, val, constraint, period) { var cur = constraint.val(d); return (val >= cur || !val) ? period.start(period.prev(d, period.val(d)-1)) : period.start(d); };
export function foo4() {}; export const { a: [{ foo4: foo }], b, c: { foo2: [{ foo3: foo4 }] } } = bar;
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-select-unknown-value-required/index.html"); }); it('should show the error message when the unknown option is selected', function() { var error = element(by.className('error')); expect(error.getText()).toBe('Error: Please select a value'); element(by.cssContainingText('option', 'Option 1')).click(); expect(error.isPresent()).toBe(false); element(by.tagName('button')).click(); expect(error.getText()).toBe('Error: Please select a value'); }); });
// META: script=websocket.sub.js var testOpen = async_test("Send binary data on a WebSocket - Blob - Connection should be opened"); var testMessage = async_test("Send binary data on a WebSocket - Blob - Message should be received"); var testClose = async_test("Send binary data on a WebSocket - Blob - Connection should be closed"); var data = ""; var datasize = 65000; var isOpenCalled = false; var wsocket = CreateWebSocket(false, false, false); wsocket.addEventListener('open', testOpen.step_func(function(evt) { wsocket.binaryType = "blob"; for (var i = 0; i < datasize; i++) data += String.fromCharCode(0); data = new Blob([data]); isOpenCalled = true; wsocket.send(data); testOpen.done(); }), true); wsocket.addEventListener('message', testMessage.step_func(function(evt) { assert_true(evt.data instanceof Blob); assert_equals(evt.data.size, datasize); wsocket.close(); testMessage.done(); }), true); wsocket.addEventListener('close', testClose.step_func(function(evt) { assert_true(isOpenCalled, "WebSocket connection should be open"); assert_true(evt.wasClean, "wasClean should be true"); testClose.done(); }), true);
/** * Utility functions for jazzing up HTMLForm elements. */ ( function ( mw, $ ) { /** * jQuery plugin to fade or snap to visible state. * * @param {boolean} instantToggle [optional] * @return {jQuery} */ $.fn.goIn = function ( instantToggle ) { if ( instantToggle === true ) { return $(this).show(); } return $(this).stop( true, true ).fadeIn(); }; /** * jQuery plugin to fade or snap to hiding state. * * @param {boolean} instantToggle [optional] * @return jQuery */ $.fn.goOut = function ( instantToggle ) { if ( instantToggle === true ) { return $(this).hide(); } return $(this).stop( true, true ).fadeOut(); }; /** * Bind a function to the jQuery object via live(), and also immediately trigger * the function on the objects with an 'instant' parameter set to true. * @param {Function} callback Takes one parameter, which is {true} when the * event is called immediately, and {jQuery.Event} when triggered from an event. */ $.fn.liveAndTestAtStart = function ( callback ){ $(this) .live( 'change', callback ) .each( function () { callback.call( this, true ); } ); }; $( function () { // Animate the SelectOrOther fields, to only show the text field when // 'other' is selected. $( '.mw-htmlform-select-or-other' ).liveAndTestAtStart( function ( instant ) { var $other = $( '#' + $(this).attr( 'id' ) + '-other' ); $other = $other.add( $other.siblings( 'br' ) ); if ( $(this).val() === 'other' ) { $other.goIn( instant ); } else { $other.goOut( instant ); } }); } ); function addMulti( $oldContainer, $container ) { var name = $oldContainer.find( 'input:first-child' ).attr( 'name' ), oldClass = ( ' ' + $oldContainer.attr( 'class' ) + ' ' ).replace( /(mw-htmlform-field-HTMLMultiSelectField|mw-chosen)/g, '' ), $select = $( '<select>' ), dataPlaceholder = mw.message( 'htmlform-chosen-placeholder' ); oldClass = $.trim( oldClass ); $select.attr( { name: name, multiple: 'multiple', 'data-placeholder': dataPlaceholder.plain(), 'class': 'htmlform-chzn-select mw-input ' + oldClass } ); $oldContainer.find( 'input' ).each( function () { var $oldInput = $(this), checked = $oldInput.prop( 'checked' ), $option = $( '<option>' ); $option.prop( 'value', $oldInput.prop( 'value' ) ); if ( checked ) { $option.prop( 'selected', true ); } $option.text( $oldInput.prop( 'value' ) ); $select.append( $option ); } ); $container.append( $select ); } function convertCheckboxesToMulti( $oldContainer, type ) { var $fieldLabel = $( '<td>' ), $td = $( '<td>' ), $fieldLabelText = $( '<label>' ), $container; if ( type === 'tr' ) { addMulti( $oldContainer, $td ); $container = $( '<tr>' ); $container.append( $td ); } else if ( type === 'div' ) { $fieldLabel = $( '<div>' ); $container = $( '<div>' ); addMulti( $oldContainer, $container ); } $fieldLabel.attr( 'class', 'mw-label' ); $fieldLabelText.text( $oldContainer.find( '.mw-label label' ).text() ); $fieldLabel.append( $fieldLabelText ); $container.prepend( $fieldLabel ); $oldContainer.replaceWith( $container ); return $container; } if ( $( '.mw-chosen' ).length ) { mw.loader.using( 'jquery.chosen', function () { $( '.mw-chosen' ).each( function () { var type = this.nodeName.toLowerCase(), $converted = convertCheckboxesToMulti( $( this ), type ); $converted.find( '.htmlform-chzn-select' ).chosen( { width: 'auto' } ); } ); } ); } $( function () { var $matrixTooltips = $( '.mw-htmlform-matrix .mw-htmlform-tooltip' ); if ( $matrixTooltips.length ) { mw.loader.using( 'jquery.tipsy', function () { $matrixTooltips.tipsy( { gravity: 's' } ); } ); } } ); }( mediaWiki, jQuery ) );
Meteor.methods({ getStatistics(refresh) { if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getStatistics' }); } if (RocketChat.authz.hasPermission(Meteor.userId(), 'view-statistics') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getStatistics' }); } if (refresh) { return RocketChat.statistics.save(); } else { return RocketChat.models.Statistics.findLast(); } } });
CKEDITOR.plugins.setLang("elementspath","de",{eleLabel:"Elementepfad",eleTitle:"%1 Element"});
var test = require('tape'); var watchify = require('../'); var browserify = require('browserify'); var vm = require('vm'); var fs = require('fs'); var path = require('path'); var mkdirp = require('mkdirp'); var os = require('os'); var tmpdir = path.join((os.tmpdir || os.tmpDir)(), 'watchify-' + Math.random()); var files = { main: path.join(tmpdir, 'main.js'), beep: path.join(tmpdir, 'beep.js'), boop: path.join(tmpdir, 'boop.js'), abc: path.join(tmpdir, 'lib', 'abc.js'), xyz: path.join(tmpdir, 'lib', 'xyz.js') }; mkdirp.sync(tmpdir); mkdirp.sync(path.join(tmpdir, 'lib')); fs.writeFileSync(files.main, [ 'var abc = require("abc");', 'var xyz = require("xyz");', 'var beep = require("./beep");', 'console.log(abc + " " + xyz + " " + beep);' ].join('\n')); fs.writeFileSync(files.beep, 'module.exports = require("./boop");'); fs.writeFileSync(files.boop, 'module.exports = require("xyz");'); fs.writeFileSync(files.abc, 'module.exports = "abc";'); fs.writeFileSync(files.xyz, 'module.exports = "xyz";'); test('properly caches exposed files', function (t) { t.plan(4); var cache = {}; var w = watchify(browserify({ entries: [files.main], basedir: tmpdir, cache: cache, packageCache: {} })); w.require('./lib/abc', {expose: 'abc'}); w.require('./lib/xyz', {expose: 'xyz'}); w.on('update', function () { w.bundle(function (err, src) { t.ifError(err); t.equal(run(src), 'ABC XYZ XYZ\n'); w.close(); }); }); w.bundle(function (err, src) { t.ifError(err); t.equal(run(src), 'abc xyz xyz\n'); setTimeout(function () { // If we're incorrectly caching exposed files, // then "files.abc" would be re-read from disk. cache[files.abc].source = 'module.exports = "ABC";'; fs.writeFileSync(files.xyz, 'module.exports = "XYZ";'); }, 1000); }); }); function run (src) { var output = ''; function log (msg) { output += msg + '\n' } vm.runInNewContext(src, { console: { log: log } }); return output; }
var webpackMerge = require('webpack-merge'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var commonConfig = require('./webpack.common.js'); var helpers = require('./helpers'); module.exports = webpackMerge(commonConfig, { devtool: 'cheap-module-eval-source-map', output: { path: helpers.root('dist'), publicPath: 'http://localhost:8080/', filename: '[name].js', chunkFilename: '[id].chunk.js' }, plugins: [ new ExtractTextPlugin('[name].css') ], devServer: { historyApiFallback: true, stats: 'minimal' } });
(function ($, Drupal, window) { "use strict"; /** * Attach the tableResponsive function to Drupal.behaviors. */ Drupal.behaviors.tableResponsive = { attach: function (context, settings) { var $tables = $(context).find('table.responsive-enabled').once('tableresponsive'); if ($tables.length) { for (var i = 0, il = $tables.length; i < il; i++) { TableResponsive.tables.push(new TableResponsive($tables[i])); } } } }; /** * The TableResponsive object optimizes table presentation for all screen sizes. * * A responsive table hides columns at small screen sizes, leaving the most * important columns visible to the end user. Users should not be prevented from * accessing all columns, however. This class adds a toggle to a table with * hidden columns that exposes the columns. Exposing the columns will likely * break layouts, but it provides the user with a means to access data, which * is a guiding principle of responsive design. */ function TableResponsive (table) { this.table = table; this.$table = $(table); this.showText = Drupal.t('Show all columns'); this.hideText = Drupal.t('Hide unimportant columns'); // Store a reference to the header elements of the table so that the DOM is // traversed only once to find them. this.$headers = this.$table.find('th'); // Add a link before the table for users to show or hide weight columns. this.$link = $('<a href="#" class="tableresponsive-toggle"></a>') .attr({ 'title': Drupal.t('Show table cells that were hidden to make the table fit within a small screen.') }) .on('click', $.proxy(this, 'eventhandlerToggleColumns')); this.$table.before($('<div class="tableresponsive-toggle-columns"></div>').append(this.$link)); // Attach a resize handler to the window. $(window) .on('resize.tableresponsive', $.proxy(this, 'eventhandlerEvaluateColumnVisibility')) .trigger('resize.tableresponsive'); } /** * Extend the TableResponsive function with a list of managed tables. */ $.extend(TableResponsive, { tables: [] }); /** * Associates an action link with the table that will show hidden columns. * * Columns are assumed to be hidden if their header has the class priority-low * or priority-medium. */ $.extend(TableResponsive.prototype, { eventhandlerEvaluateColumnVisibility: function (e) { var pegged = parseInt(this.$link.data('pegged'), 10); var hiddenLength = this.$headers.filter('.priority-medium:hidden, .priority-low:hidden').length; // If the table has hidden columns, associate an action link with the table // to show the columns. if (hiddenLength > 0) { this.$link.show().text(this.showText); } // When the toggle is pegged, its presence is maintained because the user // has interacted with it. This is necessary to keep the link visible if the // user adjusts screen size and changes the visibilty of columns. if (!pegged && hiddenLength === 0) { this.$link.hide().text(this.hideText); } }, // Toggle the visibility of columns classed with either 'priority-low' or // 'priority-medium'. eventhandlerToggleColumns: function (e) { e.preventDefault(); var self = this; var $hiddenHeaders = this.$headers.filter('.priority-medium:hidden, .priority-low:hidden'); this.$revealedCells = this.$revealedCells || $(); // Reveal hidden columns. if ($hiddenHeaders.length > 0) { $hiddenHeaders.each(function (index, element) { var $header = $(this); var position = $header.prevAll('th').length; self.$table.find('tbody tr').each(function () { var $cells = $(this).find('td:eq(' + position + ')'); $cells.show(); // Keep track of the revealed cells, so they can be hidden later. self.$revealedCells = $().add(self.$revealedCells).add($cells); }); $header.show(); // Keep track of the revealed headers, so they can be hidden later. self.$revealedCells = $().add(self.$revealedCells).add($header); }); this.$link.text(this.hideText).data('pegged', 1); } // Hide revealed columns. else { this.$revealedCells.hide(); // Strip the 'display:none' declaration from the style attributes of // the table cells that .hide() added. this.$revealedCells.each(function (index, element) { var $cell = $(this); var properties = $cell.attr('style').split(';'); var newProps = []; // The hide method adds display none to the element. The element should // be returned to the same state it was in before the columns were // revealed, so it is necessary to remove the display none // value from the style attribute. var match = /^display\s*\:\s*none$/; for (var i = 0; i < properties.length; i++) { var prop = properties[i]; prop.trim(); // Find the display:none property and remove it. var isDisplayNone = match.exec(prop); if (isDisplayNone) { continue; } newProps.push(prop); } // Return the rest of the style attribute values to the element. $cell.attr('style', newProps.join(';')); }); this.$link.text(this.showText).data('pegged', 0); // Refresh the toggle link. $(window).trigger('resize.tableresponsive'); } } }); // Make the TableResponsive object available in the Drupal namespace. Drupal.TableResponsive = TableResponsive; })(jQuery, Drupal, window);
// test for iterating over function properties var d = ""; function f(a,b) {} f.c = "Foo"; for (i in f) d+=i; result = d == "c";
Meteor.publish('settings', function() { var options = {}; if(!isAdminById(this.userId)){ options = _.extend(options, { fields: { mailChimpAPIKey: false, mailChimpListId: false } }); } return Settings.find({}, options); }); Meteor.publish('invites', function(){ if(canViewById(this.userId)){ return Invites.find({invitingUserId:this.userId}); } });
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { stringToBytes, bytesToString, getCryptoRandomBytesArray, utf8Encode, utf8Decode, } from '../../../src/utils/bytes'; describe('stringToBytes', function() { let fakeWin; beforeEach(() => { fakeWin = { crypto: { getRandomValues: array => { for (let i = 0; i < array.length; i++) { array[i] = i + 1; } }, }, }; }); it('should map a sample string appropriately', () => { const bytes = stringToBytes('abÿ'); expect(bytes.length).to.equal(3); expect(bytes[0]).to.equal(97); expect(bytes[1]).to.equal(98); expect(bytes[2]).to.equal(255); }); it('should signal an error with a character >255', () => { expect(() => { return stringToBytes('ab☺'); }).to.throw(); }); it('should convert bytes array to string', () => { const str = bytesToString(new Uint8Array([102, 111, 111])); expect(str).to.equal('foo'); }); it('should generate random bytes array when win.crypto is availble', () => { expect(getCryptoRandomBytesArray(fakeWin, 1)).to.deep .equal(new Uint8Array([1])); expect(getCryptoRandomBytesArray(fakeWin, 2)).to.deep .equal(new Uint8Array([1, 2])); expect(getCryptoRandomBytesArray(fakeWin, 3)).to.deep .equal(new Uint8Array([1, 2, 3])); }); it('should return null when trying to generate random bytes array if ' + 'win.crypto is not availble', () => { fakeWin.crypto = undefined; expect(getCryptoRandomBytesArray(fakeWin, 1)).to.be.null; }); }); describe('utf8', function() { // Examples here courtesy of StackOverflow: // http://stackoverflow.com/questions/478201/how-to-test-an-application-for // -correct-encoding-e-g-utf-8 const strings = [ 'ユーザー別サイト', '简体中文', '크로스플랫폼으로', 'מדוריםמבוקשים', 'أفضلالبحوث', 'Σὲγνωρίζωἀπὸ', 'ДесятуюМеждународную', 'แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช', ]; const bytes = [ [0xe3, 0x83, 0xa6, 0xe3, 0x83, 0xbc, 0xe3, 0x82, 0xb6, 0xe3, 0x83, 0xbc, 0xe5, 0x88, 0xa5, 0xe3, 0x82, 0xb5, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x88], [0xe7, 0xae, 0x80, 0xe4, 0xbd, 0x93, 0xe4, 0xb8, 0xad, 0xe6, 0x96, 0x87], [0xed, 0x81, 0xac, 0xeb, 0xa1, 0x9c, 0xec, 0x8a, 0xa4, 0xed, 0x94, 0x8c, 0xeb, 0x9e, 0xab, 0xed, 0x8f, 0xbc, 0xec, 0x9c, 0xbc, 0xeb, 0xa1, 0x9c], [0xd7, 0x9e, 0xd7, 0x93, 0xd7, 0x95, 0xd7, 0xa8, 0xd7, 0x99, 0xd7, 0x9d, 0xd7, 0x9e, 0xd7, 0x91, 0xd7, 0x95, 0xd7, 0xa7, 0xd7, 0xa9, 0xd7, 0x99, 0xd7, 0x9d], [0xd8, 0xa3, 0xd9, 0x81, 0xd8, 0xb6, 0xd9, 0x84, 0xd8, 0xa7, 0xd9, 0x84, 0xd8, 0xa8, 0xd8, 0xad, 0xd9, 0x88, 0xd8, 0xab], [0xce, 0xa3, 0xe1, 0xbd, 0xb2, 0xce, 0xb3, 0xce, 0xbd, 0xcf, 0x89, 0xcf, 0x81, 0xce, 0xaf, 0xce, 0xb6, 0xcf, 0x89, 0xe1, 0xbc, 0x80, 0xcf, 0x80, 0xe1, 0xbd, 0xb8], [0xd0, 0x94, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x8f, 0xd1, 0x82, 0xd1, 0x83, 0xd1, 0x8e, 0xd0, 0x9c, 0xd0, 0xb5, 0xd0, 0xb6, 0xd0, 0xb4, 0xd1, 0x83, 0xd0, 0xbd, 0xd0, 0xb0, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xbd, 0xd1, 0x83, 0xd1, 0x8e], [0xe0, 0xb9, 0x81, 0xe0, 0xb8, 0x9c, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0x94, 0xe0, 0xb8, 0xb4, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0xae, 0xe0, 0xb8, 0xb1, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0x99, 0xe0, 0xb9, 0x80, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0xb7, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0xad, 0xe0, 0xb8, 0xa1, 0xe0, 0xb9, 0x82, 0xe0, 0xb8, 0x97, 0xe0, 0xb8, 0xa3, 0xe0, 0xb8, 0xa1, 0xe0, 0xb9, 0x81, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0xb1, 0xe0, 0xb8, 0x87, 0xe0, 0xb9, 0x80, 0xe0, 0xb8, 0xa7, 0xe0, 0xb8, 0x8a], ]; it('should encode given string into utf-8 byte array', () => { for (let i = 0; i < strings.length; i++) { utf8Encode(strings[i]).then(byteArray => expect(byteArray).to.deep .equal(new Uint8Array(bytes[i]))); } }); it('should decode given utf-8 bytes into string', () => { for (let i = 0; i < bytes.length; i++) { utf8Decode(new Uint8Array(bytes[i])).then(string => expect(string).to .equal(strings[i])); } }); });
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { CompileIdentifierMetadata } from '../compile_metadata'; import { EventHandlerVars } from '../compiler_util/expression_converter'; import { isPresent } from '../facade/lang'; import * as o from '../output/output_ast'; import { ViewType } from '../private_import_core'; import { CompileMethod } from './compile_method'; import { CompilePipe } from './compile_pipe'; import { CompileQuery, addQueryToTokenMap, createQueryList } from './compile_query'; import { getPropertyInView, getViewClassName } from './util'; export var CompileViewRootNodeType; (function (CompileViewRootNodeType) { CompileViewRootNodeType[CompileViewRootNodeType["Node"] = 0] = "Node"; CompileViewRootNodeType[CompileViewRootNodeType["ViewContainer"] = 1] = "ViewContainer"; CompileViewRootNodeType[CompileViewRootNodeType["NgContent"] = 2] = "NgContent"; })(CompileViewRootNodeType || (CompileViewRootNodeType = {})); export var CompileViewRootNode = (function () { function CompileViewRootNode(type, expr, ngContentIndex) { this.type = type; this.expr = expr; this.ngContentIndex = ngContentIndex; } return CompileViewRootNode; }()); export var CompileView = (function () { function CompileView(component, genConfig, pipeMetas, styles, animations, viewIndex, declarationElement, templateVariableBindings) { var _this = this; this.component = component; this.genConfig = genConfig; this.pipeMetas = pipeMetas; this.styles = styles; this.animations = animations; this.viewIndex = viewIndex; this.declarationElement = declarationElement; this.templateVariableBindings = templateVariableBindings; this.viewChildren = []; this.nodes = []; this.rootNodes = []; this.lastRenderNode = o.NULL_EXPR; this.viewContainers = []; this.methods = []; this.ctorStmts = []; this.fields = []; this.getters = []; this.disposables = []; this.purePipes = new Map(); this.pipes = []; this.locals = new Map(); this.literalArrayCount = 0; this.literalMapCount = 0; this.pipeCount = 0; this.createMethod = new CompileMethod(this); this.animationBindingsMethod = new CompileMethod(this); this.injectorGetMethod = new CompileMethod(this); this.updateContentQueriesMethod = new CompileMethod(this); this.dirtyParentQueriesMethod = new CompileMethod(this); this.updateViewQueriesMethod = new CompileMethod(this); this.detectChangesInInputsMethod = new CompileMethod(this); this.detectChangesRenderPropertiesMethod = new CompileMethod(this); this.afterContentLifecycleCallbacksMethod = new CompileMethod(this); this.afterViewLifecycleCallbacksMethod = new CompileMethod(this); this.destroyMethod = new CompileMethod(this); this.detachMethod = new CompileMethod(this); this.viewType = getViewType(component, viewIndex); this.className = getViewClassName(component, viewIndex); this.classType = o.importType(new CompileIdentifierMetadata({ name: this.className })); this.classExpr = o.variable(this.className); if (this.viewType === ViewType.COMPONENT || this.viewType === ViewType.HOST) { this.componentView = this; } else { this.componentView = this.declarationElement.view.componentView; } this.componentContext = getPropertyInView(o.THIS_EXPR.prop('context'), this, this.componentView); var viewQueries = new Map(); if (this.viewType === ViewType.COMPONENT) { var directiveInstance_1 = o.THIS_EXPR.prop('context'); this.component.viewQueries.forEach(function (queryMeta, queryIndex) { var propName = "_viewQuery_" + queryMeta.selectors[0].name + "_" + queryIndex; var queryList = createQueryList(queryMeta, directiveInstance_1, propName, _this); var query = new CompileQuery(queryMeta, queryList, directiveInstance_1, _this); addQueryToTokenMap(viewQueries, query); }); } this.viewQueries = viewQueries; templateVariableBindings.forEach(function (entry) { _this.locals.set(entry[1], o.THIS_EXPR.prop('context').prop(entry[0])); }); if (!this.declarationElement.isNull()) { this.declarationElement.setEmbeddedView(this); } } CompileView.prototype.callPipe = function (name, input, args) { return CompilePipe.call(this, name, [input].concat(args)); }; CompileView.prototype.getLocal = function (name) { if (name == EventHandlerVars.event.name) { return EventHandlerVars.event; } var currView = this; var result = currView.locals.get(name); while (!result && isPresent(currView.declarationElement.view)) { currView = currView.declarationElement.view; result = currView.locals.get(name); } if (isPresent(result)) { return getPropertyInView(result, this, currView); } else { return null; } }; CompileView.prototype.afterNodes = function () { var _this = this; Array.from(this.viewQueries.values()) .forEach(function (queries) { return queries.forEach(function (q) { return q.afterChildren(_this.createMethod, _this.updateViewQueriesMethod); }); }); }; return CompileView; }()); function getViewType(component, embeddedTemplateIndex) { if (embeddedTemplateIndex > 0) { return ViewType.EMBEDDED; } if (component.type.isHost) { return ViewType.HOST; } return ViewType.COMPONENT; } //# sourceMappingURL=compile_view.js.map
/* globals ansispan:true */ ansispan = function(str) { str = str.replace(/>/g, '&gt;'); str = str.replace(/</g, '&lt;'); Object.keys(ansispan.foregroundColors).forEach(function(ansi) { var span = '<span style="color: ' + ansispan.foregroundColors[ansi] + '">'; // // `\033[Xm` == `\033[0;Xm` sets foreground color to `X`. // str = str.replace( new RegExp('\0o33\\[' + ansi + 'm', 'g'), span ).replace( new RegExp('\0o33\\[0;' + ansi + 'm', 'g'), span ); }); // // `\033[1m` enables bold font, `\033[22m` disables it // str = str.replace(/\033\[1m/g, '<b>').replace(/\033\[22m/g, '</b>'); // // `\033[3m` enables italics font, `\033[23m` disables it // str = str.replace(/\033\[3m/g, '<i>').replace(/\033\[23m/g, '</i>'); str = str.replace(/\033\[m/g, '</span>'); str = str.replace(/\033\[0m/g, '</span>'); return str.replace(/\033\[39m/g, '</span>'); }; ansispan.foregroundColors = { '30': 'gray', '31': 'red', '32': 'lime', '33': 'yellow', '34': '#6B98FF', '35': '#FF00FF', '36': 'cyan', '37': 'white' };
const Hapi = require('hapi'); const Inert = require('inert'); const Path = require('path'); let connection = { port: process.env.PORT || 3000, host: process.env.IP || 'localhost' }; let routes = [ { method: 'GET', path: '/scripts/{path*}', handler: { directory: { path: Path.join(__dirname, '/app/scripts') } } }, { method: 'GET', path: '/styles/{path*}', handler: { directory: { path: Path.join(__dirname, '/app/styles') } } }, { method: 'GET', path: '/assets/{path*}', handler: { directory: { path: Path.join(__dirname, '/app/assets') } } }, { method: 'GET', path: '/templates/{path*}', handler: { directory: { path: Path.join(__dirname, '/app/templates') } } }, { method: 'GET', path: '/{path*}', handler: { file: Path.join(__dirname, '/app/index.html') } } ] let server = new Hapi.Server(); server.connection(connection); server.register([Inert], (err) => { if (err) { throw err; } server.route(routes); }); server.start(() => { console.log('Server started at: ' + server.info.uri); }); server.on('response', function (request) { if(request.url.path.includes('templates')) { console.log(); console.log(new Date().toString() + ': ' + request.method.toUpperCase() + ' - ' + request.url.path + ' - (' + request.response.statusCode + ')'); } }); module.exports = server;
/** * @version $Id: index.js 10702 2008-08-21 09:31:31Z eddieajau $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ /** * Joomla! 1.5 Admininstrator index template behvaior * * @package Joomla * @since 1.5 * @version 1.0 */ //For IE6 - Background flicker fix try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} document.menu = null window.addEvent('load', function(){ element = $('menu') if(!element.hasClass('disabled')) { var menu = new JMenu(element) document.menu = menu } });
const tabsInstance = ( <Tabs defaultActiveKey={2}> <Tab eventKey={1} title="Tab 1">Tab 1 content</Tab> <Tab eventKey={2} title="Tab 2">Tab 2 content</Tab> <Tab eventKey={3} title="Tab 3" disabled>Tab 3 content</Tab> </Tabs> ); React.render(tabsInstance, mountNode);
// javascript 'shim' to trigger the click event of element(s) // when the space key is pressed. // // Created since some Assistive Technologies (for example some Screenreaders) // Will tell a user to press space on a 'button', so this functionality needs to be shimmed // See https://github.com/alphagov/govuk_elements/pull/272#issuecomment-233028270 // // Usage instructions: // GOVUK.shimLinksWithButtonRole.init(); ;(function (global) { 'use strict' var $ = global.jQuery var GOVUK = global.GOVUK || {} GOVUK.shimLinksWithButtonRole = { init: function init () { // listen to 'document' for keydown event on the any elements that should be buttons. $(document).on('keydown', '[role="button"]', function (event) { // if the keyCode (which) is 32 it's a space, let's simulate a click. if (event.which === 32) { event.preventDefault() // trigger the target's click event event.target.click() } }) } } // hand back to global global.GOVUK = GOVUK })(window)
'use strict'; /** * Module dependencies. */ var acl = require('acl'); // Using the memory backend acl = new acl(new acl.memoryBackend()); /** * Invoke Articles Permissions */ exports.invokeRolesPolicies = function() { acl.allow([{ roles: ['admin'], allows: [{ resources: '/api/articles', permissions: '*' }, { resources: '/api/articles/:articleId', permissions: '*' }] }, { roles: ['user'], allows: [{ resources: '/api/articles', permissions: ['get', 'post'] }, { resources: '/api/articles/:articleId', permissions: ['get'] }] }, { roles: ['guest'], allows: [{ resources: '/api/articles', permissions: ['get'] }, { resources: '/api/articles/:articleId', permissions: ['get'] }] }]); }; /** * Check If Articles Policy Allows */ exports.isAllowed = function(req, res, next) { var roles = (req.user) ? req.user.roles : ['guest']; // If an article is being processed and the current user created it then allow any manipulation if (req.article && req.user && req.article.user.id === req.user.id) { return next(); } // Check for user roles acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) { if (err) { // An authorization error occurred. return res.status(500).send('Unexpected authorization error'); } else { if (isAllowed) { // Access granted! Invoke next middleware return next(); } else { return res.status(403).json({ message: 'User is not authorized' }); } } }); };
/** * The MIT License (MIT) * * Copyright (c) 2015 Famous Industries Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; var test = require('tape'); var clone = require('../clone'); test('clone', function(t) { t.equal(typeof clone, 'function', 'clone should be a function'); var flatObject = {a: {}, b: {}, c: {}}; t.deepEqual(clone(flatObject), flatObject, 'clone should clone flat object'); var nestedObject = { test1: { test1test1: { test1test1test1: 3 }, test1test2: 3 }, test2: {}, test3: {} }; t.deepEqual(clone(nestedObject), nestedObject, 'clone should deep clone nested object'); t.end(); });
import warning from 'warning'; const getName = (object) => object.displayName ? `${object.displayName} ` : object.muiName ? `${object.muiName} ` : ''; function deprecatedExport(object, deprecatedPath, supportedPath) { warning(false, `Importing ${getName(object)}from '${deprecatedPath}' has been deprecated, use '${supportedPath}' instead.`); return object; } export default deprecatedExport;
// Copyright JS Foundation and other contributors, http://js.foundation // // 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. assert ((1 / 0*(-1)) == -Infinity); assert ((1 / 0*1) == Infinity);
'use strict'; var pathFn = require('path'); var Promise = require('bluebird'); var fs = require('hexo-fs'); function getExtname(str) { if (typeof str !== 'string') return ''; var extname = pathFn.extname(str); return extname[0] === '.' ? extname.slice(1) : extname; } function Render(ctx) { this.context = ctx; this.renderer = ctx.extend.renderer; } Render.prototype.isRenderable = function(path) { return this.renderer.isRenderable(path); }; Render.prototype.isRenderableSync = function(path) { return this.renderer.isRenderableSync(path); }; Render.prototype.getOutput = function(path) { return this.renderer.getOutput(path); }; Render.prototype.getRenderer = function(ext, sync) { return this.renderer.get(ext, sync); }; Render.prototype.getRendererSync = function(ext) { return this.getRenderer(ext, true); }; Render.prototype.render = function(data, options, callback) { if (!callback && typeof options === 'function') { callback = options; options = {}; } var ctx = this.context; var self = this; var ext = ''; return new Promise(function(resolve, reject) { if (!data) return reject(new TypeError('No input file or string!')); if (data.text != null) return resolve(data.text); if (!data.path) return reject(new TypeError('No input file or string!')); fs.readFile(data.path).then(resolve, reject); }).then(function(text) { data.text = text; ext = data.engine || getExtname(data.path); if (!ext || !self.isRenderable(ext)) return text; var renderer = self.getRenderer(ext); return renderer.call(ctx, data, options); }).then(function(result) { result = toString(result, data); if (data.onRenderEnd) { return data.onRenderEnd(result); } return result; }).then(function(result) { var output = self.getOutput(ext) || ext; return ctx.execFilter('after_render:' + output, result, { context: ctx, args: [data] }); }).asCallback(callback); }; Render.prototype.renderSync = function(data, options) { if (!data) throw new TypeError('No input file or string!'); options = options || {}; var ctx = this.context; if (data.text == null) { if (!data.path) throw new TypeError('No input file or string!'); data.text = fs.readFileSync(data.path); } if (data.text == null) throw new TypeError('No input file or string!'); var ext = data.engine || getExtname(data.path); var result; if (ext && this.isRenderableSync(ext)) { var renderer = this.getRendererSync(ext); result = renderer.call(ctx, data, options); } else { result = data.text; } var output = this.getOutput(ext) || ext; result = toString(result, data); if (data.onRenderEnd) { result = data.onRenderEnd(result); } return ctx.execFilterSync('after_render:' + output, result, { context: ctx, args: [data] }); }; function toString(result, options) { if (!options.hasOwnProperty('toString') || typeof result === 'string') return result; if (typeof options.toString === 'function') { return options.toString(result); } else if (typeof result === 'object') { return JSON.stringify(result); } else if (result.toString) { return result.toString(); } return result; } module.exports = Render;