code
stringlengths
2
1.05M
var mLineas = require('../models/mLineas'); var mEmple = require('../models/mEmple'); var mBorro = require('../models/mBorro'); var mAyuda = require('../models/mAyuda'); module.exports = { getAll: getAll, getAlta: getAlta, postAlta: postAlta, getModificar: getModificar, postModificar: postModificar, getDel: getDel }; function getAll(req, res) { req.session.nromenu = 7; mAyuda.getAyudaTexto(req.session.nromenu, function(ayuda){ mLineas.getAll(function(lineas){ res.render('lineaslista', { pagename: 'Archivo de Lineas de Fraccionado', lineas: lineas, ayuda: ayuda[0] }); }); }); } function getAlta(req, res){ res.render('lineasalta', { pagename: 'Alta de Linea' }); } function postAlta(req, res){ params = req.body; codigo = params.codigo; nombre = params.nombre; mLineas.insert(codigo, nombre, function(){ res.redirect('lineaslista'); }); } function getModificar(req, res){ params = req.params; id = params.id; mLineas.getLineaPorId(id, function(linea){ res.render('lineasmodificar', { pagename: 'Modificar Linea', linea: linea[0] }); }); } function postModificar(req, res){ params = req.body; id = params.id; codigo = params.codigo; nombre = params.nombre; activa = params.activa; if (activa == "on") activa = 1; else activa = 0; mLineas.update(id, codigo, nombre, activa, function(){ res.redirect('lineaslista'); }) } function getDel(req, res){ params = req.params; id = params.id; mLineas.getLineaPorId(id, function(linea){ linea=linea[0]; mBorro.add(req.session.user.usuario,"Lineas", "Borra Nombre Linea: "+ linea.nombre + ", id: " + id ,function(){ mLineas.del(id, function(){ res.redirect('/lineaslista'); }); }); }); }
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Q = require('q'); /* jshint ignore:line */ var _ = require('lodash'); /* jshint ignore:line */ var Page = require('../../../base/Page'); /* jshint ignore:line */ var deserialize = require( '../../../base/deserialize'); /* jshint ignore:line */ var serialize = require('../../../base/serialize'); /* jshint ignore:line */ var values = require('../../../base/values'); /* jshint ignore:line */ var CredentialList; var CredentialPage; var CredentialInstance; var CredentialContext; /* jshint ignore:start */ /** * @description Initialize the CredentialList * * @param {Twilio.Chat.V1} version - Version of the resource */ /* jshint ignore:end */ CredentialList = function CredentialList(version) { /* jshint ignore:start */ /** * @param {string} sid - sid of instance * * @returns {Twilio.Chat.V1.CredentialContext} */ /* jshint ignore:end */ function CredentialListInstance(sid) { return CredentialListInstance.get(sid); } CredentialListInstance._version = version; // Path Solution CredentialListInstance._solution = {}; CredentialListInstance._uri = _.template( '/Credentials' // jshint ignore:line )(CredentialListInstance._solution); /* jshint ignore:start */ /** * Streams CredentialInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory efficient. * * If a function is passed as the first argument, it will be used as the callback function. * * @param {object} [opts] - Options for request * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ CredentialListInstance.each = function each(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; if (opts.callback) { callback = opts.callback; } if (_.isUndefined(callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var currentResource = 0; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { done = true; return false; } currentResource++; callback(instance, onComplete); }); if ((limits.pageLimit && limits.pageLimit <= currentPage)) { onComplete(); } else if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); }; /* jshint ignore:start */ /** * Lists CredentialInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback function. * * @param {object} [opts] - Options for request * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ CredentialListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of CredentialInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @param {object} [opts] - Options for request * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ CredentialListInstance.page = function page(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({uri: this._uri, method: 'GET', params: data}); promise = promise.then(function(payload) { deferred.resolve(new CredentialPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single target page of CredentialInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @param {string} [targetUrl] - API-generated URL for the requested results page * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ CredentialListInstance.getPage = function getPage(targetUrl, callback) { var deferred = Q.defer(); var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl}); promise = promise.then(function(payload) { deferred.resolve(new CredentialPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * create a CredentialInstance * * @param {object} opts - Options for request * @param {credential.push_service} opts.type - * Credential type, one of "gcm" or "apn" * @param {string} [opts.friendlyName] - Friendly name for stored credential * @param {string} [opts.certificate] - * [APN only] URL encoded representation of the certificate, e. * @param {string} [opts.privateKey] - * [APN only] URL encoded representation of the private key, e. * @param {boolean} [opts.sandbox] - * [APN only] use this credential for sending to production or sandbox APNs * @param {string} [opts.apiKey] - * [GCM only] This is the "API key" for project from Google Developer console for your GCM Service application credential * @param {string} [opts.secret] - The secret * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialListInstance.create = function create(opts, callback) { if (_.isUndefined(opts)) { throw new Error('Required parameter "opts" missing.'); } if (_.isUndefined(opts.type)) { throw new Error('Required parameter "opts.type" missing.'); } var deferred = Q.defer(); var data = values.of({ 'Type': _.get(opts, 'type'), 'FriendlyName': _.get(opts, 'friendlyName'), 'Certificate': _.get(opts, 'certificate'), 'PrivateKey': _.get(opts, 'privateKey'), 'Sandbox': serialize.bool(_.get(opts, 'sandbox')), 'ApiKey': _.get(opts, 'apiKey'), 'Secret': _.get(opts, 'secret') }); var promise = this._version.create({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new CredentialInstance(this._version, payload, this._solution.sid)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Constructs a credential * * @param {string} sid - The sid * * @returns {Twilio.Chat.V1.CredentialContext} */ /* jshint ignore:end */ CredentialListInstance.get = function get(sid) { return new CredentialContext(this._version, sid); }; return CredentialListInstance; }; /* jshint ignore:start */ /** * Initialize the CredentialPage * * @param {V1} version - Version of the resource * @param {Response<string>} response - Response from the API * @param {CredentialSolution} solution - Path solution * * @returns CredentialPage */ /* jshint ignore:end */ CredentialPage = function CredentialPage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); }; _.extend(CredentialPage.prototype, Page.prototype); CredentialPage.prototype.constructor = CredentialPage; /* jshint ignore:start */ /** * Build an instance of CredentialInstance * * @param {CredentialPayload} payload - Payload response from the API * * @returns CredentialInstance */ /* jshint ignore:end */ CredentialPage.prototype.getInstance = function getInstance(payload) { return new CredentialInstance(this._version, payload); }; /* jshint ignore:start */ /** * Initialize the CredentialContext * * @property {string} sid - * A 34 character string that uniquely identifies this resource. * @property {string} accountSid - * The unique id of the Account[/console] responsible for this resource. * @property {string} friendlyName - The human-readable name of this resource. * @property {credential.push_service} type - * Indicates which push notifications service this credential is for - either gcm or apn * @property {string} sandbox - * [APN only] true when this resource should use the sandbox APN service. * @property {Date} dateCreated - The date that this resource was created. * @property {Date} dateUpdated - The date that this resource was last updated. * @property {string} url - An absolute URL for this credential resource. * * @param {V1} version - Version of the resource * @param {CredentialPayload} payload - The instance payload * @param {sid} sid - The sid */ /* jshint ignore:end */ CredentialInstance = function CredentialInstance(version, payload, sid) { this._version = version; // Marshaled Properties this.sid = payload.sid; // jshint ignore:line this.accountSid = payload.account_sid; // jshint ignore:line this.friendlyName = payload.friendly_name; // jshint ignore:line this.type = payload.type; // jshint ignore:line this.sandbox = payload.sandbox; // jshint ignore:line this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line this.url = payload.url; // jshint ignore:line // Context this._context = undefined; this._solution = {sid: sid || this.sid, }; }; Object.defineProperty(CredentialInstance.prototype, '_proxy', { get: function() { if (!this._context) { this._context = new CredentialContext(this._version, this._solution.sid); } return this._context; } }); /* jshint ignore:start */ /** * fetch a CredentialInstance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialInstance.prototype.fetch = function fetch(callback) { return this._proxy.fetch(callback); }; /* jshint ignore:start */ /** * update a CredentialInstance * * @param {object} [opts] - Options for request * @param {string} [opts.friendlyName] - Friendly name for stored credential * @param {string} [opts.certificate] - * [APN only] URL encoded representation of the certificate, e. * @param {string} [opts.privateKey] - * [APN only] URL encoded representation of the private key, e. * @param {boolean} [opts.sandbox] - * [APN only] use this credential for sending to production or sandbox APNs * @param {string} [opts.apiKey] - * [GCM only] This is the "API key" for project from Google Developer console for your GCM Service application credential * @param {string} [opts.secret] - The secret * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialInstance.prototype.update = function update(opts, callback) { return this._proxy.update(opts, callback); }; /* jshint ignore:start */ /** * remove a CredentialInstance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialInstance.prototype.remove = function remove(callback) { return this._proxy.remove(callback); }; /* jshint ignore:start */ /** * Produce a plain JSON object version of the CredentialInstance for serialization. * Removes any circular references in the object. * * @returns Object */ /* jshint ignore:end */ CredentialInstance.prototype.toJSON = function toJSON() { let clone = {}; _.forOwn(this, function(value, key) { if (!_.startsWith(key, '_') && ! _.isFunction(value)) { clone[key] = value; } }); return clone; }; /* jshint ignore:start */ /** * Initialize the CredentialContext * * @param {V1} version - Version of the resource * @param {sid} sid - The sid */ /* jshint ignore:end */ CredentialContext = function CredentialContext(version, sid) { this._version = version; // Path Solution this._solution = {sid: sid, }; this._uri = _.template( '/Credentials/<%= sid %>' // jshint ignore:line )(this._solution); }; /* jshint ignore:start */ /** * fetch a CredentialInstance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialContext.prototype.fetch = function fetch(callback) { var deferred = Q.defer(); var promise = this._version.fetch({uri: this._uri, method: 'GET'}); promise = promise.then(function(payload) { deferred.resolve(new CredentialInstance(this._version, payload, this._solution.sid)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * update a CredentialInstance * * @param {object} [opts] - Options for request * @param {string} [opts.friendlyName] - Friendly name for stored credential * @param {string} [opts.certificate] - * [APN only] URL encoded representation of the certificate, e. * @param {string} [opts.privateKey] - * [APN only] URL encoded representation of the private key, e. * @param {boolean} [opts.sandbox] - * [APN only] use this credential for sending to production or sandbox APNs * @param {string} [opts.apiKey] - * [GCM only] This is the "API key" for project from Google Developer console for your GCM Service application credential * @param {string} [opts.secret] - The secret * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialContext.prototype.update = function update(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'FriendlyName': _.get(opts, 'friendlyName'), 'Certificate': _.get(opts, 'certificate'), 'PrivateKey': _.get(opts, 'privateKey'), 'Sandbox': serialize.bool(_.get(opts, 'sandbox')), 'ApiKey': _.get(opts, 'apiKey'), 'Secret': _.get(opts, 'secret') }); var promise = this._version.update({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new CredentialInstance(this._version, payload, this._solution.sid)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * remove a CredentialInstance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed CredentialInstance */ /* jshint ignore:end */ CredentialContext.prototype.remove = function remove(callback) { var deferred = Q.defer(); var promise = this._version.remove({uri: this._uri, method: 'DELETE'}); promise = promise.then(function(payload) { deferred.resolve(payload); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; module.exports = { CredentialList: CredentialList, CredentialPage: CredentialPage, CredentialInstance: CredentialInstance, CredentialContext: CredentialContext };
// Inclusion de Mongoose var mongoose = require('../libs/mongoose').mongoose; var Schema = require('../libs/mongoose').Schema; var crypto = require('crypto'); var log = require('../libs/log')(module); var validator = require('validator'); var Mail = new Schema({ value: { type: String, required: true }, kind: { type: String, required: false } }, {_id: false}); var MailModel = mongoose.model('Mail', Mail); module.exports.MailModel = MailModel;
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ /** * BrambleExtensionLoader allows optional enabling/disabling of extensions * based on query string params. */ define(function (require, exports, module) { "use strict"; var basePath = PathUtils.directory(window.location.href); /** * We have a set of defaults we load if not instructed to do otherwise * via the disableExtensions query param. These live in src/extensions/default/* */ var brambleDefaultExtensions = [ "CSSCodeHints", "HTMLCodeHints", "JavaScriptCodeHints", "InlineColorEditor", "JavaScriptQuickEdit", "QuickOpenCSS", "QuickOpenHTML", "QuickOpenJavaScript", "QuickView", "UrlCodeHints", // Custom extensions we want loaded by default "bramble", "Autosave", "brackets-paste-and-indent" ]; /** * There are some Brackets default extensions that we don't load * but which a user might want to enable (note: not all the defaults * they ship will work in a browser, so they aren't all here). We * support loading these below via the enableExtensions param. */ var bracketsDefaultExtensions = [ "SVGCodeHints", "HtmlEntityCodeHints", "LESSSupport", "CloseOthers", "InlineTimingFunctionEditor", "WebPlatformDocs", "CodeFolding", "JSLint", "QuickOpenCSS", "RecentProjects" ]; /** * Other extensions we've tested and deemed useful in the Bramble context. * These live in src/extensions/extra/* and are usually submodules. If you * add a new extension there, update this array also. You can have this load * by adding the extension name to the enableExtensions query param. */ var extraExtensions = [ "brackets-cdn-suggestions", // https://github.com/szdc/brackets-cdn-suggestions "ImageUrlCodeHints", "HTMLHinter", "MDNDocs" ]; // Disable any extensions we found on the query string's disableExtensions param function _processDefaults(disableExtensions) { if(disableExtensions) { disableExtensions.split(",").forEach(function (ext) { ext = ext.trim(); var idx = brambleDefaultExtensions.indexOf(ext); if (idx > -1) { console.log('[Brackets] Disabling default extension `' + ext + '`'); brambleDefaultExtensions.splice(idx, 1); } }); } return brambleDefaultExtensions.map(function (ext) { return { name: ext, path: basePath + "extensions/default/" + ext }; }); } // Add any extra extensions we found on the query string's enableExtensions param function _processExtras(enableExtensions) { var extras = []; if(enableExtensions) { enableExtensions.split(",").forEach(function (ext) { ext = ext.trim(); // Extension is in src/extensions/extra/* if (extraExtensions.indexOf(ext) > -1) { console.log('[Brackets] Loading additional extension `' + ext + '`'); extras.push({ name: ext, path: basePath + "extensions/extra/" + ext }); } // Extension is in src/extensions/default/* (we don't enable all Brackets exts) if (bracketsDefaultExtensions.indexOf(ext) > -1) { console.log('[Brackets] Loading additional extension `' + ext + '`'); extras.push({ name: ext, path: basePath + "extensions/default/" + ext }); } }); } return extras; } exports.getExtensionList = function(params) { return [] .concat(_processDefaults(params.get("disableExtensions"))) .concat(_processExtras(params.get("enableExtensions"))); }; });
var path = require('path'); var logger = require('../util/logger')('COMMAND'); /* * Each file included in this folder (except `index.js`) is a command and must export the following object * { * execute: (...args) => void | command itself * } * * The execute function should not have much logic */ /* Each and every command defined, including commands used in before/after */ var commandNames = [ 'genConfig', 'openReport', 'reference', 'report', 'test', 'approve' ]; /* Commands that are only exposed to higher levels */ var exposedCommandNames = [ 'genConfig', 'reference', 'test', 'openReport', 'approve' ]; var quietLogging; /* Used to convert an array of objects {name, execute} to a unique object {[name]: execute} */ function toObjectReducer (object, command) { object[command.name] = command.execute; return object; } var commands = commandNames .map(function requireCommand (commandName) { return { name: commandName, commandDefinition: require(path.join(__dirname, commandName)) }; }) .map(function definitionToExecution (command) { return { name: command.name, execute: function execute (config, quietLogging) { if (!quietLogging) { logger.info('Executing core for `' + command.name + '`'); } var promise = command.commandDefinition.execute(config, quietLogging); // If the command didn't return a promise, assume it resolved already if (!promise) { logger.error('Resolved already:' + command.name); promise = Promise.resolve(); } // Do the catch separately or the main runner // won't be able to catch it a second time promise.catch(function (error) { logger.error('Command `' + command.name + '` ended with an error'); logger.error(error); }); return promise.then(function (result) { if (!quietLogging) { logger.success('Command `' + command.name + '` sucessfully executed'); } return result; }); } }; }) .reduce(toObjectReducer, {}); var exposedCommands = exposedCommandNames .filter(function commandIsDefined (commandName) { return commands.hasOwnProperty(commandName); }) .map(function (commandName) { return { name: commandName, execute: commands[commandName] }; }) .reduce(toObjectReducer, {}); function execute (commandName, config, quiet) { quietLogging = quiet; if (!exposedCommands.hasOwnProperty(commandName)) { if (commandName.charAt(0) === '_' && commands.hasOwnProperty(commandName.substring(1))) { commandName = commandName.substring(1); } else { throw new Error('The command `' + commandName + '` is not exposed publicly.'); } } return commands[commandName](config, quietLogging); } module.exports = execute;
'use strict'; var gulp = require('gulp'), connect = require('connect'), livereload = require('gulp-livereload'), browserify = require('browserify'), watchify = require('watchify'), source = require('vinyl-source-stream'), less = require('gulp-less'), rubySass = require('gulp-ruby-sass'), plumber = require('gulp-plumber'), autoprefixer = require('gulp-autoprefixer'), cache = require('gulp-cache'), jshint = require('gulp-jshint'), uglify = require('gulp-uglify'), minifyHtml = require('gulp-minify-html'), size = require('gulp-size'), serveStatic = require('serve-static'), serveIndex = require('serve-index'); /* browserify */ gulp.task('browserify', function() { var sourceFile = './app/scripts/main.js', destFolder = './app/scripts/browserify/', destFile = 'main.js'; var bundler = browserify({ entries: sourceFile, cache: {}, packageCache: {}, fullPaths: true, debug: true }); var bundle = function() { return bundler .bundle() .on('error', function (err) { console.log(err); }) .pipe(source(destFile)) .pipe(gulp.dest(destFolder)); }; if(global.isWatching) { bundler = watchify(bundler); bundler.on('update', bundle); } return bundle(); }); /* styles */ gulp.task('styles', function () { return gulp.src('app/styles/main.less') .pipe(plumber()) .pipe(less({ style: 'expanded', precision: 10 })) .pipe(autoprefixer({browsers: ['last 1 version']})) .pipe(gulp.dest('app/styles')); }); /* js hint */ gulp.task('jshint', function () { return gulp.src('app/scripts/**/*.js') .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); /* extras */ gulp.task('extras', function () { return gulp.src([ 'node_modules/apache-server-configs/dist/.htaccess' ], { dot: true }).pipe(gulp.dest('dist')); }); /* connect */ gulp.task('connect', ['styles'], function () { var app = connect() .use(require('connect-livereload')({port: 35729})) .use(serveStatic('app')) .use('/bower_components', serveStatic('bower_components')) .use(serveIndex('app')); require('http').createServer(app) .listen(9000) .on('listening', function () { console.log('Started connect web server on http://localhost:9000'); }); }); /* serve */ gulp.task('serve', ['watch'], function () { gulp.start('browserify'); require('opn')('http://localhost:9000'); }); /* copy bower components */ gulp.task('bower', function () { var paths = { js: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/mithril/mithril.min.js' ] } gulp.src(paths.js) .pipe(gulp.dest('app/scripts')); }); /* watch */ gulp.task('watch', ['connect', 'bower'], function () { livereload.listen(); gulp.watch([ 'app/*.html', 'app/styles/**/*.css', 'app/scripts/**/*.js' ]).on('change', livereload.changed); gulp.watch('app/styles/**/*.less', ['styles']); gulp.watch('app/scripts/**/*.js', ['browserify']); }); /* build */ gulp.task('build', ['styles','extras', 'bower'], function () { gulp.start('browserify'); /* app */ gulp.src('app/**/*') .pipe(gulp.dest('dist')) .pipe(size({title: 'build', gzip: true})); /* html */ var opts = {comments:true,spare:true, quotes: true}; gulp.src('dist/*.html') .pipe(minifyHtml(opts)) .pipe(gulp.dest('dist')); }); /* default */ gulp.task('default', function () { gulp.start('serve'); });
define(['angular', 'given', 'util'], function(angular, given, util) { 'use strict'; describe('services', function() { describe('MyModel service', function() { var $injector, MyModel; before(function() { return given.servicesForLoopBackApp( { models: { MyModel: { name: { type: String, required: true } } } }) .then(function(createInjector) { $injector = createInjector(); MyModel = $injector.get('MyModel'); }); }); it('has loopback sdk methods including aliases', function() { var methodNames = Object.keys(MyModel); console.log('methods', methodNames); expect(methodNames).to.include.members([ 'create', 'updateOrCreate', 'upsert', //'exists', 'findById', 'find', 'findOne', 'destroyById', 'deleteById', 'removeById', //'count', //'prototype$updateAttributes' ]); }); it('has a custom `all` action returning array', function() { return MyModel.all().then( function(list) { expect(list).to.have.property('length', 0); }, util.throwHttpError ); }); it('has a custom `find` action returning array', function() { return MyModel.find().then( function(list) { expect(list).to.have.property('length', 0); }, util.throwHttpError ); }); it('can create new resource', function() { var obj; return MyModel.create({ name: 'new' }).then(function(o) { obj = o; expect(obj).to.have.property('name', 'new'); }) .then(function() { return MyModel.findById(obj.id).then( function(found) { expect(found).to.have.property('name', obj.property); }, util.throwHttpError); }); }); it('can save a new resource', function() { //var obj = MyModel.new(); //obj.name = 'new-saved'; var obj = {name: 'new-saved'}; return MyModel.put(obj).then( function(res) { obj = res; expect(res.id).to.not.equal(undefined); }, util.throwHttpError ) .then(function() { return MyModel.find( { filter: { where: { name: obj.name } } } ).then( function(found) { expect(found).to.have.length(1); expect(found[0].id).to.equal(obj.id); }, util.throwHttpError ); }); }); it('can save an existing resource', function() { var obj; return MyModel.create({ name: 'create-save' }) .then( function(res) { obj = res; obj.updated = true; return obj.save().then(function(){}, util.throwHttpError); }, util.throwHttpError ) .then(function() { return MyModel.find( { filter: { where: { name: obj.name } } } ).then( function(found) { expect(found).to.have.length(1); expect(found[0].id).to.equal(obj.id); expect(found[0].updated).to.equal(true); }, util.throwHttpError ); }); }); }); // describe('$resource for model with funky name', function() { // var $injector; // before(function() { // return given.servicesForLoopBackApp( // { // models: { // 'lower-case-not-an-identifier': {} // } // }) // .then(function(createInjector) { // $injector = createInjector(); // }); // }); // // it('has a factory name that starts with upper-case', function() { // expect($injector.has('Lower-case-not-an-identifier')).to.equal(true); // }); // }); // // describe('with authentication using custom User model', function() { // var getNew, createInjector, $injector, Customer; // before(function setupLoopBackService() { // return given.servicesForLoopBackApp( // { // name: 'with authentication', // models: { // Customer: { // options: { // base: 'User', // relations: { // accessTokens: { // model: 'AccessToken', // type: 'hasMany', // foreignKey: 'userId' // } // } // } // }, // product: { // properties: { // model: String // } // } // }, // enableAuth: true // }) // .then(function(_createInjector) { // createInjector = _createInjector; // getNew = function(name) { // return createInjector().get(name); // }; // }); // }); // // beforeEach(function setupTestEnv() { // localStorage.clear(); // sessionStorage.clear(); // $injector = createInjector(); // Customer = $injector.get('Customer'); // }); // // it('returns error for an unauthorized request', function() { // return Customer.query().$promise // .then(function() { // throw new Error('User.query was supposed to fail.'); // }, function(res) { // expect(res.status).to.equal(401); // }); // }); // // it('sends the authentication token when a user is logged in', function(){ // return givenLoggedInUser('user@example.com') // .then(function(accessToken) { // return Customer.get({ id: accessToken.userId }).$promise; // }) // .then(function(user) { // expect(user.email).to.equal('user@example.com'); // }) // .catch(util.throwHttpError); // }); // // it('clears authentication data on logout', function() { // return givenLoggedInUser() // .then(function() { // return Customer.logout().$promise; // }) // .then(function() { // // NOTE(bajtos) This test is checking the LoopBackAuth.accessToken // // property, because any HTTP request will fail regardless of the // // Authorization header value, since the token was invalidated on // // the server side too. // var auth = $injector.get('LoopBackAuth'); // expect(auth.accessTokenId, 'accessTokenId').to.equal(null); // expect(auth.currentUserId, 'currentUserId').to.equal(null); // // // Check that localStorage was cleared too. // auth = getNew('LoopBackAuth'); // expect(auth.accessTokenId, 'stored accessTokenId').to.equal(null); // expect(auth.currentUserId, 'stored currentUserId').to.equal(null); // }) // .catch(util.throwHttpError); // }); // // it('returns stub 401 for User.getCurrent when not logged in', function(){ // return Customer.getCurrent().$promise // .then(function() { // throw new Error('User.getCurrent() was supposed to fail.'); // }, function(res) { // if (res instanceof Error) throw res; // expect(res.status).to.equal(401); // // check the response is a stub not coming from the server // if (res.headers('content-type') != null) { // throw new Error('Expected a stub response, got a real one'); // } // }); // }); // // it('persists accessToken and currentUserId', function() { // return givenLoggedInUser('persisted@example.com') // .then(function() { // sessionStorage.clear(); // simulate browser restart // return getNew('Customer').getCurrent().$promise; // }) // .then(function(user) { // expect(user.email).to.equal('persisted@example.com'); // }) // .catch(util.throwHttpError); // }); // // it('persists data in sessionStorage when rememberMe=false', function() { // return givenLoggedInUser(null, { rememberMe: false }) // .then(function() { // localStorage.clear(); // ensure data is not stored in localStorage // return getNew('Customer').getCurrent().$promise; // }) // .then(function() { // expect(true); // no-op, test passed // }) // .catch(util.throwHttpError); // }); // // it('adds getCurrent() to User model only', function() { // var Product = $injector.get('Product'); // expect(Product.getCurrent).to.equal(undefined); // }); // // it('sends User.login with include=user to by default', function() { // return givenLoggedInUser() // .then(function(token) { // expect(token.user).to.be.an('object'); // }); // }); // // it('can request User.login without including user data', function() { // return givenLoggedInUser(null, { include: null }) // .then(function(token) { // expect(token.user).to.equal(undefined); // }); // }); // // it('returns null as initial cached user', function() { // var value = Customer.getCachedCurrent(); // expect(value).to.equal(null); // }); // // it('caches user data from User.login response', function() { // return givenLoggedInUser() // .then(function(token) { // var value = Customer.getCachedCurrent(); // expect(value).to.be.instanceof(Customer); // expect(value).to.have.property('email', token.user.email); // }); // }); // // it('caches data from User.getCurrent response', function() { // return givenLoggedInUser() // .then(function() { // // clear the data stored by login // $injector.get('LoopBackAuth').currentUserData = null; // return Customer.getCurrent().$promise; // }) // .then(function(user) { // var value = Customer.getCachedCurrent(); // expect(value).to.be.instanceof(Customer); // expect(value).to.have.property('email', user.email); // }); // }); // // it('clears cached user on logout', function() { // return givenLoggedInUser() // .then(function() { // return Customer.logout().$promise; // }) // .then(function() { // var value = Customer.getCachedCurrent(); // expect(value).to.equal(null); // }); // }); // // it('provides User.isAuthenticated method', function() { // return givenLoggedInUser() // .then(function() { // expect(Customer.isAuthenticated()).to.equal(true); // }); // }); // // it('provides User.getCurrentId method', function () { // return givenLoggedInUser() // .then(function(token) { // expect(Customer.getCurrentId()).to.equal(token.userId); // }); // }); // // var idCounter = 0; // function givenLoggedInUser(email, loginParams) { // var credentials = { // email: email || 'user-' + (++idCounter) + '@example.com', // password: 'a-password' // }; // // return Customer.create(credentials).$promise // .then(function() { // return Customer.login(loginParams || {}, credentials).$promise; // }); // } // }); // // describe('with authentication using built-in User model', function() { // var $injector, User; // before(function setupLoopBackService() { // return given.servicesForLoopBackApp( // { // name: 'with authentication', // models: { // User: { // // use the built-in User model // }, // }, // enableAuth: true // }) // .then(function(createInjector) { // $injector = createInjector(); // User = $injector.get('User'); // }); // }); // // it('adds auth-related methods to the User model', function() { // var methodNames = Object.keys(User); // console.log('User methods', methodNames); // expect(methodNames).to.include.members([ // 'getCachedCurrent', // 'isAuthenticated', // 'getCurrentId', // ]); // }); // }); // // describe('for models with hasAndBelongsToMany relations', function() { // var $injector, Product, Category, testData; // before(function() { // return given.servicesForLoopBackApp( // { // models: { // Product: { // properties: { name: 'string' }, // options: { // relations: { // categories: { // model: 'Category', // type: 'hasAndBelongsToMany' // } // } // } // }, // Category: { // properties: { name: 'string' }, // options: { // relations: { // products: { // model: 'Product', // type: 'hasAndBelongsToMany' // } // } // } // } // }, // setupFn: (function(app, cb) { // /*globals debug:true */ // app.models.Product.create({ name: 'p1' }, function(err, prod) { // if (err) return cb(err); // debug('Created product', prod); // // prod.categories.create({ name: 'c1' }, function(err, cat) { // if (err) return cb(err); // debug('Created category', cat); // // prod.categories(true, function(err, list) { // if (err) return cb(err); // debug('Categories of product', list); // // cb(null, { // product: prod, // category: cat // }); // }); // }); // }); // }).toString() // }) // .then(function(createInjector) { // $injector = createInjector(); // Product = $injector.get('Product'); // Category = $injector.get('Category'); // testData = $injector.get('testData'); // }); // }); // // it('provides scope methods', function() { // expect(Object.keys(Product), 'Product properties') // .to.contain('categories'); // expect(Object.keys(Product.categories),'Product.categories properties') // .to.include.members([ // 'create', // 'destroyAll', // // new in loopback 2.0 // 'destroyById', // 'findById', // 'link', // 'unlink', // 'updateById' // ]); // }); // // it('gets related models with correct prototype', function() { // var list = Product.categories({ id: testData.product.id }); // return list.$promise.then(function() { // // eql does not work for arrays with objects correctly :( // expect(list).to.have.length(1); // expect(list[0]).to.eql(new Category(testData.category)); // }); // }); // // it('creates a related model', function() { // var cat = Product.categories.create( // { id: testData.product.id }, // { name: 'another-cat' }); // return cat.$promise // .then(function() { // expect(cat).to.be.an.instanceof(Category); // expect(cat).to.have.property('name', 'another-cat'); // }) // .then(function() { // var list = Product.categories({ id: testData.product.id }); // return list.$promise.then(function() { // var names = list.map(function(c) { return c.name; }); // expect(names).to.eql([testData.category.name, cat.name]); // }); // }); // }); // // // Skipped due to strongloop/loopback-datasource-juggler#95 // it.skip('removes all related models', function() { // return Product.categories.destroyAll({ id: testData.product.id }) // .$promise // .then(function() { // var list = Product.categories({ id: testData.product.id }); // return list.$promise.then(function() { // expect(list, 'product categories').to.have.length(0); // }); // }) // .then(function() { // var all = Product.find({ filter: true }); // return all.$promise // .then(function() { // expect(all, 'all categories').to.have.length(0); // }); // }); // }); // }); // // describe('for models with belongsTo relation', function() { // var $injector, Town, Country, testData; // before(function() { // return given.servicesForLoopBackApp( // { // models: { // Town: { // properties: { name: 'string' }, // options: { // relations: { // country: { // model: 'Country', // type: 'belongsTo' // } // } // } // }, // Country: { // properties: { name: 'string' }, // options: { // relations: { // towns: { // model: 'Town', // type: 'hasMany' // } // } // } // } // }, // setupFn: (function(app, cb) { // /*globals debug:true */ // app.models.Country.create( // { name: 'a-country' }, // function(err, country) { // if (err) return cb(err); // debug('Created country', country); // // country.towns.create({ name: 'a-town' }, // function(err, town) { // if (err) return cb(err); // debug('Created town', town); // // town.country(true, function(err, res) { // if (err) return cb(err); // debug('Country of the town', res); // // cb(null, { // country: country, // town: town // }); // }); // } // ); // } // ); // }).toString() // }) // .then(function(createInjector) { // $injector = createInjector(); // Town = $injector.get('Town'); // Country = $injector.get('Country'); // testData = $injector.get('testData'); // }); // }); // // it('provides scope methods', function() { // expect(Object.keys(Town), 'Town properties') // .to.contain('country'); // }); // // it('gets the related model with the correct prototype', function() { // var country = Town.country({ id: testData.town.id }); // return country.$promise.then(function() { // expect(country).to.be.instanceof(Country); // for (var k in testData.country) { // expect(country[k], 'country.' + k).to.equal(testData.country[k]); // } // }); // }); // }); }); });
'use strict'; var MongoClient = require('mongodb').MongoClient var cheerio = require('cheerio'); var Q = require('q'); var _ = require('lodash'); var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/prerender'; var db = Q.denodeify(MongoClient.connect)(mongoUri); var pages = db.then(function (db) { return Q.denodeify(db.collection.bind(db))('pages'); }); module.exports = { beforePhantomRequest: function(req, res, next) { var uri = uriFromPath(req.url); if (req.method === 'DELETE') { del(uri).then(function () { res.send(200, uri + ' deleted.'); }).catch(reportAndProceed(next)); } else if (req.method === 'POST') { // Just pass through so that Phantom will render the page next(); } else if (req.method === 'GET') { get(uri).then(function (document) { console.log('Serving from cache:', uri); _.each(document.headers, function (value, key) { res.setHeader(key, value); }); res.send(document.statusCode, document.content); }).catch(reportAndProceed(next)); } else { res.send(400, 'Only GET, POST and DELETE methods are supported.'); } }, afterPhantomRequest: function(req, res, next) { var uri = uriFromPath(req.url); var original = originalHead(req); var overrides = headOverrides(req); var head = _.merge({}, original, overrides); var document = { content: req.prerender.documentHTML, statusCode: head.statusCode, headers: head.headers, originalHead: original, overrides: overrides }; set(uri, document).then(function () { console.log('Saved:', uri); _.each(document.headers, function (value, key) { res.setHeader(key, value); }); res.send(document.statusCode, document.content); }).catch(reportAndProceed(next)); } }; function uriFromPath (path) { return path.replace(/^\//, ''); } function originalHead (req) { return { statusCode: req.prerender.statusCode, headers: req.prerender.headers.reduce(function (headers, header) { headers[header.name] = header.value; return headers; }, {}) }; } function headOverrides (req) { var $ = cheerio.load(req.prerender.documentHTML); var headersOverride = {}; $('meta[name="prerender-header"][content]').each(function (i, el) { var content = el.attribs.content.match(/([^:]+):\s*(.*)\s*/); var name = content[1]; var value = content[2]; headersOverride[name] = value; }); var overriden = { headers: headersOverride }; var statusCodeOverride = $('meta[name="prerender-status-code"][content]') .last() .attr('content'); if (statusCodeOverride) { overriden.statusCode = parseInt(statusCodeOverride, 10); } return overriden; } function get (uri) { return pages.then(function (collection) { var findOne = Q.denodeify(collection.findOne.bind(collection)); return findOne({ uri: uri }).then(function (item) { return item || Q.reject(uri + ' not found'); }); }); } function set (uri, value) { return pages.then(function (collection) { var update = Q.denodeify(collection.update.bind(collection)); var query = { uri: uri }; var options = { upsert: true }; var document = _.merge({ uri: uri, date: new Date() }, value); return update(query, document, options); }); } function del (uri) { return pages.then(function (collection) { var findAndRemove = Q.denodeify(collection.findAndRemove.bind(collection)); return findAndRemove({ uri: uri }); }); } function reportAndProceed (next) { return function (error) { console.error(error.stack || error); next(); }; }
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import MuseUI from 'muse-ui' import 'muse-ui/dist/muse-ui.css' import store from './store/index.js' import VueClipboard from 'vue-clipboard2' import infiniteScroll from 'vue-infinite-scroll' Vue.use(MuseUI); Vue.use(VueClipboard); Vue.use(infiniteScroll); Vue.config.productionTip = false; new Vue({ el: '#app', router, store, template: '<App/>', components: {App}, methods: { // 获取当前路由名称 getActiveRoute: function () { return this.$route.name }, // 提交当前路由名称 commitActiveRoute: function () { var activeRoute = this.getActiveRoute(); this.$store.commit('ACTIVE_ROUTE_CHANGE', { 'activeRoute': activeRoute }) }, }, mounted: function () { // 初始提交路由名称 this.commitActiveRoute(); } });
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({other:"Outro",classBreaks:"\u00e3_Class Breaks_____________\u00c7",classBreaksNormFieldAsPercent:"\u00e3_Class Breaks with normalizationField as percent_________________________\u00c7",heatmap:"\u00e3_Heatmap_______________\u00c7",simple:"\u00e3_Simple_____________\u00c7",simpleNormFieldAsPercent:"\u00e3_Simple with normalizationField as percent______________________\u00c7",uniqueValues:"\u00e3_Unique Values______________\u00c7",uniqueValuesNormFieldAsPercent:"\u00e3_Unique Values with normalizationField as percent_________________________\u00c7", normFieldLabel:"\u00e3_{expression1} divided by {expression2}____________________\u00c7",normFieldLabelAsPercent:"\u00e3_Percentage of {expression1} and {expression2}________________________\u00c7",competingFields:"categorias concorrentes",mostCommon:"{expression} mais comum",basicSummary:"Resumo b\u00e1sico",orderedListOfValues:"Lista ordenada de valores",sumOfCategories:"Soma das categorias",listOfCategories:"Lista de categorias",predominantCategoryWithTotal:"Categoria predominante com total",predominantCategoryWithTotalAndStrength:"Categoria predominante com total e for\u00e7a", predominantCategoryWithChart:"Categoria predominante com gr\u00e1fico",predominantCategory:"Categoria predominante",strengthOfPredominance:"For\u00e7a da predomin\u00e2ncia",marginOfVictory:"Margem de \u00eaxito",predominantCategoryValue:"Valor da categoria predominante",predominantCategoryContent:"A categoria mais comum nesta \u00e1rea \u00e9 {expression}.",predominantCategoryValueContent:"A categoria mais comum nesta \u00e1rea \u00e9 {expression1} e tem um valor de {expression2}.",predominantCategoryValueMarginContent:"{expression1} tem um valor de {expression2}, que vence todas as outras \x3cb\x3ecategorias\x3c/b\x3e por uma margem de {expression3} pontos percentuais.", predominantCategoryStrengthContent:"Com um valor de {expression1}, {expression2} \u00e9 a categoria mais comum de {title} nesta \u00e1rea, que \u00e9 {expression3} de todas as categorias combinadas.",predominantCategoryTotalContent:"Com um valor de {expression1}, {expression2} \u00e9 a categoria mais comum de todas as {expression3} {title} nesta \u00e1rea.",predominantCategoryTotalStrengthContent:"Com um valor de {expression1}, {expression2} \u00e9 a categoria mais comum nesta \u00e1rea, que perfaz {expression3} de todas as {expression4} {title}.", ageInfo_years:"Idade, em anos, de {startTime} a {endTime}",ageInfo_months:"Idade, em meses, de {startTime} a {endTime}",ageInfo_days:"Idade, em dias, de {startTime} a {endTime}",ageInfo_hours:"Idade, em horas, de {startTime} a {endTime}",ageInfo_minutes:"Idade, em minutos, de {startTime} a {endTime}",ageInfo_seconds:"Idade, em segundos, de {startTime} a {endTime}",relationship:{legendTitle:"Relacionamento",HL:"Alto - Baixo",HH:"Alto - Alto",LL:"Baixo - Caixo",LH:"Baixo - Alto",HM:"Alto - M\u00e9dio", ML:"M\u00e9dio - Baixo",MM:"M\u00e9dio - M\u00e9dio",MH:"M\u00e9dio - Alto",LM:"Baixo - M\u00e9dio",HM1:"High - Mild",HM2:"High - Medium",M2L:"Medium - Low",M2M1:"M\u00e9dio - Ligeiro",M2M2:"M\u00e9dio - M\u00e9dio",M2H:"Medium - High",M1L:"Mild - Low",M1M1:"Ligeiro - Ligeiro",M1M2:"Ligeiro - M\u00e9dio",M1H:"Mild - High",LM1:"Low - Mild",LM2:"Low - Medium"}});
export default (function (thing, encoding, name) { if (Buffer.isBuffer(thing)) { return thing; } else if (typeof thing === 'string') { return Buffer.from(thing, encoding); } else if (ArrayBuffer.isView(thing)) { return Buffer.from(thing.buffer); } else { throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView'); } });
process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', function (data) { input_stdin += data; }); process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); function readLine() { return input_stdin_array[input_currentline++]; } /////////////// ignore above this line //////////////////// function main() { var n = parseInt(readLine()); arr = readLine().split(' '); arr = arr.map(Number); var sum = arr.reduce(function (previousValue, currentValue) { return previousValue + currentValue; }); process.stdout.write(sum); }
/* global test, expect, jest */ import { mapStateToProps, mapDispatchToProps } from "../../container/MenuApp"; test("Should map state to props", () => { expect(mapStateToProps({toto: "toto"})).toEqual({toto: "toto"}); }); test("Should map dispatch to props", () => { const mockedDispatch = jest.fn(); mapDispatchToProps(mockedDispatch).onItemClicked("toto"); expect(mockedDispatch.mock.calls.length).toBe(2); mapDispatchToProps(mockedDispatch).onOutsideLayerClicked("toto"); expect(mockedDispatch.mock.calls.length).toBe(3); });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M7.01 9.49L11 6.7V5.3l-1.35-.95c-1.82.57-3.37 1.77-4.38 3.34l.39 1.34 1.35.46zM5.01 10.92l-1 .73c0 .12-.01.23-.01.35 0 1.99.73 3.81 1.94 5.21l1.14-.1.79-1.37L6.4 11.4l-1.39-.48zM18.34 9.03l.39-1.34c-1.01-1.57-2.55-2.77-4.38-3.34L13 5.3v1.4l3.99 2.79 1.35-.46zM8.37 10.98L9.73 15h4.54l1.36-4.02L12 8.44zM9.45 17l-.64 1.11.69 1.49c.79.25 1.63.4 2.5.4s1.71-.15 2.5-.41l.69-1.49-.64-1.1h-5.1zM19.98 11.65l-1-.73-1.38.48-1.46 4.34.79 1.37 1.14.1C19.27 15.81 20 13.99 20 12c0-.12-.01-.23-.02-.35z", opacity: ".3" }), h("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 3.3l1.35-.95c1.82.56 3.37 1.76 4.38 3.34l-.39 1.34-1.35.46L13 6.7V5.3zm-3.35-.95L11 5.3v1.4L7.01 9.49l-1.35-.46-.39-1.34c1.01-1.57 2.56-2.77 4.38-3.34zM7.08 17.11l-1.14.1C4.73 15.81 4 13.99 4 12c0-.12.01-.23.02-.35l1-.73 1.38.48 1.46 4.34-.78 1.37zm7.42 2.48c-.79.26-1.63.41-2.5.41s-1.71-.15-2.5-.41l-.69-1.49.64-1.1h5.11l.64 1.11-.7 1.48zM14.27 15H9.73l-1.35-4.02L12 8.44l3.63 2.54L14.27 15zm3.79 2.21l-1.14-.1-.79-1.37 1.46-4.34 1.39-.47 1 .73c.01.11.02.22.02.34 0 1.99-.73 3.81-1.94 5.21z" })), 'SportsSoccerTwoTone');
var dataModule=function(n,t,i){var r=[],u=function(t){n.ajax({url:"api/activities/Search",contentType:"application/json",method:"POST",data:t,dataType:"json",success:function(n){i.updateDom(n)}})},f=function(n){var i=this;i.id=t.observable(n.Id);i.name=t.observable(n.Name)},e=function(){return r.length==0&&n.ajax({async:!1,url:"api/gamesystems",contentType:"application/json",method:"GET",dataType:"json",success:function(t){n.each(t,function(n,t){r.push(new f(t))})}}),r},s=function(t){n.ajax({url:"api/activities/Save",contentType:"application/json",method:"POST",data:t,dataType:"json",success:function(){window.location.replace("#/")}})},o=function(){u("")};return{init:o,getActivities:u,getConsoles:e}}(jQuery,ko,listActivitiesModule);dataModule.init(); //# sourceMappingURL=dataService.min.js.map
/* eslint quotes: 0 */ 'use strict'; // eslint-disable-line import('./src/calculator-app').then(({ default: app }) => { app.start('root', () => { console.log('-------Welcome to Calculator Example-------'); }); }).catch(console.error.bind(console));
'use strict'; /** * @ngdoc filter * @name myNewProjectApp.filter:myFilter * @function * @description * # myFilter * Filter in the myNewProjectApp. */ angular.module('myNewProjectApp') .filter('myFilter', function () { return function (input) { return 'myFilter filter: ' + input; }; });
'use strict'; describe('Controller: FindCtrl', function () { // load the controller's module beforeEach(module('realtalkApp')); var FindCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); FindCtrl = $controller('FindCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
// for jasmine-node support if (typeof process !== 'undefined' && process.title && process.title === 'node') { // detect node environment var Validator = require('./../src/validator'); } // only checks numeric, string, and undefined describe('email validation rule', function() { it('should pass with the email address: johndoe@gmail.com', function() { var validator = new Validator({ email: 'johndoe@gmail.com' }, { email: 'email' }); expect(validator.passes()).toBeTruthy(); }); it ('should fail with the email address: johndoe.gmail.com', function() { var validator = new Validator({ email: 'johndoe.gmail.com' }, { email: 'email' }); expect(validator.fails()).toBeTruthy(); }); it('should fail with the email address: johndoe@gmail', function() { var validator = new Validator({ email: 'johndoe@gmail' }, { email: 'email' }); expect(validator.fails()).toBeTruthy(); }); it('should fail when the email address contains whitespace only', function() { var validator = new Validator({ email: ' ' }, { email: 'email' }); expect(validator.fails()).toBeTruthy(); }); it('should pass when the field is an empty string', function() { var validator = new Validator({ email: '' }, { email: 'email' }); expect(validator.passes()).toBeTruthy(); }); it('should pass when the field does not exist', function() { var validator = new Validator({}, { email: 'email' }); expect(validator.passes()).toBeTruthy(); expect(validator.fails()).toBeFalsy(); }); });
var KIRIAPP = KIRIAPP || {}; KIRIAPP.score = {}; KIRIAPP.score.makeScore = function() { //-------------------------------------------------- var __ = function() {}; //-------------------------------------------------- var effect = function(elmentId, delay) { var el = document.getElementById(elmentId); el.style.opacity = 1; var timerId = setInterval(function() { el.style.opacity -= 0.03; if (el.style.opacity <= 0.1) { clearInterval(timerId); timerId = null; el.style.opacity = 0; } }, delay); }; var k1 = function() { effect("k", 10); }; var h1 = function() { effect("h", 10/2); }; var s1 = function() { effect("s", 10/4); }; var s2 = function() { effect("s", 10); }; var cl = function() { effect("cl", 10/4); }; var cr = function() { effect("cr", 10/4); }; //-------------------------------------------------- var bar0 = { tr1 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] }; var bar1 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] }; var bar2 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, __, h1, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] }; var bar3 = { tr1 : [k1, __, __, k1, __, __, __, __, __, k1, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, h1, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, s1, __, __, __, __] }; var bar4 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, h1, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] }; var bar5 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, h1, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, s2, __, __, __] }; var bar6 = { tr1 : [__, __, __, __, __, __, __, __, __, __, k1, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, h1, __, __, __, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, __, __, __, __, s1, __, __, __] }; var bar7 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, __, __, __, h1, __] , tr3 : [__, __, __, __, __, __, __, __, s2, __, __, __, __, __, __, __] , tr4 : [__, __, __, __, __, __, cl, __, __, __, __, __, __, cl, __, cl] , tr5 : [__, __, cr, __, __, cr, __, cr, __, __, __, __, __, __, cr, __] }; var bar8 = { tr1 : [k1, __, __, k1, __, __, __, __, __, __, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, h1, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, s2, __, __, __, __, __, s1, __] , tr4 : [__, __, __, __, __, __, cl, __, __, __, __, __, __, __, __, __] , tr5 : [__, __, cr, __, __, cr, __, cr, __, __, __, __, cr, __, __, __] }; var bar9 = { tr1 : [k1, __, __, k1, __, __, __, __, __, k1, __, __, __, __, __, __] , tr2 : [__, __, __, __, __, __, __, __, __, __, __, h1, __, __, __, __] , tr3 : [__, __, __, __, __, __, __, __, s2, __, __, __, __, __, s1, __] , tr4 : [__, __, __, __, __, __, cl, __, __, __, cl, __, __, __, __, __] , tr5 : [__, __, cr, __, __, cr, __, cr, __, __, __, __, __, __, __, __] }; //-------------------------------------------------- var score = [ bar1, bar2, bar1, bar3 , bar4, bar5, bar4, bar6 , bar7, bar8, bar7, bar9 , bar7, bar8, bar7, bar9 ]; return score; };
module.exports = function (RED) { var Client = require('azure-iot-device').Client; var Protocols = { amqp: require('azure-iot-device-amqp').Amqp, mqtt: require('azure-iot-device-mqtt').Mqtt, http: require('azure-iot-device-http').Http, amqpWs: require('azure-iot-device-amqp').AmqpWs }; var Message = require('azure-iot-device').Message; var client = null; var clientConnectionString = ""; var clientProtocol = ""; var node = null; var nodeConfig = null; var statusEnum = { disconnected: { color: "red", text: "Disconnected" }, connected: { color: "green", text: "Connected" }, sent: { color: "blue", text: "Sent message" }, received: { color: "yellow", text: "Received" }, error: { color: "grey", text: "Error" } }; var setStatus = function (status) { node.status({ fill: status.color, shape: "dot", text: status.text }); } var sendData = function (data) { node.log('Sending Message to Azure IoT Hub :\n Payload: ' + data.toString()); // Create a message and send it to the IoT Hub every second var message = new Message(data); client.sendEvent(message, function (err, res) { if (err) { node.error('Error while trying to send message:' + err.toString()); setStatus(statusEnum.error); } else { node.log('Message sent.'); setStatus(statusEnum.sent); } }); }; var sendMessageToIoTHub = function (message, reconnect) { if (!client || reconnect) { node.log('Connection to IoT Hub not established or configuration changed. Reconnecting.'); // Update the connection string clientConnectionString = node.credentials.connectionstring; // update the protocol clientProtocol = nodeConfig.protocol; // If client was previously connected, disconnect first if (client) disconnectFromIoTHub(); // Connect the IoT Hub connectToIoTHub(message); } else { sendData(message); } }; var connectToIoTHub = function (pendingMessage) { node.log('Connecting to Azure IoT Hub:\n Protocol: ' + clientProtocol + '\n Connection string :' + clientConnectionString); client = Client.fromConnectionString(clientConnectionString, Protocols[clientProtocol]); client.open(function (err) { if (err) { node.error('Could not connect: ' + err.message); setStatus(statusEnum.disconnected); } else { node.log('Connected to Azure IoT Hub.'); setStatus(statusEnum.connected); // Check if a message is pending and send it if (pendingMessage) { node.log('Message is pending. Sending it to Azure IoT Hub.'); // Send the pending message sendData(pendingMessage); } client.on('message', function (msg) { // We received a message node.log('Message received from Azure IoT Hub\n Id: ' + msg.messageId + '\n Payload: ' + msg.data); var outpuMessage = new Message(); outpuMessage.payload = msg.data; setStatus(statusEnum.received); node.send(outpuMessage); client.complete(msg, printResultFor('Completed')); }); client.on('error', function (err) { node.error(err.message); }); client.on('disconnect', function () { disconnectFromIoTHub(); }); } }); }; var disconnectFromIoTHub = function () { if (client) { node.log('Disconnecting from Azure IoT Hub'); client.removeAllListeners(); client.close(printResultFor('close')); client = null; setStatus(statusEnum.disconnected); } }; function nodeConfigUpdated(cs, proto) { return ((clientConnectionString != cs) || (clientProtocol != proto)); } // Main function called by Node-RED function AzureIoTHubNode(config) { // Store node for further use node = this; nodeConfig = config; // Create the Node-RED node RED.nodes.createNode(this, config); this.on('input', function (msg) { // Sending msg.payload to Azure IoT Hub Hub sendMessageToIoTHub(msg.payload, nodeConfigUpdated(node.credentials.connectionstring, nodeConfig.protocol)); }); this.on('close', function () { disconnectFromIoTHub(this); }); } // Registration of the node into Node-RED RED.nodes.registerType("azureiothub", AzureIoTHubNode, { credentials: { connectionstring: { type: "text" } }, defaults: { name: { value: "Azure IoT Hub" }, protocol: { value: "amqp" } } }); // Helper function to print results in the console function printResultFor(op) { return function printResult(err, res) { if (err) node.error(op + ' error: ' + err.toString()); if (res) node.log(op + ' status: ' + res.constructor.name); }; } }
/*! * ShortUrl * Copyright(c) 2015 Andrew Shapro * MIT Licensed */ (function () { 'use strict'; /** * API for the handlers * @type {Object} */ var ShortUrlHandlers = function ($, ShortUrlUi) { var ui = new ShortUrlUi($); /** * handle ajax `done` * @param {Object} data data resolved in request */ this.completeHandler = function (data) { // when the promise resolves, we should have response data // place the url in the link text ui.replaceText('#short-url', data.url); // replace the link href with the url ui.replaceHref('#short-url', data.url); // hide the error-container ui.hideElement('#error-container'); // unhide the url-container ui.showElement('#short-url-container'); }; /** * handle ajax `fail` * @param {Object} error error rejected in request */ this.errorHandler = function (error) { // when the promise rejects, we should have an error // add the error text to the error content ui.replaceText('#error-content', error.responseJSON ? error.responseJSON.message : 'Error getting shortened URL.'); // hide the url-container ui.hideElement('#short-url-container'); // unhide the error-container ui.showElement('#error-container'); }; /** * handle submit events */ this.submitHandler = function () { // get the form data var formData = ui.getFormData('#url-form', 'url'); // post the data $.ajax({ type: 'POST', url: formData.url, data: { url: formData.data }, dataType: 'json' }) .done(this.completeHandler.bind(this)) .fail(this.errorHandler.bind(this)); }; }; self.ShortUrlHandlers = ShortUrlHandlers; }());
import addAbout from '<server/graphql>/mutations/about/add'; import updateAbout from '<server/graphql>/mutations/about/update'; import removeAbout from '<server/graphql>/mutations/about/remove'; export default { addAbout, updateAbout, removeAbout, };
import React, { Component, PropTypes } from 'react'; import { Table } from 'fixed-data-table'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { List, Map } from 'immutable'; import Modal from '../Modal'; import { ThreeBounceSpinner } from '../../../../Base/Spinners/Spinners'; import buildTableColumns from '../../Content/Table/Columns/Columns'; import * as Actions from '../../../../../actions/currentTable'; import * as TablesActions from '../../../../../actions/tables'; const propTypes = { foreignTable: PropTypes.object.isRequired, tables: PropTypes.array.isRequired, closeForeignTable: PropTypes.func.isRequired, setCurrentTable: PropTypes.func.isRequired, initTable: PropTypes.func.isRequired }; class ForeignTableModal extends Component { handleClose = () => { this.props.closeForeignTable(); } handleTableLeave = () => { const foreignTable = this.props.foreignTable; const tableName = foreignTable.get('tableName'); this.props.setCurrentTable(tableName); this.props.initTable({ tableName, filters: new List([new Map({ column: 'id', operator: '=', value: foreignTable.getIn(['rows', 0, 'id']) })]) }); } render() { const foreignTable = this.props.foreignTable; let table = false; const structureTable = foreignTable.get('structureTable'); if (structureTable) { const rows = foreignTable.get('rows'); const tableName = foreignTable.get('tableName'); const tables = this.props.tables; const columns = buildTableColumns({ structureTable, tables, tableName, rows, foreign: true }); table = ( <div className="flex-col"> <Table rowsCount={rows.size} headerHeight={51} rowHeight={45} width={document.getElementById('table-wrapper').offsetWidth - 400} height={230} > {columns} </Table> <button className="btn btn-primary" onClick={this.handleTableLeave} > Go to table </button> </div> ); } return foreignTable.get('open') && ( <Modal onClose={this.handleClose} className="foreign-table" > <div style={{ height: 245, width: document.getElementById('table-wrapper').offsetWidth - 400 }} > {table || <ThreeBounceSpinner />} </div> </Modal> ); } } ForeignTableModal.propTypes = propTypes; function mapStateToProps(state) { return { foreignTable: state.currentTable.foreignTable, tables: state.tables }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...Actions, ...TablesActions }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(ForeignTableModal);
#!/usr/bin/env node 'use strict'; (function() { var async, backupCtrl, chalk, cli, connectCtrl, databaseCtrl, getCommand, helpCtrl, main, memoryCtrl, ndx, options, pack, pad, passwordCtrl, path, processCommand, readline, revokeCtrl, tokenCtrl; ndx = require('./ndx.js'); readline = require('readline'); chalk = require('chalk'); async = require('async'); cli = require('cli'); path = require('path'); options = cli.parse(); pack = require('../package.json'); connectCtrl = require('./controllers/connect.js'); backupCtrl = require('./controllers/backup.js'); passwordCtrl = require('./controllers/password.js'); databaseCtrl = require('./controllers/database.js'); memoryCtrl = require('./controllers/memory.js'); tokenCtrl = require('./controllers/token.js'); revokeCtrl = require('./controllers/revoke.js'); helpCtrl = require('./controllers/help.js'); getCommand = function(commandName) { switch (commandName) { case 'connect': case 'login': return connectCtrl; case 'backup': return backupCtrl; case 'password': case 'pass': return passwordCtrl; case 'database': case 'exec': case 'sql': case 'd': return databaseCtrl; case 'memory': case 'mem': return memoryCtrl; case 'token': return tokenCtrl; case 'revoke': return revokeCtrl; case 'help': return helpCtrl; case 'exit': case 'quit': case 'e': case 'q': return process.exit(0); } }; pad = function(input) { while (input.length < 8) { input = ' ' + input; } return input; }; processCommand = function(keywords, i) { var commandKeyword, j, keyword, len, questions; questions = []; if (i === 0) { for (i = j = 0, len = keywords.length; j < len; i = ++j) { keyword = keywords[i]; if (i > 0) { commandKeyword = ndx.data.command.keywords[i - 1].replace('?', ''); questions.push({ name: commandKeyword, prompt: "" + (chalk.green(commandKeyword)) + (chalk.yellow('>')) + " " }); if (commandKeyword) { ndx.data[commandKeyword] = keyword; } } } } while (i < ndx.data.command.keywords.length + 1) { commandKeyword = ndx.data.command.keywords[i - 1]; if (!/\?/.test(commandKeyword)) { questions.push({ name: commandKeyword, prompt: "" + (chalk.green(commandKeyword)) + (chalk.yellow('>')) + " " }); } i++; } return async.eachSeries(questions, ndx.getData, function() { return ndx.data.command.exec(function(err, thing) { if (err) { console.log(err); } return ndx.data.command.cleanup(function(err) { return main(thing); }); }); }); }; main = function(command) { if (command) { ndx.data.command = getCommand(command); return processCommand([], 1); } switch (ndx.data.state) { case 'command': return ndx.getData({ prompt: "" + (chalk.green('ndx')) + (chalk.yellow('>')) + " " }, function(err, input) { var keywords; keywords = ndx.splitLine(input); if (keywords && keywords.length) { ndx.data.command = getCommand(keywords[0]); if (!ndx.data.command) { console.log('unexpected command'); return main(); } return processCommand(keywords, 0); } }); } }; if (options.init) { ndx.spawnSync('npm', ['install', '-g', '--silent', 'yo', 'generator-ndx', 'grunt-cli', 'bower'], function() { return console.log('done'); }); } else if (options.create && options.appname) { ndx.spawnSync('yo', ['ndx', options.appname], function() { return console.log('done'); }); } else if (options['update-packages']) { require('./controllers/update-packages')(true, true); } else if (options['update-npm']) { require('./controllers/update-packages')(true, false); } else if (options['update-bower']) { require('./controllers/update-packages')(false, true); } else { console.log(chalk.yellow('ndx framework ') + chalk.cyan('v' + pack.version)); console.log(chalk.cyan('type ') + chalk.yellow('help') + chalk.cyan(' for a list of commands')); console.log(chalk.cyan('hit ') + chalk.yellow('Ctrl-C') + chalk.cyan(' or type ') + chalk.yellow('exit') + chalk.cyan(' to exit')); main(); } }).call(this); //# sourceMappingURL=app.js.map
/** * Backend related objects */ /* global CKEDITOR, CKFinder, Bloodhound, linkList */ var jsBackend = { debug: false, current: { module: null, action: null, language: null }, // init, something like a constructor init: function () { // get url and split into chunks var chunks = document.location.pathname.split('/') // set some properties jsBackend.debug = jsBackend.data.get('debug') jsBackend.current.language = chunks[2] if (!navigator.cookieEnabled) $('#noCookies').addClass('active').css('display', 'block') if (typeof chunks[3] === 'undefined') { jsBackend.current.module = null } else { jsBackend.current.module = utils.string.ucfirst(utils.string.camelCase(chunks[3])) } if (typeof chunks[4] === 'undefined') { jsBackend.current.action = null } else { jsBackend.current.action = utils.string.ucfirst(utils.string.camelCase(chunks[4])) } // set defaults if (!jsBackend.current.module) jsBackend.current.module = 'Dashboard' if (!jsBackend.current.action) jsBackend.current.action = 'index' // init stuff jsBackend.initAjax() jsBackend.addModalEvents() jsBackend.balloons.init() jsBackend.controls.init() jsBackend.effects.init() jsBackend.tabs.init() jsBackend.forms.init() jsBackend.layout.init() jsBackend.messages.init() jsBackend.tooltip.init() jsBackend.tableSequenceByDragAndDrop.init() if (jsData.Core.preferred_editor === 'ck-editor') jsBackend.ckeditor.init() jsBackend.resizeFunctions.init() jsBackend.navigation.init() jsBackend.session.init() // do not move, should be run as the last item. if (!jsBackend.data.get('debug')) jsBackend.forms.unloadWarning() }, addModalEvents: function () { var $modals = $('[role=dialog].modal') if ($modals.length === 0) { return } $modals.on('shown.bs.modal', function () { $('#ajaxSpinner').addClass('light') $(this).attr('aria-hidden', 'false') }) $modals.on('hide.bs.modal', function () { $('#ajaxSpinner').removeClass('light') $(this).attr('aria-hidden', 'true') }) }, // init ajax initAjax: function () { // variables var $ajaxSpinner = $('#ajaxSpinner') // set defaults for AJAX $.ajaxSetup( { url: '/backend/ajax', cache: false, type: 'POST', dataType: 'json', timeout: 10000, data: { fork: { module: jsBackend.current.module, action: jsBackend.current.action, language: jsBackend.current.language } } } ) // global error handler $(document).ajaxError(function (e, XMLHttpRequest, ajaxOptions) { // 401 means we aren't authenticated anymore, so reload the page if (XMLHttpRequest.status === 401) window.location.reload() // check if a custom errorhandler is used if (typeof ajaxOptions.error === 'undefined') { // init var var textStatus = jsBackend.locale.err('SomethingWentWrong') // get real message if (typeof XMLHttpRequest.responseText !== 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message // show message jsBackend.messages.add('danger', textStatus) } }) // spinner stuff $(document).ajaxStart(function () { $ajaxSpinner.show() }) $(document).ajaxStop(function () { $ajaxSpinner.hide() }) } } /** * Navigation controls */ jsBackend.navigation = { init: function () { jsBackend.navigation.mobile() jsBackend.navigation.toggleCollapse() jsBackend.navigation.tooltip() }, mobile: function () { var navbarWidth = this.calculateNavbarWidth() var $navbarNav = $('.navbar-default .navbar-nav') $('.navbar-default .navbar-nav').css('width', navbarWidth) $('.js-nav-prev').on('click', function (e) { e.preventDefault() $navbarNav.animate({'left': '+=85px'}) this.setControls(85) }.bind(this)) $('.js-nav-next').on('click', function (e) { e.preventDefault() $navbarNav.animate({'left': '-=85px'}) this.setControls(-85) }.bind(this)) }, resize: function () { var $navbarNav = $('.navbar-default .navbar-nav') var navbarWidth = this.calculateNavbarWidth() var windowWidth = this.calculateWindowWidth() if (navbarWidth < windowWidth) { $navbarNav.css('left', '0') $('.js-nav-next').hide() } this.setControls(0) }, toggleCollapse: function () { var $wrapper = $('.main-wrapper') var $navCollapse = $('.js-toggle-nav') var collapsed = $wrapper.hasClass('navigation-collapsed') if ($wrapper.hasClass('navigation-collapsed')) { $('.js-nav-screen-text').html(jsBackend.locale.lbl('OpenNavigation')) } else { $('.js-nav-screen-text').html(jsBackend.locale.lbl('CloseNavigation')) } $navCollapse.on('click', function (e) { e.preventDefault() $wrapper.toggleClass('navigation-collapsed') if ($wrapper.hasClass('navigation-collapsed')) { $('.js-nav-screen-text').html(jsBackend.locale.lbl('OpenNavigation')) } else { $('.js-nav-screen-text').html(jsBackend.locale.lbl('CloseNavigation')) } collapsed = !collapsed utils.cookies.setCookie('navigation-collapse', collapsed) setTimeout(function () { jsBackend.resizeFunctions.init() }, 250) }) }, tooltip: function () { var $tooltip = $('[data-toggle="tooltip-nav"]') var $wrapper = $('.main-wrapper') if ($tooltip.length > 0) { $tooltip.tooltip({ trigger: 'manual' }) $tooltip.on('mouseover', function (e) { if ($wrapper.hasClass('navigation-collapsed') && $(window).width() > 787) { var $target = $(e.target) $target.tooltip('show') } }) $tooltip.on('mouseout', function (e) { $(e.target).tooltip('hide') }) } }, setControls: function (offset) { var $navbarNav = $('.navbar-default .navbar-nav') var rightOffset = this.calculateOffset(offset) if ((parseInt($navbarNav.css('left')) + offset) >= 0) { $('.js-nav-prev').hide() } else { $('.js-nav-prev').show() } if (rightOffset < 0) { $('.js-nav-next').show() } else { $('.js-nav-next').hide() } }, calculateWindowWidth: function () { return $(window).width() }, calculateNavbarWidth: function () { var $navItem = $('.navbar-default .nav-item') return $navItem.width() * $navItem.length }, calculateOffset: function (offset) { var $navbarNav = $('.navbar-default .navbar-nav') return this.calculateWindowWidth() - this.calculateNavbarWidth() - parseInt($navbarNav.css('left')) - offset } } /** * Handle form messages (action feedback: success, error, ...) */ jsBackend.balloons = { // init, something like a constructor init: function () { // variables var $toggleBalloon = $('.toggleBalloon') $('.balloon:visible').each(function () { // search linked element var linkedElement = $('*[data-message-id=' + $(this).attr('id') + ']') // linked item found? if (linkedElement !== null) { // variables var topValue = linkedElement.offset().top + linkedElement.height() + 10 var leftValue = linkedElement.offset().left - 30 // position $(this).css('position', 'absolute').css('top', topValue).css('left', leftValue) } }) // bind click $toggleBalloon.on('click', jsBackend.balloons.click) }, // handle the click event (make it appear/disappear) click: function (e) { var clickedElement = $(this) // get linked balloon var id = clickedElement.data('messageId') // rel available? if (id !== '') { // hide if already visible if ($('#' + id).is(':visible')) { // hide $('#' + id).fadeOut(500) // unbind $(window).off('resize') } else { // not visible // position jsBackend.balloons.position(clickedElement, $('#' + id)) // show $('#' + id).fadeIn(500) // set focus on first visible field if ($('#' + id + ' form input:visible:first').length > 0) $('#' + id + ' form input:visible:first').focus() // bind resize $(window).resize(function () { jsBackend.balloons.position(clickedElement, $('#' + id)) }) } } }, // position the balloon position: function (clickedElement, element) { // variables var topValue = clickedElement.offset().top + clickedElement.height() + 10 var leftValue = clickedElement.offset().left - 30 // position element.css('position', 'absolute').css('top', topValue).css('left', leftValue) } } /** * CK Editor related objects */ jsBackend.ckeditor = { prepared: false, defaultConfig: { customConfig: '', // layout configuration bodyClass: 'content', stylesSet: [], // paste options forcePasteAsPlainText: true, pasteFromWordRemoveFontStyles: true, // The CSS file(s) to be used to apply style to editor content. // It should reflect the CSS used in the target pages where the content is to be displayed. contentsCss: [], // buttons toolbar_Full: [ { name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] }, {name: 'clipboard', groups: ['clipboard', 'undo'], items: ['Undo', 'Redo']}, { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'bidi'], items: ['NumberedList', 'BulletedList', '-', 'Blockquote'] }, {name: 'links', items: ['ForkLink', 'Unlink', 'Anchor']}, {name: 'document', groups: ['mode', 'document', 'doctools'], items: ['Source', 'Templates']}, {name: 'insert', items: ['ForkImage', 'Table', 'SpecialChar', 'Iframe', 'oembed']}, {name: 'styles', items: ['Format', 'Styles']} ], skin: 'moono-lisa', toolbar: 'Full', toolbarStartupExpanded: true, // entities entities: false, entities_greek: false, entities_latin: false, // No file browser upload button in the images dialog needed filebrowserUploadUrl: null, filebrowserImageUploadUrl: null, filebrowserFlashUploadUrl: null, // uploading drag&drop images, see http://docs.ckeditor.com/#!/guide/dev_file_upload uploadUrl: '/src/Backend/Core/Js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files&responseType=json', // load some extra plugins extraPlugins: 'stylesheetparser,templates,iframe,dialogadvtab,oembed,lineutils,medialibrary,codemirror', // remove useless plugins removePlugins: 'image2,a11yhelp,about,bidi,colorbutton,elementspath,font,find,flash,forms,horizontalrule,newpage,pagebreak,preview,print,scayt,smiley,showblocks,devtools,magicline', // templates templates_files: [], templates_replaceContent: false, // custom vars editorType: 'default', toggleToolbar: false }, // initialize the editor init: function () { // the language isn't know before this init-method is called, so we set the url for the template-files just now jsBackend.ckeditor.defaultConfig.templates_files = ['/backend/ajax?fork[module]=Core&fork[action]=Templates&fork[language]=' + jsBackend.current.language] // load the editor if ($('textarea.inputEditor, textarea.inputEditorError').length > 0) { jsBackend.ckeditor.prepare() // load the editors jsBackend.ckeditor.load() } jsBackend.ckeditor.fallBackBootstrapModals() if (jsData.Core.preferred_editor === 'ck-editor') { jsBackend.ckeditor.loadEditorsInCollections() } }, loadEditorsInCollections: function () { $('[data-addfield=collection]').on('collection-field-added', function (event, formCollectionItem) { jsBackend.ckeditor.prepare() $(formCollectionItem).find('textarea.inputEditor, textarea.inputEditorError').ckeditor( jsBackend.ckeditor.callback, $.extend({}, jsBackend.ckeditor.defaultConfig) ) }) }, prepare: function () { if (jsBackend.ckeditor.prepared) { return } // language options jsBackend.ckeditor.defaultConfig.contentsLanguage = jsBackend.current.language jsBackend.ckeditor.defaultConfig.language = jsBackend.data.get('editor.language') // content Css jsBackend.ckeditor.defaultConfig.contentsCss.push('/src/Frontend/Core/Layout/Css/screen.css') if (jsBackend.data.get('theme.has_css')) jsBackend.ckeditor.defaultConfig.contentsCss.push('/src/Frontend/Themes/' + jsBackend.data.get('theme.theme') + '/Core/Layout/Css/screen.css') jsBackend.ckeditor.defaultConfig.contentsCss.push('/src/Frontend/Core/Layout/Css/editor_content.css') if (jsBackend.data.get('theme.has_editor_css')) jsBackend.ckeditor.defaultConfig.contentsCss.push('/src/Frontend/Themes/' + jsBackend.data.get('theme.theme') + '/Core/Layout/Css/editor_content.css') // bind on some global events CKEDITOR.on('dialogDefinition', jsBackend.ckeditor.onDialogDefinition) CKEDITOR.on('instanceReady', jsBackend.ckeditor.onReady) jsBackend.ckeditor.prepared = true }, destroy: function () { // the destroy will trigger errors, but it will actually be destroyed just fine! try { $.each(CKEDITOR.instances, function (i, value) { value.destroy() }) } catch (err) { } }, load: function () { // extend the editor config var editorConfig = $.extend({}, jsBackend.ckeditor.defaultConfig) // bind on inputEditor and inputEditorError $('textarea.inputEditor, textarea.inputEditorError').ckeditor(jsBackend.ckeditor.callback, editorConfig) }, callback: function () { }, checkContent: function (evt) { // get the editor var editor = evt.editor // on initialisation we should force the check, which will be passed in the data-container var forced = (typeof evt.forced === 'boolean') ? evt.forced : false // was the content changed, or is the check forced? if (editor.checkDirty() || forced) { var content = editor.getData() var warnings = [] // no alt? if (content.match(/<img(.*)alt=""(.*)/im)) warnings.push(jsBackend.locale.msg('EditorImagesWithoutAlt')) // invalid links? if (content.match(/href=("|')\/private\/([a-z]{2,})\/([a-z_]*)\/(.*)\1/im)) warnings.push(jsBackend.locale.msg('EditorInvalidLinks')) // remove the previous warnings $('#' + editor.element.getId() + '_warnings').remove() // @todo: met dit id loopt iets mis // any warnings? if (warnings.length > 0) { // append the warnings after the editor $('#cke_' + editor.element.getId()).after('<span id="' + editor.element.getId() + '_warnings" class="infoMessage editorWarning">' + warnings.join(' ') + '</span>') } } }, onDialogDefinition: function (evt) { // get the dialog definition var dialogDefinition = evt.data.definition var infoTab = '' // specific stuff for the table-dialog if (evt.data.name === 'table') { // remove the advanced tab because it is confusing fo the end-user dialogDefinition.removeContents('advanced') // get the info tab infoTab = dialogDefinition.getContents('info') // remove fields we don't want to use, because they will mess up the layout infoTab.remove('txtBorder') infoTab.remove('cmbAlign') infoTab.remove('txtCellSpace') infoTab.remove('txtCellPad') // set a beter default for the width infoTab.get('txtWidth')['default'] = '100%' } if (evt.data.name === 'oembed') { dialogDefinition.getContents('general').elements.splice( 2, 0, { type: 'button', id: 'browseServer', label: 'Browse Server', onClick: function () { var editor = this.getDialog().getParentEditor() editor.popup(window.location.origin + jsData.MediaLibrary.browseActionVideos, 800, 800) window.onmessage = function (event) { if (event.data && typeof event.data === 'object' && 'media-url' in event.data) { this.setValueOf('general', 'embedCode', event.data['media-url']) } }.bind(this.getDialog()) }, style: 'margin-top: 20px;' }) } }, onReady: function (evt) { // bind on blur and focus evt.editor.on('blur', jsBackend.ckeditor.checkContent) // force the content check jsBackend.ckeditor.checkContent({editor: evt.editor, forced: true}) }, fallBackBootstrapModals: function () { $.fn.modal.Constructor.prototype.enforceFocus = function () { var modalThis = this $(document).on('focusin.modal', function (e) { if (modalThis.$element[0] !== e.target && !modalThis.$element.has(e.target).length && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text') && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_textarea')) { modalThis.$element.focus() } }) } } } /** * Handle form functionality */ jsBackend.controls = { // init, something like a constructor init: function () { jsBackend.controls.bindCheckboxDropdownCombo() jsBackend.controls.bindCheckboxTextfieldCombo() jsBackend.controls.bindRadioButtonFieldCombo() jsBackend.controls.bindConfirm() jsBackend.controls.bindFakeDropdown() jsBackend.controls.bindMassCheckbox() jsBackend.controls.bindMassAction() jsBackend.controls.bindPasswordGenerator() jsBackend.controls.bindPasswordStrengthMeter() jsBackend.controls.bindWorkingLanguageSelection() jsBackend.controls.bindTableCheckbox() jsBackend.controls.bindTargetBlank() jsBackend.controls.bindToggleDiv() }, // bind a checkbox dropdown combo bindCheckboxDropdownCombo: function () { // variables var $checkboxDropdownCombo = $('.jsCheckboxDropdownCombo') $checkboxDropdownCombo.each(function () { var $this = $(this) var multiple = !!$this.data('multiple') || false if ($this.find('input:checkbox').length > 0 && $this.find('select').length > 0) { $this.find('input:checkbox').eq(0).on('change', function (e) { var $combo = $(this).parents().filter($checkboxDropdownCombo) var $field = $($combo.find('select')) if (!multiple) { $field = $field.eq(0) } var $this = $(this) if ($this.is(':checked')) { $field.removeClass('disabled').prop('disabled', false) var $focusDropdown = ((!multiple) ? $field : $field.eq(0)) $focusDropdown.focus() return } $field.addClass('disabled').prop('disabled', true) }).trigger('change') } }) }, // bind a checkbox textfield combo bindCheckboxTextfieldCombo: function () { // variables var $checkboxTextFieldCombo = $('.checkboxTextFieldCombo') $checkboxTextFieldCombo.each(function () { // variables var $this = $(this) // check if needed element exists if ($this.find('input:checkbox').length > 0 && $this.find('input:text').length > 0) { // variables var $checkbox = $this.find('input:checkbox').eq(0) var $textField = $this.find('input:text').eq(0) $checkbox.on('change', function (e) { // redefine var $this = $(this) // variables var $combo = $this.parents().filter($checkboxTextFieldCombo) var $field = $($combo.find('input:text')[0]) if ($this.is(':checked')) { $field.removeClass('disabled').prop('disabled', false).focus() } else { $field.addClass('disabled').prop('disabled', true) } }) if ($checkbox.is(':checked')) { $textField.removeClass('disabled').prop('disabled', false) } else { $textField.addClass('disabled').prop('disabled', true) } } }) }, // bind a radiobutton field combo bindRadioButtonFieldCombo: function () { // variables var $radiobuttonFieldCombo = $('.radiobuttonFieldCombo') $radiobuttonFieldCombo.each(function () { // variables var $this = $(this) // check if needed element exists if ($this.find('input:radio').length > 0 && $this.find('input, select, textarea').length > 0) { // variables var $radiobutton = $this.find('input:radio') var $selectedRadiobutton = $this.find('input:radio:checked') $radiobutton.on('click', function (e) { // redefine var $this = $(this) // disable all $this.parents('.radiobuttonFieldCombo:first').find('input:not([name=' + $radiobutton.attr('name') + ']), select, textarea').addClass('disabled').prop('disabled', true) // get fields that should be enabled var $fields = $('input[name=' + $radiobutton.attr('name') + ']:checked').parents('li').find('input:not([name=' + $radiobutton.attr('name') + ']), select, textarea') // enable $fields.removeClass('disabled').prop('disabled', false) // set focus if (typeof $fields[0] !== 'undefined') $fields[0].focus() }) // change? if ($selectedRadiobutton.length > 0) { $selectedRadiobutton.click() } else { $radiobutton[0].click() } } }) }, // bind confirm message bindConfirm: function () { $('.jsConfirmationTrigger').on('click', function (e) { // prevent default e.preventDefault() // get data var href = $(this).attr('href') var message = $(this).data('message') if (typeof message === 'undefined') { message = jsBackend.locale.msg('ConfirmDefault') } // the first is necessary to prevent multiple popups showing after a previous modal is dismissed without // refreshing the page var $confirmation = $('.jsConfirmation').clone().first() // bind if (href !== '') { // set data $confirmation.find('.jsConfirmationMessage').html(message) $confirmation.find('.jsConfirmationSubmit').attr('href', $(this).attr('href')) // open dialog $confirmation.modal('show') } }) }, // let the fake dropdown behave nicely, like a real dropdown bindFakeDropdown: function () { // variables var $fakeDropdown = $('.fakeDropdown') $fakeDropdown.on('click', function (e) { // prevent default behaviour e.preventDefault() // stop it e.stopPropagation() // variables var $parent = $fakeDropdown.parent() var $body = $('body') // get id var id = $(this).attr('href') // IE8 prepends full current url before links to # id = id.substring(id.indexOf('#')) if ($(id).is(':visible')) { // remove events $body.off('click') $body.off('keyup') // remove class $parent.removeClass('selected') // hide $(id).hide('blind', {}, 'fast') } else { // bind escape $body.on('keyup', function (e) { if (e.keyCode === 27) { // unbind event $body.off('keyup') // remove class $parent.removeClass('selected') // hide $(id).hide('blind', {}, 'fast') } }) // bind click outside $body.on('click', function (e) { // unbind event $body.off('click') // remove class $parent.removeClass('selected') // hide $(id).hide('blind', {}, 'fast') }) // add class $parent.addClass('selected') // show $(id).show('blind', {}, 'fast') } }) }, // bind confirm message bindMassAction: function () { var $checkboxes = $('table.jsDataGrid .check input:checkbox') var noneChecked = true // check if none is checked $checkboxes.each(function () { if ($(this).prop('checked')) { noneChecked = false } }) // set disabled if (noneChecked) { $('.jsMassAction select').prop('disabled', true) $('.jsMassAction .jsMassActionSubmit').prop('disabled', true) } // hook change events $checkboxes.on('change', function (e) { // get parent table var table = $(this).parents('table.jsDataGrid').eq(0) // any item checked? if (table.find('input:checkbox:checked').length > 0) { table.find('.jsMassAction select').prop('disabled', false) table.find('.jsMassAction .jsMassActionSubmit').prop('disabled', false) } else { // nothing checked table.find('.jsMassAction select').prop('disabled', true) table.find('.jsMassAction .jsMassActionSubmit').prop('disabled', true) } }) // hijack the form $('.jsMassAction .jsMassActionSubmit').on('click', function (e) { // prevent default action e.preventDefault() // variables var $this = $(this) var $closestForm = $this.closest('form') // not disabled if (!$this.prop('disabled')) { // get the selected element if ($this.closest('.jsMassAction').find('select[name=action] option:selected').length > 0) { // get action element var element = $this.closest('.jsMassAction').find('select[name=action] option:selected') // if the rel-attribute exists we should show the dialog if (typeof element.data('target') !== 'undefined') { // get id var id = element.data('target') $(id).modal('show') } else { // no confirm $closestForm.submit() } } else { // no confirm $closestForm.submit() } } }) }, // check all checkboxes with one checkbox in the tableheader bindMassCheckbox: function () { // mass checkbox changed $('th.check input:checkbox').on('change', function (e) { // variables var $this = $(this) // check or uncheck all the checkboxes in this datagrid $this.closest('table').find('td input:checkbox').prop('checked', $this.is(':checked')) // set selected class if ($this.is(':checked')) { $this.parents().filter('table').eq(0).find('tbody tr').addClass('selected') } else { $this.parents().filter('table').eq(0).find('tbody tr').removeClass('selected') } }) // single checkbox changed $('td.check input:checkbox').on('change', function (e) { // variables var $this = $(this) // check mass checkbox if ($this.closest('table').find('td.checkbox input:checkbox').length === $this.closest('table').find('td.checkbox input:checkbox:checked').length) { $this.closest('table').find('th .checkboxHolder input:checkbox').prop('checked', true) } else { // uncheck mass checkbox $this.closest('table').find('th .checkboxHolder input:checkbox').prop('checked', false) } }) }, bindPasswordGenerator: function () { // variables var $passwordGenerator = $('.passwordGenerator') if ($passwordGenerator.length > 0) { $passwordGenerator.passwordGenerator({ length: 8, numbers: false, lowercase: true, uppercase: true, generateLabel: utils.string.ucfirst(jsBackend.locale.lbl('Generate')) }) } }, // bind the password strength meter to the correct inputfield(s) bindPasswordStrengthMeter: function () { // variables var $passwordStrength = $('.passwordStrength') if ($passwordStrength.length > 0) { $passwordStrength.each(function () { // grab id var id = $(this).data('id') var wrapperId = $(this).attr('id') // hide all $('#' + wrapperId + ' p.strength').hide() // execute function directly var classToShow = jsBackend.controls.checkPassword($('#' + id).val()) // show $('#' + wrapperId + ' p.' + classToShow).show() // bind keypress $(document).on('keyup', '#' + id, function () { // hide all $('#' + wrapperId + ' p.strength').hide() // execute function directly var classToShow = jsBackend.controls.checkPassword($('#' + id).val()) // show $('#' + wrapperId + ' p.' + classToShow).show() }) }) } }, // check a string for passwordstrength checkPassword: function (string) { // init vars var score = 0 var uniqueChars = [] // no chars means no password if (string.length === 0) return 'none' // less then 4 chars is just a weak password if (string.length <= 4) return 'weak' // loop chars and add unique chars for (var i = 0; i < string.length; i++) { if ($.inArray(string.charAt(i), uniqueChars) === -1) uniqueChars.push(string.charAt(i)) } // less then 3 unique chars is just weak if (uniqueChars.length < 3) return 'weak' // more then 6 chars is good if (string.length >= 6) score++ // more then 8 is beter if (string.length >= 8) score++ // more then 12 is best if (string.length >= 12) score++ // upper and lowercase? if ((string.match(/[a-z]/)) && string.match(/[A-Z]/)) score += 2 // number? if (string.match(/\d+/)) score++ // special char? if (string.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++ // strong password if (score >= 6) return 'strong' // average if (score >= 2) return 'average' // fallback return 'weak' }, // toggle a div bindToggleDiv: function () { $(document).on('click', '.toggleDiv', function (e) { // prevent default e.preventDefault() // get id var id = $(this).attr('href') // show/hide $(id).toggle() // set selected class on parent if ($(id).is(':visible')) { $(this).parent().addClass('selected') } else { $(this).parent().removeClass('selected') } }) }, // bind checkboxes in a row bindTableCheckbox: function () { // set classes $('tr td.checkbox input.inputCheckbox:checked').each(function () { if (!$(this).parents('table').hasClass('noSelectedState')) { $(this).parents().filter('tr').eq(0).addClass('selected') } }) // bind change-events $(document).on('change', 'tr td.checkbox input.inputCheckbox:checkbox', function (e) { if (!$(this).parents('table').hasClass('noSelectedState')) { if ($(this).is(':checked')) { $(this).parents().filter('tr').eq(0).addClass('selected') } else { $(this).parents().filter('tr').eq(0).removeClass('selected') } } }) }, // bind target blank bindTargetBlank: function () { $('a.targetBlank').attr('target', '_blank').attr('rel', 'noopener noreferrer') }, // toggle between the working languages bindWorkingLanguageSelection: function () { // variables var $workingLanguage = $('#workingLanguage') $workingLanguage.on('change', function (e) { // preventDefault e.preventDefault() // break the url int parts var urlChunks = document.location.pathname.split('/') // get the query string, we will append it later var queryChunks = document.location.search.split('&') var newChunks = [] // any parts in the query string if (typeof queryChunks !== 'undefined' && queryChunks.length > 0) { // remove variables that could trigger an message for (var i in queryChunks) { if (queryChunks[i].substring(0, 5) !== 'token' && queryChunks[i].substring(0, 5) !== 'error' && queryChunks[i].substring(0, 6) === 'report' && queryChunks[i].substring(0, 3) === 'var' && queryChunks[i].substring(0, 9) === 'highlight') { newChunks.push(queryChunks[i]) } } } // replace the third element with the new language urlChunks[2] = $(this).val() // remove action if (urlChunks.length > 4) urlChunks.pop() var url = urlChunks.join('/') if (newChunks.length > 0) url += '?token=true&' + newChunks.join('&') // rebuild the url and redirect document.location.href = url }) } } /** * Data related methods */ jsBackend.data = { initialized: false, data: {}, init: function () { // check if var is available if (typeof jsData === 'undefined') throw new Error('jsData is not available') // populate jsBackend.data.data = jsData jsBackend.data.initialized = true }, exists: function (key) { return (typeof jsBackend.data.get(key) !== 'undefined') }, get: function (key) { // init if needed if (!jsBackend.data.initialized) jsBackend.data.init() var keys = key.split('.') var data = jsBackend.data.data for (var i = 0; i < keys.length; i++) { data = data[keys[i]] } // return return data } } /** * Backend effects */ jsBackend.effects = { // init, something like a constructor init: function () { jsBackend.effects.bindHighlight() jsBackend.effects.panels() }, // if a var highlight exists in the url it will be highlighted bindHighlight: function () { // get highlight from url var highlightId = utils.url.getGetValue('highlight') // id is set if (highlightId !== '') { // init selector of the element we want to highlight var selector = '#' + highlightId // item exists if ($(selector).length > 0) { // if its a table row we need to highlight all cells in that row if ($(selector)[0].tagName.toLowerCase() === 'tr') { selector += ' td' } // when we hover over the item we stop the effect, otherwise we will mess up background hover styles $(selector).on('mouseover', function () { $(selector).stop(true, true) }) // highlight! $(selector).effect('highlight', {}, 5000) } } }, // Adds classes to collapsible panels panels: function () { $('.panel .collapse').on({ 'show.bs.collapse': function () { // Remove open class from other panels $(this).parents('.panel-group').find('.panel').removeClass('open') // Add open class to active panel $(this).parent('.panel').addClass('open') }, 'hide.bs.collapse': function () { // Remove open class from closed panel $(this).parent('.panel').removeClass('open') } }) } } /** * Backend forms */ jsBackend.forms = { stringified: '', // init, something like a constructor init: function () { jsBackend.forms.placeholders() // make sure this is done before focusing the first field jsBackend.forms.focusFirstField() jsBackend.forms.datefields() jsBackend.forms.submitWithLinks() jsBackend.forms.tagsInput() jsBackend.forms.meta() jsBackend.forms.datePicker() jsBackend.forms.bootstrapTabFormValidation() jsBackend.forms.imagePreview() }, imagePreview: function () { $('input[type=file]').on('change', function () { let imageField = $(this).get(0) // make sure we are uploading an image by checking the data attribute if (imageField.getAttribute('data-fork-cms-role') === 'image-field' && imageField.files && imageField.files[0]) { // get the image preview by matching the image-preview data-id to the ImageField id let $imagePreview = $('[data-fork-cms-role="image-preview"][data-id="' + imageField.id + '"]') // use FileReader to get the url let reader = new FileReader() reader.onload = function (event) { $imagePreview.attr('src', event.target.result) } reader.readAsDataURL(imageField.files[0]) } }) }, bootstrapTabFormValidation: function () { $('.tab-pane input, .tab-pane textarea, .tab-pane select').on('invalid', function () { var $invalidField = $(this) // Find the tab-pane that this element is inside, and get the id var invalidTabId = $invalidField.closest('.tab-pane').attr('id') // Find the link that corresponds to the pane and have it show $('a[href=#' + invalidTabId + '], [data-target=#' + invalidTabId + ']').tab('show') $invalidField.focus() }) }, meta: function () { var $metaTabs = $('.js-do-meta-automatically') if ($metaTabs.length === 0) { return } $metaTabs.each(function () { var possibleOptions = [ 'baseFieldSelector', 'metaIdSelector', 'pageTitleSelector', 'pageTitleOverwriteSelector', 'navigationTitleSelector', 'navigationTitleOverwriteSelector', 'metaDescriptionSelector', 'metaDescriptionOverwriteSelector', 'metaKeywordsSelector', 'metaKeywordsOverwriteSelector', 'urlSelector', 'urlOverwriteSelector', 'generatedUrlSelector', 'customSelector', 'classNameSelector', 'methodNameSelector', 'parametersSelector' ] var options = {} // only add the options that have been set for (var i = 0, length = possibleOptions.length; i < length; i++) { if (typeof this.dataset[possibleOptions[i]] !== 'undefined') { options[possibleOptions[i]] = this.dataset[possibleOptions[i]] } } $(this.dataset.baseFieldSelector).doMeta(options) }) }, datefields: function () { // variables var dayNames = [ jsBackend.locale.loc('DayLongSun'), jsBackend.locale.loc('DayLongMon'), jsBackend.locale.loc('DayLongTue'), jsBackend.locale.loc('DayLongWed'), jsBackend.locale.loc('DayLongThu'), jsBackend.locale.loc('DayLongFri'), jsBackend.locale.loc('DayLongSat') ] var dayNamesMin = [ jsBackend.locale.loc('DayShortSun'), jsBackend.locale.loc('DayShortMon'), jsBackend.locale.loc('DayShortTue'), jsBackend.locale.loc('DayShortWed'), jsBackend.locale.loc('DayShortThu'), jsBackend.locale.loc('DayShortFri'), jsBackend.locale.loc('DayShortSat') ] var dayNamesShort = [ jsBackend.locale.loc('DayShortSun'), jsBackend.locale.loc('DayShortMon'), jsBackend.locale.loc('DayShortTue'), jsBackend.locale.loc('DayShortWed'), jsBackend.locale.loc('DayShortThu'), jsBackend.locale.loc('DayShortFri'), jsBackend.locale.loc('DayShortSat') ] var monthNames = [ jsBackend.locale.loc('MonthLong1'), jsBackend.locale.loc('MonthLong2'), jsBackend.locale.loc('MonthLong3'), jsBackend.locale.loc('MonthLong4'), jsBackend.locale.loc('MonthLong5'), jsBackend.locale.loc('MonthLong6'), jsBackend.locale.loc('MonthLong7'), jsBackend.locale.loc('MonthLong8'), jsBackend.locale.loc('MonthLong9'), jsBackend.locale.loc('MonthLong10'), jsBackend.locale.loc('MonthLong11'), jsBackend.locale.loc('MonthLong12') ] var monthNamesShort = [ jsBackend.locale.loc('MonthShort1'), jsBackend.locale.loc('MonthShort2'), jsBackend.locale.loc('MonthShort3'), jsBackend.locale.loc('MonthShort4'), jsBackend.locale.loc('MonthShort5'), jsBackend.locale.loc('MonthShort6'), jsBackend.locale.loc('MonthShort7'), jsBackend.locale.loc('MonthShort8'), jsBackend.locale.loc('MonthShort9'), jsBackend.locale.loc('MonthShort10'), jsBackend.locale.loc('MonthShort11'), jsBackend.locale.loc('MonthShort12') ] var $inputDatefieldNormal = $('.inputDatefieldNormal') var $inputDatefieldFrom = $('.inputDatefieldFrom') var $inputDatefieldTill = $('.inputDatefieldTill') var $inputDatefieldRange = $('.inputDatefieldRange') $('.inputDatefieldNormal, .inputDatefieldFrom, .inputDatefieldTill, .inputDatefieldRange').datepicker( { dayNames: dayNames, dayNamesMin: dayNamesMin, dayNamesShort: dayNamesShort, hideIfNoPrevNext: true, monthNames: monthNames, monthNamesShort: monthNamesShort, nextText: jsBackend.locale.lbl('Next'), prevText: jsBackend.locale.lbl('Previous'), showAnim: 'slideDown' }) // the default, nothing special $inputDatefieldNormal.each(function () { // variables var $this = $(this) // get data var data = $(this).data() var value = $(this).val() // set options $this.datepicker('option', { dateFormat: data.mask, firstDate: data.firstday }).datepicker('setDate', value) }) // date fields that have a certain start date $inputDatefieldFrom.each(function () { // variables var $this = $(this) // get data var data = $(this).data() var value = $(this).val() // set options $this.datepicker('option', { dateFormat: data.mask, firstDay: data.firstday, minDate: new Date(parseInt(data.startdate.split('-')[0], 10), parseInt(data.startdate.split('-')[1], 10) - 1, parseInt(data.startdate.split('-')[2], 10)) }).datepicker('setDate', value) }) // date fields that have a certain end date $inputDatefieldTill.each(function () { // variables var $this = $(this) // get data var data = $(this).data() var value = $(this).val() // set options $this.datepicker('option', { dateFormat: data.mask, firstDay: data.firstday, maxDate: new Date(parseInt(data.enddate.split('-')[0], 10), parseInt(data.enddate.split('-')[1], 10) - 1, parseInt(data.enddate.split('-')[2], 10)) }).datepicker('setDate', value) }) // date fields that have a certain range $inputDatefieldRange.each(function () { // variables var $this = $(this) // get data var data = $(this).data() var value = $(this).val() // set options $this.datepicker('option', { dateFormat: data.mask, firstDay: data.firstday, minDate: new Date(parseInt(data.startdate.split('-')[0], 10), parseInt(data.startdate.split('-')[1], 10) - 1, parseInt(data.startdate.split('-')[2], 10), 0, 0, 0, 0), maxDate: new Date(parseInt(data.enddate.split('-')[0], 10), parseInt(data.enddate.split('-')[1], 10) - 1, parseInt(data.enddate.split('-')[2], 10), 23, 59, 59) }).datepicker('setDate', value) }) }, // set the focus on the first field focusFirstField: function () { $('form input:visible:not(.noFocus):first').focus() }, // set placeholders placeholders: function () { // detect if placeholder-attribute is supported jQuery.support.placeholder = ('placeholder' in document.createElement('input')) if (!jQuery.support.placeholder) { // variables var $placeholder = $('input[placeholder]') // bind focus $placeholder.on('focus', function () { // grab element var $input = $(this) // only do something when the current value and the placeholder are the same if ($input.val() === $input.attr('placeholder')) { // clear $input.val('') // remove class $input.removeClass('placeholder') } }) $placeholder.blur(function () { // grab element var $input = $(this) // only do something when the input is empty or the value is the same as the placeholder if ($input.val() === '' || $input.val() === $input.attr('placeholder')) { // set placeholder $input.val($input.attr('placeholder')) // add class $input.addClass('placeholder') } }) // call blur to initialize $placeholder.blur() // hijack the form so placeholders aren't submitted as values $placeholder.parents('form').submit(function () { // find elements with placeholders $(this).find('input[placeholder]').each(function () { // grab element var $input = $(this) // if the value and the placeholder are the same reset the value if ($input.val() === $input.attr('placeholder')) $input.val('') }) }) } }, // replaces buttons with <a><span>'s (to allow more flexible styling) and handle the form submission for them submitWithLinks: function () { // the html for the button that will replace the input[submit] var replaceHTML = '<a class="{class}" href="#{id}"><span>{label}</span></a>' // are there any forms that should be submitted with a link? if ($('form.submitWithLink').length > 0) { $('form.submitWithLink').each(function () { // get id var formId = $(this).attr('id') var dontSubmit = false // validate id if (formId !== '') { // loop every button to be replaced $('form#' + formId + '.submitWithLink input[type=submit]').each(function () { $(this).after(replaceHTML.replace('{label}', $(this).val()).replace('{id}', $(this).attr('id')).replace('{class}', 'submitButton button ' + $(this).attr('class'))).css({ position: 'absolute', top: '-9000px', left: '-9000px' }).attr('tabindex', -1) }) // add onclick event for button (button can't have the name submit) $('form#' + formId + ' a.submitButton').on('click', function (e) { e.preventDefault() // is the button disabled? if ($(this).prop('disabled')) { return false } else { $('form#' + formId).submit() } }) // dont submit the form on certain elements $('form#' + formId + ' .dontSubmit').on('focus', function () { dontSubmit = true }) $('form#' + formId + ' .dontSubmit').on('blur', function () { dontSubmit = false }) // hijack the submit event $('form#' + formId).submit(function (e) { return !dontSubmit }) } }) } }, // add tagsinput to the correct input fields tagsInput: function () { if ($('.js-tags-input').length > 0) { var allTags = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: { url: '/backend/ajax', prepare: function (settings) { settings.type = 'POST' settings.data = {fork: {module: 'Tags', action: 'GetAllTags'}} return settings }, cache: false, filter: function (list) { list = list.data return list } } }) allTags.initialize() $('.js-tags-input').tagsinput({ tagClass: 'label label-primary', typeaheadjs: { name: 'Tags', source: allTags.ttAdapter() } }) } }, // show a warning when people are leaving the unloadWarning: function () { // only execute when there is a form on the page if ($('form:visible').length > 0) { // loop fields $('form input, form select, form textarea').each(function () { var $this = $(this) if (!$this.hasClass('dontCheckBeforeUnload')) { // store initial value $(this).data('initial-value', $(this).val()).addClass('checkBeforeUnload') } }) // bind before unload, this will ask the user if he really wants to leave the page $(window).on('beforeunload', jsBackend.forms.unloadWarningCheck) // if a form is submitted we don't want to ask the user if he wants to leave, we know for sure $('form').on('submit', function (e) { if (!e.isDefaultPrevented()) $(window).off('beforeunload') }) } }, // check if any element has been changed unloadWarningCheck: function (e) { // initialize var var changed = false // loop fields $('.checkBeforeUnload').each(function () { // initialize var $this = $(this) // compare values if ($this.data('initial-value') !== $this.val()) { if (typeof $this.data('initial-value') === 'undefined' && $this.val() === '') { } else { // reset var changed = true // stop looking return false } } }) // return if needed if (changed) return jsBackend.locale.msg('ValuesAreChanged') }, // Add date pickers to the appropriate input elements datePicker: function () { $('input[data-role="fork-datepicker"]').each( function (index, datePickerElement) { $(datePickerElement).datepicker() } ) } } /** * Do custom layout/interaction stuff */ jsBackend.layout = { // init, something like a constructor init: function () { // hovers $('.contentTitle').hover(function () { $(this).addClass('hover') }, function () { $(this).removeClass('hover') }) $('.jsDataGrid td a').hover(function () { $(this).parent().addClass('hover') }, function () { $(this).parent().removeClass('hover') }) jsBackend.layout.showBrowserWarning() jsBackend.layout.dataGrid() if ($('.dataFilter').length > 0) jsBackend.layout.dataFilter() // fix last childs $('.options p:last').addClass('lastChild') }, // dataFilter layout fixes dataFilter: function () { // add last child and first child for IE $('.dataFilter tbody td:first-child').addClass('firstChild') $('.dataFilter tbody td:last-child').addClass('lastChild') // init var var tallest = 0 // loop group $('.dataFilter tbody .options').each(function () { // taller? if ($(this).height() > tallest) tallest = $(this).height() }) // set new height $('.dataFilter tbody .options').height(tallest) }, // data grid layout dataGrid: function () { if (jQuery.browser.msie) { $('.jsDataGrid tr td:last-child').addClass('lastChild') $('.jsDataGrid tr td:first-child').addClass('firstChild') } // dynamic striping $('.dynamicStriping.jsDataGrid tr:nth-child(2n)').addClass('even') $('.dynamicStriping.jsDataGrid tr:nth-child(2n+1)').addClass('odd') }, // if the browser isn't supported, show a warning showBrowserWarning: function () { var showWarning = false var version = '' // check firefox if (jQuery.browser.mozilla) { // get version version = parseInt(jQuery.browser.version.substr(0, 3).replace(/\./g, '')) // lower than 19? if (version < 19) showWarning = true } // check opera if (jQuery.browser.opera) { // get version version = parseInt(jQuery.browser.version.substr(0, 1)) // lower than 9? if (version < 9) showWarning = true } // check safari, should be webkit when using 1.4 if (jQuery.browser.safari) { // get version version = parseInt(jQuery.browser.version.substr(0, 3)) // lower than 1.4? if (version < 400) showWarning = true } // check IE if (jQuery.browser.msie) { // get version version = parseInt(jQuery.browser.version.substr(0, 1)) // lower or equal than 6 if (version <= 6) showWarning = true } // show warning if needed if (showWarning) $('#showBrowserWarning').show() } } /** * Locale */ jsBackend.locale = { initialized: false, data: {}, // init, something like a constructor init: function () { $.ajax({ url: '/src/Backend/Cache/Locale/' + jsBackend.data.get('interface_language') + '.json', type: 'GET', dataType: 'json', async: false, success: function (data) { jsBackend.locale.data = data jsBackend.locale.initialized = true }, error: function (jqXHR, textStatus, errorThrown) { throw new Error('Regenerate your locale-files.') } }) }, // get an item from the locale get: function (type, key, module) { // initialize if needed if (!jsBackend.locale.initialized) { jsBackend.locale.init() } var data = jsBackend.locale.data // value to use when the translation was not found var missingTranslation = '{$' + type + key + '}' // validate if (data === null || !data.hasOwnProperty(type) || data[type] === null) { return missingTranslation } // this is for the labels prefixed with "loc" if (typeof (data[type][key]) === 'string') { return data[type][key] } // if the translation does not exist for the given module, try to fall back to the core if (!data[type].hasOwnProperty(module) || data[type][module] === null || !data[type][module].hasOwnProperty(key) || data[type][module][key] === null) { if (!data[type].hasOwnProperty('Core') || data[type]['Core'] === null || !data[type]['Core'].hasOwnProperty(key) || data[type]['Core'][key] === null) { return missingTranslation } return data[type]['Core'][key] } return data[type][module][key] }, // get an error err: function (key, module) { if (typeof module === 'undefined') module = jsBackend.current.module return jsBackend.locale.get('err', key, module) }, // get a label lbl: function (key, module) { if (typeof module === 'undefined') module = jsBackend.current.module return jsBackend.locale.get('lbl', key, module) }, // get localization loc: function (key) { return jsBackend.locale.get('loc', key) }, // get a message msg: function (key, module) { if (typeof module === 'undefined') module = jsBackend.current.module return jsBackend.locale.get('msg', key, module) } } /** * Handle form messages (action feedback: success, error, ...) */ jsBackend.messages = { timers: [], // init, something like a constructor init: function () { // bind close button $(document).on('click', '#messaging .formMessage .iconClose', function (e) { e.preventDefault() jsBackend.messages.hide($(this).parents('.formMessage')) }) }, // hide a message hide: function (element) { // fade out element.removeClass('active').delay(250).hide(1) }, // add a new message into the que add: function (type, content, optionalClass) { var uniqueId = 'e' + new Date().getTime().toString() // switch icon type var icon switch (type) { case 'danger': icon = 'times' break case 'warning': icon = 'exclamation-triangle' break case 'success': icon = 'check' break case 'info': icon = 'info' break } var html = '<div role="alert" id="' + uniqueId + '" class="alert-main alert alert-' + type + ' ' + optionalClass + ' alert-dismissible formMessage ' + type + 'Message">' + '<div class="container-fluid">' + '<i class="fa fa-' + icon + '" aria-hidden="true"></i>' + ' ' + content + '<button type="button" class="close" data-dismiss="alert" aria-label="' + utils.string.ucfirst(jsBackend.locale.lbl('Close')) + '">' + '<span aria-hidden="true" class="fa fa-close"></span>' + '</button>' + '</div>' + '</div>' // prepend if (optionalClass === undefined || optionalClass !== 'alert-static') { $('#messaging').prepend(html) } else { $('.content').prepend(html) } // show $('#' + uniqueId).addClass('active') // timeout if (optionalClass === undefined || optionalClass !== 'alert-static') { if (type === 'info' || type === 'success') { setTimeout(function () { jsBackend.messages.hide($('#' + uniqueId)) }, 5000) } } } } /** * Apply tabs */ jsBackend.tabs = { // init, something like a constructor init: function () { if ($('.nav-tabs').length > 0) { $('.nav-tabs').tab() $('.tab-content .tab-pane').each(function () { if ($(this).find('.formError').length > 0) { $($('.nav-tabs a[href="#' + $(this).attr('id') + '"]').parent()).addClass('has-error') } }) } $('.nav-tabs a').click(function (e) { // if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump if (window.history && window.history.pushState) { // an empty state object for now — either we implement a proper pop state handler ourselves, or wait for jQuery UI upstream window.history.pushState({}, document.title, this.getAttribute('href')) } else { // for browsers that do not support pushState // save current scroll height var scrolled = $(window).scrollTop() // set location hash window.location.hash = '#' + this.getAttribute('href').split('#')[1] // reset scroll height $(window).scrollTop(scrolled) } }) // Show tab if the hash is in the url var hash = window.location.hash if ($(hash).length > 0 && $(hash).hasClass('tab-pane')) { $('a[href="' + hash + '"]').tab('show') } } } /** * Apply tooltip */ jsBackend.tooltip = { // init, something like a constructor init: function () { // variables var $tooltip = $('[data-toggle="tooltip"]') if ($tooltip.length > 0) { $tooltip.tooltip() } } } /** * Enable setting of sequence by drag & drop */ jsBackend.tableSequenceByDragAndDrop = { // init, something like a constructor init: function () { // variables var $sequenceBody = $('.sequenceByDragAndDrop tbody') if ($sequenceBody.length > 0) { $sequenceBody.sortable( { items: 'tr', handle: 'td.dragAndDropHandle', placeholder: 'dragAndDropPlaceholder', forcePlaceholderSize: true, stop: function (e, ui) { jsBackend.tableSequenceByDragAndDrop.saveNewSequence($(this).closest('table.jsDataGrid')) } } ) $sequenceBody.find('[data-role="order-move"]').on('click.fork.order-move', function (e) { var $this = $(this) var $row = $this.closest('tr') var direction = $this.data('direction') e.preventDefault() if (direction === 'up') { $row.prev().insertAfter($row) } else if (direction === 'down') { $row.next().insertBefore($row) } jsBackend.tableSequenceByDragAndDrop.saveNewSequence($row.closest('table')) }) } }, saveNewSequence: function ($table) { var action = (typeof $table.data('action') === 'undefined') ? 'Sequence' : $table.data('action').toString() var module = (typeof $table.data('module') === 'undefined') ? jsBackend.current.module : $table.data('module').toString() var extraParams = {} var $rows = $table.find('tr[id*=row-]') var newIdSequence = [] // fetch extra params if (typeof $table.data('extra-params') !== 'undefined') { extraParams = $table.data('extra-params') // we convert the unvalid {'key':'value'} to the valid {"key":"value"} extraParams = extraParams.replace(/'/g, '"') // we parse it as an object extraParams = $.parseJSON(extraParams) } $rows.each(function () { newIdSequence.push($(this).data('id')) }) $.ajax({ data: $.extend({ fork: {module: module, action: action}, new_id_sequence: newIdSequence.join(',') }, extraParams), success: function (data) { // not a success so revert the changes if (data.code !== 200) { $table.sortable('cancel') jsBackend.messages.add('danger', jsBackend.locale.err('AlterSequenceFailed')) } // redo odd-even $table.find('tr').removeClass('odd').removeClass('even') $table.find('tr:even').addClass('odd') $table.find('tr:odd').addClass('even') if (data.code !== 200 && jsBackend.debug) { window.alert(data.message) } jsBackend.messages.add('success', jsBackend.locale.msg('ChangedOrderSuccessfully')) }, error: function (XMLHttpRequest) { var textStatus = jsBackend.locale.err('AlterSequenceFailed') // get real message if (typeof XMLHttpRequest.responseText !== 'undefined') { textStatus = $.parseJSON(XMLHttpRequest.responseText).message } jsBackend.messages.add('danger', textStatus) $table.sortable('cancel') if (jsBackend.debug) { window.alert(textStatus) } } }) } } window.requestAnimationFrame = (function () { var lastTime lastTime = 0 return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) { var curTime, id, timeToCall curTime = new Date().getTime() timeToCall = Math.max(0, 16 - (curTime - lastTime)) id = window.setTimeout(function () { var thisTime = curTime + timeToCall return callback(thisTime) }, timeToCall) lastTime = curTime + timeToCall return id } })() jsBackend.resizeFunctions = { init: function () { var calculate, tick, ticking ticking = false calculate = (function (_this) { return function () { jsBackend.navigation.resize() if (typeof jsBackend.analytics !== 'undefined') { jsBackend.analytics.chartDoubleMetricPerDay.init() jsBackend.analytics.chartPieChart.init() } ticking = false } })(this) tick = function () { if (!ticking) { this.requestAnimationFrame(calculate) ticking = true } } tick() return $(window).on('load resize', function () { return tick() }) } } jsBackend.session = { init: function () { jsBackend.session.sessionTimeoutPopup() }, // Display a session timeout warning 1 minute before the session might actually expire sessionTimeoutPopup: function () { setInterval(function () { window.alert(jsBackend.locale.msg('SessionTimeoutWarning')) }, (jsData.Core.session_timeout - 60) * 1000) } } $(jsBackend.init)
$(document).ready(function() { $("#error").hide(); });
// ==UserScript== // @name amazon_wishlist_sum // @namespace danibaena // @description Just a simple script to sum all items and prices in an Amazon.es' Wishlist url // @include http://www.amazon.es/gp/registry/wishlist/* // @include https://www.amazon.es/gp/registry/wishlist/* // @include https://www.amazon.es/hz/wishlist/ls/* // @include http://www.amazon.es/hz/wishlist/ls/* // @include http://www.amazon.es/gp/aw/ls/* // @include https://www.amazon.es/gp/aw/ls/* // @require https://code.jquery.com/jquery-3.2.1.slim.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant none // ==/UserScript== function addItemPricesSum() { var itemsList = !isMobile() ? $(".g-item-sortable[data-id]") : $(".awl-item-wrapper[data-price]") ; var priceClass = "a-price-whole"; var paginationID = "wishlistPagination"; var pages = document.getElementById(paginationID); var page = pages ? "Datos para esta página de la lista:<br>" : "Datos de la lista:<br>"; var itemSum = 0; var itemCounter = 0; var itemNotAvailableCounter = 0; itemsList.each(function(index , item) { var result = $(item).attr('data-price'); result = result !== '-Infinity' ? parseFloat(result) : result; if(result === '-Infinity') { itemNotAvailableCounter++; } else { itemSum += result; itemCounter++; } }); itemSum = itemSum.toFixed(2); itemSumCoinc = (itemSum/1.04).toFixed(2); itemSumCoinc = itemSumCoinc.toString().replace(".",",").replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1."); itemSum = itemSum.toString().replace(".",",").replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1."); var textList = ` <p>${page}</p> <div class="row"> <span>Artículos totales:</span> <span class="right">${itemCounter}</span> </div> <div class="row"> <span>Artículos no disponibles:</span> <span class="right">${itemNotAvailableCounter}</span> </div> <div class="row"> <span>Coste total:</span> <span class="right">${itemSum} €</span> </div> <div class="row"> <span>Coste total con COINC:</span> <span class="right">${itemSumCoinc} €</span> </div> `; var ruleDivider = '<hr class="a-divider-normal awl-divider" id="scriptlist-divider">'; var scriptList = ` ${isMobile() ? ruleDivider : ''} <div class="a-price ${priceClass}" data-a-size="m" data-a-color="base" id="scriptlist"> ${textList} </div> `; var $scriptList = $('#scriptlist'); if($scriptList.length) { $scriptList.replaceWith(scriptList); } else { $(scriptList).insertAfter('#endOfListMarker'); } } var isMobile = function() { return /Mobi/i.test(navigator.userAgent) || /Android/i.test(navigator.userAgent); }; var scriptListStyles = ` <style> #scriptlist { line-height: 1; font-size: 12px; font-weight: 400; z-index: 2; position: relative; display: block; max-width: 292px; margin: 0 auto; background-color: #fff; padding-top: 15px; ${isMobile() ? 'padding-left: 15px;' : ''} } #scriptlist p { font-weight: 600; } #scriptlist .row { display: flex; justify-content: space-between; padding-bottom: 5px; } #scriptlist .row .right { font-weight: 600; } #scriptlist-divider { margin-top: 15px; } </style> `; $(scriptListStyles).appendTo('head'); var elementToWait = !isMobile() ? ".g-item-sortable[data-id]" : ".awl-item-wrapper[data-price]"; waitForKeyElements (elementToWait, addItemPricesSum, false); waitForKeyElements ('#endOfListMarker', addItemPricesSum, false);
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.ObjectListItem. sap.ui.define(['jquery.sap.global', './ListItemBase', './library', 'sap/ui/core/IconPool'], function(jQuery, ListItemBase, library, IconPool) { "use strict"; /** * Constructor for a new ObjectListItem. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * ObjectListItem is a display control that provides summary information about an object as an item in a list. The object list item title is the key identifier of the object. Additional text and icons can be used to further distinguish it from other objects. Attributes and statuses can be used to provide additional meaning about the object to the user. * @extends sap.m.ListItemBase * @version 1.32.10 * * @constructor * @public * @since 1.12 * @alias sap.m.ObjectListItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ObjectListItem = ListItemBase.extend("sap.m.ObjectListItem", /** @lends sap.m.ObjectListItem.prototype */ { metadata : { library : "sap.m", properties : { /** * Object list item title */ title : {type : "string", group : "Misc", defaultValue : null}, /** * Object list item number */ number : {type : "string", group : "Misc", defaultValue : null}, /** * The number units qualifier of the object list item */ numberUnit : {type : "string", group : "Misc", defaultValue : null}, /** * Introductory text for the object list item. */ intro : {type : "string", group : "Misc", defaultValue : null}, /** * Object list item icon displayed to the left of the title. */ icon : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null}, /** * Icon displayed when the object list item is active. */ activeIcon : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null}, /** * By default, this is set to true but then one or more requests are sent trying to get the density perfect version of image if this version of image doesn't exist on the server. * * If bandwidth is the key for the application, set this value to false. */ iconDensityAware : {type : "boolean", group : "Misc", defaultValue : true}, /** * Set the favorite state for the object list item * @since 1.16.0 */ markFavorite : {type : "boolean", group : "Misc", defaultValue : null}, /** * Set the flagged state for the object list item * @since 1.16.0 */ markFlagged : {type : "boolean", group : "Misc", defaultValue : null}, /** * Set to true if the object list item can be marked with icons such as favorite and flag. * @since 1.16.0 */ showMarkers : {type : "boolean", group : "Misc", defaultValue : null}, /** * Object list item number and numberUnit value state. * @since 1.16.0 */ numberState : {type : "sap.ui.core.ValueState", group : "Misc", defaultValue : sap.ui.core.ValueState.None}, /** * Determines the text direction of the item title. * Available options for the title direction are LTR (left-to-right) and RTL (right-to-left). * By default the item title inherits the text direction from its parent. */ titleTextDirection: {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit}, /** * Determines the text direction of the item intro. * Available options for the intro direction are LTR (left-to-right) and RTL (right-to-left). * By default the item intro inherits the text direction from its parent. */ introTextDirection: {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit}, /** * Determines the text direction of the item number. * Available options for the number direction are LTR (left-to-right) and RTL (right-to-left). * By default the item number inherits the text direction from its parent. */ numberTextDirection: {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit}, /** * Set the locked state of the object list item. * @since 1.28 */ markLocked : {type : "boolean", group : "Misc", defaultValue : false} }, defaultAggregation : "attributes", aggregations : { /** * List of attributes displayed below the title to the left of the status fields. */ attributes : {type : "sap.m.ObjectAttribute", multiple : true, singularName : "attribute"}, /** * First status text field shown on the right side of the attributes. */ firstStatus : {type : "sap.m.ObjectStatus", multiple : false}, /** * Second status text field shown on the right side of the attributes. */ secondStatus : {type : "sap.m.ObjectStatus", multiple : false} } }}); ///** // * This file defines behavior for the control, // */ // get resource translation bundle; var oLibraryResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"); /** * @private */ ObjectListItem.prototype.exit = function(oEvent) { // image or icon if initialized if (this._oImageControl) { this._oImageControl.destroy(); } if (this._oPlaceholderIcon) { this._oPlaceholderIcon.destroy(); this._oPlaceholderIcon = undefined; } if (this._oFavIcon) { this._oFavIcon.destroy(); this._oFavIcon = undefined; } if (this._oFlagIcon) { this._oFlagIcon.destroy(); this._oFlagIcon = undefined; } if (this._oLockIcon) { this._oLockIcon.destroy(); this._oLockIcon = undefined; } if (this._oTitleText) { this._oTitleText.destroy(); this._oTitleText = undefined; } ListItemBase.prototype.exit.apply(this); }; /** * @private * @returns {boolean} */ ObjectListItem.prototype._hasAttributes = function() { var attributes = this.getAttributes(); if (attributes.length > 0) { for (var i = 0; i < attributes.length; i++) { if (!attributes[i]._isEmpty()) { return true; } } } return false; }; /** * @private * @returns {boolean} */ ObjectListItem.prototype._hasStatus = function() { return ((this.getFirstStatus() && !this.getFirstStatus()._isEmpty()) || (this.getSecondStatus() && !this.getSecondStatus()._isEmpty() )); }; /** * @private * @returns {boolean} */ ObjectListItem.prototype._hasBottomContent = function() { return (this._hasAttributes() || this._hasStatus() || this.getShowMarkers() || this.getMarkLocked()); }; /** * @private * @returns {Array} */ ObjectListItem.prototype._getVisibleAttributes = function() { var aAllAttributes = this.getAttributes(); var aVisibleAttributes = []; for (var i = 0; i < aAllAttributes.length; i++) { if (aAllAttributes[i].getVisible()) { aVisibleAttributes.push(aAllAttributes[i]); } } return aVisibleAttributes; }; /** * Lazy load list item's image. * * @private */ ObjectListItem.prototype._getImageControl = function() { var sImgId = this.getId() + '-img'; var sSize = "2.5rem"; var mProperties = { src : this.getIcon(), height : sSize, width : sSize, size: sSize, useIconTooltip : false, densityAware : this.getIconDensityAware() }; var aCssClasses = ['sapMObjLIcon']; this._oImageControl = sap.m.ImageHelper.getImageControl(sImgId, this._oImageControl, this, mProperties, aCssClasses); return this._oImageControl; }; /** * Overwrite base method to hook into list item's active handling * * @private */ ObjectListItem.prototype._activeHandlingInheritor = function() { var sActiveSrc = this.getActiveIcon(); if (!!this._oImageControl && !!sActiveSrc) { this._oImageControl.setSrc(sActiveSrc); } }; /** * Overwrite base method to hook into list item's inactive handling * * @private */ ObjectListItem.prototype._inactiveHandlingInheritor = function() { var sSrc = this.getIcon(); if (!!this._oImageControl) { this._oImageControl.setSrc(sSrc); } }; /** * @private * @returns Flag icon control */ //TODO Remove placeholder when Safari iconFont issue is addressed. ObjectListItem.prototype._getPlaceholderIcon = function() { if (!this._oPlaceholderIcon) { var oPlaceholderIconUri = IconPool.getIconURI("fridge"); this._oPlaceholderIcon = IconPool.createControlByURI({ id: this.getId() + "-placeholder", useIconTooltip : false, src: oPlaceholderIconUri }); this._oPlaceholderIcon.addStyleClass("sapMObjStatusMarkerInvisible"); } return this._oPlaceholderIcon; }; /** * @private * @returns Flag icon control */ ObjectListItem.prototype._getFlagIcon = function() { if (!this._oFlagIcon) { var oFlagIconUri = IconPool.getIconURI("flag"); this._oFlagIcon = IconPool.createControlByURI({ id: this.getId() + "-flag", tooltip: oLibraryResourceBundle.getText("TOOLTIP_OLI_FLAG_MARK_VALUE"), src: oFlagIconUri }); } return this._oFlagIcon; }; /** * @private * @returns Lock icon control */ ObjectListItem.prototype._getLockIcon = function() { if (!this._oLockIcon) { var oLockIconUri = IconPool.getIconURI("locked"); this._oLockIcon = IconPool.createControlByURI({ id: this.getId() + "-lock", tooltip: oLibraryResourceBundle.getText("TOOLTIP_OLI_LOCK_MARK_VALUE"), src: oLockIconUri }).addStyleClass("sapMObjStatusMarkerLocked"); } return this._oLockIcon; }; /** * @private * @returns Favorite icon control */ ObjectListItem.prototype._getFavoriteIcon = function() { if (!this._oFavIcon) { var oFavIconUri = IconPool.getIconURI("favorite"); this._oFavIcon = IconPool.createControlByURI({ id: this.getId() + "-favorite", tooltip: oLibraryResourceBundle.getText("TOOLTIP_OLI_FAVORITE_MARK_VALUE"), src: oFavIconUri }); } return this._oFavIcon; }; /** * @private * @returns title text control */ ObjectListItem.prototype._getTitleText = function() { if (!this._oTitleText) { this._oTitleText = new sap.m.Text(this.getId() + "-titleText", { maxLines: 2 }); this._oTitleText.setParent(this, null, true); } return this._oTitleText; }; return ObjectListItem; }, /* bExport= */ true);
import React from 'react' import test from 'tape' import { shallow } from 'enzyme' import ListItem from './' test('<ListItem />', t => { const wrapper = shallow(<ListItem>Beep</ListItem>) t.equals(wrapper.text(), 'Beep') t.end() }) test('<ListItem className />', t => { const wrapper = shallow(<ListItem className="green">Beep</ListItem>) t.equals(wrapper.props().className, 'flex items-center lh-copy pa3 ph0-l bb b--black-10 green') t.end() }) test('<ListItem left />', t => { const img = <img alt="bill murray" src="http://www.fillmurray.com/300/300" /> const wrapper = shallow(<ListItem left={img}>Beep</ListItem>) t.ok(wrapper.contains(img)) t.end() }) test('<ListItem right />', t => { const img = <img alt="bill murray" src="http://www.fillmurray.com/300/300" /> const button = <button>Click</button> const wrapper = shallow(<ListItem right={button}>Beep</ListItem>) t.ok(wrapper.contains(button)) t.ok(!wrapper.contains(img)) t.end() })
/* Web call needed to discover baseURI needed to call Users API for individual LiveEngage accounts for Accounts: This URL is for app keys that have Read/Write enabled on the API https://api.liveperson.net/api/account/{YOUR ACCOUNT NUMBER}/service/accountConfigReadWrite/baseURI.json?version=1.0 This URL is for app keys that have Read Only enabled on the API https://api.liveperson.net/api/account/{YOUR ACCOUNT NUMBER}/service/accountConfigReadOnly/baseURI.json?version=1.0 Expected response example: { "service":"accountConfigReadOnly", "account":"56072331", "baseURI":"va-a.acr.liveperson.net" } */ // To run this example, you will need to install the Request module. // run - npm install request var request = require('request'); var oauth = { consumer_key: 'your app key', consumer_secret: 'your app secret', token: 'your access token', token_secret: 'your access token secret' }; // Get a list of all the skills // Example URL: https://va-a.ac.liveperson.net/api/account/56072331/configuration/le-users/skills?v=1 var url = 'https://{YOUR BASE URI}/api/account/{YOUR ACCOUNT NUMBER}/configuration/le-users/skills?v=1'; request.get({ url: url, oauth: oauth, json: true, headers: { 'Content-Type': 'application/json' } }, function (e, r, b) { if (!e && r.statusCode == 200) { console.log(JSON.stringify(b)); } else { console.log(e); } });
// ## LayoutPage // // Represents the Layout page. Mounts to #root. // var LayoutPage = new Combo.Component({ render: function() { return ` ${HeaderComponent.render()} ${SidebarComponent.render()} <main role="main" id="content"></main> `; } });
/** * Created by alexander on 14.05.15. */ 'use strict'; module.exports = function (gulp, plugins, config, utility, logger, notifier) { return function () { logger.info('Compiling sass files to css and adding vendor prefixes.'); gulp.src(config.files.src.sassfx) .pipe(plugins.if(config.isStage, plugins.sourcemaps.init())) .pipe(plugins.sass().on('error', plugins.sass.logError)) .pipe(plugins.autoprefixer()) .pipe(plugins.if(config.isStage, plugins.sourcemaps.write('./'))) .pipe(plugins.if(config.isProduction, plugins.csso())) .pipe(gulp.dest(config.paths.dest.styles)); }; };
export const UPLOAD_FILE_SUCCESS = 'UPLOAD_FILE_SUCCESS'; export const UPLOAD_FILE_FAILURE = 'UPLOAD_FILE_FAILURE'; export const FETCH_FILES_REQUEST = 'FETCH_FILES_REQUEST'; export const FETCH_FILES_SUCCESS = 'FETCH_FILES_SUCCESS'; export const FETCH_FILES_FAILURE = 'FETCH_FILES_FAILURE'; export const UPDATE_FILE_NAME = 'UPDATE_FILE_NAME'; export const UPDATE_UPLOAD_PROGRESS = 'UPDATE_UPLOAD_PROGRESS'; export const ADD_UPLOAD_FILE = 'ADD_UPLOAD_FILE'; export const UPDATE_COMPLETED_COUNT = 'UPDATE_COMPLETED_COUNT'; export const DELETE_FILE_SUCCESS = 'DELETE_FILE_SUCCESS'; export const DELETE_FILE_FAILURE = 'DELETE_FILE_FAILURE'; export const CREATE_FOLDER_SUCCESS = 'CREATE_FOLDER_SUCCESS'; export const CREATE_FOLDER_FAILURE = 'CREATE_FOLDER_FAILURE'; export const CHANGE_CURRENT_FOLDER = 'CHANGE_CURRENT_FOLDER'; export const UPDATE_FILE_SUCCESS = 'UPDATE_FILE_SUCCESS'; export const UPDATE_FILE_FAILURE = 'UPDATE_FILE_FAILURE'; export const SELECT_ITEM = 'SELECT_ITEM'; export const UNSELECT_ITEM = 'UNSELECT_ITEM'; export const SELECT_ALL = 'SELECT_ALL'; export const UNSELECT_ALL = 'UNSELECT_ALL'; export const SET_SELECTED_ITEM_AMOUNT_TO_ZERO = 'SET_SELECTED_ITEM_AMOUNT_TO_ZERO'; export const CLOSE_UPLOADER = 'CLOSE_UPLOADER';
module.exports = function(app) { var express = require('express'); var snippetsRouter = express.Router(); snippetsRouter.get('/', function(req, res) { res.send({ 'snippets': [ { 'id': 1, 'content': 'This is the content of a snippet attached to a draft.', 'creatorEmail': 'one@gmail.com', 'createdAt': '2015-01-02T14:00:00', } ] }); }); snippetsRouter.post('/', function(req, res) { res.send({ 'snippet': { 'id': 2, 'content': 'The snippet you just sent', 'creatorEmail': 'one@gmail.com', 'createdAt': '2015-01-02T14:00:00', } }); }); snippetsRouter.get('/:id', function(req, res) { res.send({ 'snippets': { id: req.params.id } }); }); snippetsRouter.put('/:id', function(req, res) { res.send({ 'snippets': { id: req.params.id } }); }); snippetsRouter.delete('/:id', function(req, res) { res.status(204).end(); }); app.use('/api/v1/snippets', snippetsRouter); };
function rect(data) { var layer = this.layer, context = this.context; context.rect( layer.normalizeX( data.x || 0 ), layer.normalizeY( data.y || 0 ), layer.normalizeX( data.width || layer.width() ), layer.normalizeY( data.height || layer.height() ) ); } registerElement('rect', function(data) { rect.call(this, data); }); registerElement('background', function(data) { rect.call(this, data); });
var EasyBacklogImpl = function(url, apiKey, accountId) { this.url = url; this.apiKey = apiKey; this.accountId = accountId; }; EasyBacklogImpl.prototype = Object.create(IEasyBacklog); EasyBacklogImpl.prototype.setApiKey = function(apiKey) { this.apiKey = apiKey; }; EasyBacklogImpl.prototype.setAccountId = function(accountId) { this.accountId = accountId; }; EasyBacklogImpl.prototype.call = function(destination, callBackSuccess, callBackFail) { var callSuccess = callBackSuccess; var callFail = callBackFail; $.ajax({ url: this.buildUrl(destination), cache: false, async: true, type: 'GET', dataType:"json" }).done(function(data) { callSuccess(data); }).fail(function(data) { callFail(data); }); }; EasyBacklogImpl.prototype.buildUrl = function(destination) { return this.url+destination+"?api_key="+this.apiKey; };
import { DeviceEventEmitter, NativeAppEventEmitter, NativeEventEmitter, NativeModules, Platform, } from 'react-native'; const { RNBackgroundTimer } = NativeModules; const Emitter = new NativeEventEmitter(RNBackgroundTimer); class BackgroundTimer { constructor() { this.uniqueId = 0; this.callbacks = {}; Emitter.addListener('backgroundTimer.timeout', (id) => { if (this.callbacks[id]) { const callbackById = this.callbacks[id]; const { callback } = callbackById; if (!this.callbacks[id].interval) { delete this.callbacks[id]; } else { RNBackgroundTimer.setTimeout(id, this.callbacks[id].timeout); } callback(); } }); } // Original API start(delay = 0) { return RNBackgroundTimer.start(delay); } stop() { return RNBackgroundTimer.stop(); } runBackgroundTimer(callback, delay) { const EventEmitter = Platform.select({ ios: () => NativeAppEventEmitter, android: () => DeviceEventEmitter, })(); this.start(0); this.backgroundListener = EventEmitter.addListener( 'backgroundTimer', () => { this.backgroundListener.remove(); this.backgroundClockMethod(callback, delay); }, ); } backgroundClockMethod(callback, delay) { this.backgroundTimer = this.setTimeout(() => { callback(); this.backgroundClockMethod(callback, delay); }, delay); } stopBackgroundTimer() { this.stop(); this.clearTimeout(this.backgroundTimer); } // New API, allowing for multiple timers setTimeout(callback, timeout) { this.uniqueId += 1; const timeoutId = this.uniqueId; this.callbacks[timeoutId] = { callback, interval: false, timeout, }; RNBackgroundTimer.setTimeout(timeoutId, timeout); return timeoutId; } clearTimeout(timeoutId) { if (this.callbacks[timeoutId]) { delete this.callbacks[timeoutId]; // RNBackgroundTimer.clearTimeout(timeoutId); } } setInterval(callback, timeout) { this.uniqueId += 1; const intervalId = this.uniqueId; this.callbacks[intervalId] = { callback, interval: true, timeout, }; RNBackgroundTimer.setTimeout(intervalId, timeout); return intervalId; } clearInterval(intervalId) { if (this.callbacks[intervalId]) { delete this.callbacks[intervalId]; // RNBackgroundTimer.clearTimeout(intervalId); } } } export default new BackgroundTimer();
import React, {Component} from 'react'; class ClockUTC extends Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <span>{this.state.date.toUTCString()}</span> ); } } export default ClockUTC;
export function formatVideoDuration(seconds) { const mm = Math.floor(seconds / 60) || 0; const ss = ('0' + Math.floor(seconds % 60)).slice(-2); return mm + ':' + ss; }
var webpack, path, WriteFilePlugin, devServer; webpack = require('webpack'); path = require('path'); ExtractTextPlugin = require('extract-text-webpack-plugin'); devServer = { contentBase: path.resolve(__dirname, './public'), colors: true, quiet: false, noInfo: false, publicPath: '/static/', historyApiFallback: false, host: 'localhost', port: 3000, hot: true, inline: true }; module.exports = { devtool: 'source-map', debug: true, devServer: devServer, context: __dirname, entry: './app/main.jsx', output: { path: path.resolve(__dirname, './build'), filename: 'bundle.js', publicPath: devServer.publicPath }, plugins: [ new ExtractTextPlugin('custom.css', { allChunks: true }), // new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.ProvidePlugin({ 'React':'react', 'ReactDOM':'react-dom' }) ], module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'), include: path.resolve(__dirname, './app') }, { test: /\.jsx?$/, include: path.resolve(__dirname, './app'), loaders: ['babel'] } ] }, resolve: { extensions: [ '', '.js', '.jsx' ] } };
import { Vue, mergeData } from '../../vue' import { NAME_CARD_HEADER } from '../../constants/components' import { PROP_TYPE_ARRAY_OBJECT_STRING, PROP_TYPE_STRING } from '../../constants/props' import { htmlOrText } from '../../utils/html' import { sortKeys } from '../../utils/object' import { copyProps, makeProp, makePropsConfigurable, prefixPropName } from '../../utils/props' import { props as BCardProps } from '../../mixins/card' // --- Props --- export const props = makePropsConfigurable( sortKeys({ ...copyProps(BCardProps, prefixPropName.bind(null, 'header')), header: makeProp(PROP_TYPE_STRING), headerClass: makeProp(PROP_TYPE_ARRAY_OBJECT_STRING), headerHtml: makeProp(PROP_TYPE_STRING) }), NAME_CARD_HEADER ) // --- Main component --- // @vue/component export const BCardHeader = /*#__PURE__*/ Vue.extend({ name: NAME_CARD_HEADER, functional: true, props, render(h, { props, data, children }) { const { headerBgVariant, headerBorderVariant, headerTextVariant } = props return h( props.headerTag, mergeData(data, { staticClass: 'card-header', class: [ props.headerClass, { [`bg-${headerBgVariant}`]: headerBgVariant, [`border-${headerBorderVariant}`]: headerBorderVariant, [`text-${headerTextVariant}`]: headerTextVariant } ], domProps: children ? {} : htmlOrText(props.headerHtml, props.header) }), children ) } })
/** * Created by wxb on 15/12/29. */ 'use strict'; angular.module('tailorApp') .controller('MoreManageNavCtrl', function ($scope, $location, localStorageService) { $scope.privilege = localStorageService.cookie.get('user').privilege; $scope.admin = localStorageService.cookie.get('user').admin; $scope.providerCurrency = localStorageService.cookie.get('user').currency; $scope.getClass = function (path) { return $location.path().indexOf(path) !== -1 ? 'am-text-primary' : ''; }; })
let Cycle = require('@cycle/core') let express = require('express') let serverConfig = require('config') let {Observable} = require('rx') let {makeHTMLDriver} = require('@cycle/dom') let {makeHTTPDriver} = require('@cycle/http') let layout = require('./components/layout') let app = require('./app') function wrapVTreeWithHTMLBoilerplate(canonicalUrl, vtree, context, config, clientBundle) { return layout({canonicalUrl, vtree, context, config, clientBundle}) } function prependHTML5Doctype(html) { return `<!doctype html>${html}` } function wrapAppResultWithBoilerplate(appFn, canonicalUrl, config$, bundle$) { return function wrappedAppFn(sources) { const sinks = appFn(sources) const vtree$ = sinks.DOM const context$ = sinks.context const canonicalUrl$ = Observable.just(canonicalUrl) const wrappedVTree$ = Observable.combineLatest(canonicalUrl$, vtree$, context$, config$, bundle$, wrapVTreeWithHTMLBoilerplate ) return { DOM: wrappedVTree$, HTTP: sinks.HTTP } } } let clientBundle$ = Observable .create(observer => { try { const json = require('../rev-manifest.json') observer.onNext(json) } catch (err) { observer.onError(err) } observer.onCompleted() }) .catch(() => Observable.just({ 'js/bundle.js': 'js/bundle.js', 'css/styles.css': 'css/styles.css' })) let server = express() if (serverConfig.get('statsd.enabled')) { let statsdMiddleware = require('../middlewares/statsd.js') server.use(statsdMiddleware({ host: serverConfig.get('statsd.host'), port: serverConfig.get('statsd.port'), prefix: serverConfig.get('statsd.prefix') })) } server.use('/assets', express.static(__dirname + '/../public')) server.use('/assets', express.static(__dirname + '/../build')) server.get('/:exerciseSlug', (req, res) => { console.log(`req: ${req.method} ${req.url} ${req.params.exerciseSlug}`) // Ignore favicon requests if (req.url === '/favicon.ico') { res.writeHead(200, {'Content-Type': 'image/x-icon'}) res.end() return } const canonicalUrl = `${serverConfig.base_url}${req.url}` let config$ = Observable.just(Object.assign({}, serverConfig)) let actions$ = Observable.just({ type: 'navigate', data: { route: req.url, exerciseSlug: req.params.exerciseSlug } }) let wrappedAppFn = wrapAppResultWithBoilerplate(app, canonicalUrl, config$, clientBundle$) let {sources} = Cycle.run(wrappedAppFn, { DOM: makeHTMLDriver(), HTTP: makeHTTPDriver(), analytics: () => Observable.empty(), actions: () => actions$, context: () => Observable.empty(), config: () => config$ }) let html$ = sources.DOM .map(prependHTML5Doctype) html$.subscribe(html => res.send(html)) }) clientBundle$.subscribe(() => { let port = process.env.PORT || 3000 server.listen(port) console.log(`Listening on port ${port}`) })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var vector2Grid_1 = require("./../vector2Grid"); var util = require("./../../util"); var Item = (function () { function Item() { this.rotation = 0; this.isFlipped = false; this.category = "Misc"; this.destroyOnUse = true; this.name = "Item"; this.defaultSlots = [ [1, 1], [1, 1], ]; } Object.defineProperty(Item.prototype, "defaultSlots", { get: function () { return this._defaultSlots; }, set: function (value) { this._defaultSlots = value; this.slots = this.getDefaultSlotsClone(); }, enumerable: true, configurable: true }); Item.prototype.canUse = function (player) { return true; }; Item.prototype.use = function (player) { }; Item.prototype.canDestroy = function (player) { return true; }; Item.prototype.destroy = function () { }; Item.prototype.getDefaultSlotsClone = function () { return util.cloneObject(this.defaultSlots); }; Item.prototype.getDefaultSize = function () { return new vector2Grid_1.Vector2Grid(this.defaultSlots[0].length, this.defaultSlots.length); }; Item.prototype.getSize = function () { return new vector2Grid_1.Vector2Grid(this.slots[0].length, this.slots.length); }; Item.prototype.updateSlots = function () { this.slots = this.getDefaultSlotsClone(); if (this.isFlipped) { for (var rows = 0; rows < this.getDefaultSize().rows; rows++) { this.slots[rows].reverse(); } } this.slots = util.rotateMatrix(this.slots, this.rotation); }; return Item; }()); exports.Item = Item;
import { combineReducers } from 'redux'; import { FETCH_REGION_LIST, FETCH_REGION_LIST_ID, SEARCH_REGION, SEARCH_REGION_ID, REQUEST_C1_RECAP, RECEIVE_C1_RECAP, RECEIVE_CANDIDATES } from '../actions/index'; function regionList(state = {}, action) { switch (action.type) { case FETCH_REGION_LIST: return Object.assign({}, state, { names: action.payload }); case FETCH_REGION_LIST_ID: return Object.assign({}, state, { nameIds: action.payload }); default: return state; } } function selectedRegion(state = '', action) { switch (action.type) { case SEARCH_REGION: return action.region; default: return state; } } function selectedRegionId(state = null, action) { switch (action.type) { case SEARCH_REGION_ID: return action.regionId; default: return state; } } function regions(state = { isFetching: false, recapitulation: [] }, action) { switch(action.type) { case REQUEST_C1_RECAP: return Object.assign({}, state, { isFetching: true }); case RECEIVE_C1_RECAP: return Object.assign({}, state, { isFetching: false, recapitulation: action.recapitulation }); default: return state; } } function regionsRecapitulation(state = {}, action) { switch(action.type) { case REQUEST_C1_RECAP: case RECEIVE_C1_RECAP: return Object.assign({}, state, { [action.region]: regions(state[action.region], action) }); default: return state; } } function candidates(state = {}, action) { switch(action.type) { case RECEIVE_CANDIDATES: return Object.assign({}, state, { [action.regionId]: action.candidates }); default: return state; } } const rootReducer = combineReducers({ regionList, selectedRegion, selectedRegionId, regionsRecapitulation, candidates }); export default rootReducer;
module.exports = function(grunt){ //require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Hint the JS files jshint: { options: { reporter: 'node_modules/jshint-stylish', }, target: { files: { src: ['Gruntfile.js', 'src/**/*.js', '!src/assets/libs/*.js', '!**/tests/components/**'] } } }, // watch for changes watch: { js: { files: 'src/**/*.js', tasks: ['jshint', 'uglify:dev'], options: { livereload: true }, }, sass: { files: 'src/**/*.scss', task: 'sass', options: { livereload: true }, }, html: { files: 'src/**/*.html', options: { livereload: true }, } }, // Clean the builds clean: { options: { force: true }, dev: { src: ['dev'] }, prod: { src: ['prod'] } }, //copy all files copy: { prod: { //production expand: true, cwd: 'src/', src: ['**', '!**/sass/**', '!**/app/*.js', '!src/**/*.tests.js'], dest: 'prod/' }, dev: { expand: true, cwd: 'src/', src: ['**', '!**/sass/**', '!**/app/*.js', '!src/**/*.tests.js'], dest: 'dev/' } }, uglify: { options: { banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n', mangle: false }, prod: { files: { 'prod/app/about/about.controller.js': 'prod/app/about/about.controller.js', 'prod/app/about/about.factory.js': 'prod/app/about/about.factory.js', 'prod/app/home/home.controller.js': 'prod/app/home/home.controller.js', 'prod/app/shared/core/footer/footer.directive.js': 'prod/app/shared/core/footer/footer.directive.js', 'prod/app/shared/core/footer/header.directive.js': 'prod/app/shared/core/header/header.directive.js', 'prod/app/shared/core/navigation/navigation.directive.js': 'prod/app/shared/core/navigation/navigation.directive.js', 'prod/app/app.js': ['src/app/app.module.js', 'src/app/app.routes.js'], 'prod/assets/js/main.js': 'prod/assets/js/*.js' }, }, dev: { files: { 'dev/app/app.js': ['src/app/app.module.js', 'src/app/app.routes.js'], 'dev/assets/js/main.js': 'dev/assets/js/*.js' }, options: { beautify: { width: 80, beautify: true } } } }, sass: { prod: { options: { style: 'compressed' }, files: { 'prod/assets/css/style.css': 'src/assets/sass/base.scss', } }, dev: { options: { style: 'expanded' }, files: { 'dev/assets/css/style.css': 'src/assets/sass/base.scss', } } }, //connect to the Server connect: { prod: { options: { port: 8000, base: './prod', open: true } }, dev: { options: { port: 8080, base: './dev', open: true } } }, karma: { unit: { options: { frameworks: ['jasmine'], singleRun: true, browsers: ['PhantomJS'], files: [ 'src/assets/libs/angular.js', 'src/assets/libs/angular-route.js', 'src/tests/components/angular-mocks.js', 'src/app/app.module.js', 'src/app/app.routes.js', 'src/app/about/*.js', 'src/app/home/*.js', 'src/app/shared/**/*.js', 'src/**/*.test.js', ], } } } }); //load dependencies grunt.loadNpmTasks('grunt-contrib-jshint'); // JS hinting grunt.loadNpmTasks('grunt-contrib-watch'); // Watch for changes grunt.loadNpmTasks('grunt-contrib-clean'); // Clean the builds grunt.loadNpmTasks('grunt-contrib-copy'); // Copy html files grunt.loadNpmTasks('grunt-contrib-uglify'); // Minify js grunt.loadNpmTasks('grunt-contrib-sass'); // Sass compile grunt.loadNpmTasks('grunt-contrib-connect'); // Server //test grunt.loadNpmTasks('grunt-karma'); //register tasks grunt.registerTask('dev', 'development build', ["copy:dev", "jshint", "uglify:dev", "sass:dev", "connect:dev", "watch"]); grunt.registerTask('prod', 'Grunt production task', ["copy:prod", "uglify:prod", "sass:prod"]); grunt.registerTask('clean-dev', 'cleanup for dev', ["clean:dev"]); grunt.registerTask('clean-prod', 'cleanup for prod', ["clean:prod"]); grunt.registerTask('clean-all', 'clean all builds', ["clean"]); grunt.registerTask('test', ["jshint","karma"]); grunt.registerTask('default', 'Default task', []); };
version https://git-lfs.github.com/spec/v1 oid sha256:d698c911fd58bcee23edc54c2f4505c9798197ba594cd370e9ba8e4ebeb1af85 size 11740
version https://git-lfs.github.com/spec/v1 oid sha256:03d827e9a738a7622dae9cf04aa2a14cc7e90d3486e2744a3128748df84a119d size 2331
version https://git-lfs.github.com/spec/v1 oid sha256:1909143c44b8c37944f1271b9fdc63cf5e0936173b7821fd4af817fd1b19604a size 37701
import gql from 'graphql-tag'; import React, { Component } from 'react'; import { graphql } from 'react-apollo'; import { Link } from 'react-router-dom'; class Wishlist extends Component { render() { const { loading, wishlist } = this.props.data; if (loading) { return <span>Loading...</span>; } if (!wishlist) { return null; } return ( <div> <h1>Wishlist</h1> <ul> { wishlist.meetups.map(meetup => ( <li key={ meetup.id }> <Link to={ `/meetup/${meetup.id}` }> { meetup.name } ({ meetup.priceFormatted }) </Link> </li> )) } </ul> </div> ); } } const WishlistQuery = gql`{ wishlist { meetups { id name priceFormatted isAvailable } } }`; const withData = graphql(WishlistQuery); export default withData(Wishlist);
class LearningActivityController { constructor() { this.name = 'Learning Activity'; } } export default LearningActivityController;
// --------------------- IMPORTS ---------------------------------- var express = require('express') , voronoi = require('./voronoi.js').Voronoi , http = require('http') , routes = require('./routes'); var app = express(); // ------------------------- CONFIGURATION ------------------------ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); if ('development' === app.get('env')) { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); } // ----------------------- ROUTER AND RENDER ---------------------- var render_context = { title: 'au9voronoi', topbar_items: { 'Home': '/', 'About': '/about', 'Demo': '/demo'}, layout: false }; app.get('/demo', function(req,res){ res.render('demo', render_context); }); app.get('/about', function(req,res){ res.render('about', render_context); }); app.get('/', function(req,res){ res.render('index', render_context); }); app.post('/calculate', function(req,res){ var result = voronoi.main(req.body.sites); res.json(result); }); // --------------------- API FOR CALCULATION ---------------------- // -------------------------- LAUNCH SERVER ----------------------- http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();var _jestMessageUtil; function _load_jestMessageUtil() {return _jestMessageUtil = require('jest-message-util');}var _test_result_helpers; function _load_test_result_helpers() {return _test_result_helpers = require('./test_result_helpers');}var _coverage_reporter; function _load_coverage_reporter() {return _coverage_reporter = _interopRequireDefault(require('./reporters/coverage_reporter'));}var _default_reporter; function _load_default_reporter() {return _default_reporter = _interopRequireDefault(require('./reporters/default_reporter'));}var _notify_reporter; function _load_notify_reporter() {return _notify_reporter = _interopRequireDefault(require('./reporters/notify_reporter'));}var _reporter_dispatcher; function _load_reporter_dispatcher() {return _reporter_dispatcher = _interopRequireDefault(require('./reporter_dispatcher'));}var _jestSnapshot; function _load_jestSnapshot() {return _jestSnapshot = _interopRequireDefault(require('jest-snapshot'));}var _summary_reporter; function _load_summary_reporter() {return _summary_reporter = _interopRequireDefault(require('./reporters/summary_reporter'));}var _jestRunner; function _load_jestRunner() {return _jestRunner = _interopRequireDefault(require('jest-runner'));}var _test_watcher; function _load_test_watcher() {return _test_watcher = _interopRequireDefault(require('./test_watcher'));}var _verbose_reporter; function _load_verbose_reporter() {return _verbose_reporter = _interopRequireDefault(require('./reporters/verbose_reporter'));}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};} /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */const SLOW_TEST_TIME = 3000; // The default jest-runner is required because it is the default test runner // and required implicitly through the `runner` ProjectConfig option. (_jestRunner || _load_jestRunner()).default; class TestScheduler { constructor(globalConfig, options) { this._dispatcher = new (_reporter_dispatcher || _load_reporter_dispatcher()).default(); this._globalConfig = globalConfig; this._options = options; this._setupReporters(); } addReporter(reporter) { this._dispatcher.register(reporter); } removeReporter(ReporterClass) { this._dispatcher.unregister(ReporterClass); } scheduleTests(tests, watcher) {var _this = this;return _asyncToGenerator(function* () { const onStart = _this._dispatcher.onTestStart.bind(_this._dispatcher); const timings = []; const contexts = new Set(); tests.forEach(function (test) { contexts.add(test.context); if (test.duration) { timings.push(test.duration); } }); const aggregatedResults = createAggregatedResults(tests.length); const estimatedTime = Math.ceil( getEstimatedTime(timings, _this._globalConfig.maxWorkers) / 1000); // Run in band if we only have one test or one worker available. // If we are confident from previous runs that the tests will finish quickly // we also run in band to reduce the overhead of spawning workers. const runInBand = _this._globalConfig.maxWorkers <= 1 || tests.length <= 1 || tests.length <= 20 && timings.length > 0 && timings.every(function (timing) {return timing < SLOW_TEST_TIME;}); const onResult = (() => {var _ref = _asyncToGenerator(function* (test, testResult) { if (watcher.isInterrupted()) { return Promise.resolve(); } if (testResult.testResults.length === 0) { const message = 'Your test suite must contain at least one test.'; yield onFailure(test, { message, stack: new Error(message).stack }); return Promise.resolve(); } (0, (_test_result_helpers || _load_test_result_helpers()).addResult)(aggregatedResults, testResult); yield _this._dispatcher.onTestResult(test, testResult, aggregatedResults); return _this._bailIfNeeded(contexts, aggregatedResults, watcher); });return function onResult(_x, _x2) {return _ref.apply(this, arguments);};})(); const onFailure = (() => {var _ref2 = _asyncToGenerator(function* (test, error) { if (watcher.isInterrupted()) { return; } const testResult = (0, (_test_result_helpers || _load_test_result_helpers()).buildFailureTestResult)(test.path, error); testResult.failureMessage = (0, (_jestMessageUtil || _load_jestMessageUtil()).formatExecError)( testResult, test.context.config, _this._globalConfig, test.path); (0, (_test_result_helpers || _load_test_result_helpers()).addResult)(aggregatedResults, testResult); yield _this._dispatcher.onTestResult(test, testResult, aggregatedResults); });return function onFailure(_x3, _x4) {return _ref2.apply(this, arguments);};})(); const updateSnapshotState = function () { contexts.forEach(function (context) { const status = (_jestSnapshot || _load_jestSnapshot()).default.cleanup( context.hasteFS, _this._globalConfig.updateSnapshot); aggregatedResults.snapshot.filesRemoved += status.filesRemoved; }); const updateAll = _this._globalConfig.updateSnapshot === 'all'; aggregatedResults.snapshot.didUpdate = updateAll; aggregatedResults.snapshot.failure = !!( !updateAll && ( aggregatedResults.snapshot.unchecked || aggregatedResults.snapshot.unmatched || aggregatedResults.snapshot.filesRemoved)); }; yield _this._dispatcher.onRunStart(aggregatedResults, { estimatedTime, showStatus: !runInBand }); const testRunners = Object.create(null); contexts.forEach(function (_ref3) {let config = _ref3.config; if (!testRunners[config.runner]) { // $FlowFixMe testRunners[config.runner] = new (require(config.runner))( _this._globalConfig); } }); const testsByRunner = _this._partitionTests(testRunners, tests); if (testsByRunner) { try { for (const runner of Object.keys(testRunners)) { yield testRunners[runner].runTests( testsByRunner[runner], watcher, onStart, onResult, onFailure, { serial: runInBand }); } } catch (error) { if (!watcher.isInterrupted()) { throw error; } } } updateSnapshotState(); aggregatedResults.wasInterrupted = watcher.isInterrupted(); yield _this._dispatcher.onRunComplete(contexts, aggregatedResults); const anyTestFailures = !( aggregatedResults.numFailedTests === 0 && aggregatedResults.numRuntimeErrorTestSuites === 0); const anyReporterErrors = _this._dispatcher.hasErrors(); aggregatedResults.success = !( anyTestFailures || aggregatedResults.snapshot.failure || anyReporterErrors); return aggregatedResults;})(); } _partitionTests( testRunners, tests) { if (Object.keys(testRunners).length > 1) { return tests.reduce((testRuns, test) => { const runner = test.context.config.runner; if (!testRuns[runner]) { testRuns[runner] = []; } testRuns[runner].push(test); return testRuns; }, Object.create(null)); } else if (tests.length > 0 && tests[0] != null) { // If there is only one runner, don't partition the tests. return Object.assign(Object.create(null), { [tests[0].context.config.runner]: tests }); } else { return null; } } _shouldAddDefaultReporters(reporters) { return ( !reporters || !!reporters.find(reporterConfig => reporterConfig[0] === 'default')); } _setupReporters() {var _globalConfig = this._globalConfig;const collectCoverage = _globalConfig.collectCoverage,notify = _globalConfig.notify,reporters = _globalConfig.reporters; const isDefault = this._shouldAddDefaultReporters(reporters); if (isDefault) { this._setupDefaultReporters(); } if (collectCoverage) { this.addReporter(new (_coverage_reporter || _load_coverage_reporter()).default(this._globalConfig)); } if (notify) { this.addReporter( new (_notify_reporter || _load_notify_reporter()).default(this._globalConfig, this._options.startRun)); } if (reporters && Array.isArray(reporters)) { this._addCustomReporters(reporters); } } _setupDefaultReporters() { this.addReporter( this._globalConfig.verbose ? new (_verbose_reporter || _load_verbose_reporter()).default(this._globalConfig) : new (_default_reporter || _load_default_reporter()).default(this._globalConfig)); this.addReporter(new (_summary_reporter || _load_summary_reporter()).default(this._globalConfig)); } _addCustomReporters(reporters) { const customReporters = reporters.filter( reporterConfig => reporterConfig[0] !== 'default'); customReporters.forEach((reporter, index) => {var _getReporterProps = this._getReporterProps(reporter);const options = _getReporterProps.options,path = _getReporterProps.path; try { // $FlowFixMe const Reporter = require(path); this.addReporter(new Reporter(this._globalConfig, options)); } catch (error) { throw new Error( 'An error occurred while adding the reporter at path "' + path + '".' + error.message); } }); } /** * Get properties of a reporter in an object * to make dealing with them less painful. */ _getReporterProps( reporter) { if (typeof reporter === 'string') { return { options: this._options, path: reporter }; } else if (Array.isArray(reporter)) {var _reporter = _slicedToArray( reporter, 2);const path = _reporter[0],options = _reporter[1]; return { options, path }; } throw new Error('Reporter should be either a string or an array'); } _bailIfNeeded( contexts, aggregatedResults, watcher) { if (this._globalConfig.bail && aggregatedResults.numFailedTests !== 0) { if (watcher.isWatchMode()) { watcher.setState({ interrupted: true }); } else { const exit = () => process.exit(1); return this._dispatcher. onRunComplete(contexts, aggregatedResults). then(exit). catch(exit); } } return Promise.resolve(); }}exports.default = TestScheduler; const createAggregatedResults = numTotalTestSuites => { const result = (0, (_test_result_helpers || _load_test_result_helpers()).makeEmptyAggregatedTestResult)(); result.numTotalTestSuites = numTotalTestSuites; result.startTime = Date.now(); result.success = false; return result; }; const getEstimatedTime = (timings, workers) => { if (!timings.length) { return 0; } const max = Math.max.apply(null, timings); return timings.length <= workers ? max : Math.max(timings.reduce((sum, time) => sum + time) / workers, max); };
// This is the runtime configuration file. It complements the Gruntfile.js by // supplementing shared properties. require.config({ urlArgs: 'v=' + (new Date()).getTime(), paths: { "vendor": "../vendor", "almond": "../vendor/bower/almond/almond", "underscore": "../vendor/bower/lodash/dist/lodash.underscore", "jquery": "../vendor/bower/jquery/dist/jquery", "backbone": "../vendor/bower/backbone/backbone", "marionette":"../vendor/bower/backbone.marionette/lib/core/amd/backbone.marionette", "backbone.wreqr":"../vendor/bower/backbone.wreqr/lib/backbone.wreqr", "backbone.babysitter":"../vendor/bower/backbone.babysitter/lib/backbone.babysitter", "handlebars":"../vendor/bower/handlebars/handlebars", "hbs":"../vendor/bower/hbs/hbs", "json2":"../vendor/bower/json2", // Plugins "backbone.validateAll":"../vendor/bower/Backbone.validateAll/src/javascripts/Backbone.validateAll", "text":"../vendor/bower/requirejs-text/text" }, shim:{ // Backbone "backbone":{ // Depends on underscore/lodash and jQuery "deps":["underscore", "jquery"], // Exports the global window.Backbone object "exports":"Backbone" }, //Marionette "marionette":{ "deps":["underscore", "backbone", "jquery"], "exports":"Marionette" }, //Handlebars "handlebars":{ "exports":"Handlebars" }, // Backbone.validateAll plugin that depends on Backbone "backbone.validateAll":["backbone"] }, // hbs config - must duplicate in Gruntfile.js Require build locale: 'ru_ru', hbs: { i18n: true, templateExtension: "html", helperDirectory: "templates/helpers/", i18nDirectory: "templates/i18n/", compileOptions: {} // options object which is passed to Handlebars compiler } });
// TODO: make this code pretier, and add it on your api // **** var DumbEventTarget = function() { this._listeners = {}; }; DumbEventTarget.prototype._ensure = function(type) { // if type is not added to listeners, add and ensure that it is added if(!(type in this._listeners)) this._listeners[type] = []; }; DumbEventTarget.prototype.addEventListener = function(type, listener) { this._ensure(type); this._listeners[type].push(listener); }; DumbEventTarget.prototype.emit = function(type) { this._ensure(type); // other args except first(type) var args = Array.prototype.slice.call(arguments, 1); // on + type -> type is message,open,close this is for subcon.onmessage,subcon.onclose,subcon.onopen if(this['on' + type]) this['on' + type].apply(this, args);// call subcon.ontype(args) // call all listeners for(var i=0; i < this._listeners[type].length; i++) { this._listeners[type][i].apply(this, args); } }; // **** var MultiplexedWebSocket = function(ws) { var that = this; this.ws = ws; this.channels = {}; this.ws.addEventListener('message', function(e) { // message of maincon is coming like 'type,name,payload' string var t = e.data.split(','); var type = t.shift(), name = t.shift(), payload = t.join(); // if there is no channel that has this name if(!(name in that.channels)) { return; } // else var sub = that.channels[name]; switch(type) { case 'uns': delete that.channels[name]; sub.emit('close', {}); break; case 'msg': sub.emit('message', {data: payload}); break; } }); }; MultiplexedWebSocket.prototype.channel = function(raw_name) { return this.channels[escape(raw_name)] = new Channel(this.ws, escape(raw_name), this.channels); }; var Channel = function(ws, name, channels) { DumbEventTarget.call(this); var that = this; this.ws = ws; this.name = name; this.channels = channels; var onopen = function() { that.ws.send('sub,' + that.name); that.emit('open'); that.readyState = that.ws.readyState; // more(OPENed) than 0 }; // if connection have already connected if(ws.readyState > 0) { setTimeout(onopen, 0); } else { this.readyState = this.ws.readyState; // 0(CONNECTING) or more(OPENed) this.ws.addEventListener('open', onopen); } }; Channel.prototype = new DumbEventTarget() Channel.prototype.send = function(data) { this.ws.send('msg,' + this.name + ',' + data); }; Channel.prototype.close = function() { var that = this; this.ws.send('uns,' + this.name); delete this.channels[this.name]; setTimeout(function(){that.emit('close', {})},0); this.readyState = 3; // closed };
import Animate from './Animate'; import { configBezier, configSpring } from './easing'; import { translateStyle } from './util'; import AnimateGroup from './AnimateGroup'; export { configSpring, configBezier, AnimateGroup, translateStyle }; export default Animate;
(function () { 'use strict'; angular .module('app') .controller('DataTabController', DataTabController); DataTabController.$inject = ['$document', '$ionicLoading', '$ionicModal', '$ionicPopup', '$log', '$scope', '$state', 'HelpersFactory', 'IS_WEB']; function DataTabController($document, $ionicLoading, $ionicModal, $ionicPopup, $log, $scope, $state, HelpersFactory, IS_WEB) { var vm = this; var vmParent = $scope.vm; var thisTabName = 'data'; vm.tableData = []; vm.url = ''; vm.deleteTable = deleteTable; vm.deleteURL = deleteURL; vm.editURL = editURL; vm.importData = importData; vm.isWeb = isWeb; vm.urlSubmit = urlSubmit; vm.viewTable = viewTable; activate(); /** * Private Functions */ function activate() { createModal(); ionic.on('change', getFile, $document[0].getElementById('dataFile')); $log.log('In DataTabController'); // Loading tab from Spots list if ($state.current.name === 'app.spotTab.' + thisTabName) loadTab($state); // Loading tab in Map side panel $scope.$on('load-tab', function (event, args) { if (args.tabName === thisTabName) { vmParent.saveSpot().finally(function () { vmParent.spotChanged = false; loadTab({ 'current': {'name': 'app.spotTab.' + thisTabName}, 'params': {'spotId': args.spotId} }); }); } }); } function createModal() { $ionicModal.fromTemplateUrl('app/spot/data/data-table.html', { 'scope': $scope, 'animation': 'slide-in-up', 'backdropClickToClose': false, 'hardwareBackButtonClose': false }).then(function (modal) { vm.dataTableModal = modal; }); // Cleanup the modal when we're done with it! $scope.$on('$destroy', function () { vm.dataTableModal.remove(); }); } function csvSubmit(fileName, file) { if (fileName.endsWith('.csv')) { $ionicLoading.show({ template: '<ion-spinner></ion-spinner><br>Loading File Please Wait...' }); var id = HelpersFactory.getNewId(); $log.log(id, fileName); var csvToArr = HelpersFactory.csvToArray(file); $log.log('CSV to Array', csvToArr); var CSVObject = { 'id': id, 'name': fileName, 'data': csvToArr }; $log.log('CSVObject', CSVObject); if (!vmParent.spot.properties.data) vmParent.spot.properties.data = {}; if (!vmParent.spot.properties.data.tables) vmParent.spot.properties.data.tables = []; vmParent.spot.properties.data.tables.push(CSVObject); } else { var alertPopup = $ionicPopup.alert({ 'title': 'Not in CSV Format!', 'template': 'The filename: <br><b>' + fileName + '</b><br> is not in the correct format. <br>Please ' + 'ensure that the filename ends with .csv.' }); alertPopup.then(function (res) { $log.log('File Error:\n', res); }); } $ionicLoading.hide(); } function getFile(event) { if ($state.current.url === '/:spotId/data' && !_.isEmpty(event.target.files)) { $log.log('Getting Data file....'); var file = event.target.files[0]; readDataUrl(file); } } function loadTab(state) { vmParent.loadTab(state); // Need to load current state into parent if (vmParent.spot && !_.isEmpty(vmParent.spot)) $log.log('Data:', vmParent.spot.properties.data); } function readDataUrl(file) { var reader = new FileReader(); reader.onloadend = function (evt) { $log.log('Read as text', file.name); csvSubmit(file.name, evt.target.result); }; reader.readAsText(file); } /** * Public Functions */ function deleteTable(tableToDelete) { var confirmPopup = $ionicPopup.confirm({ 'title': 'Delete Table?', 'template': 'Are you sure you want to delete the table <b>' + tableToDelete.name + '</b>?' }); confirmPopup.then(function (res) { if (res) { vmParent.spot.properties.data.tables = _.without(vmParent.spot.properties.data.tables, tableToDelete); if (vmParent.spot.properties.data.tables.length === 0) delete vmParent.spot.properties.data.tables; if (_.isEmpty(vmParent.spot.properties.data)) delete vmParent.spot.properties.data; vmParent.saveSpot().then(function () { vmParent.spotChanged = false; }); } }); } function deleteURL(urlToDelete) { var confirmPopup = $ionicPopup.confirm({ 'title': 'Delete Link?', 'template': 'Are you sure you want to delete the link <b>' + urlToDelete + '</b>?' }); confirmPopup.then(function (res) { if (res) { vmParent.spot.properties.data.urls = _.without(vmParent.spot.properties.data.urls, urlToDelete); if (vmParent.spot.properties.data.urls.length === 0) delete vmParent.spot.properties.data.urls; if (_.isEmpty(vmParent.spot.properties.data)) delete vmParent.spot.properties.data; vmParent.saveSpot().then(function () { vmParent.spotChanged = false; }); } }); } // rename url function editURL(urlToEdit) { var myPopup = $ionicPopup.show({ 'template': '<input type="url" placeholder="http://" ng-model="vmChild.url">', 'title': 'Enter URL', 'scope': $scope, 'buttons': [ {'text': 'Cancel'}, { 'text': '<b>Save</b>', 'type': 'button-positive', 'onTap': function (e) { if (!vm.url) e.preventDefault(); else return vm.url; } } ] }); myPopup.then(function (url) { if (url) { vmParent.spot.properties.data.urls = _.without(vmParent.spot.properties.data.urls, urlToEdit); vmParent.spot.properties.data.urls.push(url); vmParent.saveSpot().then(function () { vmParent.spotChanged = false; vm.url = ''; }); } }); } function importData() { vm.fileNames = []; $document[0].getElementById('dataFile').click(); } function isWeb() { return IS_WEB; } function urlSubmit() { $log.log('Data URL', vm.url); if (angular.isUndefined(vm.url)) { $ionicPopup.alert({ 'title': 'Invalid URL!', 'template': 'Please include "http://" or "https://" before entering website' }); vm.url = ''; } else { if (!vmParent.spot.properties.data) vmParent.spot.properties.data = {}; if (!vmParent.spot.properties.data.urls) vmParent.spot.properties.data.urls = []; vmParent.spot.properties.data.urls.push(vm.url); vm.url = ''; } } function viewTable(tableToView) { // $log.log('tableToView', tableToView); vm.tableData = tableToView.data; vm.currentTableTitle = tableToView.name; vm.dataTableModal.show(); } } }());
module.exports = require('lodash.startswith')
'use strict'; angular.module('packs').controller('EditCourseImagesController', ['$scope', 'Cards', function ($scope, Cards) { $scope.options = {}; $scope.options.readFront = 'leave'; $scope.options.readBack = 'leave'; $scope.options.mode = 'leave'; $scope.options.speech = 'leave'; $scope.getModeStyle = function (card) { if (card.modes && card.modes.indexOf('images') === -1) { return 'text-muted'; } }; $scope.isImagesMode = function (card) { return card.modes && card.modes.indexOf('images') !== -1; }; $scope.updateCards = function () { var cardsToUpdate = $scope.course.cards.length; var cardsUpdated = 0; $scope.course.cards.forEach(function (card) { if ($scope.options.readFront === 'on') { card.imagesReadFront = true; } if ($scope.options.readFront === 'off') { card.imagesReadFront = false; } if ($scope.options.readBack === 'on') { card.imagesReadBack = true; } if ($scope.options.readBack === 'off') { card.imagesReadBack = false; } if ($scope.options.speech === 'on') { card.speechRecognitionForward = true; } if ($scope.options.speech === 'off') { card.speechRecognitionForward = false; } if ($scope.options.textAndImages === 'off') { card.textwithimages = false; } if ($scope.options.mode === 'on') { if (card.modes.indexOf('images') === -1) { card.modes.push('images'); } } if ($scope.options.mode === 'off') { if (card.modes.indexOf('images') !== -1) { card.modes.splice(card.modes.indexOf('images'), 1); } } //card.__v = undefined; new Cards(card).$update(function() { cardsUpdated++; if (cardsUpdated === cardsToUpdate) { $scope.options.readFront = 'leave'; $scope.options.readBack = 'leave'; $scope.options.mode = 'leave'; $scope.options.speech = 'leave'; } }); }); }; } ]);
/** * Particle objects used in starfield * this.speed.x * this.speed.y * this.speed.z * this.size * this.depth * this.boundries.x.min * this.boundries.x.max * this.boundries.y.min * this.boundries.y.max */ /** * Create a new particle with defined properties * @param {Object} properties */ var Particle = function ( properties ) { this.prop = properties; this.create(); }; Particle.prototype = { /** * Move the particle according to speed properties * @returns object containing particle x, y and size property */ move : function () { /** * Make a projection * @private * @param x * @param y * @param z * @returns 2d coordinate object */ function projection( x, y, z ) { return { x: x / z, y: y / z }; } this.x += this.prop.speed.x; this.y += this.prop.speed.y; this.z += this.prop.speed.z; this.projection = projection( this.x, this.y, this.z ); // reset particle if it's outside of boundries if ( this.projection.x > this.prop.boundries.x.max || this.projection.x < this.prop.boundries.x.min || this.projection.y > this.prop.boundries.y.max || this.projection.y < this.prop.boundries.y.min || this.z < 0 ) { this.create(); } //size = Math.min( this.prop.size / this.z, this.prop.size ); return { x : this.projection.x, y : this.projection.y, size : Math.min( this.prop.size / this.z, this.prop.size ) }; }, /** * Create a new particle with random properties */ create : function () { this.x = this.random( this.prop.boundries.x.min, this.prop.boundries.x.max ); this.y = this.random( this.prop.boundries.y.min, this.prop.boundries.y.max ); this.z = this.random( 0, this.prop.depth ); }, /** * Randomize within range * @param min * @param max * @returns value */ random : function ( min, max ) { // [1,6] : 1 + 1 * ( 6 - 1 ) = 6; 1 + 0 * ( 6 - 1 ) = 1 return min + Math.floor( Math.random() * (max - min ) ); } };
module.exports = function(grunt) { ////////////////// // config vars // ////////////////// // files: ['!node_modules/**/*.js', '**/*.js', '**/*.html'] // filesLib = ['index.js', 'lib/**/*.js'], var docsTmplDir = 'docs-tmpl', filesDocsTmpl = docsTmplDir + '/**/*.tmpl', filesLib = ['lib/**/*.js'], filesCSS = ['css/**/*.css'], filesTmpl = ['tmpl/**/*.tmpl'], filesWatch = filesTmpl.concat(filesLib, filesCSS, filesDocsTmpl, ['Gruntfile.js']), tasksBuild = ['readme'], tasksWatch = ['component-build', 'jshint'], processReadmeHeaderSrc = docsTmplDir + '/README_header.md.tmpl', processReadmeHeaderDestination = docsTmplDir + '/README_header.md', processLicenseSrc = docsTmplDir + '/LICENSE.tmpl', processLicenseDestination = 'LICENSE', npmConfig = grunt.file.readJSON('package.json'), filesPreProcess = {}; // console.log('filesWatch', filesWatch); npmConfig.year = grunt.template.today('yyyy'); filesPreProcess[docsTmplDir + '/README_header.md'] = docsTmplDir + '/README_header.md.tmpl'; filesPreProcess[docsTmplDir + '/LICENSE.tmpl'] = 'LICENSE'; ///////////////////////////// // Project configuration. // ///////////////////////////// grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), preprocess: { options: { context: { year: grunt.template.today('yyyy') } }, readme: { options: { context: npmConfig }, files: filesPreProcess } }, concat: { options: { separator: '' }, // // '2013' dist: { src: [docsTmplDir + '/README_header.md', docsTmplDir + '/README_footer.md', 'LICENSE'], dest: 'README.md' } }, jshint: { all: { files: { src: filesLib }, options: { jshintrc: '.jshintrc' } } }, clean: [docsTmplDir + "/**/*.md"], watch: { options: { livereload: 35730 }, files: filesWatch, tasks: tasksWatch // tasks: tasksBuild } }); /*-------------------------------------- Readme custom task ---------------------------------------*/ grunt.registerTask("readme-concat", ["preprocess:readme", "concat", "clean"]); // keep in here for the watch task grunt.registerTask('readme', 'Concatenate readme docs', function() { var done = this.async(); var exec = require('child_process').exec; exec('make readme', function(error, stdout, stderr) { done(); }); }); grunt.registerTask('component-build', 'Build component', function() { var done = this.async(); var exec = require('child_process').exec; exec('make public-quick', function(error, stdout, stderr) { done(); }); }); /////////////////////////// // Loading dependencies // /////////////////////////// for (var key in grunt.file.readJSON("package.json").devDependencies) { if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key); } // register tasks grunt.registerTask("template", ["preprocess:readme"]); grunt.registerTask("build", tasksBuild); grunt.registerTask("default", ["watch"]); };
/** * The popup script would be executed when user clicked the chrome plugin's icon * */ (function(){ // STEP 1: invoked when plugin popup page show up document.addEventListener('DOMContentLoaded', function () { jQuery('#uploadHref').click(function(){ chrome.tabs.query({active:true,currentWindow:true},function( tabsFound ){ var token = jQuery('#token').val(); if (!token) { jQuery('#errMsg').innerHTML = 'Token Is Empty' ; } else { jQuery('#errMsg').innerHTML = '' ; // STEP 2: ask background process inject code into current tab var port = chrome.extension.connect({name: "popup->background"}); port.postMessage({ tab : tabsFound[0] , message : 'injectPageVisitor' , token : token }); } }); }); }); })();
define(['joga'], function (joga) { module("HTMLInputElementBinding"); test("data-value binding updates input text value", function() { var model = new Model(); function Model() { this.name = joga.objectProperty("test"); this.element = joga.elementProperty('<input type="text" data-value="this.name()"/>'); } equal(model.element().value, "test"); model.name('test2'); equal(model.element().value, "test2"); }); test("data-value binding updates property when input text value changes", function() { var model = new Model(); function Model() { this.name = joga.objectProperty(""); this.element = joga.elementProperty('<input type="text" data-value="this.name()"/>'); } model.element().value = "test"; model.element().onchange(); equal(model.name(), "test"); }); test("data-checked binding updates input checked attribute", function() { var model = new Model(); function Model() { this.test = joga.booleanProperty(true); this.element = joga.elementProperty('<input type="checkbox" data-checked="this.test()"/>'); } equal(model.element().checked, true); model.test(false); equal(model.element().checked, false); }); test("data-checked binding updates property when input checkbox changes", function() { var model = new Model(); function Model() { this.test = joga.booleanProperty(false); this.element = joga.elementProperty('<input type="checkbox" data-checked="this.test()"/>'); } model.element().checked = true; model.element().onchange(); equal(model.test(), true); model.element().checked = false; model.element().onchange(); equal(model.test(), false); }); test("input radio bindings update property when element changes", function () { var model = new Model(); function Model() { this.selected = joga.objectProperty(); this.selectedValue = joga.objectProperty({}); this.element = joga.elementProperty('<input type="radio" data-selectedvalue="this.selectedValue()" data-selected="this.selected()"/>'); } model.element().checked = true; model.element().onchange(); equal(model.selected(), model.selectedValue()); model.element().checked = false; model.element().onchange(); equal(model.selected(), null); }); test("input radio bindings update element when property changes", function () { var model = new Model(); function Model() { this.selected = joga.objectProperty(); this.selectedValue = joga.objectProperty({}); this.element = joga.elementProperty('<input type="radio" data-selectedvalue="this.selectedValue()" data-selected="this.selected()"/>'); } model.selected(model.selectedValue()); ok(model.element().checked); model.selected(null); ok(!model.element().checked); }); });
// import React from 'react'; // import { shallow } from 'enzyme'; // import { SelectFriend } from '../index'; describe('<SelectFriend />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
import PropTypes from 'prop-types'; import React from 'react'; import { TouchableNativeFeedback, TouchableHighlight, StyleSheet, View, Platform, ActivityIndicator, Text as NativeText, } from 'react-native'; import colors from '../config/colors'; import Text from '../text/Text'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import getIconType from '../helpers/getIconType'; import normalize from '../helpers/normalizeText'; const log = () => { console.log('please attach method to this component'); //eslint-disable-line no-console }; const Button = props => { const { disabled, loading, loadingRight, activityIndicatorStyle, buttonStyle, borderRadius, title, onPress, icon, iconComponent, secondary, secondary2, secondary3, primary1, primary2, backgroundColor, color, fontSize, underlayColor, raised, textStyle, large, iconRight, fontWeight, disabledStyle, fontFamily, containerViewStyle, rounded, outline, transparent, textNumberOfLines, textEllipsizeMode, allowFontScaling, ...attributes } = props; let { Component } = props; let iconElement; if (icon) { let Icon; if (iconComponent) { Icon = iconComponent; } else if (!icon.type) { Icon = MaterialIcon; } else { Icon = getIconType(icon.type); } iconElement = ( <Icon {...icon} color={icon.color || 'white'} size={icon.size || (large ? 26 : 18)} style={[ iconRight ? styles.iconRight : styles.icon, icon.style && icon.style, ]} /> ); } let loadingElement; if (loading) { loadingElement = ( <ActivityIndicator animating={true} style={[styles.activityIndicatorStyle, activityIndicatorStyle]} color={color || 'white'} size={(large && 'large') || 'small'} /> ); } if (!Component && Platform.OS === 'ios') { Component = TouchableHighlight; } if (!Component && Platform.OS === 'android') { Component = TouchableNativeFeedback; } if (!Component) { Component = TouchableHighlight; } if (Platform.OS === 'android' && (borderRadius && !attributes.background)) { attributes.background = TouchableNativeFeedback.Ripple( 'ThemeAttrAndroid', true ); } const baseFont = { color: (textStyle && textStyle.color) || color || stylesObject.text.color, size: (textStyle && textStyle.fontSize) || fontSize || (!large && stylesObject.smallFont.fontSize) || stylesObject.text.fontSize, }; let textOptions = {}; if (textNumberOfLines) { textOptions.numberOfLines = textNumberOfLines; if (textEllipsizeMode) { textOptions.ellipsizeMode = textEllipsizeMode; } } return ( <View style={[styles.container, raised && styles.raised, containerViewStyle]} > <Component underlayColor={underlayColor || 'transparent'} onPress={onPress || log} disabled={disabled || false} {...attributes} > <View style={[ styles.button, secondary && { backgroundColor: colors.secondary }, secondary2 && { backgroundColor: colors.secondary2 }, secondary3 && { backgroundColor: colors.secondary3 }, primary1 && { backgroundColor: colors.primary1 }, primary2 && { backgroundColor: colors.primary2 }, backgroundColor && { backgroundColor: backgroundColor }, borderRadius && { borderRadius }, !large && styles.small, rounded && { borderRadius: baseFont.size * 3.8, paddingHorizontal: !large ? stylesObject.small.padding * 1.5 : stylesObject.button.padding * 1.5, }, outline && { borderWidth: 1, backgroundColor: 'transparent', borderColor: baseFont.color, }, transparent && { borderWidth: 0, backgroundColor: 'transparent', }, buttonStyle && buttonStyle, disabled && { backgroundColor: colors.disabled }, disabled && disabledStyle && disabledStyle, ]} > {icon && !iconRight && iconElement} {loading && !loadingRight && loadingElement} <Text style={[ styles.text, color && { color }, !large && styles.smallFont, fontSize && { fontSize }, textStyle && textStyle, fontWeight && { fontWeight }, fontFamily && { fontFamily }, ]} {...textOptions} allowFontScaling={allowFontScaling} > {title} </Text> {loading && loadingRight && loadingElement} {icon && iconRight && iconElement} </View> </Component> </View> ); }; Button.propTypes = { buttonStyle: View.propTypes.style, title: PropTypes.string, onPress: PropTypes.any, icon: PropTypes.object, iconComponent: PropTypes.any, secondary: PropTypes.bool, secondary2: PropTypes.bool, secondary3: PropTypes.bool, primary1: PropTypes.bool, primary2: PropTypes.bool, backgroundColor: PropTypes.string, color: PropTypes.string, fontSize: PropTypes.any, underlayColor: PropTypes.string, raised: PropTypes.bool, textStyle: NativeText.propTypes.style, disabled: PropTypes.bool, loading: PropTypes.bool, activityIndicatorStyle: View.propTypes.style, loadingRight: PropTypes.bool, Component: PropTypes.any, borderRadius: PropTypes.number, large: PropTypes.bool, iconRight: PropTypes.bool, fontWeight: PropTypes.string, disabledStyle: View.propTypes.style, fontFamily: PropTypes.string, containerViewStyle: View.propTypes.style, rounded: PropTypes.bool, outline: PropTypes.bool, transparent: PropTypes.bool, allowFontScaling: PropTypes.bool, textNumberOfLines: PropTypes.number, textEllipsizeMode: PropTypes.string }; const stylesObject = { container: { marginLeft: 15, marginRight: 15, }, button: { padding: 19, backgroundColor: colors.primary, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', }, text: { color: 'white', fontSize: normalize(16), }, icon: { marginRight: 10, }, iconRight: { marginLeft: 10, }, small: { padding: 12, }, smallFont: { fontSize: normalize(14), }, activityIndicatorStyle: { marginHorizontal: 10, height: 0, }, raised: { ...Platform.select({ ios: { shadowColor: 'rgba(0,0,0, .4)', shadowOffset: { height: 1, width: 1 }, shadowOpacity: 1, shadowRadius: 1, }, android: { elevation: 2, }, }), }, }; const styles = StyleSheet.create(stylesObject); export default Button;
(function (global, factory) { if (typeof define === "function" && define.amd) { define('/Plugin/slidepanel', ['exports', 'jquery', 'Plugin'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('jquery'), require('Plugin')); } else { var mod = { exports: {} }; factory(mod.exports, global.jQuery, global.Plugin); global.PluginSlidepanel = mod.exports; } })(this, function (exports, _jquery, _Plugin2) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _jquery2 = babelHelpers.interopRequireDefault(_jquery); var _Plugin3 = babelHelpers.interopRequireDefault(_Plugin2); var NAME = 'slidePanel'; var SlidePanel = function (_Plugin) { babelHelpers.inherits(SlidePanel, _Plugin); function SlidePanel() { babelHelpers.classCallCheck(this, SlidePanel); return babelHelpers.possibleConstructorReturn(this, (SlidePanel.__proto__ || Object.getPrototypeOf(SlidePanel)).apply(this, arguments)); } babelHelpers.createClass(SlidePanel, [{ key: 'getName', value: function getName() { return NAME; } }, { key: 'render', value: function render() { if (typeof _jquery2.default.slidePanel === 'undefined') { return; } if (!this.options.url) { this.options.url = this.$el.attr('href'); this.options.url = this.options.url && this.options.url.replace(/.*(?=#[^\s]*$)/, ''); } this.$el.data('slidePanelWrapAPI', this); } }, { key: 'show', value: function show() { var options = this.options; _jquery2.default.slidePanel.show({ url: options.url }, options); } }], [{ key: 'getDefaults', value: function getDefaults() { return { closeSelector: '.slidePanel-close', mouseDragHandler: '.slidePanel-handler', loading: { template: function template(options) { return '<div class="' + options.classes.loading + '">\n <div class="loader loader-default"></div>\n </div>'; }, showCallback: function showCallback(options) { this.$el.addClass(options.classes.loading + '-show'); }, hideCallback: function hideCallback(options) { this.$el.removeClass(options.classes.loading + '-show'); } } }; } }, { key: 'api', value: function api() { return 'click|show'; } }]); return SlidePanel; }(_Plugin3.default); _Plugin3.default.register(NAME, SlidePanel); exports.default = SlidePanel; });
'use strict'; /* Main application module */ var blogApp = angular.module('blogApp', [ 'blogAppServices', 'blogAppDirectives' ]);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Session = require('./session'); // Thanks to http://blog.matoski.com/articles/jwt-express-node-mongoose/ // set up a mongoose model var InterventSchema = new Schema({ title: { type: String, unique: false, required: true }, date: { type: Date, unique: false, required: true }, duration: { type: Number, required: true, }, speaker: { type: String, required: true }, text: { type: String, required: false }, session: { type: String, required: true }, status: { type: String, }, questions: { type: Array, }, port: { type: Number, } }); //METODI module.exports = mongoose.model('Intervent', InterventSchema);
const express = require('express') const path = require('path') const bodyParser = require('body-parser') const logger = require('morgan') // remove for production const PORT = process.env.PORT || 5000 const app = express(); // fixes app.disable('x-powered-by') // dev additions // should be conditined out for production app.use(logger('dev', { skip: () => app.get('env') === 'test' })); app .use(bodyParser.json()) .use(bodyParser.urlencoded({ extended: false })) .use(express.static(path.join(__dirname, 'public'))) .use('/ioBIN', express.static(path.join(__dirname, 'ioBIN'))) .set('views', path.join(__dirname, 'views')) .set('view engine', 'ejs') // ejs or pug? pug is simpler but ejs is more real // main app logic goes here, firebase,sockets,route objects for api usage, other render logic let qRdata={ "man": "bun", "env": "ENV", "port": "PORT", "boolTrue": "boolTrue", "boolFalse": "boolFalse", "fooBar": "globalObj.foo", "bazQux": "globalObj.baz", "nonExistant": "sausage.dogs.are.cool", "nonExistant2": "sausage" } let qData={ "boolTrue": true, "boolFalse": false, "counter": 0, "jsonProp": "I am defined in the global data object so will take preference", "loop": [ { "property": "Vue" }, { "property": "JS" }, { "property": "rules!" } ], "tags": [ "js", "front-end", "framework" ], "author": { "firstName": "Matt", "lastName": "Stow" }, "skills": [ { "name": "JS", "level": 4 }, { "name": "CSS", "level": 5 } ] } app.get('/scripts/main.js', (req, res) => { res.sendFile(path.join(__dirname, 'client','main-static.js')) }) app.get('/', (req, res) => res.render('pages/index', { title: 'snowflake-x', qrserved: qRdata, qserved:qData // qrserved: JSON.stringify(qRdata), // qserved:JSON.stringify(qData) })) // Error handler // ERROR HANDLING app.use((req, res, next) => { const err = new Error('Not Found'); err.status = 404; next(err); // Catch 404 and forward to error handler }).use((err, req, res, next) => { // eslint-disable-line no-unused-vars res .status(err.status || 500) .render('pages/error', { message: err.message // Error handler }); }); app.listen(PORT, () => console.log(`Listening on ${ PORT }`))
import Spacing from 'material-ui/styles/spacing'; export default { spacing: Spacing, fontFamily: 'Roboto, sans-serif', palette: { primary1Color: '#0097a7', // (#00bcd4)输入框聚焦边框改变颜色 check primary2Color: '#0097a7', // (#0097a7) primary3Color: '#bdbdbd', // (#bdbdbd) accent1Color: '#ff4081', // (#ff4081) 按钮颜色 accent2Color: '#EBEFF2', // (#EBEFF2) accent3Color: '#9e9e9e', // (#9e9e9e) textColor: '#5f5f5f', // (rgba(0, 0, 0, 0.87)) //文字主题颜色 alternateTextColor: '#ffffff', // (#ffffff) 按钮背景色 canvasColor: '#ffffff', // (#ffffff) borderColor: '#e0e0e0', // (#e0e0e0)边框颜色 disabledColor: '#b8c2cc', // 默认输入框hint颜色 pickerHeaderColor: '#00bcd4', // (#00bcd4) clockCircleColor: '#000', // (rgba(0, 0, 0, 0.87)) shadowColor: '#000', // (rgba(0, 0, 0, 1)) }, };
import { FETCH_AD_STARTED, FETCH_AD_COMPLETED, FETCH_AD_FAILED } from 'shared/constants/ActionTypes' import { createReducer } from 'shared/utils/redux-utils' const initialState = { ads: {} } export default createReducer(initialState, { [FETCH_AD_STARTED]: () => (initialState), [FETCH_AD_COMPLETED]: (state, action) => ({ ads: action.ads }), [FETCH_AD_FAILED]: (state, action) => ({ errors: action.errors }) })
/* ======================================================================== * Bootstrap: affix.js v3.2.0 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.2.0' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger($.Event(affixType.replace('affix', 'affixed'))) if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - this.$element.height() - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.2.0 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.2.0' Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.2.0 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.2.0' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) $el[val](data[state] == null ? this.options[state] : data[state]) // push to event loop to allow forms to submit setTimeout($.proxy(function () { if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.2.0 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.2.0' Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true } Carousel.prototype.keydown = function (e) { switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.2.0 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.2.0' Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return Plugin.call(actives, 'hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(350)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var href var $this = $(this) var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.2.0 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.2.0' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.trigger('focus') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $parent = getParent($(this)) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.2.0 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.VERSION = '3.2.0' Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab', relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() Plugin.call($(this), 'show') }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.2.0 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.2.0 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.2.0' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop <= offsets[0]) { return activeTarget != (i = targets[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.2.0 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.2.0' Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.$body.addClass('modal-open') this.setScrollbar() this.escape() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(300) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.$body.removeClass('modal-open') this.resetScrollbar() this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(150) : callbackRemove() } else if (callback) { callback() } } Modal.prototype.checkScrollbar = function () { if (document.body.clientWidth >= window.innerWidth) return this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.2.0 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.2.0' Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(document.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $parent = this.$element.parent() var parentDim = this.getPosition($parent) placement = placement == 'bottom' && pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height ? 'top' : placement == 'top' && pos.top - parentDim.scroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < parentDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { that.$element.trigger('shown.bs.' + that.type) that.hoverState = null } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(150) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var arrowDelta = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowPosition = delta.left ? 'left' : 'top' var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition) } Tooltip.prototype.replaceArrow = function (delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) this.$element.removeAttr('aria-describedby') function complete() { if (that.hoverState != 'in') $tip.detach() that.$element.trigger('hidden.bs.' + that.type) } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(150) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : null, { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop(), width: isBody ? $(window).width() : $element.outerWidth(), height: isBody ? $(window).height() : $element.outerHeight() }, isBody ? { top: 0, left: 0 } : $element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { clearTimeout(this.timeout) this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.2.0 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.2.0' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery);
const path = require("path") exports.createPages = ({ actions, graphql }) => { const { createPage } = actions const casePostTemplate = path.resolve(`src/templates/post.js`) return graphql(` { allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] } limit: 1000 ) { edges { node { frontmatter { path } } } } } `).then(result => { if (result.errors) { return Promise.reject(result.errors) } result.data.allMarkdownRemark.edges.forEach(({ node }) => { createPage({ path: node.frontmatter.path, component: casePostTemplate, context: {}, }) }) }) }
var AspxCustomerManagement = { "Are you sure you want to delete customer?": "Are you sure you want to delete customer?", "Sorry! You can not delete yourself.": "Sorry! You can not delete yourself.", "Customer ID": "Customer ID", "Culture Name": "Culture Name", "Added On": "Added On", "UpdatedOn": "UpdatedOn", "is Same User": "is Same User", "Delete": "Delete", "Successful Message": "Successful Message", "Customer has been deleted successfully.": "Customer has been deleted successfully.", "Selected customer(s) has been deleted successfully.": "Selected customer(s) has been deleted successfully.", "Failed to delete Customer!": "Failed to delete Customer!", "Error Message": "Error Message", "Customer has been created successfully.": "Customer has been created successfully.", "Delete Confirmation": "Delete Confirmation", "Are you sure you want to delete the selected customer(s)?": "Are you sure you want to delete the selected customer(s)?", "Information Alert": "Information Alert", "Please select at least one customer before delete.": "Please select at least one customer before delete.", "Period": "Period", "Number Of New Accounts": "Number Of New Accounts", "User Name": "User Name", "Session User Host Address": "Session User Host Address", "Session User Agent": "Session User Agent", "Session Browser": "Session Browser", "Session URL": "Session URL", "Start Time": "Start Time", "No Records Found!": "No Records Found!", 'Customer Name': 'Customer Name', 'Total Order Amount': 'Total Order Amount', 'Number Of Orders': 'Number Of Orders', 'Average Order Amount': 'Average Order Amount', 'Actions': 'Actions', "Export to CSV": "Export to CSV", "User Name:": "User Name:", "Search": "Search", "Add New Customer": "Add New Customer", "Delete All Selected": "Delete All Selected", "Fields marked with * are compulsory.": "Fields marked with * are compulsory.", "User Info": "User Info", "Create Login": "Create Login", "Back": "Back", "Show Reports:": "Show Reports:", "Show Year Monthly Report": "Show Year Monthly Report", "Show Current Month Weekly Report": "Show Current Month Weekly Report", "Show Today's Report": "Show Today's Report", "Host Address:": "Host Address:", " Browser Name:": " Browser Name:", "Customer Name:": "Customer Name:", "Added On":"Added On", "Updated On":"Updated On", "View":"View", "Register":"Register", "Wishlist Item has been deleted successfully.":"Wishlist Item has been deleted successfully.", "Shopping Cart Item has been deleted successfully.":"Shopping Cart Item has been deleted successfully.", "Are you sure you want to delete the selected shopping cart items(s)?": "Are you sure you want to delete the selected shopping cart items(s)?", "Please select at least one shopping cart item before delete.":"Please select at least one shopping cart item before delete.", "The customer does not have a default Shipping address":"The customer does not have a default Shipping address" };
var assert = require("assert"); var indexStringify = require('../index'); var jsonStableStringify = require('json-stable-stringify'); var validateLibOutput = require('./validate'); var data = require("../fixtures/index").input; var dataLength = JSON.stringify(data).length; suite("libs", function() { var minSamples = 120; // This needs to be true before anything else console.log('Checking index validity...'); validateLibOutput(indexStringify); console.log('Checking index validity success'); benchmark('index', function () { var result = indexStringify(data); assert.equal(result.length, dataLength); }, { minSamples: minSamples }); benchmark('json-stable-stringify', function () { var result = jsonStableStringify(data); assert.equal(result.length, dataLength); }, { minSamples: minSamples }); }, { onComplete: function() { var namesFastest = this .filter(function(bench) { return bench.name !== 'native'; }) .filter('fastest') .map('name'); assert.notEqual(namesFastest.indexOf('index'), -1, "index should be among the fastest"); } });
const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ImageminPlugin = require('imagemin-webpack-plugin').default; const autoprefixer = require('autoprefixer'); const webpack = require('webpack'); module.exports = { context: path.resolve(__dirname, './frontend'), entry: { index: './js/index.js', dashboard: './js/dashboard.js', form: './js/form.js' }, output: { path: path.resolve(__dirname, './src/wagtail_personalisation/static/js'), filename: '[name].js', sourceMapFilename: '[file].map' }, devtool: 'source-map', module: { rules: [ { test: /\.js?$/, exclude: [/node_modules/], use: [{ loader: 'babel-loader', options: { presets: ['react', 'es2015', 'stage-0'] } }] }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: "css-loader", options: { sourceMap: true, minimize: true } }, { loader: "postcss-loader", options: { sourceMap: true, plugins: [ autoprefixer ] } }, { loader: "sass-loader", options: { sourceMap: true } } ] }) }, { test: /\.(png|jpg|jpeg|gif)/, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: '../img/' } } ] }, resolve: { extensions: [ '.js', '.jsx' ], modules: [ 'node_modules' ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'commons.js', minChunks: 2 }), new CopyWebpackPlugin([ { from: './img', to: '../img' } ]), new ImageminPlugin(), new ExtractTextPlugin({ filename: '../css/[name].css', allChunks: true }) ] };
/* global angular, document, window */ 'use strict'; angular.module('starter.controllers', []) .controller('AppCtrl', function($scope, $ionicModal, $ionicPopover, $timeout) { // Form data for the login modal $scope.loginData = {}; $scope.isExpanded = false; $scope.hasHeaderFabLeft = false; $scope.hasHeaderFabRight = false; var navIcons = document.getElementsByClassName('ion-navicon'); for (var i = 0; i < navIcons.length; i++) { navIcons.addEventListener('click', function() { this.classList.toggle('active'); }); } //////////////////////////////////////// // Layout Methods //////////////////////////////////////// $scope.hideNavBar = function() { document.getElementsByTagName('ion-nav-bar')[0].style.display = 'none'; }; $scope.showNavBar = function() { document.getElementsByTagName('ion-nav-bar')[0].style.display = 'block'; }; $scope.noHeader = function() { var content = document.getElementsByTagName('ion-content'); for (var i = 0; i < content.length; i++) { if (content[i].classList.contains('has-header')) { content[i].classList.toggle('has-header'); } } }; $scope.setExpanded = function(bool) { $scope.isExpanded = bool; }; $scope.setHeaderFab = function(location) { var hasHeaderFabLeft = false; var hasHeaderFabRight = false; switch (location) { case 'left': hasHeaderFabLeft = true; break; case 'right': hasHeaderFabRight = true; break; } $scope.hasHeaderFabLeft = hasHeaderFabLeft; $scope.hasHeaderFabRight = hasHeaderFabRight; }; $scope.hasHeader = function() { var content = document.getElementsByTagName('ion-content'); for (var i = 0; i < content.length; i++) { if (!content[i].classList.contains('has-header')) { content[i].classList.toggle('has-header'); } } }; $scope.hideHeader = function() { $scope.hideNavBar(); $scope.noHeader(); }; $scope.showHeader = function() { $scope.showNavBar(); $scope.hasHeader(); }; $scope.clearFabs = function() { var fabs = document.getElementsByClassName('button-fab'); if (fabs.length && fabs.length > 1) { fabs[0].remove(); } }; }) .controller('LoginCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk) { $scope.$parent.clearFabs(); $timeout(function() { $scope.$parent.hideHeader(); }, 0); ionicMaterialInk.displayEffect(); // validating login $scope.login = function () { var inputs = document.getElementsByTagName('input'); for(var i = 0; i < inputs.length; i++) { if(inputs[i].type.toLowerCase() == 'text') { var login = inputs[i].value; } if(inputs[i].type.toLowerCase() == 'password') { var password = inputs[i].value; } } // demo version login and password just to simulate if(login=="1234" && password =='1234'){ window.location = "#/app/houselist"; }else{ //alert('No match for User and/or Password!'); alert('It is a demo version!'); window.location = "#/app/houselist"; } } }) .controller('SearchCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk) { $scope.$parent.clearFabs(); $timeout(function() { $scope.$parent.hideHeader(); }, 0); ionicMaterialInk.displayEffect(); }) .controller('FriendsCtrl', function($scope, $stateParams, $timeout, ionicMaterialInk, ionicMaterialMotion) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.$parent.setHeaderFab('left'); // Delay expansion $timeout(function() { $scope.isExpanded = true; $scope.$parent.setExpanded(true); }, 300); // Set Motion ionicMaterialMotion.fadeSlideInRight(); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('ProfileCtrl', function($scope, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('ThankCtrl', function($scope, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('RegisterCtrl', ['$scope', '$http', '$sce' , '$stateParams', '$timeout', 'ionicMaterialMotion', 'ionicMaterialInk', function($scope,$http, $sce, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { $scope.to_trusted = function(html_code) { return $sce.trustAsHtml(html_code); } // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }]) .controller('EligibilityCtrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('QuestionCtrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('HouseCtrl', function($scope, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); $scope.ok = function (idh,img,titles) { if(idh == ""){ localStorage.title1 = titles; localStorage.image1 = img; localStorage.idh1 = idh; alert(titles+' '+'added to your wishlist');//hide dialog. } }; // Set Ink ionicMaterialInk.displayEffect(); }) .controller('House1Ctrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); $http.get("/library/json/house1.json") .success(function (response) { $scope.houses = response; }) .error(function(data) { alert("ERROR"); }); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); $scope.ok = function (idh,img,titles) { if(idh == ""){ localStorage.title1 = titles; localStorage.image1 = img; localStorage.idh1 = idh; alert(titles+' '+'added to your wishlist');//hide dialog. } }; // Set Ink ionicMaterialInk.displayEffect(); }) .controller('ActivityCtrl', function($scope, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = true; $scope.$parent.setExpanded(true); $scope.$parent.setHeaderFab('right'); $timeout(function() { ionicMaterialMotion.fadeSlideIn({ selector: '.animate-fade-slide-in .item' }); }, 200); // Activate ink for controller ionicMaterialInk.displayEffect(); }) .controller('GalleryCtrl', function($scope, $stateParams, $timeout, ionicMaterialInk, ionicMaterialMotion) { $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = true; $scope.$parent.setExpanded(true); $scope.$parent.setHeaderFab(false); // Activate ink for controller ionicMaterialInk.displayEffect(); ionicMaterialMotion.pushDown({ selector: '.push-down' }); ionicMaterialMotion.fadeSlideInRight({ selector: '.animate-fade-slide-in .item' }); }) .controller('HouselistCtrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); $http.get("/library/json/houselist.json") .success(function (response) { $scope.houses = response; }) .error(function(data) { alert("ERROR"); }); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('HousemapCtrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); $http.get("/library/json/houselist.json") .success(function (response) { $scope.houses = response; }) .error(function(data) { alert("ERROR"); }); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('ModalSearchCtrl', function($scope, $ionicModal) { $scope.contact = { day: 'Friday, Sep 12, 2015', hour: '11:00 AM' } $ionicModal.fromTemplateUrl('modal-search.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }) $scope.openModal = function() { $scope.modal.show() } $scope.closeModal = function() { $scope.modal.hide(); }; $scope.$on('$destroy', function() { $scope.modal.remove(); }); }) .controller('ModalStartCtrl', function($scope, $ionicModal) { $scope.contact = { day: 'Friday, Sep 12, 2015', hour: '11:00 AM' } $ionicModal.fromTemplateUrl('modal-start.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }) $scope.openModal = function() { $scope.modal.show() } $scope.closeModal = function() { $scope.modal.hide(); }; $scope.$on('$destroy', function() { $scope.modal.remove(); }); }) .controller('ModalWishlistCtrl', function($scope, $ionicModal) { $scope.mylist = { title1: localStorage.title1, img1: localStorage.image1, title2: localStorage.title2 } $ionicModal.fromTemplateUrl('modal-wish.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }) $scope.openModal = function() { $scope.modal.show() } $scope.closeModal = function() { $scope.modal.hide(); }; $scope.$on('$destroy', function() { $scope.modal.remove(); }); $scope.del = function(idh){ localStorage.removeItem("idh"+idh); localStorage.removeItem("image"+idh); localStorage.removeItem("title"+idh); var link = document.getElementById('w'+idh); link.style.display = 'none'; }; }) .controller('Zone1Ctrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); $scope.Math = window.Math; $http.get("/library/json/zone1.json") .success(function (response) { $scope.zones = response; }) .error(function(data) { alert("ERROR"); }); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) .controller('ZonesCtrl', function($scope, $http, $stateParams, $timeout, ionicMaterialMotion, ionicMaterialInk) { // Set Header $scope.$parent.showHeader(); $scope.$parent.clearFabs(); $scope.isExpanded = false; $scope.$parent.setExpanded(false); $scope.$parent.setHeaderFab(false); $http.get("/library/json/zones.json") .success(function (response) { $scope.zones = response; }) .error(function(data) { alert("ERROR"); }); // Set Motion $timeout(function() { ionicMaterialMotion.slideUp({ selector: '.slide-up' }); }, 300); $timeout(function() { ionicMaterialMotion.fadeSlideInRight({ startVelocity: 3000 }); }, 700); // Set Ink ionicMaterialInk.displayEffect(); }) ;
import { scene, camera, renderer } from './common/scene'; import { setEvents } from './common/setEvents'; import { convertToXYZ, getEventCenter, geodecoder } from './common/geoHelpers'; import { mapTexture } from './common/mapTexture'; import { getTween, memoize } from './common/utils'; import topojson from 'topojson'; import THREE from 'THREE'; import d3 from 'd3'; d3.json('data/world.json', function (err, data) { d3.select("#loading").transition().duration(500) .style("opacity", 0).remove(); var currentCountry, overlay; var segments = 155; // number of vertices. Higher = better mouse accuracy // Setup cache for country textures var countries = topojson.feature(data, data.objects.countries); var geo = geodecoder(countries.features); var textureCache = memoize(function (cntryID, color) { var country = geo.find(cntryID); return mapTexture(country, color); }); // Base globe with blue "water" let blueMaterial = new THREE.MeshPhongMaterial({color: '#2B3B59', transparent: true}); let sphere = new THREE.SphereGeometry(200, segments, segments); let baseGlobe = new THREE.Mesh(sphere, blueMaterial); baseGlobe.rotation.y = Math.PI; baseGlobe.addEventListener('click', onGlobeClick); baseGlobe.addEventListener('mousemove', onGlobeMousemove); // add base map layer with all countries let worldTexture = mapTexture(countries, '#647089'); let mapMaterial = new THREE.MeshPhongMaterial({map: worldTexture, transparent: true}); var baseMap = new THREE.Mesh(new THREE.SphereGeometry(200, segments, segments), mapMaterial); baseMap.rotation.y = Math.PI; // create a container node and add the two meshes var root = new THREE.Object3D(); root.scale.set(2.5, 2.5, 2.5); root.add(baseGlobe); root.add(baseMap); scene.add(root); function onGlobeClick(event) { // Get pointc, convert to latitude/longitude var latlng = getEventCenter.call(this, event); // Get new camera position var temp = new THREE.Mesh(); temp.position.copy(convertToXYZ(latlng, 900)); temp.lookAt(root.position); temp.rotateY(Math.PI); for (let key in temp.rotation) { if (temp.rotation[key] - camera.rotation[key] > Math.PI) { temp.rotation[key] -= Math.PI * 2; } else if (camera.rotation[key] - temp.rotation[key] > Math.PI) { temp.rotation[key] += Math.PI * 2; } } var tweenPos = getTween.call(camera, 'position', temp.position); d3.timer(tweenPos); var tweenRot = getTween.call(camera, 'rotation', temp.rotation); d3.timer(tweenRot); } function onGlobeMousemove(event) { var map, material; // Get pointc, convert to latitude/longitude var latlng = getEventCenter.call(this, event); // Look for country at that latitude/longitude var country = geo.search(latlng[0], latlng[1]); if (country !== null && country.code !== currentCountry) { // Track the current country displayed currentCountry = country.code; // Update the html d3.select("#msg").html(country.code); // Overlay the selected country map = textureCache(country.code, '#CDC290'); material = new THREE.MeshPhongMaterial({map: map, transparent: true}); if (!overlay) { overlay = new THREE.Mesh(new THREE.SphereGeometry(201, 40, 40), material); overlay.rotation.y = Math.PI; root.add(overlay); } else { overlay.material = material; } } } setEvents(camera, [baseGlobe], 'click'); setEvents(camera, [baseGlobe], 'mousemove', 10); }); function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();
'use strict'; const webpack = require('webpack'); function build(config) { return new Promise((resolve, reject) => { webpack(config, (err, res) => { if (err) { reject(err); } resolve(res); }); }); } module.exports = build;
import React, { Component } from 'react'; import Radium from 'radium'; const styles = { wrapper: { width: '100%', }, } const FailePage = ({}) => { return ( <div style={styles.wrapper}> <h1>Falha na autenticação!!!</h1> </div> ) } export default Radium(FailePage)
import React from 'react'; import PropTypes from 'prop-types'; import ProfileDataKey from './ProfileDataKey'; const propTypes = { dataKeys: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, selected: PropTypes.bool.isRequired, label: PropTypes.string.isRequired, }).isRequired).isRequired, onDataKeyClick: PropTypes.func.isRequired, }; const ProfileDataKeyList = ({ dataKeys, onDataKeyClick }) => ( <div className='dataKeyContainer' > {dataKeys.map(dataKey => <ProfileDataKey key={dataKey.id} {...dataKey} onClick={() => onDataKeyClick(dataKey)} />, )} </div> ); ProfileDataKeyList.propTypes = propTypes; export default ProfileDataKeyList;
/* global describe, it, expect */ var Container = require('../lib/container'); // Bacteria function Bacteria() { } Bacteria.prototype.eat = function() { return 'sugar'; } // Fish function Fish(bacteria) { this.bacteria = bacteria; } Fish.prototype.eat = function() { return 'bacteria, ' + this.bacteria.eat(); } // Primate function Primate(fish, bacteria) { this.fish = fish; this.bacteria = bacteria; } Primate.prototype.eat = function() { return 'fish, ' + this.fish.eat() + ', ' + this.bacteria.eat(); } describe('Container#constructor', function() { var container = new Container(); container.constructor('bacteria', Bacteria); container.constructor('fish', [ 'bacteria' ], Fish); container.constructor('primate', [ 'fish', 'bacteria' ], Primate); describe('creating an object with no dependencies', function() { var obj = container.create('bacteria'); it('should create an object', function() { expect(obj).to.be.an('object'); expect(obj).to.be.an.instanceOf(Bacteria); }); it('should create object with normal properties', function() { expect(obj.eat()).to.equal('sugar'); }); it('should create unique instances', function() { var obj2 = container.create('bacteria'); expect(obj).to.not.be.equal(obj2); }); }); describe('creating an object with one dependency at one level', function() { var obj = container.create('fish'); it('should create an object', function() { expect(obj).to.be.an('object'); expect(obj).to.be.an.instanceOf(Fish); }); it('should create object with dependency injected', function() { expect(obj.eat()).to.equal('bacteria, sugar'); }); it('should create unique instances', function() { var obj2 = container.create('fish'); expect(obj).to.not.be.equal(obj2); }); }); describe('creating an object with two dependencies, one of which is at two levels', function() { var obj = container.create('primate'); it('should create an object', function() { expect(obj).to.be.an('object'); expect(obj).to.be.an.instanceOf(Primate); }); it('should create object with dependencies injected', function() { expect(obj.eat()).to.equal('fish, bacteria, sugar, sugar'); }); it('should create unique instances', function() { var obj2 = container.create('primate'); expect(obj).to.not.be.equal(obj2); }); }); });
// TodoApp.Views.Todos ||= {} // class TodoApp.Views.Todos.NewView extends Backbone.View // template: JST["backbone/templates/todos/new"] // events: // "submit #new-todo": "save" // constructor: (options) -> // super(options) // @model = new @collection.model() // @model.bind("change:errors", () => // this.render() // ) // save: (e) -> // e.preventDefault() // e.stopPropagation() // @model.unset("errors") // @collection.create(@model.toJSON(), // success: (todo) => // @model = todo // window.location.hash = "/#{@model.id}" // error: (todo, jqXHR) => // @model.set({errors: $.parseJSON(jqXHR.responseText)}) // ) // render: -> // @$el.html(@template(@model.toJSON() )) // this.$("form").backboneLink(@model) // return this
'user strict' var Primus = require('primus') var http = require('http') var request = require('request') var Redis = require('redis') var fs = require('fs') var bunyan = require('bunyan') var CronJob = require('cron').CronJob var log = bunyan.createLogger({ name: 'Chimera IRChat server', serializers: { req: bunyan.stdSerializers.req, res: bunyan.stdSerializers.res } }) try { var config = JSON.parse(fs.readFileSync('config.json', 'utf8')) } catch (e) { log.fatal(e) process.exit(1) } var job = new CronJob('0 0 0 * * *', function () { updateRedisKeyToDate() }, function () {}, false, config.server.timezone ) job.start() if (!config.server.allowedHost) { log.error('allowedHost configuration is empty, no one is allowed to connect!') process.exit(1) } var redis = Redis.createClient(config.redis.port, config.redis.host) var server = http.createServer().listen(config.server.port) var primus = new Primus(server, { strategy: 'online, disconnect' }) var nextRedisKey = 0 var usersConnected = [] redis.select(config.redis.db) redis.scard(getServerDate(0), function (err, reply) { if (err) { log.fatal(err) } nextRedisKey = reply }) log.info('Chimera IRChat server is running' + '\nserver port: ' + config.server.port + '\nredis port: ' + config.redis.port + '\nredis host: ' + config.redis.host + '\nredis db: ' + config.redis.db) function updateRedisKeyToDate () { nextRedisKey = 0 log.info('nextRedisKey value changed to ' + nextRedisKey + '. Today is ' + getServerDate(0)) } function getServerTime () { var currentTime = new Date() var currentHours = currentTime.getHours() var currentMinutes = currentTime.getMinutes() var currentSeconds = currentTime.getSeconds() currentHours = (currentHours < 10 ? '0' : '') + currentHours currentMinutes = (currentMinutes < 10 ? '0' : '') + currentMinutes currentSeconds = (currentSeconds < 10 ? '0' : '') + currentSeconds currentHours = (currentHours === '24') ? '00' : currentHours return currentHours + ':' + currentMinutes + ':' + currentSeconds } function getServerDate (daysToPast) { var date = Date.now() if (daysToPast > 0) { var dayMs = 1000 * 60 * 60 * 24 var diff = date - (dayMs * daysToPast) date = new Date(diff) } else { date = new Date(date) } var day = date.getDate() var month = date.getMonth() + 1 var year = date.getFullYear() return day + '.' + month + '.' + year } function chunk (array, groupsize) { var sets = [] var chunks var i = 0 chunks = array.length / groupsize while (i < chunks) { sets[i] = array.splice(0, groupsize) i++ } return sets } function isValidMessage (msg) { return (msg !== '' || msg !== undefined || msg !== null || typeof (msg) === 'string') } function cleanMessage (msg, spaces) { if (msg == null) { return null } if (!spaces) { msg = msg.replace(/\s/g, '') } return msg .replace(/(<([^>]+)>)/ig, '') .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/\s{2,}/g, ' ') } function writeMessage (type, user, msg, date, more) { return { 'type': type, 'user': user, 'date': date, 'messages': msg !== undefined ? msg : [], 'more': more } } function getHistory (spark, loadHistory) { if (usersConnected[spark.id] === undefined) { log.warn('getHistory' + usersConnected[spark.id]) return } if (spark.query === undefined || spark.query.historyLimit === undefined) { log.warn(spark.address.ip + ' kicked for not having any queries or historyLimit') log.warn(spark.query) spark.end() } var historyLimit = parseInt(spark.query.historyLimit, 10) var canGetHistory = usersConnected[spark.id].nextHistory <= config.server.daysTillHistoryExpire var userHistoryArr = usersConnected[spark.id].availableHistory var redisScan = function (date, limit) { if (limit === 0) { limit = 500 } var canGetHistory = usersConnected[spark.id].nextHistory <= (config.server.daysTillHistoryExpire !== '' ? config.server.daysTillHistoryExpire : 7) // Stop looking into the past if going too far // if (!canGetHistory) { // return // } // Get all members within the given key, which is a date redis.smembers(date, function (err, reply) { if (err) { log.error(err, reply) } if (reply !== undefined) { if (reply.length === 0) { usersConnected[spark.id].nextHistory += 1 } // Check further into the past if nothing found here if (reply.length === 0 && canGetHistory) { return redisScan(getServerDate(usersConnected[spark.id].nextHistory), limit) } // Sort and chunkify the history data var sorted = [] var chunked = [] sorted = reply.sort(function (a, b) { return JSON.parse(a).id - JSON.parse(b).id }) if (sorted.length > limit) { chunked = chunk(sorted, limit) } // Send the history data to the client and save the rest to the user object spark.write(writeMessage('History', usersConnected[spark.id].user, chunked.length === 0 ? sorted : chunked.pop(), date, chunked.length)) usersConnected[spark.id].availableHistory = chunked // No data from this day, we can check yesterday if (chunked.length === 0) { usersConnected[spark.id].nextHistory++ } } }) } if (canGetHistory && userHistoryArr.length === 0) { redisScan(getServerDate(usersConnected[spark.id].nextHistory), historyLimit) } if (userHistoryArr.length !== 0) { spark.write(writeMessage('History', usersConnected[spark.id].user, userHistoryArr.pop(), getServerDate(usersConnected[spark.id].nextHistory), userHistoryArr.length)) if (userHistoryArr.length === 0) { usersConnected[spark.id].nextHistory += 1 } } } function newUser (name, color) { return { user: name, color: color, nextHistory: 0, availableHistory: [] } } // Auth based on the host // Inspiration from Django primus.authorize(function (req, done) { var cServer = config.server var hostport = req.headers.host !== undefined ? req.headers.host.split(':') : false var protorigin = req.headers.origin !== undefined ? req.headers.origin.split('://') : false var hostname = hostport[0] var origin = protorigin[1] var allowedHosts = (cServer.allowedHost.length === 0 || cServer.allowedHost === '') ? false : cServer.allowedHost var allowedOrigins = (cServer.allowedOrigin.length === 0 || cServer.allowedOrigin === '') ? '*' : cServer.allowedOrigin var allowOrigin = false if (!hostport || (!protorigin && !cServer.allowNoOrigin)) { log.error('Received Host or Origin header is undefined!') log.error(req.headers) return } if (config.debug) { log.info('New connection; Host: ' + req.headers.host + ' | Origin: ' + req.headers.origin) } if (allowedOrigins[0] === '*') { allowOrigin = true } else { for (var i = 0; i < allowedOrigins.length; i++) { switch (allowedOrigins[i]) { case origin: allowOrigin = true break case req.headers.origin: allowOrigin = true break } } } if (!allowOrigin) { log.warn('Denying connection with origin ' + req.headers.origin + ' - Check the config? - ' + allowedOrigins) return } for (var j = 0; j < allowedHosts.length; j++) { switch (allowedHosts[j]) { case hostname: return done() case req.headers.host: return done() } } return }) primus.on('connection', function (spark) { var cConfig = config.client if (spark.address.ip === (config.bot.host || '::ffff:127.0.0.1')) { log.info('Bot connected from ip ' + spark.address.ip) } else { if (config.debug) { usersConnected[spark.id] = newUser('Zergling', '#66023') } } var connectionType = spark.query.type === undefined ? null : spark.query.type var key = spark.query.key === undefined ? null : spark.query.key if (connectionType == null) { log.warn('Someone tried to connect without a connection type! ' + spark.address.ip) return spark.end() } switch (connectionType) { case 'bot': break case 'smf': if (!cConfig.smf.allow) { return spark.end() } if (cConfig.smf.key && (key != null || key !== '')) { // SMF authing request({ uri: cConfig.smf.authUrl, method: 'POST', followAllRedirects: true, form: { 'key': key } }, function (err, res, body) { if (!err && res.statusCode === 200 && body !== '') { var data = cleanMessage(JSON.parse(body), true) if (data == null) { log.error('Data was null in smf auth, impossible!', data, spark.query) return spark.end() } data = data.split('|') usersConnected[spark.id] = newUser(data[0], data[1]) getHistory(spark, config.client.smf.loadHistory) } else { log.error('When trying to authenticate a client' + '\nres: ' + res + '\n' + err + '\n' + body + '\n' + key + '\n' + spark.query ) return spark.end() } }) // end request } break case 'blank': if (!cConfig.blank.allow) { return spark.end() } getHistory(spark, config.client.blank.loadHistory) break } spark.on('data', function (data) { if (usersConnected[spark.id] === undefined && spark.address.ip !== config.bot.host) { log.warn('Someone tried to send a message without being authed! ' + spark.address.ip) return spark.end() } var IRC = false var ircUser = '' switch (data.type) { case 'getHistory': getHistory(spark, true) return case 'ircMessage': IRC = true ircUser = data.user break case 'newMessage': break } if (data.message !== undefined) { var message = data.message.trim() if (!isValidMessage(message)) { log.warn('Received invalid message!' + data + ' | ' + message) return } var msg = cleanMessage(message, true) == null ? '' : cleanMessage(message, true) } var newId = nextRedisKey++ data = { 'id': newId.toString(), 'type': IRC ? 'CleanMessageIRC' : 'CleanMessage', 'color': IRC ? '#697263' : usersConnected[spark.id].color, 'user': IRC ? ircUser : usersConnected[spark.id].user, 'time': getServerTime(), 'date': getServerDate(0), 'message': msg !== undefined ? msg : 'undf' } primus.write(data) redis.sadd(getServerDate(0), JSON.stringify(data)) redis.expire(getServerDate(0), config.server.daysTillHistoryExpire * 24 * 60 * 60) }) spark.on('end', function () { delete usersConnected[spark.id] }) })
export default class Projectile extends Phaser.Physics.Arcade.Sprite { constructor (scene, x, y, key, frame) { // call bullet constructor super(scene, x, y, key, frame); // project attributes this.attributes = this.attributes || {}; this.attributes.bounce = this.attributes.bounce || 1; // get projectile bounce from children or default to 1 // add to physics engine and scene this.scene.physics.add.existing(this); this.scene.add.existing(this); this.setBounce(this.attributes.bounce); this.setCollideWorldBounds(true); // project bodies die when they go out of bounds // Set its pivot point to the center of the bullet this.setOrigin(0.5, 0.5); // save start position this.startX = x; this.startY = y; // default bullets as dead this.kill(false); } setBounce (bounce) { this.attributes.bounce = bounce; super.setBounce(bounce); } get alive () { return this.active; } set alive (isAlive) { this.active = !!isAlive; } kill (emitEvent = true) { this.setActive(false); this.setVisible(false); this.body.enable = false; // stop the physics body also when a projectile is killed so it doesn't update if (emitEvent) { this.emit('killed'); } } revive () { this.age = 0; this.setActive(true); this.setVisible(true); this.body.enable = true; // re-enable the physics body when a projectile is revived this.setBounce(this.attributes.bounce); // reset bounce this.emit('alive'); } reset (x, y) { this.revive(); this.body.reset(x, y); } update (time, delta) { this.age += delta; if (this.lifespan !== undefined && this.age > this.lifespan) { this.kill(); } } };
function MockStore(store) { this._store = store; } MockStore.prototype.load = function(req, cb) { process.nextTick(function() { cb(null, { transactionID: req.body.state, redirectURI: 'http://www.example.com/auth/callback' }) }); } MockStore.prototype.store = function(req, txn, cb) { req.__mock_store__ = {}; req.__mock_store__.txn = txn; process.nextTick(function() { cb(null, 'mocktxn-1') }); } MockStore.prototype.update = function(req, h, txn, cb) { req.__mock_store__ = {}; req.__mock_store__.uh = h; req.__mock_store__.utxn = txn; process.nextTick(function() { cb(null, 'mocktxn-1u') }); } MockStore.prototype.remove = function(req, h, cb) { req.__mock_store__ = {}; req.__mock_store__.removed = h; process.nextTick(function() { cb(null) }); } module.exports = MockStore;
version https://git-lfs.github.com/spec/v1 oid sha256:b8b033ce61dee6a88210b9e99b9f8bd14b7e7fda5ffec139b21631a190328926 size 267
/** * See https://github.com/kennychua/pdiffy/blob/master/examples/casperjs/CASPEREXAMPLE.md for more information **/ // Initialise Casper, and instruct it to do lots of logging var casper = require('casper').create( { verbose:true, logLevel: "debug" }); // Navigate to Google homepage casper.start('http://google.com', function() { // Replace the following with path to a local copy of pdiffy.js // PhantomJs/CasperJs only supports injection of local files, not over http phantom.injectJs('/home/htpc/Development/pdiffy/js/src/pdiffy.js'); // whole page capture actual_screenshot = 'data:image/png;base64,' + this.captureBase64('png'); }); // compare the screenshot against a known baseline casper.then(function() { // Assume the variable 'expected_screenshot' holds the base64 representation of the screenshot // you know to be correct (and has transparency ignore blocks, if required) // // var expected_screenshot = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...truncated...'; // // However, in this example, we just make expected_screenshot == actual_screenshot expected_screenshot = actual_screenshot; pdiffy(actual_screenshot).compareTo(expected_screenshot).onComplete(function(data){ results = data; }); }); // Wait for the async compareTo(...) to return, then do assertion check for test results casper.waitFor(function check() { return (results!== undefined); }, function then() { this.test.assertEquals(results.misMatchPercentage, "0.00", "Expected and actual screenshots match"); // The following will return the base64 representation of the pdiff results - highlighting areas // that are different //results.getImageDataUrl(); }); casper.run();
const toArray = (myObj) => { const newArray = [] for(let index in myObj) { if(myObj.hasOwnProperty(index)){ newArray.push(myObj[index]); } } return newArray } export { toArray }
/** * Emulate CustomEvent constructor * credits to https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent * @author Gustavo Salomé Silva <gustavonips@gmail.com * @link https://github.com/gusnips/html5-polyfill> * @license MIT */ ;(function(e,document,t){if(e.CustomEvent)return;function n(e,n){n=$.extend({bubbles:false,cancelable:false,detail:t},n);var r=document.createEvent("CustomEvent");r.initCustomEvent(e,n.bubbles,n.cancelable,n.detail);return r}n.prototype=e.Event.prototype;e.CustomEvent=n})(window, document);
version https://git-lfs.github.com/spec/v1 oid sha256:77e7b0022b2a91ba37ba6ece5615f28f86228558035c75ef63847d563d501ec2 size 244225
import * as Kit from "./kit"; import { Tag, symbol, invariant } from "./kit"; import * as Match from "@effectful/transducers/match"; import * as path from "path"; // import {sync as resolve} from "resolve" /** token type for signaling config object changes */ export const config = symbol("config"); /** token holding diff object of current options */ export const configDiff = symbol("configDiff"); /** token for marking compile time handles applications */ export const ctImport = symbol("ctImport"); /** composes function, removing duplicates */ export function postproc(f) { return function postprocRun(s) { let nxt = []; for ( let cur = s, curf = f; (curf = Kit.result(curf(cur), nxt)) != null; cur = nxt, nxt = [] ) {} // eslint-disable-line no-empty return nxt; }; } /** loads module `name` using commonjs `require` */ function resolveImport(name, opts, optional = false) { let r = opts.libs[name]; if (r == null) { if (!optional) throw new Error("not implemented: resolving imports"); /* try { const cp = resolve(name, { basedir: path.dirname(opts.file.filename) }) r = require(/ * webpackIgnore: true * /cp) } catch(e) { if (optional) { if (opts.resolveTrace) console.log(`couldn't resolve ${name} (%{e.message}), ignoring`) } else { throw new SyntaxError(`couldn't resolve ${name} (${e.message})`) } } */ } return r; } /** applies `ctImport` from the stream */ export const ctImportPass = postproc(function* ctImportPass(s) { s = Kit.auto(s); const post = []; for (const i of s) { if (i.type === ctImport) { if (i.enter) { const r = resolveImport( i.value.name, s.opts, true /*i.value.optional*/ ); if (r != null) { const p = yield* r(s.opts, i.value); if (p != null) { post.push(p); } } } } else yield i; } return Kit.pipe(...post); }); /** * Recalculates `opts` field, by propagating parent opts fields to children. * Following fields are propagated: * - `optsDiff` - recursively merging objects * - `optsAssign` - merging with `Object.assign` * - `optsSet` - fully resetting former optsSet, but parent's optsDiff/optsAssign * are still applied */ export function propagateOpts(si) { const sa = Kit.toArray(si); let cur = sa[0].value.opts || Kit.getOpts(); const stack = []; const assignStack = [{}]; const mergeStack = [{}]; for (const i of sa) { const { optsDiff: diff, optsAssign: assign, optsSet: set } = i.value; if (diff != null || assign != null || set != null) { if (i.enter) { stack.push(cur); if (set) cur = set; if (assign) assignStack.unshift(Object.assign({}, assignStack[0], assign)); if (diff) mergeStack.unshift(merge(clone(mergeStack[0]), diff)); if (assignStack.length > 1 || mergeStack.length > 1) { cur = clone(cur); if (assignStack.length > 1) Object.assign(cur, assignStack[0]); if (mergeStack.length > 1) merge(cur, mergeStack[0]); } } i.value.opts = cur; if (i.leave) { cur = stack.pop(); if (assign) assignStack.shift(); if (diff) { mergeStack.shift(); } } } else i.value.opts = cur; } return sa; } /** * in case if ns is loaded using command line it replaces all corresponding * global variables with the name of ns */ function* replaceGlobalNsName(si) { const s = Kit.auto(si); const first = yield* s.till(i => i.pos === Tag.top); const $ns = first.value.$ns; if (!$ns || $ns.strict) { yield* s; return; } for (const i of s) { if ( i.enter && i.type === Tag.Identifier && i.value.sym && !i.value.sym.declScope && i.value.node.name === $ns.name ) { i.value.sym = $ns; } yield i; } } /** for each values without `opts` fields assigns its parent `opts` field */ export function* resetOpts(s) { const stack = []; for (const i of s) { if (!i.value.opts) i.value.opts = stack[stack.length - 1].opts; if (i.enter) stack.push(i.value); if (i.leave) stack.pop(i.value); yield i; } } /** handles config `aliases` field */ function aliases(s) { s = Kit.auto(s); const aliases = s.opts.moduleAliases; if (!aliases) return s; const relAlias = aliases["."]; return _aliases(); function* subst(j) { let str = j.value.node.value; let alias; if (relAlias && str[0] === ".") { str = path.normalize(`${relAlias}/${str}`); if (Kit.isWindows) str = str.replace(/\\/g, "/"); alias = aliases[str] || str; } else alias = aliases[str]; if (!alias) { yield* s.copy(j); return; } yield s.tok(j.pos, Tag.StringLiteral, { node: { value: alias } }); Kit.skip(s.copy(j)); } function* _aliases() { for (const i of s) { if (i.enter) { if (i.pos === Tag.source && i.type === Tag.StringLiteral) { yield* subst(i); continue; } if ( i.type === Tag.Identifier && i.pos === Tag.callee && i.value.sym && !i.value.sym.declScope && i.value.sym.name === "require" ) { yield* s.copy(i); yield s.peel(); const j = s.curLev(); if (j && j.type === Tag.StringLiteral) yield* subst(s.take()); yield* s.sub(); yield* s.leave(); continue; } } yield i; } } } /** * detects all member expressions with the library's namespace as an object */ function nsProps(si) { const s = Kit.auto(si); const ns = s.first.value.$ns; for (const i of s) { if ( i.enter && i.pos === Tag.callee && i.type === Tag.MemberExpression && !i.value.node.computed ) { const obj = s.cur(); if (obj.type === Tag.Identifier && obj.value.sym === ns) { Kit.skip(s.one()); const prop = s.cur(); if (prop.type === Tag.Identifier) i.value.nsProp = prop.value.node.name; } } } } /** * Convert function `blockDirFunc` into a block directive, * otherwise ESLint complains about unused expressions */ export function callToBlockDirs(si) { const sa = Kit.toArray(si); const func = sa[0].value.opts.blockDirsFunc; if (!func) return sa; const s = Kit.auto(Kit.scope.prepare(si)); nsProps(sa); const root = s.first.value; const imps = root.rtSyms.get(s.opts.blockDirsFunc); const impsSet = imps && new Set(imps); return _callToBlockDirs(); function* _callToBlockDirs() { for (const i of s) { if (i.enter) { switch (i.type) { case Tag.CallExpression: const callee = s.cur(); if ( (impsSet && callee.type === Tag.Identifier && callee.value.sym && impsSet.has(callee.value.sym)) || (callee.type === Tag.MemberExpression && callee.value.nsProp === func) ) { for (const j of s) if (j.pos === Tag.arguments) break; const param = s.cur(); if (param.type !== Tag.StringLiteral) throw s.error(`${func} expects string a literal argument`); i.value.parentBlock.blockDirs.add(param.value.node.value); yield* Kit.reposOne(s.one(), i.pos); for (const j of s) if (j.value === i.value) break; continue; } break; } } yield i; } } } /** * checks imports in the input and apply compile time handlers * if they are available */ function namespaces(si) { const s = Kit.auto(si); const root = s.first.value; const imports = root.imports; const verbose = s.opts.verbose; if (!imports) return s; let imp = s.opts.importRT; const preset = s.opts.preset; const presets = new Set(); if (s.opts.preset) { if (Array.isArray(s.opts.preset)) { presets.add(...s.opts.preset); } else if (s.opts.preset.split) { presets.add(...s.opts.preset.split(/\s*,\s*/)); } } const libs = s.opts.libs; const namespaces = (root.namespaces = new Map()); const rtSyms = (root.rtSyms = new Map()); for (const [lib, imps] of imports) { for (const { ns, locals } of imps) { if (ns) { if (libs[lib]) s.opts.importRT = imp = lib; namespaces.set(lib, ns.sym); continue; } if (locals && (lib === imp || lib === preset)) { for (const [local, libName] of locals) Kit.mapPush(rtSyms, libName, local.sym); } } } let $ns = root.$ns; if (!$ns) { root.skipFile = false; if (imp) $ns = namespaces.get(imp); s.first.value.nsImported = !!$ns; if (!$ns) { $ns = Kit.scope.newSym(s.opts.ns || "M"); // suppressing scope warning if (!imp) $ns.num = -1; $ns.global = true; } root.$ns = $ns; } let cur = s; if (imp) { cur = applyLib(`${imp}-ct`, true, cur); cur = applyLib(`${imp}/ct`, true, cur); } for (const i of presets) cur = applyLib(i, false, cur); function applyLib(lib, optional, si) { if (verbose) // eslint-disable-next-line no-console console.log( `${optional ? "trying to apply" : "applying"} presets from ${lib}...` ); const s = Kit.auto(si); const r = resolveImport(lib, s.opts, optional); if (r != null) { return r(s); } else if (verbose) { // eslint-disable-next-line no-console console.log(`no preset ${lib} found, that's probably ok`); } return s; } return cur; } /** marks place of profile application */ export const profile = symbol("profile"); /** * applies config merge to parent's block if it has `parentBlock` scope */ export const configDiffPass = Kit.pipe( propagateConfigDiff, propagateOpts ); /** marks profile change calls in the code */ export const directives = Kit.pipe( replaceGlobalNsName, Match.inject(["*$M.profile($$)", "*$M.option($$)", "*$M.assignOption($$)"]), Kit.toArray, //TODO: remove function* matchNs(s) { s = Kit.auto(s); // skipping first profiles const first = yield* s.till(i => i.pos === Tag.top); const { $ns } = first.value; for (const i of s) { yield i; if (i.enter) { if (i.type === Match.Placeholder && i.value.v.match) { if (i.value.name === "M") { yield* s.till(j => j.type !== Match.Placeholder); const j = s.cur(); if (j.type === Tag.Identifier && j.value.sym && j.value.sym === $ns) continue; i.value.v.match = false; } } } } }, Match.commit, function* lookupProfiles(s) { s = Kit.auto(s); function getConst() { const i = s.peel(); switch (i.type) { case Tag.BooleanLiteral: case Tag.NumericLiteral: case Tag.StringLiteral: Kit.skip(s.leave()); return i.value.node.value; case Tag.NullLiteral: Kit.skip(s.leave()); return i.value.node.value; case Tag.RegExpLiteral: Kit.skip(s.leave()); return new RegExp(i.value.node.pattern, i.value.node.flags); case Tag.ArrayExpression: const arr = []; Kit.skip(s.peelTo(Tag.elements)); while (s.curLev()) arr.push(getConst()); Kit.skip(s.leave()); Kit.skip(s.leave()); return arr; case Tag.ObjectExpression: const res = {}; Kit.skip(s.peelTo(Tag.properties)); for (const j of s.sub()) { s.peel(j); switch (j.type) { case Tag.ObjectProperty: const k = s.cur(); invariant(k.pos === Tag.key); if (k.type !== Tag.Identifier) throw s.error("not supported object key"); Kit.skip(s.copy()); res[k.value.node.name] = getConst(); break; default: throw s.error("not supported object construct"); } Kit.skip(s.leave()); } Kit.skip(s.leave()); Kit.skip(s.leave()); return res; default: throw s.error("not supported static expression"); } } for (const i of s.sub()) { switch (i.type) { case Match.Root: if (i.enter) { // TODO: this now works only for single NS :( if (i.value.index === 0) { Kit.skip(s.till(j => j.enter && j.type === Match.Placeholder)); const j = s.cur(); Kit.skip(s.till(j => j.enter && j.type === Match.Placeholder)); const k = s.cur(); if (k.type !== Tag.StringLiteral) throw s.error("only string literals are supported"); Kit.skip(s.till(j => j.leave && j.type === Match.Root)); const name = k.value.node.value; yield s.tok(profile, { ns: j.value.node.name, node: { name } }); } else { Kit.skip(s.till(j => j.enter && j.type === Match.Placeholder)); Kit.skip(s.till(j => j.enter && j.type === Match.Placeholder)); yield s.tok(i.pos, configDiff, { node: getConst(), alg: i.value.index === 1 ? "merge" : "assign" }); Kit.skip(s.till(j => j.leave && j.type === Match.Root)); } } break; case Match.Placeholder: continue; default: yield i; } } }, Match.clean ); /** invokes profile handlers */ export const applyProfiles = postproc(function* applyProfiles(s) { s = Kit.auto(s); const post = []; for (const i of s) { if (i.type === profile) { if (i.enter) { const run = i.value.run || s.opts.profiles[i.value.node.name]; if (run == null) { throw s.error( `profile ${ i.value.node.name } is not defined, available:[${Object.keys(s.opts.profiles)}]` ); } const p = yield* run.call(i.value); if (p != null) post.push(p); } continue; } yield i; } return Kit.pipe(...post); }); /** * injects resulting items of `i.value.node` generator, passing it * `ExtIterator::sub` as an argument */ export const sub = symbol("sub"); /** * injects resulting items of `i.value.node` generator, passing it * `ExtIterator::one` as an argument */ export const one = symbol("one"); /** * handles `sub` tokens and `one` tokens */ export function applySubAndOne(s) { function* _applySubAndOne(si) { const sa = Kit.toArray(si); if (!sa.length) return; s = Kit.auto(sa); for (const i of s) { if (i.enter) { switch (i.type) { case sub: invariant(i.leave); yield* _applySubAndOne(i.value.run(s.sub())); continue; case one: invariant(i.leave); yield* _applySubAndOne(i.value.run(s.one())); continue; } } yield i; } } return _applySubAndOne(s); } /** * moves content of to specified destination * now only function scope works */ export const hoist = symbol("hoist"); /** * interpret hoist tokens * TODO: move to @effectful/transducers */ export function applyHoist(si) { const s = Kit.auto(si); function* scope() { const buf = []; const nxt = [..._applyHoist(buf)]; yield* buf; yield* nxt; } function* _applyHoist(funScope) { for (const i of s.sub()) { if (i.type === hoist) { if (i.enter) { const buf = [..._applyHoist(funScope)]; funScope.push(...buf); } } else if (i.enter && i.value.func) { yield i; yield* scope(); } else yield i; } } return scope(); } /** * specifies transform function */ export const preprocess = symbol("preprocess"); const MAX_PREPROCESS_COUNT = 10; /** * applies transform from `preprocess` token `node` field to * the whole token stream, repeats process until no more `preprocess` * tokens emitted */ export function preprocessPass(s) { let num = 0; function* _preprocessPass(s) { if (++num > MAX_PREPROCESS_COUNT) throw new Error("too many transforms"); s = Kit.share(s); for (const i of s) { if (i.type === preprocess) { yield* s; return i.value; } yield i; } return null; } for (let i = s, j = [], next; ; i = next.node(j), j = []) { next = Kit.result(_preprocessPass(i), j); if (next === null) return j; } } /** calculates qualified names for each expression if it is applicable */ export function setQNames(si) { const s = Kit.auto(si); function* getQName(ids) { const i = s.cur(); switch (i.type) { case Tag.Identifier: ids.push(i.value.node.name); yield* s.copy(); break; case Tag.MemberExpression: const cur = (i.value.qname = []); yield s.peel(); yield* getQName(cur); yield* getQName(cur); yield* s.leave(); ids.push(...cur); break; default: ids.push("*"); yield* _setQNames(s.one()); } } function* _setQNames(sw, cnst) { for (const i of sw) { yield i; if (i.enter) { switch (i.type) { case Tag.FunctionDeclaration: case Tag.FunctionExpression: case Tag.ObjectMethod: case Tag.ClassMethod: case Tag.ClassPrivateMethod: const id = s.curLev(); if (id && id.type === Tag.Identifier) i.value.scopeName = id.value.node.name; break; case Tag.VariableDeclaration: yield* _setQNames(s.sub(), i.value.node.kind === "const"); break; case Tag.CallExpression: yield* getQName((i.value.qname = [])); break; case Tag.VariableDeclarator: case Tag.AssignmentExpression: const cqn = []; yield* getQName(cqn); const j = s.curLev(); if (j != null) { j.lqname = cqn; yield* _setQNames(s.one()); } if (i.type === Tag.VariableDeclarator && cnst) { const j = s.curLev(); if (!j) break; switch (j.type) { case Tag.FunctionExpression: case Tag.ArrowFunctionExpression: j.value.scopeName = cqn[0]; } } break; } } } } return _setQNames(s); } /** marks `throw` statement to be handled by monadic library rather than js */ export function* assignThrowEff(s) { for (const i of s) { if ( i.enter && i.type === Tag.ThrowStatement && i.value.opts.transform && i.value.opts.jsExceptions === false ) i.value.bind = true; yield i; } } /** * marks call expressions to be effectful if they match some patter * from `bindCalls` option */ export function assignBindCalls(s) { s = Kit.auto(s); if (!s.opts.bindCalls) return s; return _assignBindCalls(); function* _assignBindCalls() { const { $ns } = s.first.value; for (const i of s) { if ( i.type === Tag.CallExpression && s.opts.transform && i.value.bind == null ) { const prof = s.opts.bindCalls; if (prof) { const q = i.value.qname; if (q != null) { let v = null; if (v == null && prof.byQName != null) v = prof.byQName[q.join(".")]; if (v == null && prof.byId != null) v = prof.byId[q[q.length - 1]]; if (v == null && prof.byNs != null && q.length > 1) v = prof.byNs[q[0]]; if (v == null && prof.libNs && q.length === 2 && q[0] === $ns.orig) v = prof.libNs[q[1]]; if (v == null) v = prof.all; if (v != null) i.value.bind = v; } } } yield i; } } } /** * object merging algorithm for options merge, * like Object.assign but recursively merges all plain object fields * arrays are concatenated rather than merged * properties with names starting with "$" are copied by reference */ export function merge(a, b) { if (a === undefined) return b; if (b === undefined) return a; if (Array.isArray(a)) return a.concat(b); else if (a && typeof a === "object") { for (const i in b) { if (i[0] === "$") a[i] = b[i]; else if (i in a) { a[i] = merge(a[i], b[i]); } else a[i] = b[i]; } return a; } return b; } export function clone(obj) { return merge({}, obj); } /** * moves `configDiff` tokens into `optsDiff` property for each sub-token on * the same level */ export function* propagateConfigDiff(s) { const stack = []; let cur = { level: 0, merge: null, assign: null }; let level = 0; for (const i of s) { if (i.type === configDiff) { if (i.enter) { if (cur.level < level) { stack.push(cur); cur = { level, merge: null, assign: null }; } if (i.value.alg === "assign") cur.assign = Object.assign(cur.assign || {}, i.value.node); else cur.merge = merge(cur.merge || {}, i.value.node); } continue; } if (i.enter) { if (cur.level === level) { if (cur.merge) { i.value.optsDiff = Object.assign( i.value.optsDiff || {}, cur.merge, i.value.optsDiff ); } if (cur.assign) i.value.optsAssign = Object.assign( i.value.optsAssign || {}, cur.assign, i.value.optsAssign ); } level++; } if (i.leave) { if (cur.level === level) { cur = stack.pop(); } level--; } yield i; } } /** combines a few preparation passes */ export const prepare = Kit.pipe( aliases, namespaces, callToBlockDirs, function(si) { const sa = Kit.toArray(si); let s = Kit.auto(sa); const { configure, preproc } = s.opts; if (configure || preproc) s = Kit.auto(preprocConfig(s)); if (configure) { configure(s); s = Kit.auto(propagateOpts(sa)); } if (preproc) return propagateOpts(preproc(Kit.auto(sa))); return s; function preprocConfig(s) { s = Kit.scope.assignBody(s); s = setQNames(s); return Kit.toArray(s); } }, propagateBlockDirs ); /** for `ns` function application marks inner expression to be effectful */ export function unwrapNs(si) { const s = Kit.auto(si); if (!s.opts.bindCalls) return s; const { $ns } = s.first.value; function* _unwrapNs() { for (const i of s.sub()) { if (i.enter) { if (i.type === Tag.CallExpression) { const j = s.cur(); if (j.type === Tag.Identifier && j.value.sym === $ns) { const def = s.opts.bindCalls; if (def != null && def.ns) { const lab = s.label(); s.peel(i); Kit.skip(s.peelTo(Tag.arguments)); s.cur().value.bind = true; yield* Kit.reposOne(_unwrapNs(), i.pos); Kit.skip(lab()); continue; } } } } yield i; } } return _unwrapNs(); } /** sets options `opts` to each function root tag */ export const setFuncOpts = function setFuncOpts(opts) { const generator = opts.generator; const async = opts.async; return function* setFuncOpts(s) { for (const i of s) { if (i.enter) { switch (i.type) { case Tag.ClassMethod: case Tag.ObjectMethod: if (i.value.node.kind !== "method") { i.value.optsAssign = { transform: null }; break; } case Tag.ArrowFunctionExpression: case Tag.FunctionExpression: case Tag.FunctionDeclaration: if ( (generator == null || generator === !!i.value.node.generator) && (async == null || async === !!i.value.node.async) ) i.value.optsAssign = Object.assign( i.value.optsAssign || {}, opts ); break; } } yield i; } }; }; /** * Converts JS block directives into profiles call */ export function propagateBlockDirs(si) { const s = Kit.auto(si); const { blockDirectives } = s.opts; if (!blockDirectives) return s; let any = false; const r = Kit.toArray(_propagateBlockDirs()); return any ? propagateOpts(r) : r; function* _propagateBlockDirs(value) { function dir(i, name) { const descr = blockDirectives[name]; if (descr) { any = true; value.optsAssign = Object.assign(value.optsAssign || {}, descr); Kit.skip(s.copy(i)); return true; } return false; } for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Tag.BlockStatement: case Tag.Program: yield i; yield* _propagateBlockDirs(i.value); continue; /** babel parser recognizes directives only for progs and funct block*/ case Tag.ExpressionStatement: if (s.cur().type === Tag.StringLiteral) { if (dir(i, s.cur().value.node.value)) continue; } break; case Tag.Directive: if (dir(i, i.value.node.value.value)) continue; break; } } yield i; } } } /** * posts option diff to the stream, * so all the next in the scope options are updated with * `x => Object.assign(x, opts)` */ export const injectOpts = opts => function* injectOpts() { yield Kit.tok(configDiff, { node: opts, alg: "assign" }); }; /** sets options to each sub-function */ export const injectFuncOpts = (opts, withSelf = false) => { const run = setFuncOpts(opts); return function* injectFuncOpts() { if (withSelf) { const value = { dst: "func" }; yield Kit.enter(hoist, value); yield Kit.tok(one, { run }); yield Kit.leave(hoist, value); return Kit.pipe( applyHoist, applySubAndOne ); } yield Kit.tok(sub, { run }); return applySubAndOne; }; }; export const STATISTICS = (typeof window !== "undefined" && window.chrome) || (typeof performance !== "undefined" && process.env.EFFECTFUL_STAT); /** Marks and assign a name to set of passes */ export const stage = STATISTICS ? Kit.curry(function(name, si) { let s = Kit.auto(Kit.toArray(si)); const first = s.first.value; const origStage = first.savedMeasure; if (name.startsWith("after-")) { first.savedMeasure = null; } else { performance.mark(name); first.savedMeasure = name; } if (origStage) performance.measure( // `${origStage}:${first.funcId ? first.funcId.orig : "*"}`, origStage, origStage ); return hooks(s, name); }) : Kit.curry(function(name, si) { let s = Kit.auto(Kit.toArray(si)); return hooks(s, name); }); function hooks(s, nextStage) { const origStage = s.first.value.savedStageName; if (origStage && s.opts.after) { let hook = s.opts.after[origStage]; if (hook) s = Kit.auto(hook(s)); } s.first.value.savedStageName = nextStage; if (s.opts.before) { const hook = s.opts.before[nextStage]; if (hook != null) s = hook(s); } return s; }
$(document).ready(function() { //toggles the image on click $("#toggle_second").click(function() { $("#toggle_second").toggleClass("transparent"); }); }); //used for mask and opacity $(document).ready(function() { //set height of container of images from it's child div height function setHeight() { $('#opacity, #mask').height($('#mask_first, #opacity_first').height()); } $(window).resize(setHeight); setHeight(); //functions called from sliders of mask and opacity function refreshOpacity() { $( "#opacity_second" ).fadeTo(0,1-$('#opacity_slider').slider('value')/100); } function refreshMask() { var resizeValue = $('#mask_slider').slider('value'); $( "#mask_second" ).width(resizeValue); } var maskWidth = $('#mask_first').width(); //slider for mask and opacity $(function() { $('#opacity_slider').slider({ orientation: "horizontal", range: "min", max: 100, slide: refreshOpacity, change: refreshOpacity }); $('#mask_slider').slider({ orientation: "horizontal", range: "min", max: maskWidth+10, slide: refreshMask, change: refreshMask }); }); //sets width of two diff images in mask view function setWidth() { $("#mask_top").width($("#mask_first").width()); } $(window).resize(setWidth); setWidth(); });
'use strict'; const expect = require('chai').expect; const Plugin = require('.'); describe('pegjs-brunch', function () { it('should initialize with no arguments', function () { const plugin = new Plugin(); expect(plugin).to.be.ok; }); it('should initialize with empty brunch config', function () { const plugin = new Plugin({}); expect(plugin).to.be.ok; }); it('should initialize with empty plugins config', function () { const plugin = new Plugin({plugins: {}}); expect(plugin).to.be.ok; }); it('should initialize with empty plugin config', function () { const plugin = new Plugin({plugins: {pegjs: {}}}); expect(plugin).to.be.ok; }); it('should generate parser from valid grammar', function (done) { const data = 'Integer\n\t= \'-\'\n\t[1-9][0-9]*'; const plugin = new Plugin({ plugins: {pegjs: {output: 'source'}} }); plugin.compile({data: data, path: 'file.pegjs'}).then((file) => { expect(file.data).to.be.a('string'); done(); }).catch(done); }); it('should throw error for invalid grammar', function (done) { const data = 'blahblah'; const plugin = new Plugin(); plugin.compile({data: data, path: 'file.pegjs'}).then((file) => { expect(file).not.to.be.ok; }, (error) => { expect(error).to.be.ok; done(); }).catch(done); }); it('should provide line no./column for invalid grammar', function (done) { const data = 'blahblah'; const plugin = new Plugin(); plugin.compile({data: data, path: 'file.pegjs'}).then((file) => { expect(file).not.to.be.ok; }, (error) => { expect(error.message).to.match(/1:9/); done(); }).catch(done); }); it('should generate parser as string regardless of config', function (done) { const data = 'Integer\n\t= \'-\'?[1-9][0-9]*'; const plugin = new Plugin({ plugins: {pegjs: {output: 'parser'}} }); plugin.compile({data: data, path: 'file.pegjs'}).then((file) => { expect(file.data).to.be.a('string'); done(); }).catch(done); }); it('should pass other options to parser', function (done) { const data = 'Integer\n\t= \'-\'?[1-9][0-9]*'; const plugin = new Plugin({ plugins: {pegjs: {format: 'globals', exportVar: 'foo', output: 'source'}} }); plugin.compile({data: data, path: 'file.pegjs'}).then((file) => { expect(file.data).to.be.a('string'); expect(file.data).to.match(/\bfoo\s*=\s*/); done(); }).catch(done); }); it('should be registered as Brunch plugin', function () { expect(Plugin.prototype.brunchPlugin).to.be.true; }); it('should generate JavaScript files', function () { expect(Plugin.prototype.type).to.equal('javascript'); }); it('should process PEG.js grammar files', function () { expect(Plugin.prototype.extension).to.equal('pegjs'); }); it('should enable processor chaining', function () { expect(Plugin.prototype.targetExtension).to.equal('js'); }); });
"use strict"; // ------------------------------------------------------------------------------ // Copyright (c) 2016 San Dinh Studios. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // ------------------------------------------------------------------------------ var robotlegs_1 = require("robotlegs"); var ISignalMap_1 = require("./api/ISignalMap"); var SignalMap_1 = require("./impl/SignalMap"); var SignalMediatorExtension = (function () { function SignalMediatorExtension() { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ this._uid = robotlegs_1.UID.create(SignalMediatorExtension); } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ SignalMediatorExtension.prototype.extend = function (context) { context.injector.bind(ISignalMap_1.ISignalMap).to(SignalMap_1.SignalMap).inSingletonScope(); }; SignalMediatorExtension.prototype.toString = function () { return this._uid; }; return SignalMediatorExtension; }()); exports.SignalMediatorExtension = SignalMediatorExtension; //# sourceMappingURL=SignalMediatorExtension.js.map
// Component and content creation classes and functions import component, {state} from 'kompo'; import {delegate, create} from 'kompo-util'; // Example components with self-explanatory name import table, {tableActions} from '../../../src/js/table/infiniteTable'; // Create root component const root = component.construct('div', function({}) { const scrollable = create('div', {'class': 'o-Scrollable'}), topSpacer = create('div', {'style': 'height: 0'}), bottomSpacer = create('div', {'style': 'height: 0'}), t1 = table({ classes: ['o-Table', 'u-mbn'], oddRowClass: 'o-Table-row--isOdd', evenRowClass: 'o-Table-row--isEven', selectedClass: 'selected', uniqueKey: 'id', on: (table) => { delegate(table, 'tr', 'click', function(e) { e.preventDefault(); const target = e.target.parentNode, tableProps = table.kompo.props, key = keySelected(tableProps, target); // Remove if already in selected if (tableProps.selected.hasOwnProperty(key)) { target.classList.remove(tableProps.selectedClass); delete tableProps.selected[key]; return } tableProps.selected[key] = target; target.classList.add(tableProps.selectedClass); }); }, minimizeWhitelist: ['firstname'], scrollableElement: scrollable, topSpacer, bottomSpacer }); this.appendChild(scrollable); scrollable.appendChild(topSpacer); component.mount(this, t1); scrollable.appendChild(t1); scrollable.appendChild(bottomSpacer); }); function keySelected(tableProps, row) { if (!tableProps.selected) { tableProps.selected = {}; } const s = component.getState(row); return s[tableProps.uniqueKey]; } // Create instance of root and // append table to body document.body.appendChild(state.app(root(), { limit: 10, minimize: true, offset: 0, data: [ { id: 1, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 2, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 3, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 4, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 5, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 6, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 7, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 8, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 9, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 10, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 11, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 12, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 13, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 14, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 15, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 16, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 17, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 18, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' }, { id: 19, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 20, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 21, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 22, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 23, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 24, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 25, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 26, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 27, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 28, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 29, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 30, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 31, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 32, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 33, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' },{ id: 34, firstname: 'rick', lastname: 'deckard', movie: 'blade runner 123456789' },{ id: 35, firstname: 'mia', lastname: 'wallace', movie: 'pulp fiction' },{ id: 36, firstname: 'rocky', lastname: 'balboa', movie: 'rocky' } ] }).start());
(function() { 'use strict'; describe('service webDevTec', function() { var webDevTec; beforeEach(module('jsNode')); beforeEach(inject(function(_webDevTec_) { webDevTec = _webDevTec_; })); it('should be registered', function() { expect(webDevTec).not.toEqual(null); }); describe('getTec function', function() { it('should exist', function() { expect(webDevTec.getTec).not.toEqual(null); }); it('should return array of object', function() { var data = webDevTec.getTec(); expect(data).toEqual(jasmine.any(Array)); expect(data[0]).toEqual(jasmine.any(Object)); expect(data.length > 5).toBeTruthy(); }); }); }); })();
module.exports = { extends: [ // Use the Standard config as the base // https://github.com/stylelint/stylelint-config-standard 'stylelint-config-standard', // Enforce a standard order for CSS properties // https://github.com/stormwarning/stylelint-config-recess-order 'stylelint-config-recess-order', // Override rules that would interfere with Prettier // https://github.com/shannonmoeller/stylelint-config-prettier 'stylelint-config-prettier', // Override rules to allow linting of CSS modules // https://github.com/pascalduez/stylelint-config-css-modules 'stylelint-config-css-modules', ], plugins: [ // Bring in some extra rules for SCSS 'stylelint-scss', ], // Rule lists: // - https://stylelint.io/user-guide/rules/ // - https://github.com/kristerkari/stylelint-scss#list-of-rules rules: { // Allow newlines inside class attribute values 'string-no-newline': null, // Limit the number of universal selectors in a selector, // to avoid very slow selectors 'selector-max-universal': 1, // Disallow allow global element/type selectors in scoped modules 'selector-max-type': [0, { ignore: ['child', 'descendant', 'compounded'] }], // === // PRETTIER // === // Allow for non-descending specificity in selectors, since 'no-descending-specificity': null, // === // SCSS // === 'scss/dollar-variable-colon-space-after': 'always', 'scss/dollar-variable-colon-space-before': 'never', 'scss/dollar-variable-no-missing-interpolation': true, 'scss/dollar-variable-pattern': /^[a-z-]+$/, 'scss/double-slash-comment-whitespace-inside': 'always', 'scss/operator-no-newline-before': true, 'scss/operator-no-unspaced': true, 'scss/selector-no-redundant-nesting-selector': true, // Allow SCSS and CSS module keywords beginning with `@` 'at-rule-no-unknown': null, 'scss/at-rule-no-unknown': true, }, }
"use strict"; var express = require('express') , v1 = require('./v1/auth') ; var auth = express(); auth.use('/v1', v1); module.exports = auth;