code
stringlengths
2
1.05M
var searchData= [ ['cache',['Cache',['../classCache.html',1,'']]], ['conversation',['Conversation',['../classConversation.html',1,'']]] ];
'use strict'; function curry (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { var nextArgs = Array.prototype.slice.call(arguments), allArgs = args.concat(nextArgs); return fn.apply(this, allArgs); }; } function compose () { var args = Array.prototype.slice.call(arguments).reverse(); return function (obj) { return args.reduce(function (result, F) { return F(result); }, obj); }; } module.exports = { identity: function (i) { return i; }, constant: function (k) { return function () { return k; }; }, noop: function () {}, compose: compose, curry: curry };
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * @flow */ /** * Get a hash for the provider object. Hashes are unique per-hasher, so if you have two different * hashers, there is no guarantee that they will give the same hash for the same object. * * One use case for this is with lists of React elements. Just create a hasher and use the hash as * a key: * * class MyComponent extends React.Component { * constructor(props) { * super(props); * this._hasher = new Hasher(); * } * render() { * return this.props.items.map(item => ( * <ItemView key={this._hasher.getHash(item)} model={item} /> * )); * } * } */ export default class Hasher<K> { _hashes: WeakMap<K, string>; _objectCount: number; constructor() { this._hashes = new WeakMap(); this._objectCount = 0; } getHash(item: K): string | number { if (item === null) { return 'null'; } const type = typeof item; switch (typeof item) { case 'object': { let hash = this._hashes.get(item); if (hash == null) { hash = `${type}:${this._objectCount}`; this._hashes.set(item, hash); this._objectCount = this._objectCount + 1 === Number.MAX_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : this._objectCount + 1; } return hash; } case 'undefined': return 'undefined'; case 'string': case 'boolean': return `${type}:${item.toString()}`; case 'number': return item; default: throw new Error('Unhashable object'); } } }
//Categories service used to communicate Categories REST endpoints (function () { 'use strict'; angular .module('categories') .factory('CategoriesService', CategoriesService); CategoriesService.$inject = ['$resource']; function CategoriesService($resource) { return $resource('api/categories/:categoryId', { categoryId: '@_id' }, { update: { method: 'PUT' } }); } })();
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft() { if (!(this instanceof Graft)) { return new Graft(); } Transform.call(this, { objectMode: true, highWaterMark: 16 }); var that = this; function readFirst() { /*jshint validthis:true */ this.removeListener('readable', readFirst); that._transform(wrap(this.read(), this), null, noop); } this._session = jschan.memorySession(); this._session.on('channel', function(channel) { channel.on('readable', readFirst); }); this._nextChannel = this._session.WriteChannel(); this.on('pipe', function(source) { source.on('ready', that.emit.bind(that, 'ready')); this.on('end', function() { source.end(); }); }); this._patterns = []; } inherits(Graft, Transform); Graft.prototype._transform = function flowing(obj, enc, done) { if (!obj._session && !obj._channel) { // it quacks like a duck, so it's a duck - s/duck/request/g var channel = this._nextChannel; this._nextChannel = this._session.WriteChannel(); channel.write(obj); return done(); } var i; for (i = 0; i < this._patterns.length; i++) { if (this._patterns[i].pattern(obj)) { this._patterns[i].stream.write(obj, done); return; } } this.push(obj); done(); }; Graft.prototype.branch = function(pattern, stream) { if (!pattern) { throw new Error('missing pattern'); } if (!stream) { throw new Error('missing destination'); } this._patterns.push({ pattern: pattern, stream: stream }); return this; }; Graft.prototype.where = function(pattern, stream) { return this.branch(function(req) { return deepMatch(pattern, req); }, stream); }; Graft.prototype.close = function(cb) { function complete() { /*jshint validthis:true */ this._session.close(function(err) { if (err) { return cb(err); } return cb(); }); } if (this._readableState.endEmitted) { complete.call(this); } else { this.on('end', complete); } if (!this._readableState.flowing) { this.resume(); } this.end(); }; Graft.prototype.ReadChannel = function() { return this._nextChannel.ReadChannel(); }; Graft.prototype.WriteChannel = function() { return this._nextChannel.WriteChannel(); }; module.exports = Graft;
'use strict'; // Declare app level module which depends on views, and components var accountModule = angular.module('accountModule', []); var partnerModule = angular.module('partnerModule', []); var dodoModule = angular.module('dodoModule', []); angular.module('myApp', [ 'ngMaterial', 'ngRoute', 'myApp.version', 'accountModule', 'partnerModule', 'dodoModule' ]). config(['$routeProvider', function ($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]).factory('storageService', ['$log', '$rootScope', function ($log, $rootScope) { var localStorageMaxCount = 10; var storageService = { save: function (storageName, data) { localStorage[storageName] = JSON.stringify(data); if (localStorage.length > localStorageMaxCount) { $log.warn('local storage count (length) is over 10, this may be a bug, please check it out - Message from StorageService'); } $rootScope.$broadcast(storageName, data); return data; }, load: function (storageName) { var storedData = localStorage[storageName]; if (typeof storedData !== "undefined") { return JSON.parse(storedData); } else { return undefined; } }, clear: function (storageName) { delete localStorage[storageName]; $rootScope.$broadcast(storageName); return undefined; }, swipeAll: function () { localStorage.clear(); return 'localStorage is cleared!'; }, status: function () { $log.info('Current status -> localstorage: ', localStorage); } }; return storageService; }]).config(['$sceProvider', function ($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }]).run(['storageService', '$location', '$http', function (storageService, $location, $http) { var currentUser = storageService.load('currentUser'); if (typeof currentUser == "undefined") { $location.path('/account/login'); } else { $http.defaults.headers.common["X-Parse-Session-Token"] = currentUser.sessionToken; } }]) .config(function ($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('pink') .accentPalette('orange'); });
"use strict"; const root = require('./helpers.js').root const ip = require('ip'); exports.HOST = ip.address(); exports.DEV_PORT = 3000; exports.E2E_PORT = 4201; exports.PROD_PORT = 8088; exports.UNIVERSAL_PORT = process.env.PORT || 8000; exports.SHOW_WEBPACK_BUNDLE_ANALYZER = false; /** * These constants set whether or not you will use proxy for Webpack DevServer * For advanced configuration details, go to: * https://webpack.github.io/docs/webpack-dev-server.html#proxy */ exports.USE_DEV_SERVER_PROXY = false; exports.DEV_SERVER_PROXY_CONFIG = { '**': 'http://localhost:8089' } /** * These constants set the source maps that will be used on build. * For info on source map options, go to: * https://webpack.github.io/docs/configuration.html#devtool */ exports.DEV_SOURCE_MAPS = 'eval'; exports.PROD_SOURCE_MAPS = 'source-map'; /** * Set watch options for Dev Server. For better HMR performance, you can * try setting poll to 1000 or as low as 300 and set aggregateTimeout to as low as 0. * These settings will effect CPU usage, so optimal setting will depend on your dev environment. * https://github.com/webpack/docs/wiki/webpack-dev-middleware#watchoptionsaggregatetimeout */ exports.DEV_SERVER_WATCH_OPTIONS = { poll: undefined, aggregateTimeout: 300, ignored: /node_modules/ } /** * specifies which @ngrx dev tools will be available when you build and load * your app in dev mode. Options are: monitor | logger | both | none */ exports.STORE_DEV_TOOLS = 'monitor' exports.EXCLUDE_SOURCE_MAPS = [ // these packages have problems with their sourcemaps root('node_modules/@angular'), root('node_modules/@nguniversal'), root('node_modules/rxjs') ] exports.MY_COPY_FOLDERS = [ // use this for folders you want to be copied in to Client dist // src/assets and index.html are already copied by default. // format is { from: 'folder_name', to: 'folder_name' } ] exports.MY_POLYFILL_DLLS = [ // list polyfills that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_VENDOR_DLLS = [ // list vendors that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_CLIENT_PLUGINS = [ // use this to import your own webpack config Client plugins. ] exports.MY_CLIENT_PRODUCTION_PLUGINS = [ // use this to import your own webpack config plugins for production use. ] exports.MY_CLIENT_RULES = [ // use this to import your own rules for Client webpack config. ] exports.MY_TEST_RULES = [ // use this to import your own rules for Test webpack config. ] exports.MY_TEST_PLUGINS = [ // use this to import your own Test webpack config plugins. ]
function report(str) { console.log(str); } function vec3(x,y,z) { return new THREE.Vector3(x,y,z); } SCENE = {}; SCENE.getCard = function(boxW, boxH, rotZ) { boxD = 0.1; if (!rotZ) rotZ = 0; //report("getImageCard "+imageUrl); var material = new THREE.MeshLambertMaterial( { color: 0xdddddd, //map: THREE.ImageUtils.loadTexture(imageUrl) //transparent: true }); material.side = THREE.DoubleSide; material.transparency = 0.5; var geometry = new THREE.PlaneGeometry( boxW, boxH ); var obj = new THREE.Mesh( geometry, material ); var card = new THREE.Object3D(); card.add(obj); obj.rotation.z = rotZ; obj.position.y += 0.5*boxH + boxD; obj.position.x += 0.0*boxW; obj.position.z += 0.0*boxD; card.obj = obj; card.material = material; return card; } var scene; SCENE.scene = scene; if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var container, stats; var camera, renderer; var object, arrow; var useFog = true; var useGround = true; function start() { init(); animate(); } function init() { P = {}; P.v0 = 0.04; P.theta0 = 0; P.xbias = 0; P.lastTrackedTime = 0; P.pauseTime = 5; container = document.createElement( 'div' ); document.body.appendChild( container ); // scene scene = new THREE.Scene(); clearColor = 0xcce0ff; if (useFog) //scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 ); //NOFOG scene.fog = new THREE.Fog( clearColor, 500, 10000 ); //NOFOG //scene.fog = new THREE.Fog( 0xcce0ff, 500, 50000 ); //NOFOG // camera //camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 ); camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 30000 ); camera.position.y = 50; camera.position.z = 1500; scene.add( camera ); P.camera = camera; // lights var light, materials; scene.add( new THREE.AmbientLight( 0x666666 ) ); var group = new THREE.Scene(); scene.add(group); light = new THREE.DirectionalLight( 0xdfebff, 1.75 ); light.position.set( 50, 200, 100 ); light.position.multiplyScalar( 1.3 ); light.castShadow = true; //light.shadowCameraVisible = true; light.shadowMapWidth = 1024; light.shadowMapHeight = 1024; //var d = 300; var d = 1200; light.shadowCameraLeft = -d; light.shadowCameraRight = d; light.shadowCameraTop = d; light.shadowCameraBottom = -d; light.shadowCameraFar = 1000; light.shadowDarkness = 0.5; scene.add( light ); // ground if (useGround) { var texLoader = new THREE.TextureLoader(); //var groundTexture = texLoader.load( "textures/terrain/grasslight-big.jpg" ); //groundTexture.repeat.set( 25, 25 ); //var groundTexture = texLoader.load( "textures/terrain/dark_grass.png" ); //groundTexture.repeat.set( 15, 15 ); var groundTexture = texLoader.load( "textures/terrain/red_earth.png" ); groundTexture.repeat.set( 15, 15 ); //var groundTexture = texLoader.load( "textures/terrain/BrownLeaves.jpg" ); groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; //groundTexture.repeat.set( 5, 5 ); groundTexture.anisotropy = 16; var groundMaterial = new THREE.MeshPhongMaterial( { color: 0x664444, specular: 0x111111, map: groundTexture } ); var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial ); mesh.position.y = -250; mesh.rotation.x = - Math.PI / 2; mesh.receiveShadow = true; scene.add( mesh ); } // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor( clearColor ); //NOFOG container.appendChild( renderer.domElement ); renderer.gammaInput = true; renderer.gammaOutput = true; //renderer.shadowMapEnabled = true; renderer.shadowMap.enabled = true; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); trackball = 1; if (trackball) { //controls = new THREE.TrackballControls( camera, container ); //controls = new THREE.EditorControls( camera, container ); //controls = new THREE.OrthographicTrackballControls( camera, container ); //controls = new THREE.OrbitControls( camera, container ); controls = new THREE.PVControls( camera, container, scene ); controls.rotateSpeed = 2.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [ 65, 83, 68 ]; //controls.addEventListener( 'change', render ); } } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } // function animate() { requestAnimationFrame( animate ); render(); var time = Date.now(); //arrow.setLength( windMag ); //arrow.setDirection( SKIRT.windForce ); var ct = new Date().getTime() / 1000; // Adjust renderer.render( scene, camera ); stats.update(); } function render() { var timer = Date.now() * 0.0002; //sphere.position.copy( ballPosition ); //camera.lookAt( scene.position ); }
#!/usr/bin/env node var mkdirp = require('yeoman-generator/node_modules/mkdirp') var path = require('path') var fs = require('fs') var win32 = process.platform === 'win32' var homeDir = process.env[ win32? 'USERPROFILE' : 'HOME'] var libPath = path.join(homeDir, '.generator-lego', 'node_modules') var configPath = path.join(homeDir, '.generator-lego', 'config.json') // USERPROFILE 文件夹创建 mkdirp.sync(libPath) fs.writeFileSync(configPath, JSON.stringify({}, null, 4), { encoding: 'utf8' })
exports.platform = function () { switch(process.platform){ case 'win32': dep='win'; break; case 'linux': case 'mac': dep=process.platform; } return 'node-' + dep; };
/** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ //Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.1.11', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.getElementsByTagName('script'); } function defaultOnError(err) { throw err; } //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite and existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part, length = ary.length; for (i = 0; i < length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = normalizedBaseParts.concat(name); trimDots(name); name = name.join('/'); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break outerLoop; } } } } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); context.require([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { mod = getModule(depMap); if (mod.error && name === 'error') { fn(mod.error); } else { mod.on(name, fn); } } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return getOwn(config.config, mod.map.id) || {}; }, exports: mod.exports || (mod.exports = {}) }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { var map = mod.map, modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, bundleId = getOwn(bundlesMap, this.map.id), name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } //If a paths config, then just load that file instead to //resolve the plugin, as it is built into that paths layer. if (bundleId) { this.map.url = context.nameToUrl(bundleId); this.load(); return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths since they require special processing, //they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); //Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { each(value, function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } //Save pointer to main module ID for pkg name. //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, ''); }); } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); removeScript(id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; //Clean queued defines too. Go backwards //in array so that the splices do not //mess up the iteration. eachReverse(defQueue, function(args, i) { if(args[0] === id) { defQueue.splice(i, 1); } }); if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); if (pkgMain) { moduleName = pkgMain; } bundleId = getOwn(bundlesMap, moduleName); if (bundleId) { return context.nameToUrl(bundleId, ext, skipExt); } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.getElementsByTagName('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = defaultOnError; /** * Creates the node for the load command. Only used in browser envs. */ req.createNode = function (config, moduleName, url) { var node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; return node; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //read https://github.com/jrburke/requirejs/issues/187 //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: //https://github.com/jrburke/requirejs/issues/273 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Preserve dataMain in case it is a path (i.e. contains '?') mainScript = dataMain; //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } //Strip off any trailing .js since mainScript is now //like a module name. mainScript = mainScript.replace(jsSuffixRegExp, ''); //If mainScript is still a path, fall back to dataMain if (req.jsExtRegExp.test(mainScript)) { mainScript = dataMain; } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps && isFunction(callback)) { deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this));
var add = require('./add'); QUnit.test('add example', function () { // add function returns sum of numbers QUnit.equal(add(2, 3), 5); // it also concatenates strings QUnit.equal(add('foo', 'bar'), 'foobar') });
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /** * This sample shows how to: * - Get the current user's metadata * - Get the current user's profile photo * - Attach the photo as a file attachment to an email message * - Upload the photo to the user's root drive * - Get a sharing link for the file and add it to the message * - Send the email */ const express = require('express'); const router = express.Router(); const graphHelper = require('../utils/graphHelper.js'); const emailer = require('../utils/emailer.js'); const passport = require('passport'); // ////const fs = require('fs'); // ////const path = require('path'); // Get the home page. router.get('/', (req, res) => { // check if user is authenticated if (!req.isAuthenticated()) { res.render('login'); } else { renderSendMail(req, res); } }); // Authentication request. router.get('/login', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { res.redirect('/'); }); // Authentication callback. // After we have an access token, get user data and load the sendMail page. router.get('/token', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { graphHelper.getUserData(req.user.accessToken, (err, user) => { if (!err) { req.user.profile.displayName = user.body.displayName; req.user.profile.emails = [{ address: user.body.mail || user.body.userPrincipalName }]; renderSendMail(req, res); } else { renderError(err, res); } }); }); // Load the sendMail page. function renderSendMail(req, res) { res.render('sendMail', { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address }); } // Do prep before building the email message. // The message contains a file attachment and embeds a sharing link to the file in the message body. function prepForEmailMessage(req, callback) { const accessToken = req.user.accessToken; const displayName = req.user.profile.displayName; const destinationEmailAddress = req.body.default_email; // Get the current user's profile photo. graphHelper.getProfilePhoto(accessToken, (errPhoto, profilePhoto) => { // //// TODO: MSA flow with local file (using fs and path?) if (!errPhoto) { // Upload profile photo as file to OneDrive. graphHelper.uploadFile(accessToken, profilePhoto, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, profilePhoto ); callback(null, mailBody); }); }); } else { var fs = require('fs'); var readableStream = fs.createReadStream('public/img/test.jpg'); var picFile; var chunk; readableStream.on('readable', function() { while ((chunk=readableStream.read()) != null) { picFile = chunk; } }); readableStream.on('end', function() { graphHelper.uploadFile(accessToken, picFile, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, picFile ); callback(null, mailBody); }); }); }); } }); } // Send an email. router.post('/sendMail', (req, res) => { const response = res; const templateData = { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address, actual_recipient: req.body.default_email }; prepForEmailMessage(req, (errMailBody, mailBody) => { if (errMailBody) renderError(errMailBody); graphHelper.postSendMail(req.user.accessToken, JSON.stringify(mailBody), (errSendMail) => { if (!errSendMail) { response.render('sendMail', templateData); } else { if (hasAccessTokenExpired(errSendMail)) { errSendMail.message += ' Expired token. Please sign out and sign in again.'; } renderError(errSendMail, response); } }); }); }); router.get('/disconnect', (req, res) => { req.session.destroy(() => { req.logOut(); res.clearCookie('graphNodeCookie'); res.status(200); res.redirect('/'); }); }); // helpers function hasAccessTokenExpired(e) { let expired; if (!e.innerError) { expired = false; } else { expired = e.forbidden && e.message === 'InvalidAuthenticationToken' && e.response.error.message === 'Access token has expired.'; } return expired; } /** * * @param {*} e * @param {*} res */ function renderError(e, res) { e.innerError = (e.response) ? e.response.text : ''; res.render('error', { error: e }); } module.exports = router;
(function($,window){ })(Zepto,window);
module.exports = require('./src/angularjs-dependencies-wrapper');
////////////////////////////////////////////////////////////////////////// // // // This is a generated file. You can view the original // // source in your browser if your browser supports source maps. // // // // If you are using Chrome, open the Developer Tools and click the gear // // icon in its lower right corner. In the General Settings panel, turn // // on 'Enable source maps'. // // // // If you are using Firefox 23, go to `about:config` and set the // // `devtools.debugger.source-maps-enabled` preference to true. // // (The preference should be on by default in Firefox 24; versions // // older than 23 do not support source maps.) // // // ////////////////////////////////////////////////////////////////////////// (function () { /* Imports */ var Meteor = Package.meteor.Meteor; var TAPi18next = Package['tap:i18n'].TAPi18next; var TAPi18n = Package['tap:i18n'].TAPi18n; var Session = Package.session.Session; /* Package-scope variables */ var i18n, setLanguage; (function () { /////////////////////////////////////////////////////////////////////////////// // // // packages/telescope-i18n/i18n.js // // // /////////////////////////////////////////////////////////////////////////////// // // do this better: // 1 setLanguage = function (language) { // 2 // Session.set('i18nReady', false); // 3 // console.log('i18n loading… '+language) // 4 // 5 // moment // 6 Session.set('momentReady', false); // 7 // console.log('moment loading…') // 8 if (language.toLowerCase() === "en") { // 9 Session.set('momentReady', true); // 10 } else { // 11 $.getScript("//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/lang/" + language.toLowerCase() + ".js", function (result) { moment.locale(language); // 13 Session.set('momentReady', true); // 14 Session.set('momentLocale', language); // 15 // console.log('moment loaded!') // 16 }); // 17 } // 18 // 19 // TAPi18n // 20 Session.set("TAPi18nReady", false); // 21 // console.log('TAPi18n loading…') // 22 TAPi18n.setLanguage(language) // 23 .done(function () { // 24 Session.set("TAPi18nReady", true); // 25 // console.log('TAPi18n loaded!') // 26 }); // 27 // 28 // T9n // 29 T9n.setLanguage(language); // 30 } // 31 // 32 i18n = { // 33 t: function (str, options) { // 34 if (Meteor.isServer) { // 35 return TAPi18n.__(str, options, Settings.get('language', 'en')); // 36 } else { // 37 return TAPi18n.__(str, options); // 38 } // 39 } // 40 }; // 41 // 42 Meteor.startup(function () { // 43 // 44 if (Meteor.isClient) { // 45 // 46 // doesn't quite work yet // 47 // Tracker.autorun(function (c) { // 48 // console.log('momentReady',Session.get('momentReady')) // 49 // console.log('i18nReady',Session.get('i18nReady')) // 50 // var ready = Session.get('momentReady') && Session.get('i18nReady'); // 51 // if (ready) { // 52 // Session.set('i18nReady', true); // 53 // Session.set('locale', language); // 54 // console.log('i18n ready! '+language) // 55 // } // 56 // }); // 57 // 58 setLanguage(Settings.get('language', 'en')); // 59 } // 60 // 61 }); // 62 // 63 /////////////////////////////////////////////////////////////////////////////// }).call(this); /* Exports */ if (typeof Package === 'undefined') Package = {}; Package['telescope-i18n'] = { i18n: i18n, setLanguage: setLanguage }; })();
describe('async methods', () => { it('commits multiple valid inserts to the database', done => { const methodUnderTest = async (unitOfWork) => { const insert = { method: 'insert' }; await new unitOfWork.Users(getUserWithEmail('1')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('2')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('3')).save(null, insert); }; new SomeService(methodUnderTest) .runMethodUnderTest() .then(() => bookshelf.Users.count()) .then(count => expect(count).to.equal('3')) .then(() => done(), done); }) });
'use strict'; var CurrentCourseStore = require('../../../js/stores/CurrentCourseStore'); var CourseActions = require('../../../js/actions/CourseActions'); require('../../../utils/createAuthenticatedSuite')('Store: CurrentCourse', function() { it('should be empty on init', function(done) { (CurrentCourseStore.course === null).should.be.true; // jshint ignore:line done(); }); it('should set course on action', function(done) { var course = { id: 1 }; CourseActions.setCourse(course, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); done(); }); }); it('should load a course on action', function(done) { CourseActions.openCourse(1, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); CurrentCourseStore.course.should.have.property('title'); CurrentCourseStore.course.should.have.property('slug'); CurrentCourseStore.course.should.have.property('description'); done(); }); }); it('should create a new lesson on action', function(done) { var lesson = { title: 'lesson to test creation', description: 'test description', bodyElements: [] }; // Make sure `this.course` is set in store before attempting to access `this.course.id` CourseActions.setCourse({ id: 1 }, function() { CourseActions.createLesson(lesson, function(err, lesson) { console.log('error creating lesson:', err); (err === null).should.be.true; // jshint ignore:line lesson.should.be.instanceOf(Object); lesson.should.have.property('title'); lesson.should.have.property('description'); lesson.should.have.property('bodyElements'); done(); }); }); }); });
export * from './PythonHome'; export * from './PythonNav';
const JSONBox = require("../JSONBox"); const rmdir = require("rmdir"); const appRootDir = require("app-root-dir"); const Q = require("q"); const path = require("path"); const async = require("asyncawait/async"); const await = require("asyncawait/await"); const expect = require("chai").expect; const fs = require("fs"); const mkdirp = require("mkdirp"); const sinon = require("sinon"); const uuid = require("uuid"); const assign = require("lodash.assign"); const testDir = "store-test"; const createMockData = async(function() { this.obj = { id: "76ba67b8-7907-11e6-8b77-86f30ca893d3", some: "data", is: "cool" }; this.obj2 = { id: "bc7e5fb6-7907-11e6-8b77-86f30ca893d3", muchas: "gracias" }; await(Q.nfcall(mkdirp ,path.join(appRootDir.get(), testDir))); fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj.id}.json`), JSON.stringify(this.obj), { flag: "w+" }); fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj2.id}.json`), JSON.stringify(this.obj2), { flag: "w+" }); }); describe("JSONBox", function() { before(function() { this.uuid = sinon.stub(uuid, "v4").returns("53ccfe14-7916-11e6-8b77-86f30ca893d3"); }); after(function() { this.uuid.restore(); }) afterEach(function(done) { Q.nfcall(rmdir, path.join(appRootDir.get(), testDir)) .then(() => done()) .catch(() => done()); }); it("Get all entries (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); const expected = [this.obj, this.obj2]; box.all(function(error, data) { if(error) done(error); expect(data).to.eql(expected); done(); }); }); }); it("Get all entries (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); return box.all(); }) .then(data => { expect(data).to.eql([this.obj, this.obj2]); done(); }) .catch(done); }); it("Get a single entry (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.get(this.obj.id, function(error, data) { if(error) done(error); expect(data).to.eql(this.obj); done(); }.bind(this)); }); }); it("Get a single entry (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); return box.get(this.obj.id); }) .then(data => { expect(data).to.eql(this.obj); done(); }) .catch(done); }); it("Store an entry (callback style)", function(done) { const box = JSONBox.of({ name: testDir }); const storable = { abc: 123, def: "456" }; box.store(storable, function(error, data) { if(error) done(error); expect(data).to.eql(assign({}, data, { id: "53ccfe14-7916-11e6-8b77-86f30ca893d3" })); done(); }.bind(this)); }); it("Store an entry (promise style)", function(done) { const box = JSONBox.of({ name: testDir }); const storable = { abc: 123, def: "456" }; box.store(storable) .then(data => { expect(data).to.eql(assign({}, data, { id: "53ccfe14-7916-11e6-8b77-86f30ca893d3" })); done(); }) .catch(done); }); it("Store an null entry (callback style), expect Error", function(done) { const box = JSONBox.of({ name: testDir }); box.store(null, function(error, data) { if(error) done(); else done(new Error("Expected to throw an Error!")); }); }); it("Store an null entry (promise style), expect Error", function(done) { const box = JSONBox.of({ name: testDir }); box.store(null) .then(data => done(new Error("Expected to throw an Error!"))) .catch(() => done()); }); it("Deletes an entry (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.delete(this.obj, function(error) { if(error) done(error); done(); }.bind(this)); }); }); it("Deletes an entry (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.delete(this.obj.id) .then(() => done()) .catch(done); }); }); });
const SafeHarborModules = require('./SafeHarborModules'); const SafeHarborInverters = require('./SafeHarborInverters'); module.exports = () => { SafeHarborModules(); SafeHarborInverters(); }
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('tallytextApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
'use strict' const React = require('react'); import {Sidebar} from 'react-semantify'; const UISidebar = React.createClass({ render : function() { return ( <Sidebar className="ui top sidebar menu push scale down" init={true}> <a className="item"> Our company </a> <a className="item"> Dashboard </a> <a className="item"> My recipes </a> <a href="/logout" className="item right floated"> Logout </a> </Sidebar> ) } }); module.exports = UISidebar;
const express = require('express'); const app = express(); const port = 8080; app.get('/', (req, res) => { res.send('Hello World\n'); }); app.listen(port, () => { console.log(`application is listening on port ${port}...`); });
/*! Backstretch - v2.0.4 - 2013-06-19 * http://srobbin.com/jquery-plugins/backstretch/ * Copyright (c) 2013 Scott Robbin; Licensed MIT */ (function (a, d, p) { a.fn.backstretch = function (c, b) { (c === p || 0 === c.length) && a.error("No images were supplied for Backstretch"); 0 === a(d).scrollTop() && d.scrollTo(0, 0); return this.each(function () { var d = a(this), g = d.data("backstretch"); if (g) { if ("string" == typeof c && "function" == typeof g[c]) { g[c](b); return } b = a.extend(g.options, b); g.destroy(!0) } g = new q(this, c, b); d.data("backstretch", g) }) }; a.backstretch = function (c, b) { return a("body").backstretch(c, b).data("backstretch") }; a.expr[":"].backstretch = function (c) { return a(c).data("backstretch") !== p }; a.fn.backstretch.defaults = {centeredX: !0, centeredY: !0, duration: 5E3, fade: 0}; var r = {left: 0, top: 0, overflow: "hidden", margin: 0, padding: 0, height: "100%", width: "100%", zIndex: -999999}, s = {position: "absolute", display: "none", margin: 0, padding: 0, border: "none", width: "auto", height: "auto", maxHeight: "none", maxWidth: "none", zIndex: -999999}, q = function (c, b, e) { this.options = a.extend({}, a.fn.backstretch.defaults, e || {}); this.images = a.isArray(b) ? b : [b]; a.each(this.images, function () { a("<img />")[0].src = this }); this.isBody = c === document.body; this.$container = a(c); this.$root = this.isBody ? l ? a(d) : a(document) : this.$container; c = this.$container.children(".backstretch").first(); this.$wrap = c.length ? c : a('<div class="backstretch"></div>').css(r).appendTo(this.$container); this.isBody || (c = this.$container.css("position"), b = this.$container.css("zIndex"), this.$container.css({position: "static" === c ? "relative" : c, zIndex: "auto" === b ? 0 : b, background: "none"}), this.$wrap.css({zIndex: -999998})); this.$wrap.css({position: this.isBody && l ? "fixed" : "absolute"}); this.index = 0; this.show(this.index); a(d).on("resize.backstretch", a.proxy(this.resize, this)).on("orientationchange.backstretch", a.proxy(function () { this.isBody && 0 === d.pageYOffset && (d.scrollTo(0, 1), this.resize()) }, this)) }; q.prototype = {resize: function () { try { var a = {left: 0, top: 0}, b = this.isBody ? this.$root.width() : this.$root.innerWidth(), e = b, g = this.isBody ? d.innerHeight ? d.innerHeight : this.$root.height() : this.$root.innerHeight(), j = e / this.$img.data("ratio"), f; j >= g ? (f = (j - g) / 2, this.options.centeredY && (a.top = "-" + f + "px")) : (j = g, e = j * this.$img.data("ratio"), f = (e - b) / 2, this.options.centeredX && (a.left = "-" + f + "px")); this.$wrap.css({width: b, height: g}).find("img:not(.deleteable)").css({width: e, height: j}).css(a) } catch (h) { } return this }, show: function (c) { if (!(Math.abs(c) > this.images.length - 1)) { var b = this, e = b.$wrap.find("img").addClass("deleteable"), d = {relatedTarget: b.$container[0]}; b.$container.trigger(a.Event("backstretch.before", d), [b, c]); this.index = c; clearInterval(b.interval); b.$img = a("<img />").css(s).bind("load",function (f) { var h = this.width || a(f.target).width(); f = this.height || a(f.target).height(); a(this).data("ratio", h / f); a(this).fadeIn(b.options.speed || b.options.fade, function () { e.remove(); b.paused || b.cycle(); a(["after", "show"]).each(function () { b.$container.trigger(a.Event("backstretch." + this, d), [b, c]) }) }); b.resize() }).appendTo(b.$wrap); b.$img.attr("src", b.images[c]); return b } }, next: function () { return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0) }, prev: function () { return this.show(0 === this.index ? this.images.length - 1 : this.index - 1) }, pause: function () { this.paused = !0; return this }, resume: function () { this.paused = !1; this.next(); return this }, cycle: function () { 1 < this.images.length && (clearInterval(this.interval), this.interval = setInterval(a.proxy(function () { this.paused || this.next() }, this), this.options.duration)); return this }, destroy: function (c) { a(d).off("resize.backstretch orientationchange.backstretch"); clearInterval(this.interval); c || this.$wrap.remove(); this.$container.removeData("backstretch") }}; var l, f = navigator.userAgent, m = navigator.platform, e = f.match(/AppleWebKit\/([0-9]+)/), e = !!e && e[1], h = f.match(/Fennec\/([0-9]+)/), h = !!h && h[1], n = f.match(/Opera Mobi\/([0-9]+)/), t = !!n && n[1], k = f.match(/MSIE ([0-9]+)/), k = !!k && k[1]; l = !((-1 < m.indexOf("iPhone") || -1 < m.indexOf("iPad") || -1 < m.indexOf("iPod")) && e && 534 > e || d.operamini && "[object OperaMini]" === {}.toString.call(d.operamini) || n && 7458 > t || -1 < f.indexOf("Android") && e && 533 > e || h && 6 > h || "palmGetResource"in d && e && 534 > e || -1 < f.indexOf("MeeGo") && -1 < f.indexOf("NokiaBrowser/8.5.0") || k && 6 >= k) })(jQuery, window);
'use strict'; var request = require('request') var uuid = require('node-uuid') var env = require('./env') var World = function World(callback) { var self = this this.collection = null this.lastResponse = null this.doc1 = null this.doc2 = null this.generateCollectionId = function() { this.collection = uuid.v1() } this.generateDocumentId = function() { // MongoDB either accepts a 12 byte string or 24 hex characters this.doc1 = uuid.v1().replace(/-/gi, '').substring(0,24) } this.get = function(path, callback) { var uri = this.uri(path) request.get(uri, function(error, response) { if (error) { return callback.fail(new Error('Error on GET request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.post = function(path, requestBody, callback) { var uri = this.uri(path) request({url: uri, body: requestBody, method: 'POST'}, function(error, response) { if (error) { return callback(new Error('Error on POST request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback(null, self.lastResponse.headers.location) }) } this.put = function(path, requestBody, callback) { var uri = this.uri(path) request({url: uri, body: requestBody, method: 'PUT'}, function(error, response) { if (error) { return callback(new Error('Error on PUT request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback(null, self.lastResponse.headers.locations) }) } this.delete = function(path, callback) { var uri = this.uri(path) request({url: uri, method: 'DELETE'}, function(error, response) { if (error) { return callback(new Error('Error on DELETE request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.options = function(path, callback) { var uri = this.uri(path) request({'uri': uri, method: 'OPTIONS'}, function(error, response) { if (error) { return callback.fail(new Error('Error on OPTIONS request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.rootPath = function() { return '/' } this.rootUri = function() { return this.uri(this.rootPath()) } this.collectionPath = function(collection) { return '/' + collection } this.collectionUri = function(collection) { return this.uri(this.collectionPath(collection)) } this.documentPath = function(collection, document) { return this.collectionPath(collection) + '/' + document } this.documentUri = function(collection, document) { return this.uri(this.documentPath(collection, document)) } this.uri = function(path) { return env.BASE_URL + path } callback() } exports.World = World
var gulp = require('gulp'); gulp.task('default', function() { console.log("Currently there are no available tasks. There will be!"); }); /** * Builds the client files into a jar and moves it to the 'build/client' folder. */ /* gulp.task('build-client', function() { return gulp.src('.') .pipe() // Build source/client/bin and data/client into a JAR. .pipe(gulp.dest('build/client')); }); */ /** * Builds the server files into a jar and moves it to the 'build/client' folder. */ /* gulp.task('build-server', function() { return gulp.src('.') .pipe() // Build source/server/bin and data/server into a JAR. .pipe(gulp.dest('build/server')); }); */
/*********************************************** gruntfile.js for jquery-bootstrap https://github.com/fcoo/jquery-bootstrap ***********************************************/ module.exports = function(grunt) { "use strict"; //*********************************************** grunt.initConfig({ "fcoo_grunt_plugin":{ default: { "haveJavaScript": true, //true if the packages have js-files "haveStyleSheet": true, //true if the packages have css and/or scss-files "haveGhPages" : true, //true if there is a branch "gh-pages" used for demos "beforeProdCmd": "", //Cmd to be run at the start of prod-task. Multi cmd can be seperated by "&" "beforeDevCmd" : "", //Cmd to be run at the start of dev-task "afterProdCmd" : "", //Cmd to be run at the end of prod-task "afterDevCmd" : "", //Cmd to be run at the end of dev-task "DEBUG" : false //if true different debugging is on and the tempoary files are not deleted } } }); //**************************************************************** //Load grunt-packages grunt.loadNpmTasks('grunt-fcoo-grunt-plugin'); };
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.3-4-250 description: > Object.getOwnPropertyDescriptor - returned object contains the property 'get' if the value of property 'get' is not explicitly specified when defined by Object.defineProperty. includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; Object.defineProperty(obj, "property", { set: function () {}, configurable: true }); var desc = Object.getOwnPropertyDescriptor(obj, "property"); return "get" in desc; } runTestCase(testcase);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm']]; module.exports = exports['default'];
/** * @file 棱镜配置文件 */ var pkg = require('./package.json'); module.exports = { appid: pkg.appid, name: pkg.name, desc: pkg.description, host: `https://${pkg.appid}.h5app.alipay.com/www/`, pages: [ { entry: 'index.html', src: './src/pages/index/index.js', title: '首页', desc: '首页 - 描述' }, { entry: 'list.html', src : './src/pages/list/list.js', title: 'list列表', desc: 'list列表 - list列表页' } ] };
import { isNull } from '../checks/isNull'; import { isObject } from '../checks/isObject'; import { mustSatisfy } from '../checks/mustSatisfy'; /** * @hidden */ function beObject() { return "be a non-null `object`"; } /** * @hidden */ export function mustBeNonNullObject(name, value, contextBuilder) { mustSatisfy(name, isObject(value) && !isNull(value), beObject, contextBuilder); return value; }
export default Ember.Handlebars.makeBoundHelper(function(price) { var number = parseFloat(price/100).toFixed(2), dollar = number.split('.')[0], cents = number.split('.')[1], dollars = dollar.split('').reverse().join('') .replace(/(\d{3}(?!$))/g, '$1,') .split('').reverse().join(''); return '$' + dollars + '.' + cents; });
angular.module('fdb.directives', ['mcus.directives']); angular.module('fdb.services', ['mcus.services']); angular.module('fdb.filters', []); angular.module('fdb', ['fdb.services', 'fdb.directives', 'fdb.filters']). controller('UserFrontendCtrl', function($scope, $http, $timeout, $filter, $location) { // $scope.deleteUser = function(user){ // if(confirm('Delete user ' + user.username + ' ?')){ // $http.post(Config.baseUrl + '/UsersFrontends/delete', {'id' : user.id}).success(function (resp) { // if(resp == 'true'){ // for(var index = 0; index < $scope.users.length; index++) { // if ($scope.users[index].UsersFrontend.id == user.id) { // $scope.users.splice(index, 1); // break; // } // } // }else{ // alert('Error. Can not delete this user. View logs for more detail'); // } // }) // } // } $scope.lockUser = function(user){ if(user.status == 'lock'){ message = 'Unlock this user with email: '; status = 'active'; }else if(user.status == 'active'){ message = 'Lock this user with email: '; status = 'lock'; } if(confirm(message + user.email + '?')){ $http.post(Config.baseUrl + '/UsersFrontends/edit', {'id' : user.id, 'status' : status}).success(function (resp) { console.log(resp); if(resp.data){ user.status = status; }else{ alert('Error'); } }) } } $scope.search = function (row) { if(row.UsersFrontend.username && angular.lowercase(row.UsersFrontend.username).indexOf($scope.query || '') !== -1){ return true; } if(row.UsersFrontend.fullname && angular.lowercase(row.UsersFrontend.fullname).indexOf($scope.query || '') !== -1){ return true; } if(row.UsersFrontend.email && angular.lowercase(row.UsersFrontend.email).indexOf($scope.query || '') !== -1){ return true; } if(row.UsersFrontend.facebook_id && angular.lowercase(row.UsersFrontend.facebook_id).indexOf($scope.query || '') !== -1){ return true; } if(row.UsersFrontend.status && angular.lowercase(row.UsersFrontend.status).indexOf($scope.query || '') !== -1){ return true; } return false; }; $scope.editUser = function(user){ $scope.showError = true; $scope.editingUser = angular.copy(user); if ($scope.editUserForm.$invalid) { return; } } $scope.applyEditUser = function(){ $scope.showError = true; console.log($scope.editUserForm); if ($scope.editUserForm.$invalid) { return; } var ptNotAllowSpecialCharacter = /[^a-zA-Z0-9]/; if (ptNotAllowSpecialCharacter.test($scope.editingUser.username)) { alert('Error, username contain special characters'); return false; } $http.post(Config.baseUrl + '/UsersFrontends/checkExistEmail', {'email' : $scope.editingUser.email, 'id' : $scope.editingUser.id}).success(function (res) { // Not allow edit with existed email if(res.check > 0){ alert('Error!. This email existed'); return; } }) var userData = {}; userData.id = $scope.editingUser.id; userData.fullname = $scope.editingUser.fullname; userData.username = $scope.editingUser.username; userData.email = $scope.editingUser.email; userData.facebook_id = $scope.editingUser.facebook_id; userData.status = $scope.editingUser.status; $http.post(Config.baseUrl + '/UsersFrontends/edit', userData).success(function (res) { if(res.data){ response = res.data; response.UsersFrontend.created = $scope.editingUser.created; response.UsersFrontend.modified = $scope.editingUser.modified; // remove old user object for(var index = 0; index < $scope.users.length; index++) { if ($scope.users[index].UsersFrontend.id == $scope.editingUser.id) { $scope.users.splice(index, 1); break; } } // add new user object $scope.users.push(response); angular.element('#cancelEdit').trigger('click'); } }) } })
import React from "react"; import styled from "styled-components"; import Img from "gatsby-image"; import { graphql } from "gatsby"; import Center from "../components/center"; import ResponsiveContainer from "../components/responsive-container"; import Inset from "../components/inset"; import Text from "../components/text"; import colors from "../constants/colors"; import Layout from "../layouts"; import VersandhausWalzLogo from "../assets/compressed/versandhaus-walz.png"; import OttoLogo from "../assets/compressed/otto.png"; import LudwigMediaLogo from "../assets/compressed/ludwigmedia.png"; import BadischerWeinLogo from "../assets/compressed/badischer-wein.png"; import DrawkitContentManColour from "../assets/drawkit-content-man-colour.svg"; import Stack from "../components/stack"; const customers = [ { src: OttoLogo, alt: "Otto (GmbH & CoKG)" }, { src: VersandhausWalzLogo, alt: "Versandhaus Walz" }, { src: LudwigMediaLogo, alt: "LUDWIG:media gmbh" }, { src: BadischerWeinLogo, alt: "Badischer Wein eKfr" } ]; const HeroImage = styled.img` width: 80%; height: auto; @media (min-width: 48em) { width: auto; height: 80vh; max-height: 460px; margin-left: -32px; } `; const HeroLayout = styled(Stack)` margin: 64px 0 32px; @media (min-width: 48em) { margin-top: 0; flex-direction: row; } `; const HeroArea = styled.div` position: relative; background-color: ${colors.black}; display: flex; align-items: center; @media (min-width: 48em) { height: 80vh; } `; const HeroTextArea = styled.div` position: relative; `; const HeroText = styled.h1` line-height: 1.1; font-size: 2.5rem; max-width: 22ch; margin-top: 0; color: ${colors.white}; text-align: center; @media (min-width: 48em) { font-size: 3rem; text-align: left; } `; const HeroTextHighlicht = styled.span` color: ${colors.orange}; `; const HeroTextSubheadline = styled.p` line-height: 1.1; font-size: 1.6rem; max-width: 22ch; color: #ddb992; margin: 0; text-align: center; @media (min-width: 48em) { text-align: left; font-size: 2rem; } `; const CustomerContainer = ResponsiveContainer.extend` display: flex; align-items: center; flex-direction: column; @media (min-width: 700px) { flex-direction: row; } `; const CustomerList = Center.extend` padding: 32px 0; background-color: hsla(31, 17%, 93%, 1); `; const CustomerLogo = styled.div` flex: 1 1 auto; max-height: 60px; margin: 10px; transition: all 0.5s ease-in-out; > img { max-width: 100%; max-height: 100%; } `; const H2 = styled.h2` color: ${colors.textPrimary}; margin: 0 0 24px; `; const H3 = styled.h3` color: ${colors.textPrimary}; margin: 0 0 16px; `; const SkillGrid = styled.div` display: grid; grid-template-columns: 1fr; grid-gap: 16px; @media (min-width: 700px) { grid-template-columns: 1fr 1fr; } `; const ServiceSection = styled.div` background-color: hsla(13, 10%, 97%, 1); padding: 32px 0; `; const Skill = styled.div` background-color: white; border-radius: 4px; display: flex; flex-direction: column; text-align: left; color: ${colors.text}; animation: fadein 2s; `; const SkillImage = styled.div` max-height: 175px; background-color: #ffe6df; border-radius: 4px 4px 0 0; overflow: hidden; `; const IndexPage = ({ data }) => ( <Layout> <HeroArea> <ResponsiveContainer> <HeroLayout alignItems="center" scale="xl"> <HeroTextArea> <HeroText> Wir liefern digitale Lösungen,<br /> <HeroTextHighlicht>die unsere Kunden lieben.</HeroTextHighlicht> </HeroText> <HeroTextSubheadline>Und das seit 15 Jahren!</HeroTextSubheadline> </HeroTextArea> <HeroImage src={DrawkitContentManColour} alt="" /> </HeroLayout> </ResponsiveContainer> </HeroArea> <CustomerList> <CustomerContainer> {customers.map(logo => ( <CustomerLogo key={logo.alt}> <img src={logo.src} alt={logo.alt} /> </CustomerLogo> ))} </CustomerContainer> </CustomerList> <ServiceSection> <ResponsiveContainer> <Center> <H2>Unsere Leistungen</H2> </Center> <SkillGrid> {data.allContentfulServices.edges.map(({ node }) => ( <Skill key={node.id}> <SkillImage> {node.image && <Img fluid={node.image.fluid} />} </SkillImage> <Inset scale="xl"> <H3>{node.title}</H3> <Text.Detail> <div dangerouslySetInnerHTML={{ __html: node.description.childMarkdownRemark.html }} /> </Text.Detail> </Inset> </Skill> ))} </SkillGrid> </ResponsiveContainer> </ServiceSection> </Layout> ); export default IndexPage; export const query = graphql` query AllServices { allContentfulServices(sort: { fields: [order], order: ASC }) { edges { node { id title description { childMarkdownRemark { html } } image { fluid(maxWidth: 426) { ...GatsbyContentfulFluid } } } } } contentfulAsset(title: { eq: "Hero" }) { fluid(maxHeight: 1000) { ...GatsbyContentfulFluid } } } `;
var fs = require('fs'); var path = require('path'); var log = require('./logging').logger; var Project = module.exports; Project.PROJECT_FILE = 'ionic.config.json'; Project.OLD_PROJECT_FILE = 'ionic.project'; Project.OLD_V2_PROJECT_FILE = 'ionic.config.js'; Project.PROJECT_DEFAULT = { name: '', app_id: '' // eslint-disable-line camelcase }; Project.data = null; Project.wrap = function wrap(appDirectory, data) { return { get: function get(key) { return Project.get(data, key); }, remove: function remove(key) { return Project.remove(data, key); }, set: function set(key, value) { return Project.set(data, key, value); }, save: function save() { return Project.save(appDirectory, data); } }; }; Project.load = function load(appDirectory) { if (!appDirectory) { // Try to grab cwd appDirectory = process.cwd(); } var projectFile = path.join(appDirectory, Project.PROJECT_FILE); var oldProjectFile = path.join(appDirectory, Project.OLD_PROJECT_FILE); var oldV2ProjectFile = path.join(appDirectory, Project.OLD_V2_PROJECT_FILE); var data; var found; try { data = JSON.parse(fs.readFileSync(projectFile)); found = true; if (fs.existsSync(oldV2ProjectFile)) { log.warn(('WARN: ionic.config.js has been deprecated, you can remove it.').yellow); } } catch (e) { if (e instanceof SyntaxError) { log.error('Uh oh! There\'s a syntax error in your ' + Project.PROJECT_FILE + ' file:\n' + e.stack); process.exit(1); } } if (!found) { try { data = JSON.parse(fs.readFileSync(oldProjectFile)); log.warn('WARN: ionic.project has been renamed to ' + Project.PROJECT_FILE + ', please rename it.'); found = true; } catch (e) { if (e instanceof SyntaxError) { log.error('Uh oh! There\'s a syntax error in your ionic.project file:\n' + e.stack); process.exit(1); } } } if (!found) { data = Project.PROJECT_DEFAULT; if (fs.existsSync(oldV2ProjectFile)) { log.warn('WARN: ionic.config.js has been deprecated in favor of ionic.config.json.'); log.info('Creating default ionic.config.json for you now...\n'); data.v2 = true; if (fs.existsSync('tsconfig.json')) { data.typescript = true; } } var parts = path.join(appDirectory, '.').split(path.sep); var dirname = parts[parts.length - 1]; Project.create(appDirectory, dirname); Project.save(appDirectory, data); } return Project.wrap(appDirectory, data); }; Project.create = function create(appDirectory, name) { var data = Project.PROJECT_DEFAULT; if (name) { Project.set(data, 'name', name); } return Project.wrap(appDirectory, data); }; Project.save = function save(appDirectory, data) { if (!data) { throw new Error('No data passed to Project.save'); } try { var filePath = path.join(appDirectory, Project.PROJECT_FILE); var jsonData = JSON.stringify(data, null, 2); fs.writeFileSync(filePath, jsonData + '\n'); } catch (e) { log.error('Unable to save settings file:', e); } }; Project.get = function get(data, key) { if (!data) { return null; } if (key) { return data[key]; } else { return data; } }; Project.set = function set(data, key, value) { if (!data) { data = Project.PROJECT_DEFAULT; } data[key] = value; }; Project.remove = function remove(data, key) { if (!data) { data = Project.PROJECT_DEFAULT; } data[key] = ''; };
'use strict'; var q = require('q'); var announcer = require('pd-api-announcer'); var methodNomen = require('./nomenclt'); var nm = require('./parenthood-nomenclt'); module.exports = function (Parent, Child) { var hasChildName = methodNomen.ifOwns(Child); Parent[hasChildName] = function (parentSid, childSid) { return q.Promise(function (resolve, reject) { var cId = childSid + ''; var redisKey = nm.childOf(Child.modelName(), Parent.modelName(), parentSid); Child.redis.zsetExists(redisKey, cId).then(function (reply) { resolve(reply); }).fail(function (err) { if (announcer.error(err).isSysFor('zsetItem', 'gone')) { throw announcer.error.sys(Child.modelName(), 'gone'); } }).fail(function (err) { reject(err); }); }); }; };
export const ic_local_atm = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M11 17h2v-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h4V8h-2V7h-2v1h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1H9v2h2v1zm9-13H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4V6h16v12z"},"children":[]}]};
'use strict'; var inherits = require('util').inherits; var _ = require('lodash'); var GremlinMethod = require('../function'); function GetPropertiesMethod() { GremlinMethod.call(this, 'getProperties', arguments[0]); } inherits(GetPropertiesMethod, GremlinMethod); GetPropertiesMethod.prototype.run = function(element) { var o = {}; return element.properties; }; module.exports = GetPropertiesMethod;
var gsc_basicmatch = /[a-z0-9]/i; function gsc_getquery(elt, q) { q = ltrim(q); q = q.replace('\s+', ' '); if (q.length == 0 || !gsc_basicmatch.test(q)) { gsc_emptyresults(elt); return ''; } if (elt.currentQuery && (elt.currentQuery == q || elt.tempQuery == q)) return ''; elt.currentQuery = q; return q; } function gsc_hide(elt) { if (elt) elt.style.display = 'none'; } function gsc_ishidden(elt) { return elt.style.display == 'none'; } function gsc_show(elt) { if (elt) elt.style.display = 'block'; } function gsc_emptyresults(elt) { if (!elt) return; elt.innerHTML = ''; elt.numResults = 0; elt.selectedIndex = 0; elt.results = []; gsc_hide(elt); } function gsc_addresult(elt, qElt, q, c, sel) { if (!elt) return; if (sel) elt.selectedIndex = elt.numResults; idx = elt.numResults; elt.results[elt.numResults++] = c; var _res = ''; _res += '<div class="' + (sel ? 'srs' : 'sr') + '"' + ' onmouseover="gsc_mouseover(\'' + elt.id + '\', \'' + qElt.id + '\', ' + idx + ')"' + ' onmouseout="gsc_mouseout(\'' + elt.id + '\', ' + idx + ')"' + ' onclick="gsc_mouseclick(\'' + elt.id + '\', \'' + qElt.id + '\', ' + idx + ')">'; _res += '<span class="srt">' + q + '</span>'; if (c.length > 0) _res += '<span class="src">ID: ' + c + '</span>'; _res += '</div>'; elt.innerHTML += _res; } function gsc_mouseover(id, qId, idx) { elt = document.getElementById(id); elt.selectedIndex = idx; qElt = document.getElementById(qId); qElt.focus(); gsc_highlightsel(elt); } function gsc_mouseout(id, idx) { elt = document.getElementById(id); elt.selectedIndex = -1; gsc_highlightsel(elt); } function gsc_mouseclick(id, qId, idx) { elt = document.getElementById(id); qElt = document.getElementById(qId); qElt.value = elt.results[idx]; qElt.form.submit(); } function gsc_handleup(elt, qElt) { if (elt.numResults > 0 && gsc_ishidden(elt)) { gsc_show(elt); return; } if (elt.selectedIndex == 0) return; else if (elt.selectedIndex < 0) elt.selectedIndex = elt.numResults - 1; else elt.selectedIndex--; gsc_highlightsel(elt, qElt); } function gsc_handledown(elt, qElt) { if (elt.numResults > 0 && gsc_ishidden(elt)) { gsc_show(elt); return; } if (elt.selectedIndex == elt.numResults - 1) return; else if (elt.selectedIndex < 0) elt.selectedIndex = 0; else elt.selectedIndex++; gsc_highlightsel(elt, qElt); } function gsc_highlightsel(elt, qElt) { divs = elt.getElementsByTagName('div'); for (i = 0; i < divs.length; i++) { if (i == elt.selectedIndex) { divs[i].className = 'srs'; elt.tempQuery = elt.results[i]; if (qElt) { qElt.value = elt.results[i]; if (qElt.createTextRange) { r = qElt.createTextRange(); r.moveStart('character', elt.currentQuery.length); r.moveEnd('character', qElt.value.length); r.select(); } } } else divs[i].className = 'sr'; } }
/** * @class Oskari.mapframework.domain.AbstractLayer * * Superclass for layer objects copy pasted from wmslayer. Need to check * if something should be moved back to wmslayer. Nothing else currently uses this. */ Oskari.clazz.define('Oskari.mapframework.domain.AbstractMapLayerModel', /** * @method create called automatically on construction * @static */ function (params, options) { /* Internal id for this map layer */ this._id = null; /* Name of this layer */ this._name = null; /* Description for layer */ this._description = null; /* either NORMAL_LAYER, GROUP_LAYER or BASE_LAYER */ this._type = null; /* either WMS, WMTS, WFS or VECTOR */ this._layerType = ''; /* optional params */ this._params = params || {}; /* optional options */ this._options = options || {}; /* modules can "tag" the layers with this for easier reference */ this._metaType = null; /* Max scale for layer */ this._maxScale = null; /* Min scale for layer */ this._minScale = null; /* is layer visible */ this._visible = null; /* opacity from 0 to 100 */ this._opacity = null; /* visible layer switch off enable/disable */ this._isSticky = null; this._inspireName = null; this._organizationName = null; this._dataUrl = null; this._orderNumber = null; /* * Array of sublayers. Notice that only type BASE_LAYER can * have sublayers. */ this._subLayers = []; /* Array of styles that this layer supports */ this._styles = []; /* Currently selected style */ this._currentStyle = null; /* Legend image location */ this._legendImage = null; /* is it possible to ask for feature info */ this._featureInfoEnabled = null; /* is this layer queryable (GetFeatureInfo) boolean */ this._queryable = null; this._queryFormat = null; // f.ex. permissions.publish this._permissions = {}; // if given, tells where the layer has content // array of Openlayers.Geometry[] objects if already processed from _geometryWKT this._geometry = []; // wellknown text for polygon geometry this._geometryWKT = null; // Tools array for layer specific functions this._tools = []; /* link to metadata service */ this._metadataIdentifier = null; this._backendStatus = null; }, { /** * @method setId * @param {String} id * unique identifier for map layer used to reference the layer internally * (e.g. MapLayerService) */ setId: function (id) { this._id = id; }, /** * @method getId * @return {String} * unique identifier for map layer used to reference the layer internally * (e.g. MapLayerService) */ getId: function () { return this._id; }, /** * @method setQueryFormat * @param {String} queryFormat * f.ex. 'text/html' */ setQueryFormat: function (queryFormat) { this._queryFormat = queryFormat; }, /** * @method getQueryFormat * f.ex. 'text/html' * @return {String} */ getQueryFormat: function () { return this._queryFormat; }, /** * @method setName * @param {String} name * name for the maplayer that is shown in UI */ setName: function (name) { this._name = name; }, /** * @method getName * @return {String} maplayer UI name */ getName: function () { return this._name; }, /** * @method setType * @param {String} type * layer type (e.g. NORMAL, BASE, GROUP) * * Not as type WMS or Vector but base or normal layer. * See #setAsBaseLayer(), #setAsGroupLayer() and #setAsNormalLayer() */ setType: function (type) { this._type = type; }, /** * @method getType * @return {String} maplayer type (BASE/NORMAL) */ getType: function () { return this._type; }, /** * @method setDataUrl * @param {String} param * URL string used to show more info about the layer */ setDataUrl: function (param) { this._dataUrl = param; }, /** * @method getDataUrl * @return {String} URL string used to show more info about the layer */ getDataUrl: function () { return this._dataUrl; }, /** * @method setOrganizationName * @param {String} param * organization name under which the layer is listed in UI */ setOrganizationName: function (param) { this._organizationName = param; }, /** * @method getOrganizationName * @return {String} organization name under which the layer is listed in UI */ getOrganizationName: function () { return this._organizationName; }, /** * @method setInspireName * @param {String} param * inspire theme name under which the layer is listed in UI */ setInspireName: function (param) { this._inspireName = param; }, /** * @method getInspireName * @return {String} inspire theme name under which the layer is listed in UI */ getInspireName: function () { return this._inspireName; }, /** * @method setFeatureInfoEnabled * @return {Boolean} featureInfoEnabled true to enable feature info functionality */ setFeatureInfoEnabled: function (featureInfoEnabled) { this._featureInfoEnabled = featureInfoEnabled; }, /** * @method isFeatureInfoEnabled * @return {Boolean} true if feature info functionality should be enabled */ isFeatureInfoEnabled: function () { if (this._featureInfoEnabled === true) { return true; } return false; }, /** * @method setDescription * @param {String} description * map layer description text */ setDescription: function (description) { this._description = description; }, /** * @method getDescription * @return {String} map layer description text */ getDescription: function () { return this._description; }, /** * @method addSubLayer * @param {Oskari.mapframework.domain.WmsLayer} map layer * actual sub map layer that is used for a given scale range (only for * base & group layers) * * If layer has sublayers, it is basically a "metalayer" for maplayer ui * purposes and actual map images to show are done with sublayers */ addSubLayer: function (layer) { this._subLayers.push(layer); }, /** * @method getSubLayers * @return {Oskari.mapframework.domain.WmsLayer[]} array of sub map layers * * If layer has sublayers, it is basically a "metalayer" for maplayer ui * purposes and actual map images to show are done with sublayers */ getSubLayers: function () { return this._subLayers; }, /** * @method setMaxScale * @param {Number} maxScale * largest scale when the layer is shown (otherwise not shown in map and * "greyed out"/disabled in ui) */ setMaxScale: function (maxScale) { this._maxScale = maxScale; }, /** * @method getMaxScale * @return {Number} * largest scale when the layer is shown (otherwise not shown in map and * "greyed out"/disabled in ui) */ getMaxScale: function () { return this._maxScale; }, /** * @method setMinScale * @param {Number} minScale * smallest scale when the layer is shown (otherwise not shown in map and * "greyed out"/disabled in ui) */ setMinScale: function (minScale) { this._minScale = minScale; }, /** * @method getMinScale * @return {Number} * smallest scale when the layer is shown (otherwise not shown in map and * "greyed out"/disabled in ui) */ getMinScale: function () { return this._minScale; }, /** * @method setOrderNumber * @param {Number} orderNumber */ setOrderNumber: function (orderNumber) { this._orderNumber = orderNumber; }, /** * @method getOrderNumber * @return {Number} orderNumber */ getOrderNumber: function () { return this._orderNumber; }, /** * @method isVisible * @return {Boolean} true if this is should be shown */ isVisible: function () { return this._visible === true; }, /** * @method setVisible * @param {Boolean} visible true if this is should be shown */ setVisible: function (visible) { this._visible = visible; }, /** * @method setOpacity * @param {Number} opacity * 0-100 in percents */ setOpacity: function (opacity) { this._opacity = opacity; }, /** * @method getOpacity * @return {Number} opacity * 0-100 in percents */ getOpacity: function () { return this._opacity; }, /** * @method setGeometryWKT * Set geometry as wellknown text * @param {String} value * WKT geometry */ setGeometryWKT: function (value) { this._geometryWKT = value; }, /** * @method getGeometryWKT * Get geometry as wellknown text * @return {String} WKT geometry */ getGeometryWKT: function () { return this._geometryWKT; }, /** * @method setGeometry * @param {OpenLayers.Geometry.Geometry[]} value * array of WKT geometries or actual OpenLayer geometries */ setGeometry: function (value) { this._geometry = value; }, /** * @method getGeometry * @return {OpenLayers.Geometry.Geometry[]} * array of WKT geometries or actual OpenLayer geometries */ getGeometry: function () { return this._geometry; }, /** * @method addPermission * @param {String} action * action key that we want to add permission setting for * @param {String} permission * actual permission setting for action */ addPermission: function (action, permission) { this._permissions[action] = permission; }, /** * @method removePermission * @param {String} action * action key from which permission setting should be removed */ removePermission: function (action) { this._permissions[action] = null; delete this._permissions[action]; }, /** * @method getPermission * @param {String} action * action key for which permission we want * @return {String} permission setting for given action */ getPermission: function (action) { return this._permissions[action]; }, /** * @method getMetadataIdentifier * Gets the identifier (uuid style) for getting layers metadata * @return {String} */ getMetadataIdentifier: function () { return this._metadataIdentifier; }, /** * @method setMetadataIdentifier * Sets the identifier (uuid style) for getting layers metadata * @param {String} metadataid */ setMetadataIdentifier: function (metadataid) { this._metadataIdentifier = metadataid; }, /** * @method getBackendStatus * Status text for layer operatibility (f.ex. 'DOWN') * @return {String} */ getBackendStatus: function () { return this._backendStatus; }, /** * @method setBackendStatus * Status text for layer operatibility (f.ex. 'DOWN') * @param {String} backendStatus */ setBackendStatus: function (backendStatus) { this._backendStatus = backendStatus; }, /** * @method setMetaType * @param {String} type used to group layers by f.ex. functionality. * Layers can be fetched based on metatype f.ex. 'myplaces' */ setMetaType: function (type) { this._metaType = type; }, /** * @method getMetaType * @return {String} type used to group layers by f.ex. functionality. * Layers can be fetched based on metatype f.ex. 'myplaces' */ getMetaType: function () { return this._metaType; }, /** * @method addStyle * @param {Oskari.mapframework.domain.Style} style * adds style to layer */ addStyle: function (style) { this._styles.push(style); }, /** * @method getStyles * @return {Oskari.mapframework.domain.Style[]} * Gets layer styles */ getStyles: function () { return this._styles; }, /** * @method selectStyle * @param {String} styleName * Selects a #Oskari.mapframework.domain.Style with given name as #getCurrentStyle. * If style is not found, assigns an empty #Oskari.mapframework.domain.Style to #getCurrentStyle */ selectStyle: function (styleName) { var style = null, i; // Layer have styles if (this._styles.length > 0) { // There is default style defined if (styleName !== '') { for (i = 0; i < this._styles.length; i += 1) { style = this._styles[i]; if (style.getName() === styleName) { this._currentStyle = style; if (style.getLegend() !== '') { this._legendImage = style.getLegend(); } return; } } } // There is not default style defined else { //var style = // Oskari.clazz.create('Oskari.mapframework.domain.Style'); // Layer have more than one style, set first // founded style to default // Because of layer style error this if clause // must compare at there is more than one style. if (this._styles.length > 1) { this._currentStyle = this._styles[0]; } // Layer have not styles, add empty style to // default else { style = Oskari.clazz.create('Oskari.mapframework.domain.Style'); style.setName(''); style.setTitle(''); style.setLegend(''); this._currentStyle = style; } return; } } // Layer have not styles else { style = Oskari.clazz.create('Oskari.mapframework.domain.Style'); style.setName(''); style.setTitle(''); style.setLegend(''); this._currentStyle = style; return; } }, /** * @method getCurrentStyle * @return {Oskari.mapframework.domain.Style} current style */ getCurrentStyle: function () { return this._currentStyle; }, /** * @method getTools * @return {Oskari.mapframework.domain.Tool[]} * Get layer tools */ getTools: function () { return this._tools; }, /** * @method setTools * @params {Oskari.mapframework.domain.Tool[]} * Set layer tools */ setTools: function (tools) { this._tools = tools; }, /** * @method addTool * @params {Oskari.mapframework.domain.Tool} * adds layer tool to tools */ addTool: function (tool) { this._tools.push(tool); }, /** * @method getTool * @return {Oskari.mapframework.domain.Tool} * adds layer tool to tools */ getTool: function (toolName) { var tool = null, i; // Layer have tools if (this._tools.length > 0 ) { // if (toolName !== '') { for (i = 0; i < this._tools.length; i += 1) { tool = this._tools[i]; if (tool.getName() === toolName) { return tool; } } } } return tool; }, /** * @method setLegendImage * @return {String} legendImage URL to a legend image */ setLegendImage: function (legendImage) { this._legendImage = legendImage; }, /** * @method getLegendImage * @return {String} URL to a legend image */ getLegendImage: function () { return this._legendImage; }, /** * @method getLegendImage * @return {Boolean} true if layer has a legendimage or its styles have legend images */ hasLegendImage: function () { var i; if (this._legendImage) { return true; } else { for (i = 0; i < this._styles.length; i += 1) { if (this._styles[i].getLegend()) { return true; } } } return false; }, /** * @method setSticky * True if layer switch off is disable * @param {Boolean} isSticky */ setSticky: function (isSticky) { this._isSticky = isSticky; }, /** * @method isSticky * True if layer switch off is disable */ isSticky: function () { return this._isSticky; }, /** * @method setQueryable * True if we should call GFI on the layer * @param {Boolean} queryable */ setQueryable: function (queryable) { this._queryable = queryable; }, /** * @method getQueryable * True if we should call GFI on the layer * @param {Boolean} queryable */ getQueryable: function () { return this._queryable; }, /** * @method setAsBaseLayer * sets layer type to BASE_LAYER */ setAsBaseLayer: function () { this._type = 'BASE_LAYER'; }, /** * @method setAsNormalLayer * sets layer type to NORMAL_LAYER */ setAsNormalLayer: function () { this._type = 'NORMAL_LAYER'; }, /** * @method setAsGroupLayer * Sets layer type to GROUP_LAYER */ setAsGroupLayer: function () { this._type = 'GROUP_LAYER'; }, /** * @method isGroupLayer * @return {Boolean} true if this is a group layer (=has sublayers) */ isGroupLayer: function () { return this._type === 'GROUP_LAYER'; }, /** * @method isBaseLayer * @return {Boolean} true if this is a base layer (=has sublayers) */ isBaseLayer: function () { return this._type === 'BASE_LAYER'; }, /** * @method isInScale * @param {Number} scale scale to compare to * @return {Boolean} true if given scale is between this layers min/max scales. Always return true for base-layers. */ isInScale: function (scale) { var _return = this.isBaseLayer(); if (!scale) { var sandbox = Oskari.$().sandbox; scale = sandbox.getMap().getScale(); } // Check layer scales only normal layers if (!this.isBaseLayer()) { if ((scale > this.getMaxScale() || !this.getMaxScale()) && (scale < this.getMinScale()) || !this.getMinScale()) { _return = true; } } return _return; }, /** * @method getLayerType * @return {String} layer type in lower case */ getLayerType: function () { return this._layerType.toLowerCase(); }, /** * @method isLayerOfType * @param {String} flavour layer type to check against. A bit misleading since setType is base/group/normal, this is used to check if the layer is a WMS layer. * @return {Boolean} true if flavour is the specified layer type */ isLayerOfType: function (flavour) { return flavour && flavour.toLowerCase() === this.getLayerType(); }, /** * @method getIconClassname * @return {String} layer icon classname used in the CSS style. */ getIconClassname: function () { if (this.isBaseLayer()) { return 'layer-base'; } else if (this.isGroupLayer()) { return 'layer-group'; } else { return 'layer-' + this.getLayerType(); } }, /** * @method getParams * @return {Object} optional layer parameters for OpenLayers, empty object if no parameters were passed in construction */ getParams: function () { return this._params; }, /** * @method getOptions * @return {Object} optional layer options for OpenLayers, empty object if no options were passed in construction */ getOptions: function () { return this._options; } });
var _ = require('underscore'), check = require('validator').check, sanitize = require('validator').sanitize, later = require('later'), util = require('./util'), condition = require('./condition'); var Rules = { types: [ 'trigger', 'schedule' ], alertTypes: { 'email': { // later }, 'sms': { // later } }, /** * Validates a rule type * * @param string type * * @return boolean */ validateRuleType: function(type) { return typeof type == 'string' && _.contains(Rules.types, type); }, /** * Validates an rule scedule * * @param object schedule * * @return boolean */ validateSchedule: function(schedule) { if (typeof schedule != 'object' || typeof schedule.schedules == 'undefined') { if (_.isEmpty(schedule) || (schedule instanceof Array && schedule.length == 0) || typeof schedule == 'string') return false; schedule = {schedules: schedule}; } // attempt to compile schedule in later.js try { later.schedule(schedule); } catch (e) { return false; } return true; }, /** * Validates an alert * * @param object|Array alert * * @return boolean */ validateAlert: function(alert) { // validate alert type if (typeof alert != 'object') return false; if( alert instanceof Array ) { for (var i in alert) { if (!Rules.validateAlert(alert[i])) return false; } return true; } var alertTemplate = Rules.alertTypes[alert.type]; if (typeof alertTemplate == 'undefined') return false; // validate the endpoint (e-mail address, phone number) if (typeof alert.endpoint == 'undefined') return false; if (alert.type == 'email') { // validate e-mail address try { check(alert.endpoint).isEmail(); } catch (e) { return false; } } else if (alert.type == 'sms') { try { check(sanitize(alert.endpoint).toInt()).len(3); } catch (e) { return false; } } return true; }, /** * Validates a rule * * @param object rule * * @return boolean */ validate: function(rule) { if (typeof rule != 'object') return false; if (!Rules.validateRuleType(rule.type)) return false; if (!condition(rule.condition).isValid()) return false; // validate schedule rules if (rule.type == 'schedule' && !Rules.validateSchedule(rule.schedule)) return false; if (!Rules.validateAlert(rule.alert)) return false; return true; }, }; module.exports = Rules;
var keystone = require('keystone'), async = require('async'); exports = module.exports = function(req, res) { var view = new keystone.View(req, res), locals = res.locals; // Init locals locals.section = 'ideas'; locals.page.title = 'Ideas - Evilcome'; locals.filters = { category: req.params.category }; locals.data = { posts: [], categories: [] }; // Load all categories view.on('init', function(next) { keystone.list('PostCategory').model.find().sort('name').exec(function(err, results) { if (err || !results.length) { return next(err); } locals.data.categories = results; // Load the counts for each category async.each(locals.data.categories, function(category, next) { keystone.list('Post').model.count().where('category').in([category.id]).exec(function(err, count) { category.postCount = count; next(err); }); }, function(err) { next(err); }); }); }); // Load the current category filter view.on('init', function(next) { if (req.params.category) { keystone.list('PostCategory').model.findOne({ key: locals.filters.category }).exec(function(err, result) { locals.data.category = result; next(err); }); } else { next(); } }); // Load the posts view.on('init', function(next) { var q = keystone.list('Post').model.find().where('state', 'published').sort('-publishedDate').populate('author categories'); if (locals.data.category) { q.where('categories').in([locals.data.category]); } q.exec(function(err, results) { locals.data.posts = results; next(err); }); }); // Render the view view.render('site/idea'); }
var should = require('should'); var sinon = require('sinon'); var Chintz = require('../lib/main'); var atomName = 'test-atom'; var moleculeName = 'test-molecule'; var invalidName = 'invalid-element-name'; var called; describe('prepare', function() { describe('with no arguments', function() { it('returns itself', function() { var chintz = new Chintz(__dirname + '/chintz'); var result = chintz.prepare(); result.should.eql(chintz); }); }); describe('passed an element name', function() { it('returns itself', function() { var chintz = new Chintz(__dirname + '/chintz'); var result = chintz.prepare(atomName); result.should.eql(chintz); }); }); }); describe('render', function() { var chintz; var result; describe('unprepared element', function() { var expected = ""; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(invalidName) .render(invalidName, null, callback); }); it('calls back with an empty string', function() { called.should.be.true; }); }); describe('prepared element', function() { describe('with no data', function() { var expected = "Test atom template \n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(atomName) .render(atomName, null, callback); }); it('calls back with the template', function() { called.should.be.true; }); }); describe('with bad data', function() { var expected = "Test atom template \n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(atomName) .render(atomName, { non_existent_key: 'blah' }, callback); }); it('calls back with the template', function() { called.should.be.true; }); }); describe('with good data', function() { var string = "-- string value to template in --"; var expected = "Test atom template " + string + "\n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(atomName) .render(atomName, { string: string }, callback); }); it('calls back with the template, expected', function() { called.should.be.true; }); }); }); describe('prepared nested elements', function() { describe('with no data', function() { var expected = "Test molecule template, with nested Test atom template \n\n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(moleculeName) .render(moleculeName, null, callback); }); it('calls back with the template', function() { called.should.be.true; }); }); describe('with bad data', function() { var expected = "Test molecule template, with nested Test atom template \n\n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(moleculeName) .render(moleculeName, { non_existent_key: 'blah' }, callback); }); it('calls back with the template', function() { called.should.be.true; }); }); describe('with good data', function() { var string = "-- atom string --"; var molString = "-- molecule string --"; var expected = "Test molecule template, with nested Test atom template " + string + "\n" + molString + "\n"; beforeEach(function(done) { var callback = function(s) { called = true; s.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(moleculeName) .render(moleculeName, { string: string, molString: molString }, callback); }); it('calls back with the template, expected', function() { called.should.be.true; }); }); }); }); describe('getDependencies', function() { describe('get non existent deps', function() { beforeEach(function(done) { var expected = []; var callback = function(d) { called = true; d.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(atomName) .getDependencies('nonexistent', callback); }); it('calls back with an empty array', function() { called.should.be.true; }); }); describe('get existing dependencies', function() { beforeEach(function(done) { var expected = [ "test dependency" ]; var callback = function(d) { called = true; d.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .prepare(atomName) .getDependencies('test_deps', callback); }); it('calls back with the expected dependencies', function() { called.should.be.true; }); }); describe('get handled dependencies', function() { beforeEach(function(done) { var expected = [ "a handled dependency" ]; var callback = function(d) { called = true; d.should.eql(expected); done(); }; called = false; new Chintz(__dirname + '/chintz') .registerHandlers( { 'handled_test_deps': { format: function(deps) { return expected } } } ) .prepare(atomName) .getDependencies('handled_test_deps', callback); }); it('calls back with the expected dependencies', function() { called.should.be.true; }); }); });
const createSortDownIcon = (button) => { button.firstChild.remove(); const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('height', '12'); svg.setAttribute('viewBox', '0 0 503 700'); const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', `M43.302,409.357h418.36c37.617,0,56.426,45.527,29.883,72.07l-209.18,209.18c-16.523,16.523-43.243,16.523-59.59,0 L13.419,481.428C-13.124,454.885,5.685,409.357,43.302,409.357z`); svg.appendChild(path); button.appendChild(svg); }; export default createSortDownIcon;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $(function () { $('[data-toggle="popover"]').popover(); $('.main-hide-div').hide(); $('#UserTab a').click(function (e) { e.preventDefault(); $(this).tab('show'); }); $(document).on('click','[class*="main-JS-delete"]', function(){ if(!confirm('Etes-vous sûr de vouloir supprimer cet élément ?')) return false; }); });
module.exports = (api) => { api.cache(true); return { presets: [ [ "@babel/preset-env", { useBuiltIns: "usage", corejs: 3, }, ], ], }; };
import * as React from "react"; import Slide from "../../components/slide"; const bgImage = require("../../images/hulk-feriggno-bixby.jpg"); class ImageSlide extends React.Component { render() { return ( <span/> ); } } export default ( <Slide key="intro-cli-productivity-illustration" bgImage={bgImage}> <ImageSlide/> </Slide> );
const fetch = require("isomorphic-fetch"); function getUrl(query, variables) { const urlRoot = `http://localhost:3000/graphql?query=${query}`; if (variables == null) { return urlRoot; } else { return urlRoot + `&variables=${JSON.stringify(variables)}`; } } function run(query, variables) { const url = getUrl(query, variables) return fetch(encodeURI(url)) .then(response => response.json()) .then(json => (console.log(JSON.stringify(json, null, 2)), json)) .catch(e => console.error(e)); } // Single operation query run(`{ hero { name } }`) // Query Operations cna have names, but that's only // required when a query has several operations. // This one has a name, but only one op. // The response looks the same as an un-named operation. run(` query HeroNameQuery { hero { name } }`); // Requests more fields, including some deeply-nested members // of the `friends` property. // The syntax is like a relaxed version of JSON without values run(`{ hero { id name friends { id, name } } }`); // GraphQL is designed for deeply-nested queries, hence "Graph". run(`{ hero { name friends { name appearsIn friends { name } } } }`); // Pass hard-coded parameters... run(`{ human(id: "1000") { name } }`) // ... or typed runtime query parameters. // parameter names start with $ // the sigil isn't included in the passed variable name run(` query HumanById($id: String!) { human(id: $id) { name } }`, { id: "1001" }) // fields can be aliased // The field names in the response will be called `luke` and leia`, not `human`. // Aliases are required to fetch the same field several times - using /// "human" twice is invalid. run(`{ luke: human(id: "1003") { name }, leia: human(id: "1000") { name } }`); // Common parts of queries can be extracted into fragmments // with a syntax like Object rest params run(` fragment HumanFragment on Human { name, homePlanet } { luke: human(id: "1000") { ...HumanFragment }, leia: human(id: "1003") { ...HumanFragment } } `) // The speciala field __typename identifies the result object's type. // This is especially useful for interface fields. run(` fragment HeroFragment on Character { name __typename } { hope: hero(episode: NEWHOPE) { ...HeroFragment }, empire: hero(episode: EMPIRE) { ...HeroFragment }, jedi: hero(episode: JEDI) { ...HeroFragment }, hero { ...HeroFragment } } `)
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosAnalytics extends React.Component { render() { if(this.props.bare) { return <g> <path d="M256,32C141.174,32,46.544,118.404,33.54,229.739C32.534,238.354,32,247.114,32,256c0,1.783,0.026,3.561,0.067,5.333 C34.901,382.581,134.071,480,256,480c105.255,0,193.537-72.602,217.542-170.454c1.337-5.451,2.474-10.979,3.404-16.579 C478.943,280.939,480,268.594,480,256C480,132.288,379.712,32,256,32z M462.585,280.352c-7.265-7.807-13.064-16.09-15.702-20.429 c-0.871-1.47-21.682-35.994-52.828-35.994c-27.937,0-42.269,26.269-51.751,43.65c-1.415,2.593-2.75,5.041-3.978,7.118 c-11.566,19.587-27.693,30.608-43.105,29.541c-13.586-0.959-25.174-11.403-32.628-29.41c-9.331-22.54-29.551-46.812-53.689-50.229 c-11.428-1.619-28.553,0.866-45.325,21.876c-3.293,4.124-6.964,9.612-11.215,15.967c-10.572,15.804-26.549,39.686-38.653,41.663 c-21.02,3.438-35.021-12.596-35.583-13.249l-0.487-0.58l-0.587-0.479c-0.208-0.17-15.041-12.417-29.047-33.334 c0-0.155-0.006-0.31-0.006-0.464c0-28.087,5.497-55.325,16.339-80.958c10.476-24.767,25.476-47.013,44.583-66.12 s41.354-34.107,66.12-44.583C200.675,53.497,227.913,48,256,48s55.325,5.497,80.958,16.339 c24.767,10.476,47.013,25.476,66.12,44.583s34.107,41.354,44.583,66.12C458.503,200.675,464,227.913,464,256 C464,264.197,463.518,272.318,462.585,280.352z"></path> </g>; } return <IconBase> <path d="M256,32C141.174,32,46.544,118.404,33.54,229.739C32.534,238.354,32,247.114,32,256c0,1.783,0.026,3.561,0.067,5.333 C34.901,382.581,134.071,480,256,480c105.255,0,193.537-72.602,217.542-170.454c1.337-5.451,2.474-10.979,3.404-16.579 C478.943,280.939,480,268.594,480,256C480,132.288,379.712,32,256,32z M462.585,280.352c-7.265-7.807-13.064-16.09-15.702-20.429 c-0.871-1.47-21.682-35.994-52.828-35.994c-27.937,0-42.269,26.269-51.751,43.65c-1.415,2.593-2.75,5.041-3.978,7.118 c-11.566,19.587-27.693,30.608-43.105,29.541c-13.586-0.959-25.174-11.403-32.628-29.41c-9.331-22.54-29.551-46.812-53.689-50.229 c-11.428-1.619-28.553,0.866-45.325,21.876c-3.293,4.124-6.964,9.612-11.215,15.967c-10.572,15.804-26.549,39.686-38.653,41.663 c-21.02,3.438-35.021-12.596-35.583-13.249l-0.487-0.58l-0.587-0.479c-0.208-0.17-15.041-12.417-29.047-33.334 c0-0.155-0.006-0.31-0.006-0.464c0-28.087,5.497-55.325,16.339-80.958c10.476-24.767,25.476-47.013,44.583-66.12 s41.354-34.107,66.12-44.583C200.675,53.497,227.913,48,256,48s55.325,5.497,80.958,16.339 c24.767,10.476,47.013,25.476,66.12,44.583s34.107,41.354,44.583,66.12C458.503,200.675,464,227.913,464,256 C464,264.197,463.518,272.318,462.585,280.352z"></path> </IconBase>; } };IosAnalytics.defaultProps = {bare: false}
self.postMessage(0); self.addEventListener('message', function (msg) { if (msg.data === 'Hello') { self.postMessage(1); } else if (msg.data instanceof self.ArrayBuffer) { var view = new Int32Array(msg.data); if (view[0] === 2) { self.postMessage(3); } } });
YUI.add('yui2-button', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.8.2r1 */ /** * @module button * @description <p>The Button Control enables the creation of rich, graphical * buttons that function like traditional HTML form buttons. <em>Unlike</em> * traditional HTML form buttons, buttons created with the Button Control can have * a label that is different from its value. With the inclusion of the optional * <a href="module_menu.html">Menu Control</a>, the Button Control can also be * used to create menu buttons and split buttons, controls that are not * available natively in HTML. The Button Control can also be thought of as a * way to create more visually engaging implementations of the browser's * default radio-button and check-box controls.</p> * <p>The Button Control supports the following types:</p> * <dl> * <dt>push</dt> * <dd>Basic push button that can execute a user-specified command when * pressed.</dd> * <dt>link</dt> * <dd>Navigates to a specified url when pressed.</dd> * <dt>submit</dt> * <dd>Submits the parent form when pressed.</dd> * <dt>reset</dt> * <dd>Resets the parent form when pressed.</dd> * <dt>checkbox</dt> * <dd>Maintains a "checked" state that can be toggled on and off.</dd> * <dt>radio</dt> * <dd>Maintains a "checked" state that can be toggled on and off. Use with * the ButtonGroup class to create a set of controls that are mutually * exclusive; checking one button in the set will uncheck all others in * the group.</dd> * <dt>menu</dt> * <dd>When pressed will show/hide a menu.</dd> * <dt>split</dt> * <dd>Can execute a user-specified command or display a menu when pressed.</dd> * </dl> * @title Button * @namespace YAHOO.widget * @requires yahoo, dom, element, event * @optional container, menu */ (function () { /** * The Button class creates a rich, graphical button. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;input&#62;</code>, <code>&#60;button&#62;</code>, * <code>&#60;a&#62;</code>, or <code>&#60;span&#62;</code> element to * be used to create the button. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-6043025">HTMLInputElement</a>|<a href="http://www.w3.org * /TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-34812697"> * HTMLButtonElement</a>|<a href=" * http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html# * ID-33759296">HTMLElement</a>} p_oElement Object reference for the * <code>&#60;input&#62;</code>, <code>&#60;button&#62;</code>, * <code>&#60;a&#62;</code>, or <code>&#60;span&#62;</code> element to be * used to create the button. * @param {Object} p_oElement Object literal specifying a set of * configuration attributes used to create the button. * @param {Object} p_oAttributes Optional. Object literal specifying a set * of configuration attributes used to create the button. * @namespace YAHOO.widget * @class Button * @constructor * @extends YAHOO.util.Element */ // Shorthard for utilities var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, UA = YAHOO.env.ua, Overlay = YAHOO.widget.Overlay, Menu = YAHOO.widget.Menu, // Private member variables m_oButtons = {}, // Collection of all Button instances m_oOverlayManager = null, // YAHOO.widget.OverlayManager instance m_oSubmitTrigger = null, // The button that submitted the form m_oFocusedButton = null; // The button that has focus // Private methods /** * @method createInputElement * @description Creates an <code>&#60;input&#62;</code> element of the * specified type. * @private * @param {String} p_sType String specifying the type of * <code>&#60;input&#62;</code> element to create. * @param {String} p_sName String specifying the name of * <code>&#60;input&#62;</code> element to create. * @param {String} p_sValue String specifying the value of * <code>&#60;input&#62;</code> element to create. * @param {String} p_bChecked Boolean specifying if the * <code>&#60;input&#62;</code> element is to be checked. * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-6043025">HTMLInputElement</a>} */ function createInputElement(p_sType, p_sName, p_sValue, p_bChecked) { var oInput, sInput; if (Lang.isString(p_sType) && Lang.isString(p_sName)) { if (UA.ie) { /* For IE it is necessary to create the element with the "type," "name," "value," and "checked" properties set all at once. */ sInput = "<input type=\"" + p_sType + "\" name=\"" + p_sName + "\""; if (p_bChecked) { sInput += " checked"; } sInput += ">"; oInput = document.createElement(sInput); } else { oInput = document.createElement("input"); oInput.name = p_sName; oInput.type = p_sType; if (p_bChecked) { oInput.checked = true; } } oInput.value = p_sValue; } return oInput; } /** * @method setAttributesFromSrcElement * @description Gets the values for all the attributes of the source element * (either <code>&#60;input&#62;</code> or <code>&#60;a&#62;</code>) that * map to Button configuration attributes and sets them into a collection * that is passed to the Button constructor. * @private * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-6043025">HTMLInputElement</a>|<a href="http://www.w3.org/ * TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID- * 48250443">HTMLAnchorElement</a>} p_oElement Object reference to the HTML * element (either <code>&#60;input&#62;</code> or <code>&#60;span&#62; * </code>) used to create the button. * @param {Object} p_oAttributes Object reference for the collection of * configuration attributes used to create the button. */ function setAttributesFromSrcElement(p_oElement, p_oAttributes) { var sSrcElementNodeName = p_oElement.nodeName.toUpperCase(), sClass = (this.CLASS_NAME_PREFIX + this.CSS_CLASS_NAME), me = this, oAttribute, oRootNode, sText; /** * @method setAttributeFromDOMAttribute * @description Gets the value of the specified DOM attribute and sets it * into the collection of configuration attributes used to configure * the button. * @private * @param {String} p_sAttribute String representing the name of the * attribute to retrieve from the DOM element. */ function setAttributeFromDOMAttribute(p_sAttribute) { if (!(p_sAttribute in p_oAttributes)) { /* Need to use "getAttributeNode" instead of "getAttribute" because using "getAttribute," IE will return the innerText of a <code>&#60;button&#62;</code> for the value attribute rather than the value of the "value" attribute. */ oAttribute = p_oElement.getAttributeNode(p_sAttribute); if (oAttribute && ("value" in oAttribute)) { YAHOO.log("Setting attribute \"" + p_sAttribute + "\" using source element's attribute value of \"" + oAttribute.value + "\"", "info", me.toString()); p_oAttributes[p_sAttribute] = oAttribute.value; } } } /** * @method setFormElementProperties * @description Gets the value of the attributes from the form element * and sets them into the collection of configuration attributes used to * configure the button. * @private */ function setFormElementProperties() { setAttributeFromDOMAttribute("type"); if (p_oAttributes.type == "button") { p_oAttributes.type = "push"; } if (!("disabled" in p_oAttributes)) { p_oAttributes.disabled = p_oElement.disabled; } setAttributeFromDOMAttribute("name"); setAttributeFromDOMAttribute("value"); setAttributeFromDOMAttribute("title"); } switch (sSrcElementNodeName) { case "A": p_oAttributes.type = "link"; setAttributeFromDOMAttribute("href"); setAttributeFromDOMAttribute("target"); break; case "INPUT": setFormElementProperties(); if (!("checked" in p_oAttributes)) { p_oAttributes.checked = p_oElement.checked; } break; case "BUTTON": setFormElementProperties(); oRootNode = p_oElement.parentNode.parentNode; if (Dom.hasClass(oRootNode, sClass + "-checked")) { p_oAttributes.checked = true; } if (Dom.hasClass(oRootNode, sClass + "-disabled")) { p_oAttributes.disabled = true; } p_oElement.removeAttribute("value"); p_oElement.setAttribute("type", "button"); break; } p_oElement.removeAttribute("id"); p_oElement.removeAttribute("name"); if (!("tabindex" in p_oAttributes)) { p_oAttributes.tabindex = p_oElement.tabIndex; } if (!("label" in p_oAttributes)) { // Set the "label" property sText = sSrcElementNodeName == "INPUT" ? p_oElement.value : p_oElement.innerHTML; if (sText && sText.length > 0) { p_oAttributes.label = sText; } } } /** * @method initConfig * @description Initializes the set of configuration attributes that are * used to instantiate the button. * @private * @param {Object} Object representing the button's set of * configuration attributes. */ function initConfig(p_oConfig) { var oAttributes = p_oConfig.attributes, oSrcElement = oAttributes.srcelement, sSrcElementNodeName = oSrcElement.nodeName.toUpperCase(), me = this; if (sSrcElementNodeName == this.NODE_NAME) { p_oConfig.element = oSrcElement; p_oConfig.id = oSrcElement.id; Dom.getElementsBy(function (p_oElement) { switch (p_oElement.nodeName.toUpperCase()) { case "BUTTON": case "A": case "INPUT": setAttributesFromSrcElement.call(me, p_oElement, oAttributes); break; } }, "*", oSrcElement); } else { switch (sSrcElementNodeName) { case "BUTTON": case "A": case "INPUT": setAttributesFromSrcElement.call(this, oSrcElement, oAttributes); break; } } } // Constructor YAHOO.widget.Button = function (p_oElement, p_oAttributes) { if (!Overlay && YAHOO.widget.Overlay) { Overlay = YAHOO.widget.Overlay; } if (!Menu && YAHOO.widget.Menu) { Menu = YAHOO.widget.Menu; } var fnSuperClass = YAHOO.widget.Button.superclass.constructor, oConfig, oElement; if (arguments.length == 1 && !Lang.isString(p_oElement) && !p_oElement.nodeName) { if (!p_oElement.id) { p_oElement.id = Dom.generateId(); YAHOO.log("No value specified for the button's \"id\" " + "attribute. Setting button id to \"" + p_oElement.id + "\".", "info", this.toString()); } YAHOO.log("No source HTML element. Building the button " + "using the set of configuration attributes.", "info", this.toString()); fnSuperClass.call(this, (this.createButtonElement(p_oElement.type)), p_oElement); } else { oConfig = { element: null, attributes: (p_oAttributes || {}) }; if (Lang.isString(p_oElement)) { oElement = Dom.get(p_oElement); if (oElement) { if (!oConfig.attributes.id) { oConfig.attributes.id = p_oElement; } YAHOO.log("Building the button using an existing " + "HTML element as a source element.", "info", this.toString()); oConfig.attributes.srcelement = oElement; initConfig.call(this, oConfig); if (!oConfig.element) { YAHOO.log("Source element could not be used " + "as is. Creating a new HTML element for " + "the button.", "info", this.toString()); oConfig.element = this.createButtonElement(oConfig.attributes.type); } fnSuperClass.call(this, oConfig.element, oConfig.attributes); } } else if (p_oElement.nodeName) { if (!oConfig.attributes.id) { if (p_oElement.id) { oConfig.attributes.id = p_oElement.id; } else { oConfig.attributes.id = Dom.generateId(); YAHOO.log("No value specified for the button's " + "\"id\" attribute. Setting button id to \"" + oConfig.attributes.id + "\".", "info", this.toString()); } } YAHOO.log("Building the button using an existing HTML " + "element as a source element.", "info", this.toString()); oConfig.attributes.srcelement = p_oElement; initConfig.call(this, oConfig); if (!oConfig.element) { YAHOO.log("Source element could not be used as is." + " Creating a new HTML element for the button.", "info", this.toString()); oConfig.element = this.createButtonElement(oConfig.attributes.type); } fnSuperClass.call(this, oConfig.element, oConfig.attributes); } } }; YAHOO.extend(YAHOO.widget.Button, YAHOO.util.Element, { // Protected properties /** * @property _button * @description Object reference to the button's internal * <code>&#60;a&#62;</code> or <code>&#60;button&#62;</code> element. * @default null * @protected * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-48250443">HTMLAnchorElement</a>|<a href=" * http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html * #ID-34812697">HTMLButtonElement</a> */ _button: null, /** * @property _menu * @description Object reference to the button's menu. * @default null * @protected * @type {<a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a>| * <a href="YAHOO.widget.Menu.html">YAHOO.widget.Menu</a>} */ _menu: null, /** * @property _hiddenFields * @description Object reference to the <code>&#60;input&#62;</code> * element, or array of HTML form elements used to represent the button * when its parent form is submitted. * @default null * @protected * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-6043025">HTMLInputElement</a>|Array */ _hiddenFields: null, /** * @property _onclickAttributeValue * @description Object reference to the button's current value for the * "onclick" configuration attribute. * @default null * @protected * @type Object */ _onclickAttributeValue: null, /** * @property _activationKeyPressed * @description Boolean indicating if the key(s) that toggle the button's * "active" state have been pressed. * @default false * @protected * @type Boolean */ _activationKeyPressed: false, /** * @property _activationButtonPressed * @description Boolean indicating if the mouse button that toggles * the button's "active" state has been pressed. * @default false * @protected * @type Boolean */ _activationButtonPressed: false, /** * @property _hasKeyEventHandlers * @description Boolean indicating if the button's "blur", "keydown" and * "keyup" event handlers are assigned * @default false * @protected * @type Boolean */ _hasKeyEventHandlers: false, /** * @property _hasMouseEventHandlers * @description Boolean indicating if the button's "mouseout," * "mousedown," and "mouseup" event handlers are assigned * @default false * @protected * @type Boolean */ _hasMouseEventHandlers: false, /** * @property _nOptionRegionX * @description Number representing the X coordinate of the leftmost edge of the Button's * option region. Applies only to Buttons of type "split". * @default 0 * @protected * @type Number */ _nOptionRegionX: 0, // Constants /** * @property CLASS_NAME_PREFIX * @description Prefix used for all class names applied to a Button. * @default "yui-" * @final * @type String */ CLASS_NAME_PREFIX: "yui-", /** * @property NODE_NAME * @description The name of the node to be used for the button's * root element. * @default "SPAN" * @final * @type String */ NODE_NAME: "SPAN", /** * @property CHECK_ACTIVATION_KEYS * @description Array of numbers representing keys that (when pressed) * toggle the button's "checked" attribute. * @default [32] * @final * @type Array */ CHECK_ACTIVATION_KEYS: [32], /** * @property ACTIVATION_KEYS * @description Array of numbers representing keys that (when presed) * toggle the button's "active" state. * @default [13, 32] * @final * @type Array */ ACTIVATION_KEYS: [13, 32], /** * @property OPTION_AREA_WIDTH * @description Width (in pixels) of the area of a split button that * when pressed will display a menu. * @default 20 * @final * @type Number */ OPTION_AREA_WIDTH: 20, /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied to * the button's root element. * @default "button" * @final * @type String */ CSS_CLASS_NAME: "button", // Protected attribute setter methods /** * @method _setType * @description Sets the value of the button's "type" attribute. * @protected * @param {String} p_sType String indicating the value for the button's * "type" attribute. */ _setType: function (p_sType) { if (p_sType == "split") { this.on("option", this._onOption); } }, /** * @method _setLabel * @description Sets the value of the button's "label" attribute. * @protected * @param {String} p_sLabel String indicating the value for the button's * "label" attribute. */ _setLabel: function (p_sLabel) { this._button.innerHTML = p_sLabel; /* Remove and add the default class name from the root element for Gecko to ensure that the button shrinkwraps to the label. Without this the button will not be rendered at the correct width when the label changes. The most likely cause for this bug is button's use of the Gecko-specific CSS display type of "-moz-inline-box" to simulate "inline-block" supported by IE, Safari and Opera. */ var sClass, nGeckoVersion = UA.gecko; if (nGeckoVersion && nGeckoVersion < 1.9 && Dom.inDocument(this.get("element"))) { sClass = (this.CLASS_NAME_PREFIX + this.CSS_CLASS_NAME); this.removeClass(sClass); Lang.later(0, this, this.addClass, sClass); } }, /** * @method _setTabIndex * @description Sets the value of the button's "tabindex" attribute. * @protected * @param {Number} p_nTabIndex Number indicating the value for the * button's "tabindex" attribute. */ _setTabIndex: function (p_nTabIndex) { this._button.tabIndex = p_nTabIndex; }, /** * @method _setTitle * @description Sets the value of the button's "title" attribute. * @protected * @param {String} p_nTabIndex Number indicating the value for * the button's "title" attribute. */ _setTitle: function (p_sTitle) { if (this.get("type") != "link") { this._button.title = p_sTitle; } }, /** * @method _setDisabled * @description Sets the value of the button's "disabled" attribute. * @protected * @param {Boolean} p_bDisabled Boolean indicating the value for * the button's "disabled" attribute. */ _setDisabled: function (p_bDisabled) { if (this.get("type") != "link") { if (p_bDisabled) { if (this._menu) { this._menu.hide(); } if (this.hasFocus()) { this.blur(); } this._button.setAttribute("disabled", "disabled"); this.addStateCSSClasses("disabled"); this.removeStateCSSClasses("hover"); this.removeStateCSSClasses("active"); this.removeStateCSSClasses("focus"); } else { this._button.removeAttribute("disabled"); this.removeStateCSSClasses("disabled"); } } }, /** * @method _setHref * @description Sets the value of the button's "href" attribute. * @protected * @param {String} p_sHref String indicating the value for the button's * "href" attribute. */ _setHref: function (p_sHref) { if (this.get("type") == "link") { this._button.href = p_sHref; } }, /** * @method _setTarget * @description Sets the value of the button's "target" attribute. * @protected * @param {String} p_sTarget String indicating the value for the button's * "target" attribute. */ _setTarget: function (p_sTarget) { if (this.get("type") == "link") { this._button.setAttribute("target", p_sTarget); } }, /** * @method _setChecked * @description Sets the value of the button's "target" attribute. * @protected * @param {Boolean} p_bChecked Boolean indicating the value for * the button's "checked" attribute. */ _setChecked: function (p_bChecked) { var sType = this.get("type"); if (sType == "checkbox" || sType == "radio") { if (p_bChecked) { this.addStateCSSClasses("checked"); } else { this.removeStateCSSClasses("checked"); } } }, /** * @method _setMenu * @description Sets the value of the button's "menu" attribute. * @protected * @param {Object} p_oMenu Object indicating the value for the button's * "menu" attribute. */ _setMenu: function (p_oMenu) { var bLazyLoad = this.get("lazyloadmenu"), oButtonElement = this.get("element"), sMenuCSSClassName, /* Boolean indicating if the value of p_oMenu is an instance of YAHOO.widget.Menu or YAHOO.widget.Overlay. */ bInstance = false, oMenu, oMenuElement, oSrcElement; function onAppendTo() { oMenu.render(oButtonElement.parentNode); this.removeListener("appendTo", onAppendTo); } function setMenuContainer() { oMenu.cfg.queueProperty("container", oButtonElement.parentNode); this.removeListener("appendTo", setMenuContainer); } function initMenu() { var oContainer; if (oMenu) { Dom.addClass(oMenu.element, this.get("menuclassname")); Dom.addClass(oMenu.element, this.CLASS_NAME_PREFIX + this.get("type") + "-button-menu"); oMenu.showEvent.subscribe(this._onMenuShow, null, this); oMenu.hideEvent.subscribe(this._onMenuHide, null, this); oMenu.renderEvent.subscribe(this._onMenuRender, null, this); if (Menu && oMenu instanceof Menu) { if (bLazyLoad) { oContainer = this.get("container"); if (oContainer) { oMenu.cfg.queueProperty("container", oContainer); } else { this.on("appendTo", setMenuContainer); } } oMenu.cfg.queueProperty("clicktohide", false); oMenu.keyDownEvent.subscribe(this._onMenuKeyDown, this, true); oMenu.subscribe("click", this._onMenuClick, this, true); this.on("selectedMenuItemChange", this._onSelectedMenuItemChange); oSrcElement = oMenu.srcElement; if (oSrcElement && oSrcElement.nodeName.toUpperCase() == "SELECT") { oSrcElement.style.display = "none"; oSrcElement.parentNode.removeChild(oSrcElement); } } else if (Overlay && oMenu instanceof Overlay) { if (!m_oOverlayManager) { m_oOverlayManager = new YAHOO.widget.OverlayManager(); } m_oOverlayManager.register(oMenu); } this._menu = oMenu; if (!bInstance && !bLazyLoad) { if (Dom.inDocument(oButtonElement)) { oMenu.render(oButtonElement.parentNode); } else { this.on("appendTo", onAppendTo); } } } } if (Overlay) { if (Menu) { sMenuCSSClassName = Menu.prototype.CSS_CLASS_NAME; } if (p_oMenu && Menu && (p_oMenu instanceof Menu)) { oMenu = p_oMenu; bInstance = true; initMenu.call(this); } else if (Overlay && p_oMenu && (p_oMenu instanceof Overlay)) { oMenu = p_oMenu; bInstance = true; oMenu.cfg.queueProperty("visible", false); initMenu.call(this); } else if (Menu && Lang.isArray(p_oMenu)) { oMenu = new Menu(Dom.generateId(), { lazyload: bLazyLoad, itemdata: p_oMenu }); this._menu = oMenu; this.on("appendTo", initMenu); } else if (Lang.isString(p_oMenu)) { oMenuElement = Dom.get(p_oMenu); if (oMenuElement) { if (Menu && Dom.hasClass(oMenuElement, sMenuCSSClassName) || oMenuElement.nodeName.toUpperCase() == "SELECT") { oMenu = new Menu(p_oMenu, { lazyload: bLazyLoad }); initMenu.call(this); } else if (Overlay) { oMenu = new Overlay(p_oMenu, { visible: false }); initMenu.call(this); } } } else if (p_oMenu && p_oMenu.nodeName) { if (Menu && Dom.hasClass(p_oMenu, sMenuCSSClassName) || p_oMenu.nodeName.toUpperCase() == "SELECT") { oMenu = new Menu(p_oMenu, { lazyload: bLazyLoad }); initMenu.call(this); } else if (Overlay) { if (!p_oMenu.id) { Dom.generateId(p_oMenu); } oMenu = new Overlay(p_oMenu, { visible: false }); initMenu.call(this); } } } }, /** * @method _setOnClick * @description Sets the value of the button's "onclick" attribute. * @protected * @param {Object} p_oObject Object indicating the value for the button's * "onclick" attribute. */ _setOnClick: function (p_oObject) { /* Remove any existing listeners if a "click" event handler has already been specified. */ if (this._onclickAttributeValue && (this._onclickAttributeValue != p_oObject)) { this.removeListener("click", this._onclickAttributeValue.fn); this._onclickAttributeValue = null; } if (!this._onclickAttributeValue && Lang.isObject(p_oObject) && Lang.isFunction(p_oObject.fn)) { this.on("click", p_oObject.fn, p_oObject.obj, p_oObject.scope); this._onclickAttributeValue = p_oObject; } }, // Protected methods /** * @method _isActivationKey * @description Determines if the specified keycode is one that toggles * the button's "active" state. * @protected * @param {Number} p_nKeyCode Number representing the keycode to * be evaluated. * @return {Boolean} */ _isActivationKey: function (p_nKeyCode) { var sType = this.get("type"), aKeyCodes = (sType == "checkbox" || sType == "radio") ? this.CHECK_ACTIVATION_KEYS : this.ACTIVATION_KEYS, nKeyCodes = aKeyCodes.length, bReturnVal = false, i; if (nKeyCodes > 0) { i = nKeyCodes - 1; do { if (p_nKeyCode == aKeyCodes[i]) { bReturnVal = true; break; } } while (i--); } return bReturnVal; }, /** * @method _isSplitButtonOptionKey * @description Determines if the specified keycode is one that toggles * the display of the split button's menu. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). * @return {Boolean} */ _isSplitButtonOptionKey: function (p_oEvent) { var bShowMenu = (Event.getCharCode(p_oEvent) == 40); var onKeyPress = function (p_oEvent) { Event.preventDefault(p_oEvent); this.removeListener("keypress", onKeyPress); }; // Prevent the browser from scrolling the window if (bShowMenu) { if (UA.opera) { this.on("keypress", onKeyPress); } Event.preventDefault(p_oEvent); } return bShowMenu; }, /** * @method _addListenersToForm * @description Adds event handlers to the button's form. * @protected */ _addListenersToForm: function () { var oForm = this.getForm(), onFormKeyPress = YAHOO.widget.Button.onFormKeyPress, bHasKeyPressListener, oSrcElement, aListeners, nListeners, i; if (oForm) { Event.on(oForm, "reset", this._onFormReset, null, this); Event.on(oForm, "submit", this._onFormSubmit, null, this); oSrcElement = this.get("srcelement"); if (this.get("type") == "submit" || (oSrcElement && oSrcElement.type == "submit")) { aListeners = Event.getListeners(oForm, "keypress"); bHasKeyPressListener = false; if (aListeners) { nListeners = aListeners.length; if (nListeners > 0) { i = nListeners - 1; do { if (aListeners[i].fn == onFormKeyPress) { bHasKeyPressListener = true; break; } } while (i--); } } if (!bHasKeyPressListener) { Event.on(oForm, "keypress", onFormKeyPress); } } } }, /** * @method _showMenu * @description Shows the button's menu. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event) that triggered * the display of the menu. */ _showMenu: function (p_oEvent) { if (YAHOO.widget.MenuManager) { YAHOO.widget.MenuManager.hideVisible(); } if (m_oOverlayManager) { m_oOverlayManager.hideAll(); } var oMenu = this._menu, aMenuAlignment = this.get("menualignment"), bFocusMenu = this.get("focusmenu"), fnFocusMethod; if (this._renderedMenu) { oMenu.cfg.setProperty("context", [this.get("element"), aMenuAlignment[0], aMenuAlignment[1]]); oMenu.cfg.setProperty("preventcontextoverlap", true); oMenu.cfg.setProperty("constraintoviewport", true); } else { oMenu.cfg.queueProperty("context", [this.get("element"), aMenuAlignment[0], aMenuAlignment[1]]); oMenu.cfg.queueProperty("preventcontextoverlap", true); oMenu.cfg.queueProperty("constraintoviewport", true); } /* Refocus the Button before showing its Menu in case the call to YAHOO.widget.MenuManager.hideVisible() resulted in another element in the DOM being focused after another Menu was hidden. */ this.focus(); if (Menu && oMenu && (oMenu instanceof Menu)) { // Since Menus automatically focus themselves when made visible, temporarily // replace the Menu focus method so that the value of the Button's "focusmenu" // attribute determines if the Menu should be focus when made visible. fnFocusMethod = oMenu.focus; oMenu.focus = function () {}; if (this._renderedMenu) { oMenu.cfg.setProperty("minscrollheight", this.get("menuminscrollheight")); oMenu.cfg.setProperty("maxheight", this.get("menumaxheight")); } else { oMenu.cfg.queueProperty("minscrollheight", this.get("menuminscrollheight")); oMenu.cfg.queueProperty("maxheight", this.get("menumaxheight")); } oMenu.show(); oMenu.focus = fnFocusMethod; oMenu.align(); /* Stop the propagation of the event so that the MenuManager doesn't blur the menu after it gets focus. */ if (p_oEvent.type == "mousedown") { Event.stopPropagation(p_oEvent); } if (bFocusMenu) { oMenu.focus(); } } else if (Overlay && oMenu && (oMenu instanceof Overlay)) { if (!this._renderedMenu) { oMenu.render(this.get("element").parentNode); } oMenu.show(); oMenu.align(); } }, /** * @method _hideMenu * @description Hides the button's menu. * @protected */ _hideMenu: function () { var oMenu = this._menu; if (oMenu) { oMenu.hide(); } }, // Protected event handlers /** * @method _onMouseOver * @description "mouseover" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onMouseOver: function (p_oEvent) { var sType = this.get("type"), oElement, nOptionRegionX; if (sType === "split") { oElement = this.get("element"); nOptionRegionX = (Dom.getX(oElement) + (oElement.offsetWidth - this.OPTION_AREA_WIDTH)); this._nOptionRegionX = nOptionRegionX; } if (!this._hasMouseEventHandlers) { if (sType === "split") { this.on("mousemove", this._onMouseMove); } this.on("mouseout", this._onMouseOut); this._hasMouseEventHandlers = true; } this.addStateCSSClasses("hover"); if (sType === "split" && (Event.getPageX(p_oEvent) > nOptionRegionX)) { this.addStateCSSClasses("hoveroption"); } if (this._activationButtonPressed) { this.addStateCSSClasses("active"); } if (this._bOptionPressed) { this.addStateCSSClasses("activeoption"); } if (this._activationButtonPressed || this._bOptionPressed) { Event.removeListener(document, "mouseup", this._onDocumentMouseUp); } }, /** * @method _onMouseMove * @description "mousemove" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onMouseMove: function (p_oEvent) { var nOptionRegionX = this._nOptionRegionX; if (nOptionRegionX) { if (Event.getPageX(p_oEvent) > nOptionRegionX) { this.addStateCSSClasses("hoveroption"); } else { this.removeStateCSSClasses("hoveroption"); } } }, /** * @method _onMouseOut * @description "mouseout" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onMouseOut: function (p_oEvent) { var sType = this.get("type"); this.removeStateCSSClasses("hover"); if (sType != "menu") { this.removeStateCSSClasses("active"); } if (this._activationButtonPressed || this._bOptionPressed) { Event.on(document, "mouseup", this._onDocumentMouseUp, null, this); } if (sType === "split" && (Event.getPageX(p_oEvent) > this._nOptionRegionX)) { this.removeStateCSSClasses("hoveroption"); } }, /** * @method _onDocumentMouseUp * @description "mouseup" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onDocumentMouseUp: function (p_oEvent) { this._activationButtonPressed = false; this._bOptionPressed = false; var sType = this.get("type"), oTarget, oMenuElement; if (sType == "menu" || sType == "split") { oTarget = Event.getTarget(p_oEvent); oMenuElement = this._menu.element; if (oTarget != oMenuElement && !Dom.isAncestor(oMenuElement, oTarget)) { this.removeStateCSSClasses((sType == "menu" ? "active" : "activeoption")); this._hideMenu(); } } Event.removeListener(document, "mouseup", this._onDocumentMouseUp); }, /** * @method _onMouseDown * @description "mousedown" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onMouseDown: function (p_oEvent) { var sType, bReturnVal = true; function onMouseUp() { this._hideMenu(); this.removeListener("mouseup", onMouseUp); } if ((p_oEvent.which || p_oEvent.button) == 1) { if (!this.hasFocus()) { this.focus(); } sType = this.get("type"); if (sType == "split") { if (Event.getPageX(p_oEvent) > this._nOptionRegionX) { this.fireEvent("option", p_oEvent); bReturnVal = false; } else { this.addStateCSSClasses("active"); this._activationButtonPressed = true; } } else if (sType == "menu") { if (this.isActive()) { this._hideMenu(); this._activationButtonPressed = false; } else { this._showMenu(p_oEvent); this._activationButtonPressed = true; } } else { this.addStateCSSClasses("active"); this._activationButtonPressed = true; } if (sType == "split" || sType == "menu") { this._hideMenuTimer = Lang.later(250, this, this.on, ["mouseup", onMouseUp]); } } return bReturnVal; }, /** * @method _onMouseUp * @description "mouseup" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onMouseUp: function (p_oEvent) { var sType = this.get("type"), oHideMenuTimer = this._hideMenuTimer, bReturnVal = true; if (oHideMenuTimer) { oHideMenuTimer.cancel(); } if (sType == "checkbox" || sType == "radio") { this.set("checked", !(this.get("checked"))); } this._activationButtonPressed = false; if (sType != "menu") { this.removeStateCSSClasses("active"); } if (sType == "split" && Event.getPageX(p_oEvent) > this._nOptionRegionX) { bReturnVal = false; } return bReturnVal; }, /** * @method _onFocus * @description "focus" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onFocus: function (p_oEvent) { var oElement; this.addStateCSSClasses("focus"); if (this._activationKeyPressed) { this.addStateCSSClasses("active"); } m_oFocusedButton = this; if (!this._hasKeyEventHandlers) { oElement = this._button; Event.on(oElement, "blur", this._onBlur, null, this); Event.on(oElement, "keydown", this._onKeyDown, null, this); Event.on(oElement, "keyup", this._onKeyUp, null, this); this._hasKeyEventHandlers = true; } this.fireEvent("focus", p_oEvent); }, /** * @method _onBlur * @description "blur" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onBlur: function (p_oEvent) { this.removeStateCSSClasses("focus"); if (this.get("type") != "menu") { this.removeStateCSSClasses("active"); } if (this._activationKeyPressed) { Event.on(document, "keyup", this._onDocumentKeyUp, null, this); } m_oFocusedButton = null; this.fireEvent("blur", p_oEvent); }, /** * @method _onDocumentKeyUp * @description "keyup" event handler for the document. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onDocumentKeyUp: function (p_oEvent) { if (this._isActivationKey(Event.getCharCode(p_oEvent))) { this._activationKeyPressed = false; Event.removeListener(document, "keyup", this._onDocumentKeyUp); } }, /** * @method _onKeyDown * @description "keydown" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onKeyDown: function (p_oEvent) { var oMenu = this._menu; if (this.get("type") == "split" && this._isSplitButtonOptionKey(p_oEvent)) { this.fireEvent("option", p_oEvent); } else if (this._isActivationKey(Event.getCharCode(p_oEvent))) { if (this.get("type") == "menu") { this._showMenu(p_oEvent); } else { this._activationKeyPressed = true; this.addStateCSSClasses("active"); } } if (oMenu && oMenu.cfg.getProperty("visible") && Event.getCharCode(p_oEvent) == 27) { oMenu.hide(); this.focus(); } }, /** * @method _onKeyUp * @description "keyup" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onKeyUp: function (p_oEvent) { var sType; if (this._isActivationKey(Event.getCharCode(p_oEvent))) { sType = this.get("type"); if (sType == "checkbox" || sType == "radio") { this.set("checked", !(this.get("checked"))); } this._activationKeyPressed = false; if (this.get("type") != "menu") { this.removeStateCSSClasses("active"); } } }, /** * @method _onClick * @description "click" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onClick: function (p_oEvent) { var sType = this.get("type"), oForm, oSrcElement, bReturnVal; switch (sType) { case "submit": if (p_oEvent.returnValue !== false) { this.submitForm(); } break; case "reset": oForm = this.getForm(); if (oForm) { oForm.reset(); } break; case "split": if (this._nOptionRegionX > 0 && (Event.getPageX(p_oEvent) > this._nOptionRegionX)) { bReturnVal = false; } else { this._hideMenu(); oSrcElement = this.get("srcelement"); if (oSrcElement && oSrcElement.type == "submit" && p_oEvent.returnValue !== false) { this.submitForm(); } } break; } return bReturnVal; }, /** * @method _onDblClick * @description "dblclick" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onDblClick: function (p_oEvent) { var bReturnVal = true; if (this.get("type") == "split" && Event.getPageX(p_oEvent) > this._nOptionRegionX) { bReturnVal = false; } return bReturnVal; }, /** * @method _onAppendTo * @description "appendTo" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onAppendTo: function (p_oEvent) { /* It is necessary to call "_addListenersToForm" using "setTimeout" to make sure that the button's "form" property returns a node reference. Sometimes, if you try to get the reference immediately after appending the field, it is null. */ Lang.later(0, this, this._addListenersToForm); }, /** * @method _onFormReset * @description "reset" event handler for the button's form. * @protected * @param {Event} p_oEvent Object representing the DOM event * object passed back by the event utility (YAHOO.util.Event). */ _onFormReset: function (p_oEvent) { var sType = this.get("type"), oMenu = this._menu; if (sType == "checkbox" || sType == "radio") { this.resetValue("checked"); } if (Menu && oMenu && (oMenu instanceof Menu)) { this.resetValue("selectedMenuItem"); } }, /** * @method _onFormSubmit * @description "submit" event handler for the button's form. * @protected * @param {Event} p_oEvent Object representing the DOM event * object passed back by the event utility (YAHOO.util.Event). */ _onFormSubmit: function (p_oEvent) { this.createHiddenFields(); }, /** * @method _onDocumentMouseDown * @description "mousedown" event handler for the document. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onDocumentMouseDown: function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), oButtonElement = this.get("element"), oMenuElement = this._menu.element; if (oTarget != oButtonElement && !Dom.isAncestor(oButtonElement, oTarget) && oTarget != oMenuElement && !Dom.isAncestor(oMenuElement, oTarget)) { this._hideMenu(); // In IE when the user mouses down on a focusable element // that element will be focused and become the "activeElement". // (http://msdn.microsoft.com/en-us/library/ms533065(VS.85).aspx) // However, there is a bug in IE where if there is a // positioned element with a focused descendant that is // hidden in response to the mousedown event, the target of // the mousedown event will appear to have focus, but will // not be set as the activeElement. This will result // in the element not firing key events, even though it // appears to have focus. The following call to "setActive" // fixes this bug. if (UA.ie && oTarget.focus) { oTarget.setActive(); } Event.removeListener(document, "mousedown", this._onDocumentMouseDown); } }, /** * @method _onOption * @description "option" event handler for the button. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onOption: function (p_oEvent) { if (this.hasClass(this.CLASS_NAME_PREFIX + "split-button-activeoption")) { this._hideMenu(); this._bOptionPressed = false; } else { this._showMenu(p_oEvent); this._bOptionPressed = true; } }, /** * @method _onMenuShow * @description "show" event handler for the button's menu. * @private * @param {String} p_sType String representing the name of the event * that was fired. */ _onMenuShow: function (p_sType) { Event.on(document, "mousedown", this._onDocumentMouseDown, null, this); var sState = (this.get("type") == "split") ? "activeoption" : "active"; this.addStateCSSClasses(sState); }, /** * @method _onMenuHide * @description "hide" event handler for the button's menu. * @private * @param {String} p_sType String representing the name of the event * that was fired. */ _onMenuHide: function (p_sType) { var sState = (this.get("type") == "split") ? "activeoption" : "active"; this.removeStateCSSClasses(sState); if (this.get("type") == "split") { this._bOptionPressed = false; } }, /** * @method _onMenuKeyDown * @description "keydown" event handler for the button's menu. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ _onMenuKeyDown: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0]; if (Event.getCharCode(oEvent) == 27) { this.focus(); if (this.get("type") == "split") { this._bOptionPressed = false; } } }, /** * @method _onMenuRender * @description "render" event handler for the button's menu. * @private * @param {String} p_sType String representing the name of the * event thatwas fired. */ _onMenuRender: function (p_sType) { var oButtonElement = this.get("element"), oButtonParent = oButtonElement.parentNode, oMenu = this._menu, oMenuElement = oMenu.element, oSrcElement = oMenu.srcElement, oItem; if (oButtonParent != oMenuElement.parentNode) { oButtonParent.appendChild(oMenuElement); } this._renderedMenu = true; // If the user has designated an <option> of the Menu's source // <select> element to be selected, sync the selectedIndex with // the "selectedMenuItem" Attribute. if (oSrcElement && oSrcElement.nodeName.toLowerCase() === "select" && oSrcElement.value) { oItem = oMenu.getItem(oSrcElement.selectedIndex); // Set the value of the "selectedMenuItem" attribute // silently since this is the initial set--synchronizing // the value of the source <SELECT> element in the DOM with // its corresponding Menu instance. this.set("selectedMenuItem", oItem, true); // Call the "_onSelectedMenuItemChange" method since the // attribute was set silently. this._onSelectedMenuItemChange({ newValue: oItem }); } }, /** * @method _onMenuClick * @description "click" event handler for the button's menu. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ _onMenuClick: function (p_sType, p_aArgs) { var oItem = p_aArgs[1], oSrcElement; if (oItem) { this.set("selectedMenuItem", oItem); oSrcElement = this.get("srcelement"); if (oSrcElement && oSrcElement.type == "submit") { this.submitForm(); } this._hideMenu(); } }, /** * @method _onSelectedMenuItemChange * @description "selectedMenuItemChange" event handler for the Button's * "selectedMenuItem" attribute. * @param {Event} event Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onSelectedMenuItemChange: function (event) { var oSelected = event.prevValue, oItem = event.newValue, sPrefix = this.CLASS_NAME_PREFIX; if (oSelected) { Dom.removeClass(oSelected.element, (sPrefix + "button-selectedmenuitem")); } if (oItem) { Dom.addClass(oItem.element, (sPrefix + "button-selectedmenuitem")); } }, /** * @method _onLabelClick * @description "click" event handler for the Button's * <code>&#60;label&#62;</code> element. * @param {Event} event Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onLabelClick: function (event) { this.focus(); var sType = this.get("type"); if (sType == "radio" || sType == "checkbox") { this.set("checked", (!this.get("checked"))); } }, // Public methods /** * @method createButtonElement * @description Creates the button's HTML elements. * @param {String} p_sType String indicating the type of element * to create. * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>} */ createButtonElement: function (p_sType) { var sNodeName = this.NODE_NAME, oElement = document.createElement(sNodeName); oElement.innerHTML = "<" + sNodeName + " class=\"first-child\">" + (p_sType == "link" ? "<a></a>" : "<button type=\"button\"></button>") + "</" + sNodeName + ">"; return oElement; }, /** * @method addStateCSSClasses * @description Appends state-specific CSS classes to the button's root * DOM element. */ addStateCSSClasses: function (p_sState) { var sType = this.get("type"), sPrefix = this.CLASS_NAME_PREFIX; if (Lang.isString(p_sState)) { if (p_sState != "activeoption" && p_sState != "hoveroption") { this.addClass(sPrefix + this.CSS_CLASS_NAME + ("-" + p_sState)); } this.addClass(sPrefix + sType + ("-button-" + p_sState)); } }, /** * @method removeStateCSSClasses * @description Removes state-specific CSS classes to the button's root * DOM element. */ removeStateCSSClasses: function (p_sState) { var sType = this.get("type"), sPrefix = this.CLASS_NAME_PREFIX; if (Lang.isString(p_sState)) { this.removeClass(sPrefix + this.CSS_CLASS_NAME + ("-" + p_sState)); this.removeClass(sPrefix + sType + ("-button-" + p_sState)); } }, /** * @method createHiddenFields * @description Creates the button's hidden form field and appends it * to its parent form. * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-6043025">HTMLInputElement</a>|Array} */ createHiddenFields: function () { this.removeHiddenFields(); var oForm = this.getForm(), oButtonField, sType, bCheckable, oMenu, oMenuItem, sButtonName, oValue, oMenuField, oReturnVal, sMenuFieldName, oMenuSrcElement, bMenuSrcElementIsSelect = false; if (oForm && !this.get("disabled")) { sType = this.get("type"); bCheckable = (sType == "checkbox" || sType == "radio"); if ((bCheckable && this.get("checked")) || (m_oSubmitTrigger == this)) { YAHOO.log("Creating hidden field.", "info", this.toString()); oButtonField = createInputElement((bCheckable ? sType : "hidden"), this.get("name"), this.get("value"), this.get("checked")); if (oButtonField) { if (bCheckable) { oButtonField.style.display = "none"; } oForm.appendChild(oButtonField); } } oMenu = this._menu; if (Menu && oMenu && (oMenu instanceof Menu)) { YAHOO.log("Creating hidden field for menu.", "info", this.toString()); oMenuItem = this.get("selectedMenuItem"); oMenuSrcElement = oMenu.srcElement; bMenuSrcElementIsSelect = (oMenuSrcElement && oMenuSrcElement.nodeName.toUpperCase() == "SELECT"); if (oMenuItem) { oValue = (oMenuItem.value === null || oMenuItem.value === "") ? oMenuItem.cfg.getProperty("text") : oMenuItem.value; sButtonName = this.get("name"); if (bMenuSrcElementIsSelect) { sMenuFieldName = oMenuSrcElement.name; } else if (sButtonName) { sMenuFieldName = (sButtonName + "_options"); } if (oValue && sMenuFieldName) { oMenuField = createInputElement("hidden", sMenuFieldName, oValue); oForm.appendChild(oMenuField); } } else if (bMenuSrcElementIsSelect) { oMenuField = oForm.appendChild(oMenuSrcElement); } } if (oButtonField && oMenuField) { this._hiddenFields = [oButtonField, oMenuField]; } else if (!oButtonField && oMenuField) { this._hiddenFields = oMenuField; } else if (oButtonField && !oMenuField) { this._hiddenFields = oButtonField; } oReturnVal = this._hiddenFields; } return oReturnVal; }, /** * @method removeHiddenFields * @description Removes the button's hidden form field(s) from its * parent form. */ removeHiddenFields: function () { var oField = this._hiddenFields, nFields, i; function removeChild(p_oElement) { if (Dom.inDocument(p_oElement)) { p_oElement.parentNode.removeChild(p_oElement); } } if (oField) { if (Lang.isArray(oField)) { nFields = oField.length; if (nFields > 0) { i = nFields - 1; do { removeChild(oField[i]); } while (i--); } } else { removeChild(oField); } this._hiddenFields = null; } }, /** * @method submitForm * @description Submits the form to which the button belongs. Returns * true if the form was submitted successfully, false if the submission * was cancelled. * @protected * @return {Boolean} */ submitForm: function () { var oForm = this.getForm(), oSrcElement = this.get("srcelement"), /* Boolean indicating if the event fired successfully (was not cancelled by any handlers) */ bSubmitForm = false, oEvent; if (oForm) { if (this.get("type") == "submit" || (oSrcElement && oSrcElement.type == "submit")) { m_oSubmitTrigger = this; } if (UA.ie) { bSubmitForm = oForm.fireEvent("onsubmit"); } else { // Gecko, Opera, and Safari oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("submit", true, true); bSubmitForm = oForm.dispatchEvent(oEvent); } /* In IE and Safari, dispatching a "submit" event to a form WILL cause the form's "submit" event to fire, but WILL NOT submit the form. Therefore, we need to call the "submit" method as well. */ if ((UA.ie || UA.webkit) && bSubmitForm) { oForm.submit(); } } return bSubmitForm; }, /** * @method init * @description The Button class's initialization method. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;input&#62;</code>, <code>&#60;button&#62;</code>, * <code>&#60;a&#62;</code>, or <code>&#60;span&#62;</code> element to * be used to create the button. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-6043025">HTMLInputElement</a>|<a href="http:// * www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html * #ID-34812697">HTMLButtonElement</a>|<a href="http://www.w3.org/TR * /2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-33759296"> * HTMLElement</a>} p_oElement Object reference for the * <code>&#60;input&#62;</code>, <code>&#60;button&#62;</code>, * <code>&#60;a&#62;</code>, or <code>&#60;span&#62;</code> element to be * used to create the button. * @param {Object} p_oElement Object literal specifying a set of * configuration attributes used to create the button. * @param {Object} p_oAttributes Optional. Object literal specifying a * set of configuration attributes used to create the button. */ init: function (p_oElement, p_oAttributes) { var sNodeName = p_oAttributes.type == "link" ? "a" : "button", oSrcElement = p_oAttributes.srcelement, oButton = p_oElement.getElementsByTagName(sNodeName)[0], oInput; if (!oButton) { oInput = p_oElement.getElementsByTagName("input")[0]; if (oInput) { oButton = document.createElement("button"); oButton.setAttribute("type", "button"); oInput.parentNode.replaceChild(oButton, oInput); } } this._button = oButton; YAHOO.widget.Button.superclass.init.call(this, p_oElement, p_oAttributes); var sId = this.get("id"), sButtonId = sId + "-button"; oButton.id = sButtonId; var aLabels, oLabel; var hasLabel = function (element) { return (element.htmlFor === sId); }; var setLabel = function () { oLabel.setAttribute((UA.ie ? "htmlFor" : "for"), sButtonId); }; if (oSrcElement && this.get("type") != "link") { aLabels = Dom.getElementsBy(hasLabel, "label"); if (Lang.isArray(aLabels) && aLabels.length > 0) { oLabel = aLabels[0]; } } m_oButtons[sId] = this; var sPrefix = this.CLASS_NAME_PREFIX; this.addClass(sPrefix + this.CSS_CLASS_NAME); this.addClass(sPrefix + this.get("type") + "-button"); Event.on(this._button, "focus", this._onFocus, null, this); this.on("mouseover", this._onMouseOver); this.on("mousedown", this._onMouseDown); this.on("mouseup", this._onMouseUp); this.on("click", this._onClick); // Need to reset the value of the "onclick" Attribute so that any // handlers registered via the "onclick" Attribute are fired after // Button's default "_onClick" listener. var fnOnClick = this.get("onclick"); this.set("onclick", null); this.set("onclick", fnOnClick); this.on("dblclick", this._onDblClick); var oParentNode; if (oLabel) { if (this.get("replaceLabel")) { this.set("label", oLabel.innerHTML); oParentNode = oLabel.parentNode; oParentNode.removeChild(oLabel); } else { this.on("appendTo", setLabel); Event.on(oLabel, "click", this._onLabelClick, null, this); this._label = oLabel; } } this.on("appendTo", this._onAppendTo); var oContainer = this.get("container"), oElement = this.get("element"), bElInDoc = Dom.inDocument(oElement); if (oContainer) { if (oSrcElement && oSrcElement != oElement) { oParentNode = oSrcElement.parentNode; if (oParentNode) { oParentNode.removeChild(oSrcElement); } } if (Lang.isString(oContainer)) { Event.onContentReady(oContainer, this.appendTo, oContainer, this); } else { this.on("init", function () { Lang.later(0, this, this.appendTo, oContainer); }); } } else if (!bElInDoc && oSrcElement && oSrcElement != oElement) { oParentNode = oSrcElement.parentNode; if (oParentNode) { this.fireEvent("beforeAppendTo", { type: "beforeAppendTo", target: oParentNode }); oParentNode.replaceChild(oElement, oSrcElement); this.fireEvent("appendTo", { type: "appendTo", target: oParentNode }); } } else if (this.get("type") != "link" && bElInDoc && oSrcElement && oSrcElement == oElement) { this._addListenersToForm(); } YAHOO.log("Initialization completed.", "info", this.toString()); this.fireEvent("init", { type: "init", target: this }); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to * create the button. * @param {Object} p_oAttributes Object literal specifying a set of * configuration attributes used to create the button. */ initAttributes: function (p_oAttributes) { var oAttributes = p_oAttributes || {}; YAHOO.widget.Button.superclass.initAttributes.call(this, oAttributes); /** * @attribute type * @description String specifying the button's type. Possible * values are: "push," "link," "submit," "reset," "checkbox," * "radio," "menu," and "split." * @default "push" * @type String * @writeonce */ this.setAttributeConfig("type", { value: (oAttributes.type || "push"), validator: Lang.isString, writeOnce: true, method: this._setType }); /** * @attribute label * @description String specifying the button's text label * or innerHTML. * @default null * @type String */ this.setAttributeConfig("label", { value: oAttributes.label, validator: Lang.isString, method: this._setLabel }); /** * @attribute value * @description Object specifying the value for the button. * @default null * @type Object */ this.setAttributeConfig("value", { value: oAttributes.value }); /** * @attribute name * @description String specifying the name for the button. * @default null * @type String */ this.setAttributeConfig("name", { value: oAttributes.name, validator: Lang.isString }); /** * @attribute tabindex * @description Number specifying the tabindex for the button. * @default null * @type Number */ this.setAttributeConfig("tabindex", { value: oAttributes.tabindex, validator: Lang.isNumber, method: this._setTabIndex }); /** * @attribute title * @description String specifying the title for the button. * @default null * @type String */ this.configureAttribute("title", { value: oAttributes.title, validator: Lang.isString, method: this._setTitle }); /** * @attribute disabled * @description Boolean indicating if the button should be disabled. * (Disabled buttons are dimmed and will not respond to user input * or fire events. Does not apply to button's of type "link.") * @default false * @type Boolean */ this.setAttributeConfig("disabled", { value: (oAttributes.disabled || false), validator: Lang.isBoolean, method: this._setDisabled }); /** * @attribute href * @description String specifying the href for the button. Applies * only to buttons of type "link." * @type String */ this.setAttributeConfig("href", { value: oAttributes.href, validator: Lang.isString, method: this._setHref }); /** * @attribute target * @description String specifying the target for the button. * Applies only to buttons of type "link." * @type String */ this.setAttributeConfig("target", { value: oAttributes.target, validator: Lang.isString, method: this._setTarget }); /** * @attribute checked * @description Boolean indicating if the button is checked. * Applies only to buttons of type "radio" and "checkbox." * @default false * @type Boolean */ this.setAttributeConfig("checked", { value: (oAttributes.checked || false), validator: Lang.isBoolean, method: this._setChecked }); /** * @attribute container * @description HTML element reference or string specifying the id * attribute of the HTML element that the button's markup should be * rendered into. * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>|String * @default null * @writeonce */ this.setAttributeConfig("container", { value: oAttributes.container, writeOnce: true }); /** * @attribute srcelement * @description Object reference to the HTML element (either * <code>&#60;input&#62;</code> or <code>&#60;span&#62;</code>) * used to create the button. * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>|String * @default null * @writeonce */ this.setAttributeConfig("srcelement", { value: oAttributes.srcelement, writeOnce: true }); /** * @attribute menu * @description Object specifying the menu for the button. * The value can be one of the following: * <ul> * <li>Object specifying a rendered <a href="YAHOO.widget.Menu.html"> * YAHOO.widget.Menu</a> instance.</li> * <li>Object specifying a rendered <a href="YAHOO.widget.Overlay.html"> * YAHOO.widget.Overlay</a> instance.</li> * <li>String specifying the id attribute of the <code>&#60;div&#62; * </code> element used to create the menu. By default the menu * will be created as an instance of * <a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a>. * If the <a href="YAHOO.widget.Menu.html#CSS_CLASS_NAME"> * default CSS class name for YAHOO.widget.Menu</a> is applied to * the <code>&#60;div&#62;</code> element, it will be created as an * instance of <a href="YAHOO.widget.Menu.html">YAHOO.widget.Menu * </a>.</li><li>String specifying the id attribute of the * <code>&#60;select&#62;</code> element used to create the menu. * </li><li>Object specifying the <code>&#60;div&#62;</code> element * used to create the menu.</li> * <li>Object specifying the <code>&#60;select&#62;</code> element * used to create the menu.</li> * <li>Array of object literals, each representing a set of * <a href="YAHOO.widget.MenuItem.html">YAHOO.widget.MenuItem</a> * configuration attributes.</li> * <li>Array of strings representing the text labels for each menu * item in the menu.</li> * </ul> * @type <a href="YAHOO.widget.Menu.html">YAHOO.widget.Menu</a>|<a * href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a>|<a * href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-58190037">HTMLElement</a>|String|Array * @default null * @writeonce */ this.setAttributeConfig("menu", { value: null, method: this._setMenu, writeOnce: true }); /** * @attribute lazyloadmenu * @description Boolean indicating the value to set for the * <a href="YAHOO.widget.Menu.html#lazyLoad">"lazyload"</a> * configuration property of the button's menu. Setting * "lazyloadmenu" to <code>true </code> will defer rendering of * the button's menu until the first time it is made visible. * If "lazyloadmenu" is set to <code>false</code>, the button's * menu will be rendered immediately if the button is in the * document, or in response to the button's "appendTo" event if * the button is not yet in the document. In either case, the * menu is rendered into the button's parent HTML element. * <em>This attribute does not apply if a * <a href="YAHOO.widget.Menu.html">YAHOO.widget.Menu</a> or * <a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a> * instance is passed as the value of the button's "menu" * configuration attribute. <a href="YAHOO.widget.Menu.html"> * YAHOO.widget.Menu</a> or <a href="YAHOO.widget.Overlay.html"> * YAHOO.widget.Overlay</a> instances should be rendered before * being set as the value for the "menu" configuration * attribute.</em> * @default true * @type Boolean * @writeonce */ this.setAttributeConfig("lazyloadmenu", { value: (oAttributes.lazyloadmenu === false ? false : true), validator: Lang.isBoolean, writeOnce: true }); /** * @attribute menuclassname * @description String representing the CSS class name to be * applied to the root element of the button's menu. * @type String * @default "yui-button-menu" * @writeonce */ this.setAttributeConfig("menuclassname", { value: (oAttributes.menuclassname || (this.CLASS_NAME_PREFIX + "button-menu")), validator: Lang.isString, method: this._setMenuClassName, writeOnce: true }); /** * @attribute menuminscrollheight * @description Number defining the minimum threshold for the "menumaxheight" * configuration attribute. When set this attribute is automatically applied * to all submenus. * @default 90 * @type Number */ this.setAttributeConfig("menuminscrollheight", { value: (oAttributes.menuminscrollheight || 90), validator: Lang.isNumber }); /** * @attribute menumaxheight * @description Number defining the maximum height (in pixels) for a menu's * body element (<code>&#60;div class="bd"&#60;</code>). Once a menu's body * exceeds this height, the contents of the body are scrolled to maintain * this value. This value cannot be set lower than the value of the * "minscrollheight" configuration property. * @type Number * @default 0 */ this.setAttributeConfig("menumaxheight", { value: (oAttributes.menumaxheight || 0), validator: Lang.isNumber }); /** * @attribute menualignment * @description Array defining how the Button's Menu is aligned to the Button. * The default value of ["tl", "bl"] aligns the Menu's top left corner to the Button's * bottom left corner. * @type Array * @default ["tl", "bl"] */ this.setAttributeConfig("menualignment", { value: (oAttributes.menualignment || ["tl", "bl"]), validator: Lang.isArray }); /** * @attribute selectedMenuItem * @description Object representing the item in the button's menu * that is currently selected. * @type YAHOO.widget.MenuItem * @default null */ this.setAttributeConfig("selectedMenuItem", { value: null }); /** * @attribute onclick * @description Object literal representing the code to be executed * when the button is clicked. Format:<br> <code> {<br> * <strong>fn:</strong> Function, &#47;&#47; The handler to call * when the event fires.<br> <strong>obj:</strong> Object, * &#47;&#47; An object to pass back to the handler.<br> * <strong>scope:</strong> Object &#47;&#47; The object to use * for the scope of the handler.<br> } </code> * @type Object * @default null */ this.setAttributeConfig("onclick", { value: oAttributes.onclick, method: this._setOnClick }); /** * @attribute focusmenu * @description Boolean indicating whether or not the button's menu * should be focused when it is made visible. * @type Boolean * @default true */ this.setAttributeConfig("focusmenu", { value: (oAttributes.focusmenu === false ? false : true), validator: Lang.isBoolean }); /** * @attribute replaceLabel * @description Boolean indicating whether or not the text of the * button's <code>&#60;label&#62;</code> element should be used as * the source for the button's label configuration attribute and * removed from the DOM. * @type Boolean * @default false */ this.setAttributeConfig("replaceLabel", { value: false, validator: Lang.isBoolean, writeOnce: true }); }, /** * @method focus * @description Causes the button to receive the focus and fires the * button's "focus" event. */ focus: function () { if (!this.get("disabled")) { this._button.focus(); } }, /** * @method blur * @description Causes the button to lose focus and fires the button's * "blur" event. */ blur: function () { if (!this.get("disabled")) { this._button.blur(); } }, /** * @method hasFocus * @description Returns a boolean indicating whether or not the button * has focus. * @return {Boolean} */ hasFocus: function () { return (m_oFocusedButton == this); }, /** * @method isActive * @description Returns a boolean indicating whether or not the button * is active. * @return {Boolean} */ isActive: function () { return this.hasClass(this.CLASS_NAME_PREFIX + this.CSS_CLASS_NAME + "-active"); }, /** * @method getMenu * @description Returns a reference to the button's menu. * @return {<a href="YAHOO.widget.Overlay.html"> * YAHOO.widget.Overlay</a>|<a * href="YAHOO.widget.Menu.html">YAHOO.widget.Menu</a>} */ getMenu: function () { return this._menu; }, /** * @method getForm * @description Returns a reference to the button's parent form. * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1- * 20000929/level-one-html.html#ID-40002357">HTMLFormElement</a>} */ getForm: function () { var oButton = this._button, oForm; if (oButton) { oForm = oButton.form; } return oForm; }, /** * @method getHiddenFields * @description Returns an <code>&#60;input&#62;</code> element or * array of form elements used to represent the button when its parent * form is submitted. * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-6043025">HTMLInputElement</a>|Array} */ getHiddenFields: function () { return this._hiddenFields; }, /** * @method destroy * @description Removes the button's element from its parent element and * removes all event handlers. */ destroy: function () { YAHOO.log("Destroying ...", "info", this.toString()); var oElement = this.get("element"), oMenu = this._menu, oLabel = this._label, oParentNode, aButtons; if (oMenu) { YAHOO.log("Destroying menu.", "info", this.toString()); if (m_oOverlayManager && m_oOverlayManager.find(oMenu)) { m_oOverlayManager.remove(oMenu); } oMenu.destroy(); } YAHOO.log("Removing DOM event listeners.", "info", this.toString()); Event.purgeElement(oElement); Event.purgeElement(this._button); Event.removeListener(document, "mouseup", this._onDocumentMouseUp); Event.removeListener(document, "keyup", this._onDocumentKeyUp); Event.removeListener(document, "mousedown", this._onDocumentMouseDown); if (oLabel) { Event.removeListener(oLabel, "click", this._onLabelClick); oParentNode = oLabel.parentNode; oParentNode.removeChild(oLabel); } var oForm = this.getForm(); if (oForm) { Event.removeListener(oForm, "reset", this._onFormReset); Event.removeListener(oForm, "submit", this._onFormSubmit); } YAHOO.log("Removing CustomEvent listeners.", "info", this.toString()); this.unsubscribeAll(); oParentNode = oElement.parentNode; if (oParentNode) { oParentNode.removeChild(oElement); } YAHOO.log("Removing from document.", "info", this.toString()); delete m_oButtons[this.get("id")]; var sClass = (this.CLASS_NAME_PREFIX + this.CSS_CLASS_NAME); aButtons = Dom.getElementsByClassName(sClass, this.NODE_NAME, oForm); if (Lang.isArray(aButtons) && aButtons.length === 0) { Event.removeListener(oForm, "keypress", YAHOO.widget.Button.onFormKeyPress); } YAHOO.log("Destroyed.", "info", this.toString()); }, fireEvent: function (p_sType , p_aArgs) { var sType = arguments[0]; // Disabled buttons should not respond to DOM events if (this.DOM_EVENTS[sType] && this.get("disabled")) { return false; } return YAHOO.widget.Button.superclass.fireEvent.apply(this, arguments); }, /** * @method toString * @description Returns a string representing the button. * @return {String} */ toString: function () { return ("Button " + this.get("id")); } }); /** * @method YAHOO.widget.Button.onFormKeyPress * @description "keypress" event handler for the button's form. * @param {Event} p_oEvent Object representing the DOM event object passed * back by the event utility (YAHOO.util.Event). */ YAHOO.widget.Button.onFormKeyPress = function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), nCharCode = Event.getCharCode(p_oEvent), sNodeName = oTarget.nodeName && oTarget.nodeName.toUpperCase(), sType = oTarget.type, /* Boolean indicating if the form contains any enabled or disabled YUI submit buttons */ bFormContainsYUIButtons = false, oButton, oYUISubmitButton, // The form's first, enabled YUI submit button /* The form's first, enabled HTML submit button that precedes any YUI submit button */ oPrecedingSubmitButton, oEvent; function isSubmitButton(p_oElement) { var sId, oSrcElement; switch (p_oElement.nodeName.toUpperCase()) { case "INPUT": case "BUTTON": if (p_oElement.type == "submit" && !p_oElement.disabled) { if (!bFormContainsYUIButtons && !oPrecedingSubmitButton) { oPrecedingSubmitButton = p_oElement; } } break; default: sId = p_oElement.id; if (sId) { oButton = m_oButtons[sId]; if (oButton) { bFormContainsYUIButtons = true; if (!oButton.get("disabled")) { oSrcElement = oButton.get("srcelement"); if (!oYUISubmitButton && (oButton.get("type") == "submit" || (oSrcElement && oSrcElement.type == "submit"))) { oYUISubmitButton = oButton; } } } } break; } } if (nCharCode == 13 && ((sNodeName == "INPUT" && (sType == "text" || sType == "password" || sType == "checkbox" || sType == "radio" || sType == "file")) || sNodeName == "SELECT")) { Dom.getElementsBy(isSubmitButton, "*", this); if (oPrecedingSubmitButton) { /* Need to set focus to the first enabled submit button to make sure that IE includes its name and value in the form's data set. */ oPrecedingSubmitButton.focus(); } else if (!oPrecedingSubmitButton && oYUISubmitButton) { /* Need to call "preventDefault" to ensure that the form doesn't end up getting submitted twice. */ Event.preventDefault(p_oEvent); if (UA.ie) { oYUISubmitButton.get("element").fireEvent("onclick"); } else { oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("click", true, true); if (UA.gecko < 1.9) { oYUISubmitButton.fireEvent("click", oEvent); } else { oYUISubmitButton.get("element").dispatchEvent(oEvent); } } } } }; /** * @method YAHOO.widget.Button.addHiddenFieldsToForm * @description Searches the specified form and adds hidden fields for * instances of YAHOO.widget.Button that are of type "radio," "checkbox," * "menu," and "split." * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-40002357">HTMLFormElement</a>} p_oForm Object reference * for the form to search. */ YAHOO.widget.Button.addHiddenFieldsToForm = function (p_oForm) { var proto = YAHOO.widget.Button.prototype, aButtons = Dom.getElementsByClassName( (proto.CLASS_NAME_PREFIX + proto.CSS_CLASS_NAME), "*", p_oForm), nButtons = aButtons.length, oButton, sId, i; if (nButtons > 0) { YAHOO.log("Form contains " + nButtons + " YUI buttons.", "info", this.toString()); for (i = 0; i < nButtons; i++) { sId = aButtons[i].id; if (sId) { oButton = m_oButtons[sId]; if (oButton) { oButton.createHiddenFields(); } } } } }; /** * @method YAHOO.widget.Button.getButton * @description Returns a button with the specified id. * @param {String} p_sId String specifying the id of the root node of the * HTML element representing the button to be retrieved. * @return {YAHOO.widget.Button} */ YAHOO.widget.Button.getButton = function (p_sId) { return m_oButtons[p_sId]; }; // Events /** * @event focus * @description Fires when the menu item receives focus. Passes back a * single object representing the original DOM event object passed back by * the event utility (YAHOO.util.Event) when the event was fired. See * <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> * for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event blur * @description Fires when the menu item loses the input focus. Passes back * a single object representing the original DOM event object passed back by * the event utility (YAHOO.util.Event) when the event was fired. See * <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for * more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event option * @description Fires when the user invokes the button's option. Passes * back a single object representing the original DOM event (either * "mousedown" or "keydown") that caused the "option" event to fire. See * <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> * for more information on listening for this event. * @type YAHOO.util.CustomEvent */ })(); (function () { // Shorthard for utilities var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Button = YAHOO.widget.Button, // Private collection of radio buttons m_oButtons = {}; /** * The ButtonGroup class creates a set of buttons that are mutually * exclusive; checking one button in the set will uncheck all others in the * button group. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the button group. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object * specifying the <code>&#60;div&#62;</code> element of the button group. * @param {Object} p_oElement Object literal specifying a set of * configuration attributes used to create the button group. * @param {Object} p_oAttributes Optional. Object literal specifying a set * of configuration attributes used to create the button group. * @namespace YAHOO.widget * @class ButtonGroup * @constructor * @extends YAHOO.util.Element */ YAHOO.widget.ButtonGroup = function (p_oElement, p_oAttributes) { var fnSuperClass = YAHOO.widget.ButtonGroup.superclass.constructor, sNodeName, oElement, sId; if (arguments.length == 1 && !Lang.isString(p_oElement) && !p_oElement.nodeName) { if (!p_oElement.id) { sId = Dom.generateId(); p_oElement.id = sId; YAHOO.log("No value specified for the button group's \"id\"" + " attribute. Setting button group id to \"" + sId + "\".", "info"); } this.logger = new YAHOO.widget.LogWriter("ButtonGroup " + sId); this.logger.log("No source HTML element. Building the button " + "group using the set of configuration attributes."); fnSuperClass.call(this, (this._createGroupElement()), p_oElement); } else if (Lang.isString(p_oElement)) { oElement = Dom.get(p_oElement); if (oElement) { if (oElement.nodeName.toUpperCase() == this.NODE_NAME) { this.logger = new YAHOO.widget.LogWriter("ButtonGroup " + p_oElement); fnSuperClass.call(this, oElement, p_oAttributes); } } } else { sNodeName = p_oElement.nodeName.toUpperCase(); if (sNodeName && sNodeName == this.NODE_NAME) { if (!p_oElement.id) { p_oElement.id = Dom.generateId(); YAHOO.log("No value specified for the button group's" + " \"id\" attribute. Setting button group id " + "to \"" + p_oElement.id + "\".", "warn"); } this.logger = new YAHOO.widget.LogWriter("ButtonGroup " + p_oElement.id); fnSuperClass.call(this, p_oElement, p_oAttributes); } } }; YAHOO.extend(YAHOO.widget.ButtonGroup, YAHOO.util.Element, { // Protected properties /** * @property _buttons * @description Array of buttons in the button group. * @default null * @protected * @type Array */ _buttons: null, // Constants /** * @property NODE_NAME * @description The name of the tag to be used for the button * group's element. * @default "DIV" * @final * @type String */ NODE_NAME: "DIV", /** * @property CLASS_NAME_PREFIX * @description Prefix used for all class names applied to a ButtonGroup. * @default "yui-" * @final * @type String */ CLASS_NAME_PREFIX: "yui-", /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied * to the button group's element. * @default "buttongroup" * @final * @type String */ CSS_CLASS_NAME: "buttongroup", // Protected methods /** * @method _createGroupElement * @description Creates the button group's element. * @protected * @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-22445964">HTMLDivElement</a>} */ _createGroupElement: function () { var oElement = document.createElement(this.NODE_NAME); return oElement; }, // Protected attribute setter methods /** * @method _setDisabled * @description Sets the value of the button groups's * "disabled" attribute. * @protected * @param {Boolean} p_bDisabled Boolean indicating the value for * the button group's "disabled" attribute. */ _setDisabled: function (p_bDisabled) { var nButtons = this.getCount(), i; if (nButtons > 0) { i = nButtons - 1; do { this._buttons[i].set("disabled", p_bDisabled); } while (i--); } }, // Protected event handlers /** * @method _onKeyDown * @description "keydown" event handler for the button group. * @protected * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ _onKeyDown: function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), nCharCode = Event.getCharCode(p_oEvent), sId = oTarget.parentNode.parentNode.id, oButton = m_oButtons[sId], nIndex = -1; if (nCharCode == 37 || nCharCode == 38) { nIndex = (oButton.index === 0) ? (this._buttons.length - 1) : (oButton.index - 1); } else if (nCharCode == 39 || nCharCode == 40) { nIndex = (oButton.index === (this._buttons.length - 1)) ? 0 : (oButton.index + 1); } if (nIndex > -1) { this.check(nIndex); this.getButton(nIndex).focus(); } }, /** * @method _onAppendTo * @description "appendTo" event handler for the button group. * @protected * @param {Event} p_oEvent Object representing the event that was fired. */ _onAppendTo: function (p_oEvent) { var aButtons = this._buttons, nButtons = aButtons.length, i; for (i = 0; i < nButtons; i++) { aButtons[i].appendTo(this.get("element")); } }, /** * @method _onButtonCheckedChange * @description "checkedChange" event handler for each button in the * button group. * @protected * @param {Event} p_oEvent Object representing the event that was fired. * @param {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>} * p_oButton Object representing the button that fired the event. */ _onButtonCheckedChange: function (p_oEvent, p_oButton) { var bChecked = p_oEvent.newValue, oCheckedButton = this.get("checkedButton"); if (bChecked && oCheckedButton != p_oButton) { if (oCheckedButton) { oCheckedButton.set("checked", false, true); } this.set("checkedButton", p_oButton); this.set("value", p_oButton.get("value")); } else if (oCheckedButton && !oCheckedButton.set("checked")) { oCheckedButton.set("checked", true, true); } }, // Public methods /** * @method init * @description The ButtonGroup class's initialization method. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the button group. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object * specifying the <code>&#60;div&#62;</code> element of the button group. * @param {Object} p_oElement Object literal specifying a set of * configuration attributes used to create the button group. * @param {Object} p_oAttributes Optional. Object literal specifying a * set of configuration attributes used to create the button group. */ init: function (p_oElement, p_oAttributes) { this._buttons = []; YAHOO.widget.ButtonGroup.superclass.init.call(this, p_oElement, p_oAttributes); this.addClass(this.CLASS_NAME_PREFIX + this.CSS_CLASS_NAME); var sClass = (YAHOO.widget.Button.prototype.CLASS_NAME_PREFIX + "radio-button"), aButtons = this.getElementsByClassName(sClass); this.logger.log("Searching for child nodes with the class name " + sClass + " to add to the button group."); if (aButtons.length > 0) { this.logger.log("Found " + aButtons.length + " child nodes with the class name " + sClass + " Attempting to add to button group."); this.addButtons(aButtons); } this.logger.log("Searching for child nodes with the type of " + " \"radio\" to add to the button group."); function isRadioButton(p_oElement) { return (p_oElement.type == "radio"); } aButtons = Dom.getElementsBy(isRadioButton, "input", this.get("element")); if (aButtons.length > 0) { this.logger.log("Found " + aButtons.length + " child nodes" + " with the type of \"radio.\" Attempting to add to" + " button group."); this.addButtons(aButtons); } this.on("keydown", this._onKeyDown); this.on("appendTo", this._onAppendTo); var oContainer = this.get("container"); if (oContainer) { if (Lang.isString(oContainer)) { Event.onContentReady(oContainer, function () { this.appendTo(oContainer); }, null, this); } else { this.appendTo(oContainer); } } this.logger.log("Initialization completed."); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to * create the button group. * @param {Object} p_oAttributes Object literal specifying a set of * configuration attributes used to create the button group. */ initAttributes: function (p_oAttributes) { var oAttributes = p_oAttributes || {}; YAHOO.widget.ButtonGroup.superclass.initAttributes.call( this, oAttributes); /** * @attribute name * @description String specifying the name for the button group. * This name will be applied to each button in the button group. * @default null * @type String */ this.setAttributeConfig("name", { value: oAttributes.name, validator: Lang.isString }); /** * @attribute disabled * @description Boolean indicating if the button group should be * disabled. Disabling the button group will disable each button * in the button group. Disabled buttons are dimmed and will not * respond to user input or fire events. * @default false * @type Boolean */ this.setAttributeConfig("disabled", { value: (oAttributes.disabled || false), validator: Lang.isBoolean, method: this._setDisabled }); /** * @attribute value * @description Object specifying the value for the button group. * @default null * @type Object */ this.setAttributeConfig("value", { value: oAttributes.value }); /** * @attribute container * @description HTML element reference or string specifying the id * attribute of the HTML element that the button group's markup * should be rendered into. * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>|String * @default null * @writeonce */ this.setAttributeConfig("container", { value: oAttributes.container, writeOnce: true }); /** * @attribute checkedButton * @description Reference for the button in the button group that * is checked. * @type {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>} * @default null */ this.setAttributeConfig("checkedButton", { value: null }); }, /** * @method addButton * @description Adds the button to the button group. * @param {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>} * p_oButton Object reference for the <a href="YAHOO.widget.Button.html"> * YAHOO.widget.Button</a> instance to be added to the button group. * @param {String} p_oButton String specifying the id attribute of the * <code>&#60;input&#62;</code> or <code>&#60;span&#62;</code> element * to be used to create the button to be added to the button group. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-6043025">HTMLInputElement</a>|<a href=" * http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html# * ID-33759296">HTMLElement</a>} p_oButton Object reference for the * <code>&#60;input&#62;</code> or <code>&#60;span&#62;</code> element * to be used to create the button to be added to the button group. * @param {Object} p_oButton Object literal specifying a set of * <a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a> * configuration attributes used to configure the button to be added to * the button group. * @return {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>} */ addButton: function (p_oButton) { var oButton, oButtonElement, oGroupElement, nIndex, sButtonName, sGroupName; if (p_oButton instanceof Button && p_oButton.get("type") == "radio") { oButton = p_oButton; } else if (!Lang.isString(p_oButton) && !p_oButton.nodeName) { p_oButton.type = "radio"; oButton = new Button(p_oButton); } else { oButton = new Button(p_oButton, { type: "radio" }); } if (oButton) { nIndex = this._buttons.length; sButtonName = oButton.get("name"); sGroupName = this.get("name"); oButton.index = nIndex; this._buttons[nIndex] = oButton; m_oButtons[oButton.get("id")] = oButton; if (sButtonName != sGroupName) { oButton.set("name", sGroupName); } if (this.get("disabled")) { oButton.set("disabled", true); } if (oButton.get("checked")) { this.set("checkedButton", oButton); } oButtonElement = oButton.get("element"); oGroupElement = this.get("element"); if (oButtonElement.parentNode != oGroupElement) { oGroupElement.appendChild(oButtonElement); } oButton.on("checkedChange", this._onButtonCheckedChange, oButton, this); this.logger.log("Button " + oButton.get("id") + " added."); } return oButton; }, /** * @method addButtons * @description Adds the array of buttons to the button group. * @param {Array} p_aButtons Array of <a href="YAHOO.widget.Button.html"> * YAHOO.widget.Button</a> instances to be added * to the button group. * @param {Array} p_aButtons Array of strings specifying the id * attribute of the <code>&#60;input&#62;</code> or <code>&#60;span&#62; * </code> elements to be used to create the buttons to be added to the * button group. * @param {Array} p_aButtons Array of object references for the * <code>&#60;input&#62;</code> or <code>&#60;span&#62;</code> elements * to be used to create the buttons to be added to the button group. * @param {Array} p_aButtons Array of object literals, each containing * a set of <a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a> * configuration attributes used to configure each button to be added * to the button group. * @return {Array} */ addButtons: function (p_aButtons) { var nButtons, oButton, aButtons, i; if (Lang.isArray(p_aButtons)) { nButtons = p_aButtons.length; aButtons = []; if (nButtons > 0) { for (i = 0; i < nButtons; i++) { oButton = this.addButton(p_aButtons[i]); if (oButton) { aButtons[aButtons.length] = oButton; } } } } return aButtons; }, /** * @method removeButton * @description Removes the button at the specified index from the * button group. * @param {Number} p_nIndex Number specifying the index of the button * to be removed from the button group. */ removeButton: function (p_nIndex) { var oButton = this.getButton(p_nIndex), nButtons, i; if (oButton) { this.logger.log("Removing button " + oButton.get("id") + "."); this._buttons.splice(p_nIndex, 1); delete m_oButtons[oButton.get("id")]; oButton.removeListener("checkedChange", this._onButtonCheckedChange); oButton.destroy(); nButtons = this._buttons.length; if (nButtons > 0) { i = this._buttons.length - 1; do { this._buttons[i].index = i; } while (i--); } this.logger.log("Button " + oButton.get("id") + " removed."); } }, /** * @method getButton * @description Returns the button at the specified index. * @param {Number} p_nIndex The index of the button to retrieve from the * button group. * @return {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>} */ getButton: function (p_nIndex) { return this._buttons[p_nIndex]; }, /** * @method getButtons * @description Returns an array of the buttons in the button group. * @return {Array} */ getButtons: function () { return this._buttons; }, /** * @method getCount * @description Returns the number of buttons in the button group. * @return {Number} */ getCount: function () { return this._buttons.length; }, /** * @method focus * @description Sets focus to the button at the specified index. * @param {Number} p_nIndex Number indicating the index of the button * to focus. */ focus: function (p_nIndex) { var oButton, nButtons, i; if (Lang.isNumber(p_nIndex)) { oButton = this._buttons[p_nIndex]; if (oButton) { oButton.focus(); } } else { nButtons = this.getCount(); for (i = 0; i < nButtons; i++) { oButton = this._buttons[i]; if (!oButton.get("disabled")) { oButton.focus(); break; } } } }, /** * @method check * @description Checks the button at the specified index. * @param {Number} p_nIndex Number indicating the index of the button * to check. */ check: function (p_nIndex) { var oButton = this.getButton(p_nIndex); if (oButton) { oButton.set("checked", true); } }, /** * @method destroy * @description Removes the button group's element from its parent * element and removes all event handlers. */ destroy: function () { this.logger.log("Destroying..."); var nButtons = this._buttons.length, oElement = this.get("element"), oParentNode = oElement.parentNode, i; if (nButtons > 0) { i = this._buttons.length - 1; do { this._buttons[i].destroy(); } while (i--); } this.logger.log("Removing DOM event handlers."); Event.purgeElement(oElement); this.logger.log("Removing from document."); oParentNode.removeChild(oElement); }, /** * @method toString * @description Returns a string representing the button group. * @return {String} */ toString: function () { return ("ButtonGroup " + this.get("id")); } }); })(); YAHOO.register("button", YAHOO.widget.Button, {version: "2.8.2r1", build: "8"}); }, '2.8.2' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event", "yui2-skin-sam-button", "yui2-element"], "optional": ["yui2-containercore", "yui2-skin-sam-menu", "yui2-menu"]});
'use strict'; if (/^((?!chrome).)*safari/i.test(navigator.userAgent)){ alert("We have detected you are using Safari. Please switch to Chrome or Firefox to properly use this app."); } var weekAbbrev = { Mo: "monday", Tu: "tuesday", We: "wednesday", Th: "thursday", Fr: "friday", Sa: "saturday", Su: "sunday" }; var badString = function(str){ return str == null || str.trim().length === 0; } //returns an ics object var parseCourseworkString = function(){ var cs = document.getElementById("classes").value.trim(), quarterLength = document.getElementById("weeks").value.trim(), calObj = ics(), startDate = document.getElementById("startDate").value.trim() + " "; if(badString(cs)){ alert("Please copy paste in the Axess course table"); return; } if(badString(startDate)){ alert("Please input start date in the MM/DD/YYYY format"); return; } if(badString(quarterLength) || !_.isNumber(parseInt(quarterLength)) || parseInt(quarterLength) < 1){ alert("Please insert a valid number of weeks in the quarter."); return; } var counter = 0; //removes descrepancy between Firefox and Chrome copy pasting. var prelimFilter = _.chain(cs.split("\n")).filter(function(row){ return row.trim().length > 0 }).value().join('\n').split('Academic Calendar Deadlines'); _.chain(prelimFilter).map(function(row){ return _.compact(row.split("\n")); }).filter(function(items){ if(items.length != 6 && items.length > 3){ counter ++; } return items.length === 6; }).map(function(items){ var name = items[0], desc = items[1] + " Unit: " + items[2] + " Grading:" + items[3], location = items[5], timeObj = items[4].split(" "), timeStart = new Date(startDate + timeObj[1].substr(0, timeObj[1].length - 2) + " " + timeObj[1].substr(-2)), timeEnd = new Date(startDate + timeObj[3].substr(0, timeObj[3].length - 2) + " " + timeObj[3].substr(-2)); if(timeStart===null || timeEnd === null || timeStart.toString()==="Invalid Date" || timeEnd.toString()==="Invalid Date"){ alert("Please input a correct start date format of MM/DD/YYYY"); throw "Badly formatted Start Date (╯°□°)╯︵ ┻━┻"; } var wkNumber = timeStart.getWeek(), repeat = timeObj[0].match(/.{1,2}/g).join(','), shiftedStart = Date.today().setWeek(wkNumber).sunday().last()[weekAbbrev[repeat.split(',')[0]]]().at(timeObj[1]), //Alterations to the dates because the library acts strangely shiftedEnd = Date.today().setWeek(wkNumber).sunday().last()[weekAbbrev[repeat.split(',')[0]]]().at(timeObj[3]); calObj.addEvent(name, desc, location, shiftedStart, shiftedEnd, repeat, quarterLength * repeat.split(',').length); }); calObj.download("schedule", ".ics"); if(counter > 0){ alert(counter + (counter > 1 ? " classes ": " class ") + "failed to be exported. The formatting was weird.") } }
// autocomplet : this function will be executed every time we change the text function autocomplet() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code0').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id').show(); $('#itemcode_list_id').html(data); } }); } else { $('#itemcode_list_id').hide(); } } //set_item : this function will be executed when we select an item function set_item(item) { // change input value $('#code0').val(item); // hide proposition list $('#itemcode_list_id').hide(); } //=================================================== This is for code1 ============================================ function autocomplet_1() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code1').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code1.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_1').show(); $('#itemcode_list_id_1').html(data); } }); } else { $('#itemcode_list_id_1').hide(); } } // set_item : this function will be executed when we select an item function set_item_1(item) { // change input value $('#code1').val(item); // hide proposition list $('#itemcode_list_id_1').hide(); } //================================================== End of code1 =================================================== //=================================================== This is for code2 ============================================ function autocomplet_2() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code2').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code2.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_2').show(); $('#itemcode_list_id_2').html(data); } }); } else { $('#itemcode_list_id_2').hide(); } } // set_item : this function will be executed when we select an item function set_item_2(item) { // change input value $('#code2').val(item); // hide proposition list $('#itemcode_list_id_2').hide(); } //================================================== End of code2 =================================================== //=================================================== This is for code3 ============================================ function autocomplet_3() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code3').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code3.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_3').show(); $('#itemcode_list_id_3').html(data); } }); } else { $('#itemcode_list_id_3').hide(); } } // set_item : this function will be executed when we select an item function set_item_3(item) { // change input value $('#code3').val(item); // hide proposition list $('#itemcode_list_id_3').hide(); } //================================================== End of code3 =================================================== //=================================================== This is for code4 ============================================ function autocomplet_4() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code4').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code4.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_4').show(); $('#itemcode_list_id_4').html(data); } }); } else { $('#itemcode_list_id_4').hide(); } } // set_item : this function will be executed when we select an item function set_item_4(item) { // change input value $('#code4').val(item); // hide proposition list $('#itemcode_list_id_4').hide(); } //================================================== End of code4 =================================================== //=================================================== This is for code5 ============================================ function autocomplet_5() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code5').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code5.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_5').show(); $('#itemcode_list_id_5').html(data); } }); } else { $('#itemcode_list_id_5').hide(); } } // set_item : this function will be executed when we select an item function set_item_5(item) { // change input value $('#code5').val(item); // hide proposition list $('#itemcode_list_id_5').hide(); } //================================================== End of code5 =================================================== //=================================================== This is for code6 ============================================ function autocomplet_6() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code6').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code6.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_6').show(); $('#itemcode_list_id_6').html(data); } }); } else { $('#itemcode_list_id_6').hide(); } } // set_item : this function will be executed when we select an item function set_item_6(item) { // change input value $('#code6').val(item); // hide proposition list $('#itemcode_list_id_6').hide(); } //================================================== End of code6 =================================================== //=================================================== This is for code7 ============================================ function autocomplet_7() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code7').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code7.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_7').show(); $('#itemcode_list_id_7').html(data); } }); } else { $('#itemcode_list_id_7').hide(); } } // set_item : this function will be executed when we select an item function set_item_7(item) { // change input value $('#code7').val(item); // hide proposition list $('#itemcode_list_id_7').hide(); } //================================================== End of code7 =================================================== //=================================================== This is for code8 ============================================ function autocomplet_8() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code8').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code8.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_8').show(); $('#itemcode_list_id_8').html(data); } }); } else { $('#itemcode_list_id_8').hide(); } } // set_item : this function will be executed when we select an item function set_item_8(item) { // change input value $('#code8').val(item); // hide proposition list $('#itemcode_list_id_8').hide(); } //================================================== End of code8 =================================================== //=================================================== This is for code9 ============================================ function autocomplet_9() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code9').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code9.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_9').show(); $('#itemcode_list_id_9').html(data); } }); } else { $('#itemcode_list_id_9').hide(); } } // set_item : this function will be executed when we select an item function set_item_9(item) { // change input value $('#code9').val(item); // hide proposition list $('#itemcode_list_id_9').hide(); } //================================================== End of code9 =================================================== //=================================================== This is for code10 ============================================ function autocomplet_10() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code10').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code10.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_10').show(); $('#itemcode_list_id_10').html(data); } }); } else { $('#itemcode_list_id_10').hide(); } } // set_item : this function will be executed when we select an item function set_item_10(item) { // change input value $('#code10').val(item); // hide proposition list $('#itemcode_list_id_10').hide(); } //================================================== End of code10 =================================================== //=================================================== This is for code11 ============================================ function autocomplet_11() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code11').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code11.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_11').show(); $('#itemcode_list_id_11').html(data); } }); } else { $('#itemcode_list_id_11').hide(); } } // set_item : this function will be executed when we select an item function set_item_11(item) { // change input value $('#code11').val(item); // hide proposition list $('#itemcode_list_id_11').hide(); } //================================================== End of code11 =================================================== //=================================================== This is for code12 ============================================ function autocomplet_12() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code12').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code12.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_12').show(); $('#itemcode_list_id_12').html(data); } }); } else { $('#itemcode_list_id_12').hide(); } } // set_item : this function will be executed when we select an item function set_item_12(item) { // change input value $('#code12').val(item); // hide proposition list $('#itemcode_list_id_12').hide(); } //================================================== End of code12 =================================================== //=================================================== This is for code13 ============================================ function autocomplet_13() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code13').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code13.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_13').show(); $('#itemcode_list_id_13').html(data); } }); } else { $('#itemcode_list_id_13').hide(); } } // set_item : this function will be executed when we select an item function set_item_13(item) { // change input value $('#code13').val(item); // hide proposition list $('#itemcode_list_id_13').hide(); } //================================================== End of code13 =================================================== //=================================================== This is for code14 ============================================ function autocomplet_14() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code14').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code14.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_14').show(); $('#itemcode_list_id_14').html(data); } }); } else { $('#itemcode_list_id_14').hide(); } } // set_item : this function will be executed when we select an item function set_item_14(item) { // change input value $('#code14').val(item); // hide proposition list $('#itemcode_list_id_14').hide(); } //================================================== End of code14 =================================================== //=================================================== This is for code15 ============================================ function autocomplet_15() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code15').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code15.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_15').show(); $('#itemcode_list_id_15').html(data); } }); } else { $('#itemcode_list_id_15').hide(); } } // set_item : this function will be executed when we select an item function set_item_15(item) { // change input value $('#code15').val(item); // hide proposition list $('#itemcode_list_id_15').hide(); } //================================================== End of code15 =================================================== //=================================================== This is for code16 ============================================ function autocomplet_16() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code16').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code16.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_16').show(); $('#itemcode_list_id_16').html(data); } }); } else { $('#itemcode_list_id_16').hide(); } } // set_item : this function will be executed when we select an item function set_item_16(item) { // change input value $('#code16').val(item); // hide proposition list $('#itemcode_list_id_16').hide(); } //================================================== End of code16 =================================================== //=================================================== This is for code17 ============================================ function autocomplet_17() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code17').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code17.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_17').show(); $('#itemcode_list_id_17').html(data); } }); } else { $('#itemcode_list_id_17').hide(); } } // set_item : this function will be executed when we select an item function set_item_17(item) { // change input value $('#code17').val(item); // hide proposition list $('#itemcode_list_id_17').hide(); } //================================================== End of code17 =================================================== //=================================================== This is for code18 ============================================ function autocomplet_18() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code18').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code18.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_18').show(); $('#itemcode_list_id_18').html(data); } }); } else { $('#itemcode_list_id_18').hide(); } } // set_item : this function will be executed when we select an item function set_item_18(item) { // change input value $('#code18').val(item); // hide proposition list $('#itemcode_list_id_18').hide(); } //================================================== End of code18 =================================================== //=================================================== This is for code19 ============================================ function autocomplet_19() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code19').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code19.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_19').show(); $('#itemcode_list_id_19').html(data); } }); } else { $('#itemcode_list_id_19').hide(); } } // set_item : this function will be executed when we select an item function set_item_19(item) { // change input value $('#code19').val(item); // hide proposition list $('#itemcode_list_id_19').hide(); } //================================================== End of code19 =================================================== //=================================================== This is for code20 ============================================ function autocomplet_20() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#code20').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_code20.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemcode_list_id_20').show(); $('#itemcode_list_id_20').html(data); } }); } else { $('#itemcode_list_id_20').hide(); } } // set_item : this function will be executed when we select an item function set_item_20(item) { // change input value $('#code20').val(item); // hide proposition list $('#itemcode_list_id_20').hide(); } //================================================== End of code20 =================================================== //================================================== Satrt of desc0 ====================================================== function autocomplet2() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc0').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id').show(); $('#itemdesc_list_id').html(data); } }); } else { $('#itemdesc_list_id').hide(); } } function set_item2(item) { // change input value $('#desc0').val(item); // hide proposition list $('#itemdesc_list_id').hide(); } //================================================== End of desc0 ====================================================== //================================================== Satrt of desc1 ====================================================== function autocomplet2_1() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc1').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_1.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_1').show(); $('#itemdesc_list_id_1').html(data); } }); } else { $('#itemdesc_list_id_1').hide(); } } function set_item2_1(item) { // change input value $('#desc1').val(item); // hide proposition list $('#itemdesc_list_id_1').hide(); } //================================================== End of desc1 ====================================================== //================================================== Satrt of desc2 ====================================================== function autocomplet2_2() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc2').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_2.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_2').show(); $('#itemdesc_list_id_2').html(data); } }); } else { $('#itemdesc_list_id_2').hide(); } } function set_item2_2(item) { // change input value $('#desc2').val(item); // hide proposition list $('#itemdesc_list_id_2').hide(); } //================================================== End of desc2 ====================================================== //================================================== Satrt of desc3 ====================================================== function autocomplet2_3() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc3').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_3.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_3').show(); $('#itemdesc_list_id_3').html(data); } }); } else { $('#itemdesc_list_id_3').hide(); } } function set_item2_3(item) { // change input value $('#desc3').val(item); // hide proposition list $('#itemdesc_list_id_3').hide(); } //================================================== End of desc3 ====================================================== //================================================== Satrt of desc4 ====================================================== function autocomplet2_4() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc4').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_4.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_4').show(); $('#itemdesc_list_id_4').html(data); } }); } else { $('#itemdesc_list_id_4').hide(); } } function set_item2_4(item) { // change input value $('#desc4').val(item); // hide proposition list $('#itemdesc_list_id_4').hide(); } //================================================== End of desc4 ====================================================== //================================================== Satrt of desc5 ====================================================== function autocomplet2_5() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc5').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_5.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_5').show(); $('#itemdesc_list_id_5').html(data); } }); } else { $('#itemdesc_list_id_5').hide(); } } function set_item2_5(item) { // change input value $('#desc5').val(item); // hide proposition list $('#itemdesc_list_id_5').hide(); } //================================================== End of desc5 ====================================================== //================================================== Satrt of desc6 ====================================================== function autocomplet2_6() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc6').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_6.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_6').show(); $('#itemdesc_list_id_6').html(data); } }); } else { $('#itemdesc_list_id_6').hide(); } } function set_item2_6(item) { // change input value $('#desc6').val(item); // hide proposition list $('#itemdesc_list_id_6').hide(); } //================================================== End of desc6 ====================================================== //================================================== Satrt of desc7 ====================================================== function autocomplet2_7() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc7').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_7.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_7').show(); $('#itemdesc_list_id_7').html(data); } }); } else { $('#itemdesc_list_id_7').hide(); } } function set_item2_7(item) { // change input value $('#desc7').val(item); // hide proposition list $('#itemdesc_list_id_7').hide(); } //================================================== End of desc7 ====================================================== //================================================== Satrt of desc8 ====================================================== function autocomplet2_8() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc8').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_8.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_8').show(); $('#itemdesc_list_id_8').html(data); } }); } else { $('#itemdesc_list_id_8').hide(); } } function set_item2_8(item) { // change input value $('#desc8').val(item); // hide proposition list $('#itemdesc_list_id_8').hide(); } //================================================== End of desc8 ====================================================== //================================================== Satrt of desc9 ====================================================== function autocomplet2_9() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc9').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_9.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_9').show(); $('#itemdesc_list_id_9').html(data); } }); } else { $('#itemdesc_list_id_9').hide(); } } function set_item2_9(item) { // change input value $('#desc9').val(item); // hide proposition list $('#itemdesc_list_id_9').hide(); } //================================================== End of desc9 ====================================================== //================================================== Satrt of desc10 ====================================================== function autocomplet2_10() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc10').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_10.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_10').show(); $('#itemdesc_list_id_10').html(data); } }); } else { $('#itemdesc_list_id_10').hide(); } } function set_item2_10(item) { // change input value $('#desc10').val(item); // hide proposition list $('#itemdesc_list_id_10').hide(); } //================================================== End of desc10 ====================================================== //================================================== Satrt of desc11 ====================================================== function autocomplet2_11() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc11').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_11.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_11').show(); $('#itemdesc_list_id_11').html(data); } }); } else { $('#itemdesc_list_id_11').hide(); } } function set_item2_11(item) { // change input value $('#desc11').val(item); // hide proposition list $('#itemdesc_list_id_11').hide(); } //================================================== End of desc11 ====================================================== //================================================== Satrt of desc12 ====================================================== function autocomplet2_12() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc12').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_12.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_12').show(); $('#itemdesc_list_id_12').html(data); } }); } else { $('#itemdesc_list_id_12').hide(); } } function set_item2_12(item) { // change input value $('#desc12').val(item); // hide proposition list $('#itemdesc_list_id_12').hide(); } //================================================== End of desc12 ====================================================== //================================================== Satrt of desc13 ====================================================== function autocomplet2_13() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc13').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_13.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_13').show(); $('#itemdesc_list_id_13').html(data); } }); } else { $('#itemdesc_list_id_13').hide(); } } function set_item2_13(item) { // change input value $('#desc13').val(item); // hide proposition list $('#itemdesc_list_id_13').hide(); } //================================================== End of desc13 ====================================================== //================================================== Satrt of desc14 ====================================================== function autocomplet2_14() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc14').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_14.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_14').show(); $('#itemdesc_list_id_14').html(data); } }); } else { $('#itemdesc_list_id_14').hide(); } } function set_item2_14(item) { // change input value $('#desc14').val(item); // hide proposition list $('#itemdesc_list_id_14').hide(); } //================================================== End of desc14 ====================================================== //================================================== Satrt of desc15 ====================================================== function autocomplet2_15() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc15').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_15.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_15').show(); $('#itemdesc_list_id_15').html(data); } }); } else { $('#itemdesc_list_id_15').hide(); } } function set_item2_15(item) { // change input value $('#desc15').val(item); // hide proposition list $('#itemdesc_list_id_15').hide(); } //================================================== End of desc15 ====================================================== //================================================== Satrt of desc16 ====================================================== function autocomplet2_16() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc16').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_16.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_16').show(); $('#itemdesc_list_id_16').html(data); } }); } else { $('#itemdesc_list_id_16').hide(); } } function set_item2_16(item) { // change input value $('#desc16').val(item); // hide proposition list $('#itemdesc_list_id_16').hide(); } //================================================== End of desc16 ====================================================== //================================================== Satrt of desc17 ====================================================== function autocomplet2_17() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc17').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_17.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_17').show(); $('#itemdesc_list_id_17').html(data); } }); } else { $('#itemdesc_list_id_17').hide(); } } function set_item2_17(item) { // change input value $('#desc17').val(item); // hide proposition list $('#itemdesc_list_id_17').hide(); } //================================================== End of desc17 ====================================================== //================================================== Satrt of desc18 ====================================================== function autocomplet2_18() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc18').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_18.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_18').show(); $('#itemdesc_list_id_18').html(data); } }); } else { $('#itemdesc_list_id_18').hide(); } } function set_item2_18(item) { // change input value $('#desc18').val(item); // hide proposition list $('#itemdesc_list_id_18').hide(); } //================================================== End of desc18 ====================================================== //================================================== Satrt of desc19 ====================================================== function autocomplet2_19() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc19').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_19.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_19').show(); $('#itemdesc_list_id_19').html(data); } }); } else { $('#itemdesc_list_id_19').hide(); } } function set_item2_19(item) { // change input value $('#desc19').val(item); // hide proposition list $('#itemdesc_list_id_19').hide(); } //================================================== End of desc19 ====================================================== //================================================== Satrt of desc120 ====================================================== function autocomplet2_20() { var min_length = 0; // min caracters to display the autocomplete var keyword = $('#desc20').val(); if (keyword.length >= min_length) { $.ajax({ url: 'ajax_refresh_item_desc_20.php', type: 'POST', data: {keyword:keyword}, success:function(data){ $('#itemdesc_list_id_20').show(); $('#itemdesc_list_id_20').html(data); } }); } else { $('#itemdesc_list_id_20').hide(); } } function set_item2_20(item) { // change input value $('#desc20').val(item); // hide proposition list $('#itemdesc_list_id_20').hide(); } //================================================== End of desc20 ======================================================
'use strict'; angular.module('core').controller('HomeController', ['$scope', 'Authentication', function($scope, Authentication) { // This provides Authentication context. $scope.authentication = Authentication; $scope.alerts = [ { icon:'glyphicon-user', color:'btn-success', total:'20,408', description:'TOTAL CUSTOMERS' }, { icon:'glyphicon-calendar', color:'btn-primary', total:'8,382', description:'UPCOMING EVENTS' }, { icon:'glyphicon-edit', color:'btn-success', total:'527', description:'NEW CUSTOMERS IN 24H' }, { icon:'glyphicon-record', color:'btn-info', total:'85,000', description:'EMAILS SENT' }, { icon:'glyphicon-eye-open', color:'btn-warning', total:'20,408', description:'FOLLOW UPS REQUIRED' }, { icon:'glyphicon-flag', color:'btn-danger', total:'348', description:'REFERRALS TO MODERATE' } ]; } ]);
"use strict"; let keyMirror = require('react/lib/keyMirror'); module.exports = keyMirror({ INITIALIZE: null, CREATE_AUTHOR: null, UPDATE_AUTHOR: null, DELETE_AUTHOR: null });
module.exports = function(grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { project: 'bootstrap-timepicker', version: '0.2.3' }, 'gh-pages': { options: { add: true, push: false }, src: [ 'css/bootstrap-timepicker.min.css', 'js/bootstrap-timepicker.min.js' ] }, jasmine: { build: { src : ['spec/js/libs/jquery/jquery.min.js', 'spec/js/libs/bootstrap/js/bootstrap.min.js', 'spec/js/libs/autotype/index.js', 'js/bootstrap-timepicker.js'], options: { specs : 'spec/js/*Spec.js', helpers : 'spec/js/helpers/*.js', timeout : 100 } } }, jshint: { options: { browser: true, camelcase: true, curly: true, eqeqeq: true, eqnull: true, immed: true, indent: 2, latedef: true, newcap: true, noarg: true, quotmark: true, sub: true, strict: true, trailing: true, undef: true, unused: true, white: false, globals: { jQuery: true, $: true, expect: true, it: true, beforeEach: true, afterEach: true, describe: true, loadFixtures: true, console: true, module: true } }, files: ['js/bootstrap-timepicker.js', 'Gruntfile.js', 'package.json', 'spec/js/*Spec.js'] }, less: { dev: { options: { paths: ['css'] }, files: { 'css/bootstrap-timepicker.css': ['less/*.less'] } }, prod: { options: { paths: ['css'], yuicompress: true }, files: { 'css/bootstrap-timepicker.min.css': ['less/*.less'] } } }, uglify: { options: { banner: '/*! <%= meta.project %> v<%= meta.version %> \n' + '* http://jdewit.github.com/bootstrap-timepicker \n' + '* Copyright (c) <%= grunt.template.today("yyyy") %> Joris de Wit \n' + '* MIT License \n' + '*/' }, build: { src: ['<banner:meta.banner>','js/<%= pkg.name %>.js'], dest: 'js/<%= pkg.name %>.min.js' } }, watch: { js: { files: ['js/bootstrap-timepicker.js', 'spec/js/*Spec.js'], tasks: ['jshint', 'jasmine'], options: { livereload: true } }, less: { files: ['less/timepicker.less'], tasks: ['less:dev'], options: { livereload: true } } } }); grunt.registerTask('default', ['jshint', 'jasmine', 'less:dev']); grunt.registerTask('test', ['jasmine', 'jshint']); grunt.registerTask('compile', ['jshint', 'jasmine', 'uglify', 'less:prod']); };
var Encore = require('@symfony/webpack-encore'); // Manually configure the runtime environment if not already configured yet by the "encore" command. // It's useful when you use tools that rely on webpack.config.js file. if (!Encore.isRuntimeEnvironmentConfigured()) { Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev'); } Encore // directory where compiled assets will be stored .setOutputPath('public/build/') // public path used by the web server to access the output path .setPublicPath('/build') // only needed for CDN's or sub-directory deploy //.setManifestKeyPrefix('build/') /* * ENTRY CONFIG * * Add 1 entry for each "page" of your app * (including one that's included on every page - e.g. "app") * * Each entry will result in one JavaScript file (e.g. app.js) * and one CSS file (e.g. app.css) if your JavaScript imports CSS. */ .addEntry('app', './assets/js/app.js') //.addEntry('page1', './assets/js/page1.js') //.addEntry('page2', './assets/js/page2.js') // When enabled, Webpack "splits" your files into smaller pieces for greater optimization. .splitEntryChunks() // will require an extra script tag for runtime.js // but, you probably want this, unless you're building a single-page app .enableSingleRuntimeChunk() /* * FEATURE CONFIG * * Enable & configure other features below. For a full * list of features, see: * https://symfony.com/doc/current/frontend.html#adding-more-features */ .cleanupOutputBeforeBuild() .enableBuildNotifications() .enableSourceMaps(!Encore.isProduction()) // enables hashed filenames (e.g. app.abc123.css) .enableVersioning(Encore.isProduction()) // enables @babel/preset-env polyfills .configureBabelPresetEnv((config) => { config.useBuiltIns = 'usage'; config.corejs = 3; }) // enables Sass/SCSS support //.enableSassLoader() // uncomment if you use TypeScript //.enableTypeScriptLoader() // uncomment to get integrity="..." attributes on your script & link tags // requires WebpackEncoreBundle 1.4 or higher //.enableIntegrityHashes(Encore.isProduction()) // uncomment if you're having problems with a jQuery plugin //.autoProvidejQuery() // uncomment if you use API Platform Admin (composer req api-admin) //.enableReactPreset() //.addEntry('admin', './assets/js/admin.js') ; module.exports = Encore.getWebpackConfig();
const Assigner = require('assign.js') let assigner = new Assigner() const fp = require('fastify-plugin') const WebSocket = require('ws') const url = require('url') module.exports = { addWSServer: function (paths, wsOptions = {}) { return fp((fastify, opts, next) => { const lib = opts.library || 'ws' if (lib !== 'ws' && lib !== 'uws') return next(new Error('Invalid "library" option')) let wssServers = [] for (let path in paths) wssServers[path] = new WebSocket.Server( assigner.assign( {}, wsOptions, { noServer: true }) ) fastify.server.on('upgrade', (request, socket, head) => { const pathname = url.parse(request.url).pathname if ( wssServers[pathname] ) { wssServers[pathname].handleUpgrade(request, socket, head, (ws) => { wssServers[pathname].emit('connection', ws) }) } else { socket.destroy() } }) fastify.decorate('ws', { broadcast: async function broadcast (data, identifySockets, target) { for (let path in wssServers) await wssServers[ path ].broadcast( data, identifySockets, target ) } }) for (let path in wssServers) { let wss = wssServers[ path ] wss.broadcast = async function broadcast (data, identifySockets, target) { let sockets = await identifySockets( wss.clients, target ) sockets.forEach(function each (client) { if (client.readyState === WebSocket.OPEN) { client.send(data) } }) } wss.on('connection', (socket) => { console.log('Client connected.') socket.on('message', (msg) => { paths[path](socket, msg).catch(console.error) }) socket.on('close', () => {}) }) fastify.addHook('onClose', (fastify, done) => { return wss.close(done) }) } next() }, { fastify: '>=2.x', name: 'fastify-ws' }) } }
var _ = require('underscore'); var keystone = require('../../'); var utils = keystone.utils; /** * Content Class * * Accessed via `Keystone.content` * * @api public */ var Content = function () {}; /** * Loads page content by page key (optional). * * If page key is not provided, returns a hash of all page contents in the database. * * ####Example: * * keystone.content.fetch('home', function(err, content) { ... }); * * @param {String} key (optional) * @param {Function} callback * @api public */ Content.prototype.fetch = function (page, callback) { if (utils.isFunction(page)) { callback = page; page = null; } var content = this; if (!this.AppContent) { return callback({ error: 'invalid page', message: 'No pages have been registered.' }); } if (page) { if (!this.pages[page]) { return callback({ error: 'invalid page', message: 'The page ' + page + ' does not exist.' }); } this.AppContent.findOne({ key: page }, function (err, result) { if (err) return callback(err); return callback(null, content.pages[page].populate(result ? result.content.data : {})); }); } else { this.AppContent.find(function (err, results) { if (err) return callback(err); var data = {}; results.forEach(function (i) { if (content.pages[i.key]) { data[i.key] = content.pages[i.key].populate(i.content.data); } }); _.each(content.pages, function (i) { if (!data[i.key]) { data[i.key] = i.populate(); } }); return data; }); } }; /** * Sets page content by page key. * * Merges content with existing content. * * ####Example: * * keystone.content.store('home', { title: 'Welcome' }, function(err) { ... }); * * @param {String} key * @param {Object} content * @param {Function} callback * @api public */ Content.prototype.store = function (page, content, callback) { if (!this.pages[page]) { return callback({ error: 'invalid page', message: 'The page ' + page + ' does not exist.' }); } content = this.pages[page].validate(content); // TODO: Handle validation errors this.AppContent.findOne({ key: page }, function (err, doc) { if (err) return callback(err); if (doc) { if (doc.content) { doc.history.push(doc.content); } _.defaults(content, doc.content); } else { doc = new content.AppContent({ key: page }); } doc.content = { data: this.pages[page].clean(content) }; doc.lastChangeDate = Date.now(); doc.save(callback); }); }; /** * Registers a page. Should not be called directly, use Page.register() instead. * * @param {Page} page * @api private */ Content.prototype.page = function (key, page) { if (!this.pages) { this.pages = {}; } if (arguments.length === 1) { if (!this.pages[key]) { throw new Error('keystone.content.page() Error: page ' + key + ' cannot be registered more than once.'); } return this.pages[key]; } this.initModel(); if (this.pages[key]) { throw new Error('keystone.content.page() Error: page ' + key + ' cannot be registered more than once.'); } this.pages[key] = page; return page; }; /** * Ensures the Mongoose model for storing content is initialised. * * Called automatically when pages are added. * * @api private */ Content.prototype.initModel = function () { if (this.AppContent) return; var contentSchemaDef = { createdAt: { type: Date, default: Date.now }, data: { type: keystone.mongoose.Schema.Types.Mixed }, }; var ContentSchema = new keystone.mongoose.Schema(contentSchemaDef); var PageSchema = new keystone.mongoose.Schema({ page: { type: String, index: true }, lastChangeDate: { type: Date, index: true }, content: contentSchemaDef, history: [ContentSchema], }, { collection: 'app_content' }); this.AppContent = keystone.mongoose.model('App_Content', PageSchema); }; /** * Outputs client-side editable data for content management * * Called automatically when pages are added. * * @api private */ Content.prototype.editable = function (user, options) { if (!user || !user.canAccessKeystone) { return undefined; } if (options.list) { var list = keystone.list(options.list); if (!list) { return JSON.stringify({ type: 'error', err: 'list not found' }); } var data = { type: 'list', path: list.path, singular: list.singular, plural: list.plural, }; if (options.id) { data.id = options.id; } return JSON.stringify(data); } }; /** * The exports object is an instance of Content. * * @api public */ module.exports = new Content(); // Expose Classes exports.Page = require('./page'); exports.Types = require('./types');
var winston = require('winston'); var fs = require('fs'); var presets = {}; function presetsAction(player, values, callback) { var value = decodeURIComponent(values[0]); if (value.startsWith('{')) var preset = JSON.parse(value); else var preset = presets[value]; if (preset) { winston.info("Preset found: ", preset); player.discovery.applyPreset(preset, function (err, result) { if (err) { winston.error("Error loading preset: ", err); } else { winston.info("Playing ", preset); } }); } else { winston.error("No preset found..."); var simplePresets = []; for (var key in presets) { if (presets.hasOwnProperty(key)) { simplePresets.push(key); } } callback(simplePresets); } } function initPresets(api) { var presetsFilename = __dirname + '/../../presets.json'; fs.exists(presetsFilename, function (exists) { if (exists) { presets = require(presetsFilename); winston.info('loaded presets', presets); } else { winston.info('no preset file, ignoring...'); } api.registerAction('preset', presetsAction); }); } module.exports = function (api) { initPresets(api); }
export const UPDATE_TREE_FILTER = 'SIMPR_UPDATE_TREE_FILTER'; export const fireUpdateTreeFilter = (filter) => ({ type: UPDATE_TREE_FILTER, payload: { filter }, });
function MetricConfiguationDataView(metricConfiguration) { var DynamicPropertyType = { Boolean : 1, Int : 2, Double : 3, String : 4, Color : 5, Percent : 6 }; var _items = []; var _rows = []; var _currentColumnId = 0; var enabledColumnId = -1; var _propertyNameColumnId = -1; var _metricConfiguration = metricConfiguration; var _breaks = metricConfiguration.breaks; var _propertyRowLabels = _buildPropertyNameRows(); var _columns = _buildColumns(); var data = buildData(); var _propertyNameColumn = undefined; var onRowsChanged = new Slick.Event(); function destroy() { _propertyNameColumn = null; _columns.length = 0; _propertyRowLabels.length = 0; } function getColumns() { return _columns; } function getPropertyNameColumn() { if (!_propertyNameColumn) { var columnId = _getNextColumnId(); _propertyNameColumn = { id : columnId, name : 'Property', field : 'property', focusable : false, minWidth : 150, sortable : false, resizable : true, editor : null, metricBreak : null, cssClass : 'breakPropertyNames' }; _propertyNameColumnId = columnId; } return _propertyNameColumn; } function _buildColumns() { var column; var columnsArray = []; columnsArray.push(getPropertyNameColumn()); var breaks = _buildBreakColumns(); var allColumns = _.union(columnsArray, breaks); return allColumns; } function _buildBreakColumns() { var columnsArray = []; var breaks = _metricConfiguration.breaks; for (var i = 0; i < breaks.length; i++) { //start off withe break columnnumber equal to 1, so the breaks names are one based. break1, break2 etc var breakColumnNumber = i + 1; var column = { id : _getNextColumnId(), name : 'Break ' + breakColumnNumber, field : 'break' + i, minWidth : 100, sortable : false, resizable : true, metricBreak : breaks[i], /* editor : Slick.Editors.TransposedEditor, formatter : Slick.Formatters.TransposedFormatter,*/ /* headerCssClass : 'breakHeaderName', cssClass : 'breakPropertyValues'*/ }; columnsArray.push(column); } return columnsArray; } function _buildPropertyNameRows() { var metricConfiguration = _metricConfiguration; var fields = _getAllPropertyFields(metricConfiguration); var propertyFields = []; var rowId = 0; _.forEach(fields, function(field) { //var editorFormatter = getEditorAndFormatter(field.propertyType); var breakField = { name : field.propertyName, row : rowId, propertyType : field.propertyType, display : field.displayName, visible : field.hidden, fromStyle : true, readOnly : field.readonly, // enabled : field.enabled, /* editor : editorFormatter.editor, formatter : editorFormatter.formatter*/ }; propertyFields.push(breakField); rowId++; }); return propertyFields; } function _getAllPropertyFields(metricConfiguration) { /* var markerKey = metricConfiguration.getMarkerStylingClientKey(); var breakKey = metricConfiguration.getBreakCalculationClientKey(); var markerFields = MetricStylingService.getMarkerFields(markerKey); var breakCalcFields = MetricStylingService.getBreakCalcFields(breakKey);*/ var markerFields = markerStylingOptions.properties; var breakCalcFields = breakCalculation.properties; var allFields = _.union(breakCalcFields, markerFields); return allFields; } function buildData(metricConfiguration) { for (var i = _propertyRowLabels.length - 1; i >= 0; i--) { //noinspection AssignmentResultUsedJS var rowNode = ( _rows[i] = {}); var field = _propertyRowLabels[i]; rowNode.field = field; for (var x = 0; x < _columns.length; x++) { var column = _columns[x]; if (column.id === _propertyNameColumnId) { rowNode[column.field] = field.display; continue; } if (column.id === enabledColumnId) { rowNode[column.field] = field.enabled; continue; } var breakId = column.metricBreak ? column.metricBreak.id : -1; rowNode[column.field] = getPropertyValue(field.name, breakId); } } } function getPropertyValue(propertyName, breakId) { //-1 indicates the property is not part of a break, but part of the property set. var propBreak = _breaks[breakId]; if (propBreak.breakValidationValues[propertyName] !== undefined) { return propBreak.breakValidationValues[propertyName]; } if (propBreak.markerConfigurationValues[propertyName]) { return propBreak.markerConfigurationValues[propertyName]; } return null; } function _getNextColumnId() { var result = _currentColumnId; _currentColumnId++; return result; } function getEditorAndFormatter(propertyType) { var result = { editor : undefined, formatter : undefined }; if (propertyType === DynamicPropertyType.String) { result.editor = Slick.Editors.TransposedText; result.formatter = null; return result; } if (propertyType === DynamicPropertyType.Double) { result.editor = Slick.Editors.TransposedFloat; result.formatter = null; return result; } if (propertyType === DynamicPropertyType.Percent) { result.editor = Slick.Editors.TransposedPercent; result.formatter = Slick.Formatters.TransposedPercent; return result; } if (propertyType === DynamicPropertyType.Int) { result.editor = Slick.Editors.TransposedInteger; result.formatter = null; return result; } if (propertyType === DynamicPropertyType.Color) { result.editor = Slick.Editors.TransposedColor; result.formatter = Slick.Formatters.TransposedColor; return result; } if (propertyType === DynamicPropertyType.Boolean) { result.editor = Slick.Editors.TransposedCheckbox; result.formatter = Slick.Formatters.TransposedCheckbox; return result; } return Slick.Editors.TransposedText; } function getLength() { return _rows.length - 1; } /** * Return a item at row index `i`. * When `i` is out of range, return `null`. * @public * @param {Number} i index * @param {String} colId column ID * @returns {Object|null} item */ function getItem(_x4, _x5) { var _again = true; _function: while (_again) { var i = _x4, colId = _x5; item = v = key = nested = undefined; _again = false; if (colId != null) { // `i` can be passed item `Object` type internally. var item = typeof i === 'number' ? getItem(i) : i, v = item && item[colId]; if (v == null) { for (var key in item) { if (item.hasOwnProperty(key)) { var nested = item[key]; if (typeof nested === 'object') { _x4 = nested; _x5 = colId; _again = true; continue _function; } } } return null; } return item; } return _rows[i] || null; } } function getValue(i, columnDef) { return getItem(i, columnDef.id) != null ? getItem(i, columnDef.id)[columnDef.field] : ''; } /** * Notify changed. */ function _refresh() { _rows = _genRowsFromItems(_items); onRowsChanged.notify(); } function getItemMetadata(row, cell) { if(cell === _propertyNameColumnId){ return {}; } var rowData = row; var rowField = _rows[row].field; var editorFormatter = getEditorAndFormatter(rowField.propertyType); var columnsResult = {}; columnsResult[cell] = { editor : editorFormatter.editor, formatter: editorFormatter.formatter, }; var rowMetaData = { columns : columnsResult }; return rowMetaData; } $.extend(this, { // methods "getColumns" : getColumns, "getPropertyNameColumn" : getPropertyNameColumn, "buildData" : buildData, "getPropertyValue" : getPropertyValue, "getLength" : getLength, "getItem" : getItem, "getValue" : getValue, "getItemMetadata" : getItemMetadata, "destroy" : destroy, "onRowsChanged" : onRowsChanged }); }
module.exports = { livereload: { options: { livereload: '<%= express.options.livereload %>' }, files: [ '<%= yeoman.currentDir %>', '<%= yeoman.demo %>/**/*.html', '<%= yeoman.demo %>/**/*.js', '<%= yeoman.styles %>/{,*/}*.css', '<%= yeoman.src %>/**/*.html', '<%= yeoman.src %>/{,*/}*.js', '<%= yeoman.src %>/{,*/}*.css', '<%= yeoman.src %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] }, test: { options: { livereload: { port: 35728 } }, files: [ '<%= yeoman.src %>/{,*/}*.html', '{<%= yeoman.build %>,<%= yeoman.src %>}/app/{,*/}*.js' ], tasks: ['test'] } };
import { createStore } from 'redux' import { combineReducers } from 'redux'; import { todoReducer } from '../todo-reducer'; import { appReducer } from '../app-reducer'; const todoApp = combineReducers({ todos: todoReducer, app: appReducer }) export const store = createStore(todoApp); store.getState() // outputs -> // { // todos: { // todos: [] // }, // app: { // settingsVisible: false, // ... // } // }
version https://git-lfs.github.com/spec/v1 oid sha256:dd32b7eaa7daed7371af2e06195ec013df98eb5920727aaf459d9419ef607ff9 size 21785
version https://git-lfs.github.com/spec/v1 oid sha256:2624aaed17536733cabbaeeac1e3b7c75455924c253869c12a812940c3e1241f size 1195
if (Meteor.isClient) { // counter starts at 0 Template.main.helpers({ }); Template.main.events({ }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); }
/* global fetch */ import React from 'react'; import { render } from 'react-dom'; import { Link } from 'react-router'; function Home() { return ( <div className="container"> <h2>Who are you?</h2> <Link to="/caseHandler">A Case Handler</Link> {' or '} <Link to="/adjudicator">An Adjudicator</Link> </div> ); } export default Home;
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var UseOfAllTypeScriptObjectsBinder = (function (_super) { __extends(UseOfAllTypeScriptObjectsBinder, _super); function UseOfAllTypeScriptObjectsBinder() { return _super.call(this, ['ID'], null, true, MaceTestObject) || this; } return UseOfAllTypeScriptObjectsBinder; }(Binder)); //# sourceMappingURL=UseOfAllTypeScriptObjectsBinder.js.map
import AppDispatcher from '../dispatcher/AppDispatcher'; import AppConstants from '../constants/AppConstants'; const ActionTypes = AppConstants.ActionTypes; export function showMenu() { AppDispatcher.dispatchViewAction(ActionTypes.SHOW_MENU); } export function hideMenu() { AppDispatcher.dispatchViewAction(ActionTypes.HIDE_MENU); } export function showModal() { AppDispatcher.dispatchViewAction(ActionTypes.SHOW_MODAL); } export function toggleHeaderNotificationMenu() { AppDispatcher.dispatchViewAction(ActionTypes.TOGGLE_HEADER_NOTIFICATION_MENU); } export function toggleHeaderMessageMenu() { AppDispatcher.dispatchViewAction(ActionTypes.TOGGLE_HEADER_MESSAGE_MENU); }
/** * Created by suman on 09/05/16. */ var core = require('chanakya'), http = require('http'), Q = require('q'); core.validator('isPhoneno', function (message) { var deferred = Q.defer(); http.get('http://apilayer.net/api/validate?access_key=eba101687da317945a45f798464256da&number=' + message + '&country_code=&format=1', function (res) { res.setEncoding('utf8'); res.on('data', function (d) { d = JSON.parse(d); deferred.resolve(d.valid); }); }).on('error', function (e) { deferred.reject(new Error(e)); }); return deferred.promise; }); core.validator('isOTP', function (message) { return Q.fcall(function () { return message == 1234; }); }); core.validator('isStatement', function (message) { // var deferred = Q.defer(); // // http.get('http://demo1036853.mockable.io/wit', function (res) { // res.setEncoding('utf8'); // res.on('data', function (d) { // d = JSON.parse(d); // deferred.resolve(d.intent); // }); // }).on('error', function (e) { // deferred.reject(new Error(e)); // }); // return deferred.promise; return Q.fcall(function () { return (message == 'hi' || message == 'Hi'); }); }); core.validator('isOffer', function (message) { return Q.fcall(function () { return (message == 'offer' || message == 'Offer'); }); });
import {FileSelect} from 'widget/fileSelect' import {Form, form} from 'widget/form/form' import {FormCombo} from 'widget/form/combo' import {Layout} from 'widget/layout' import {Panel} from 'widget/panel/panel' import {activatable} from 'widget/activation/activatable' import {compose} from 'compose' import {msg} from 'translate' import {parseCsvFile$} from 'csv' import {withRecipe} from '../body/process/recipeContext' import Color from 'color' import Icon from 'widget/icon' import Label from 'widget/label' import React from 'react' import _ from 'lodash' import guid from 'guid' import styles from './legendImport.module.css' const fields = { rows: new Form.Field() .notEmpty(), name: new Form.Field() .notBlank(), valueColumn: new Form.Field() .notBlank(), labelColumn: new Form.Field() .notBlank(), colorColumnType: new Form.Field() .notBlank(), colorColumn: new Form.Field() .skip((v, {colorColumnType}) => colorColumnType !== 'single') .notBlank(), redColumn: new Form.Field() .skip((v, {colorColumnType}) => colorColumnType !== 'multiple') .notBlank(), greenColumn: new Form.Field() .skip((v, {colorColumnType}) => colorColumnType !== 'multiple') .notBlank(), blueColumn: new Form.Field() .skip((v, {colorColumnType}) => colorColumnType !== 'multiple') .notBlank() } class _LegendImport extends React.Component { state = { columns: undefined, rows: undefined, validMappings: undefined } render() { const {activatable: {deactivate}, form} = this.props const invalid = form.isInvalid() return ( <Panel type='modal' className={styles.panel}> <Panel.Header icon='file-import' title={msg('map.legendBuilder.import.title')} /> <Panel.Content> {this.renderContent()} </Panel.Content> <Panel.Buttons onEscape={deactivate} onEnter={() => invalid || this.save()}> <Panel.Buttons.Main> <Panel.Buttons.Cancel onClick={deactivate}/> <Panel.Buttons.Apply disabled={invalid} onClick={() => this.save()} /> </Panel.Buttons.Main> </Panel.Buttons> </Panel> ) } renderContent() { const {validMappings} = this.state return ( <Layout> {this.renderFileSelect()} {validMappings ? this.renderForm() : null} </Layout> ) } renderForm() { const {inputs: {colorColumnType}} = this.props return ( <React.Fragment> {this.renderColorColumnType()} {colorColumnType.value === 'single' ? this.renderMapping('colorColumn') : ( <Layout type='horizontal-nowrap'> {this.renderMapping('redColumn')} {this.renderMapping('greenColumn')} {this.renderMapping('blueColumn')} </Layout> )} <Layout type='horizontal'> {this.renderMapping('valueColumn')} {this.renderMapping('labelColumn')} </Layout> </React.Fragment> ) } renderColorColumnType() { const {inputs: {colorColumnType}} = this.props return ( <Form.Buttons label={msg('map.legendBuilder.import.colorColumnType.label')} tooltip={msg('map.legendBuilder.import.colorColumnType.tooltip')} input={colorColumnType} options={[ {value: 'single', label: msg('map.legendBuilder.import.colorColumnType.single')}, {value: 'multiple', label: msg('map.legendBuilder.import.colorColumnType.multiple')}, ]} /> ) } renderMapping(name) { const {inputs} = this.props const {validMappings} = this.state const options = (validMappings[name] || []).map(column => ({value: column, label: column})) return ( <FormCombo className={styles.field} input={inputs[name]} options={options} label={msg(['map.legendBuilder.import.column', name, 'label'])} placeholder={msg(['map.legendBuilder.import.column', name, 'placeholder'])} tooltip={msg(['map.legendBuilder.import.column', name, 'tooltip'])} onChange={({value}) => this.selectedColumn(name, value)} /> ) } renderFileSelect() { const {stream, inputs: {name}} = this.props return ( <Layout spacing={'compact'}> <Label>{msg('map.legendBuilder.import.file.label')}</Label> <FileSelect single onSelect={file => this.onSelectFile(file)}> {name.value ? <div> {stream('LOAD_CSV_ROWS').active ? <Icon name={'spinner'} className={styles.spinner}/> : null} {name.value} </div> : null } </FileSelect> </Layout> ) } componentDidUpdate(prevProps, prevState) { const {rows: prevRows} = prevState const {rows} = this.state if (rows !== prevRows) { this.setDefaults() } } selectedColumn(field, column) { const {inputs} = this.props; ['valueColumn', 'labelColumn', 'colorColumn', 'redColumn', 'blueColumn', 'greenColumn'] .filter(f => f !== field) .forEach(f => { if (inputs[f].value === column) { inputs[f].set(null) // TODO: This is not having any effect } }) } setDefaults() { const {inputs} = this.props const {columns, rows} = this.state const validMappings = getValidMappings(columns, rows) this.setState({validMappings}) const defaults = getDefaults(columns, rows, validMappings) Object.keys(defaults).forEach(field => inputs[field].set(defaults[field])) } onSelectFile(file) { const {stream, inputs: {name, rows: rowsInput}} = this.props name.set(file.name) stream('LOAD_CSV_ROWS', parseCsvFile$(file), ({columns, rows}) => { rowsInput.set(rows) this.setState({columns, rows}) } ) } save() { const {inputs, recipeActionBuilder, activatable: {deactivate}} = this.props const { rows, valueColumn, labelColumn, colorColumnType, colorColumn, redColumn, greenColumn, blueColumn } = inputs const entries = rows.value.map(row => ({ id: guid(), color: colorColumnType.value === 'single' ? Color(trim(row[colorColumn.value])).hex() : Color.rgb([ trim(row[redColumn.value]), trim(row[greenColumn.value]), trim(row[blueColumn.value]) ]).hex(), value: trim(row[valueColumn.value]), label: trim(row[labelColumn.value]) })) recipeActionBuilder('SET_IMPORTED_LEGEND_ENTRIES', {entries}) .set('ui.importedLegendEntries', entries) .dispatch() deactivate() } } const policy = () => ({_: 'allow'}) const trim = value => _.isString(value) ? value.trim() : value export const LegendImport = compose( _LegendImport, activatable({ id: 'legendImport', policy, alwaysAllow: true }), withRecipe(), form({fields}), ) export const getValidMappings = (columns, rows) => { const toInts = column => { return rows .map(row => { const value = row[column] try { return _.isInteger(value) ? value : _.isInteger(parseInt(value)) ? parseInt(value) : null } catch (_e) { return false } }) .filter(i => _.isInteger(i)) } const valueColumn = columns.filter(column => _.uniq(toInts(column)).length === rows.length ) const labelColumn = columns.filter(column => _.uniq(rows .map(row => _.isNaN(row[column]) ? null : _.isNil(row[column]) ? null : row[column].toString().trim() ) .filter(value => value) ).length === rows.length ) const colorColumn = columns.filter(column => _.uniq(rows .map(row => { try { return Color(row[column].trim()).hex() } catch(_e) { return false } }) .filter(value => value) ).length === rows.length ) const colorChannel = columns.filter(column => toInts(column).length === rows.length ) return ({valueColumn, labelColumn, colorColumn, redColumn: colorChannel, greenColumn: colorChannel, blueColumn: colorChannel}) } export const getDefaults = (columns, rows, validMappings) => { const mappings = _.cloneDeep(validMappings) const selectedColumn = column => { if (!column) return Object.keys(mappings).forEach(key => mappings[key] = mappings[key].filter(c => c !== column) ) } const firstContaining = (columns, strings) => columns.find(column => strings.find(s => column.toLowerCase().includes(s.toLowerCase()))) const colorColumnType = mappings.colorColumn.length ? 'single' : (mappings.redColumn.length >= 4 && mappings.greenColumn.length >= 4 && mappings.blueColumn.length >= 4) ? 'multiple' : null const colorColumn = mappings.colorColumn.length ? mappings.colorColumn[0] : null selectedColumn(colorColumn) const valueColumn = mappings.valueColumn.length ? colorColumnType === 'single' ? mappings.valueColumn[0] : firstContaining(mappings.valueColumn, ['class', 'value', 'type']) : null selectedColumn(valueColumn) const labelColumn = mappings.labelColumn.length ? firstContaining(mappings.labelColumn, ['desc', 'label', 'name']) : null selectedColumn(labelColumn) const redColumn = mappings.redColumn.length ? firstContaining(mappings.redColumn, ['red']) : null selectedColumn(redColumn) const greenColumn = mappings.greenColumn.length ? firstContaining(mappings.greenColumn, ['green']) : null selectedColumn(greenColumn) const blueColumn = mappings.blueColumn.length ? firstContaining(mappings.blueColumn, ['blue']) : null selectedColumn(blueColumn) return _.transform({ valueColumn, labelColumn, colorColumnType, colorColumn, redColumn, greenColumn, blueColumn }, (defaults, value, key) => { if (value) { defaults[key] = value } return defaults }) }
import * as ActionTypes from '../constants/constants'; const initialState = { isAuthenticated: false, isFetching: false, loaded: false, message: '' }; const authReducer = (state = initialState, action) => { switch (action.type) { case ActionTypes.REQUEST_CHECK_TOKEN: return { ...state, isAuthenticated: action.isAuthenticated, isFetching: action.isFetching, loaded: false, }; case ActionTypes.TOKEN_VALID: return { ...state, isAuthenticated: action.isAuthenticated, isFetching: action.isFetching, loaded: true, }; case ActionTypes.TOKEN_INVALID: return { ...state, isAuthenticated: action.isAuthenticated, isFetching: action.isFetching, loaded: true, }; case ActionTypes.REQUEST_LOGIN: return { ...state, isAuthenticated: action.isAuthenticated, isFetching: action.isFetching, user: action.creds, message: '', }; case ActionTypes.LOGIN_SUCCESS: return { ...state, isAuthenticated: true, isFetching: false, message: '', }; case ActionTypes.LOGIN_FAILURE: return { ...state, isAuthenticated: false, isFetching: false, message: action.message, }; default: return state; } }; export default authReducer;
function isString(value) { if (typeof value !== 'string' || value === '' || value === null) { return false; } return true; } function isNumber(value) { if (typeof Number.parseInt(value, 10) !== 'number' || Number.isNaN(value) || value === null) { return false; } return true; } function isInRange(value, start, end) { if (value < start || value > end) { return false; } return true; } function isEmail(value) { const atIndex = value.indexOf('@'); if (atIndex < 1) { return false; } if (value.substring(atIndex, value.length).indexOf('.') < 1) { return false; } return true; } module.exports = { isNumber, isString, isInRange, isEmail, };
'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; Snakeskin.addDirective( 'op', { block: true, group: 'op', logic: true } );
import mongoose from 'mongoose'; const friendSchema = mongoose.Schema({ "id": Number, "gender": String, "firstName": String, "lastName": String, "email": String, "ipAddress": String, "job": String, "company": String, "birthDate": Date, "latitude": String, "longitude": String, }); const Friend = mongoose.model('Friend', friendSchema); export default Friend;
import { isSticky } from '~/lib/utils/sticky'; describe('sticky', () => { const el = { offsetTop: 0, classList: {}, }; beforeEach(() => { el.offsetTop = 0; el.classList.add = jasmine.createSpy('spy'); el.classList.remove = jasmine.createSpy('spy'); }); describe('classList.remove', () => { it('does not call classList.remove when stuck', () => { isSticky(el, 0, 0); expect( el.classList.remove, ).not.toHaveBeenCalled(); }); it('calls classList.remove when not stuck', () => { el.offsetTop = 10; isSticky(el, 0, 0); expect( el.classList.remove, ).toHaveBeenCalledWith('is-stuck'); }); }); describe('classList.add', () => { it('calls classList.add when stuck', () => { isSticky(el, 0, 0); expect( el.classList.add, ).toHaveBeenCalledWith('is-stuck'); }); it('does not call classList.add when not stuck', () => { el.offsetTop = 10; isSticky(el, 0, 0); expect( el.classList.add, ).not.toHaveBeenCalled(); }); }); });
import React from 'react'; import { assert } from 'chai'; import { createShallow, getClasses } from '../test-utils'; import CardContent from './CardContent'; describe('<CardContent />', () => { let shallow; let classes; before(() => { shallow = createShallow({ untilSelector: 'CardContent' }); classes = getClasses(<CardContent />); }); it('should render a div with the root class', () => { const wrapper = shallow(<CardContent />); assert.strictEqual(wrapper.name(), 'div'); assert.strictEqual(wrapper.hasClass(classes.root), true); }); });
(function() { "use strict"; var src$parser$$default = (function() { "use strict"; /* * Generated by PEG.js 0.9.0. * * http://pegjs.org/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function peg$SyntaxError(message, expected, found, location) { this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, peg$SyntaxError); } } peg$subclass(peg$SyntaxError, Error); function peg$parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, parser = this, peg$FAILED = {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = function(elements) { return { type : 'messageFormatPattern', elements: elements, location: location() }; }, peg$c1 = function(text) { var string = '', i, j, outerLen, inner, innerLen; for (i = 0, outerLen = text.length; i < outerLen; i += 1) { inner = text[i]; for (j = 0, innerLen = inner.length; j < innerLen; j += 1) { string += inner[j]; } } return string; }, peg$c2 = function(messageText) { return { type : 'messageTextElement', value: messageText, location: location() }; }, peg$c3 = /^[^ \t\n\r,.+={}#]/, peg$c4 = { type: "class", value: "[^ \\t\\n\\r,.+={}#]", description: "[^ \\t\\n\\r,.+={}#]" }, peg$c5 = "{", peg$c6 = { type: "literal", value: "{", description: "\"{\"" }, peg$c7 = ",", peg$c8 = { type: "literal", value: ",", description: "\",\"" }, peg$c9 = "}", peg$c10 = { type: "literal", value: "}", description: "\"}\"" }, peg$c11 = function(id, format) { return { type : 'argumentElement', id : id, format: format && format[2], location: location() }; }, peg$c12 = "number", peg$c13 = { type: "literal", value: "number", description: "\"number\"" }, peg$c14 = "date", peg$c15 = { type: "literal", value: "date", description: "\"date\"" }, peg$c16 = "time", peg$c17 = { type: "literal", value: "time", description: "\"time\"" }, peg$c18 = function(type, style) { return { type : type + 'Format', style: style && style[2], location: location() }; }, peg$c19 = "plural", peg$c20 = { type: "literal", value: "plural", description: "\"plural\"" }, peg$c21 = function(pluralStyle) { return { type : pluralStyle.type, ordinal: false, offset : pluralStyle.offset || 0, options: pluralStyle.options, location: location() }; }, peg$c22 = "selectordinal", peg$c23 = { type: "literal", value: "selectordinal", description: "\"selectordinal\"" }, peg$c24 = function(pluralStyle) { return { type : pluralStyle.type, ordinal: true, offset : pluralStyle.offset || 0, options: pluralStyle.options, location: location() } }, peg$c25 = "select", peg$c26 = { type: "literal", value: "select", description: "\"select\"" }, peg$c27 = function(options) { return { type : 'selectFormat', options: options, location: location() }; }, peg$c28 = "=", peg$c29 = { type: "literal", value: "=", description: "\"=\"" }, peg$c30 = function(selector, pattern) { return { type : 'optionalFormatPattern', selector: selector, value : pattern, location: location() }; }, peg$c31 = "offset:", peg$c32 = { type: "literal", value: "offset:", description: "\"offset:\"" }, peg$c33 = function(number) { return number; }, peg$c34 = function(offset, options) { return { type : 'pluralFormat', offset : offset, options: options, location: location() }; }, peg$c35 = { type: "other", description: "whitespace" }, peg$c36 = /^[ \t\n\r]/, peg$c37 = { type: "class", value: "[ \\t\\n\\r]", description: "[ \\t\\n\\r]" }, peg$c38 = { type: "other", description: "optionalWhitespace" }, peg$c39 = /^[0-9]/, peg$c40 = { type: "class", value: "[0-9]", description: "[0-9]" }, peg$c41 = /^[0-9a-f]/i, peg$c42 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, peg$c43 = "0", peg$c44 = { type: "literal", value: "0", description: "\"0\"" }, peg$c45 = /^[1-9]/, peg$c46 = { type: "class", value: "[1-9]", description: "[1-9]" }, peg$c47 = function(digits) { return parseInt(digits, 10); }, peg$c48 = /^[^{}\\\0-\x1F \t\n\r]/, peg$c49 = { type: "class", value: "[^{}\\\\\\0-\\x1F\\x7f \\t\\n\\r]", description: "[^{}\\\\\\0-\\x1F\\x7f \\t\\n\\r]" }, peg$c50 = "\\\\", peg$c51 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, peg$c52 = function() { return '\\'; }, peg$c53 = "\\#", peg$c54 = { type: "literal", value: "\\#", description: "\"\\\\#\"" }, peg$c55 = function() { return '\\#'; }, peg$c56 = "\\{", peg$c57 = { type: "literal", value: "\\{", description: "\"\\\\{\"" }, peg$c58 = function() { return '\u007B'; }, peg$c59 = "\\}", peg$c60 = { type: "literal", value: "\\}", description: "\"\\\\}\"" }, peg$c61 = function() { return '\u007D'; }, peg$c62 = "\\u", peg$c63 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, peg$c64 = function(digits) { return String.fromCharCode(parseInt(digits, 16)); }, peg$c65 = function(chars) { return chars.join(''); }, peg$currPos = 0, peg$savedPos = 0, peg$posDetailsCache = [{ line: 1, column: 1, seenCR: false }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos) ); } function error(message) { throw peg$buildException( message, null, input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos) ); } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p, ch; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column, seenCR: details.seenCR }; while (p < pos) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, found, location) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0100-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1000-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } if (expected !== null) { cleanupExpected(expected); } return new peg$SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, location ); } function peg$parsestart() { var s0; s0 = peg$parsemessageFormatPattern(); return s0; } function peg$parsemessageFormatPattern() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsemessageFormatElement(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsemessageFormatElement(); } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c0(s1); } s0 = s1; return s0; } function peg$parsemessageFormatElement() { var s0; s0 = peg$parsemessageTextElement(); if (s0 === peg$FAILED) { s0 = peg$parseargumentElement(); } return s0; } function peg$parsemessageText() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = []; s2 = peg$currPos; s3 = peg$parse_(); if (s3 !== peg$FAILED) { s4 = peg$parsechars(); if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$currPos; s3 = peg$parse_(); if (s3 !== peg$FAILED) { s4 = peg$parsechars(); if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s3 = [s3, s4, s5]; s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c1(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsews(); if (s1 !== peg$FAILED) { s0 = input.substring(s0, peg$currPos); } else { s0 = s1; } } return s0; } function peg$parsemessageTextElement() { var s0, s1; s0 = peg$currPos; s1 = peg$parsemessageText(); if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c2(s1); } s0 = s1; return s0; } function peg$parseargument() { var s0, s1, s2; s0 = peg$parsenumber(); if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = []; if (peg$c3.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c4); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c3.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c4); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { s0 = input.substring(s0, peg$currPos); } else { s0 = s1; } } return s0; } function peg$parseargumentElement() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 123) { s1 = peg$c5; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseargument(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$currPos; if (input.charCodeAt(peg$currPos) === 44) { s6 = peg$c7; peg$currPos++; } else { s6 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s6 !== peg$FAILED) { s7 = peg$parse_(); if (s7 !== peg$FAILED) { s8 = peg$parseelementFormat(); if (s8 !== peg$FAILED) { s6 = [s6, s7, s8]; s5 = s6; } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } } else { peg$currPos = s5; s5 = peg$FAILED; } if (s5 === peg$FAILED) { s5 = null; } if (s5 !== peg$FAILED) { s6 = peg$parse_(); if (s6 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s7 = peg$c9; peg$currPos++; } else { s7 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s7 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c11(s3, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseelementFormat() { var s0; s0 = peg$parsesimpleFormat(); if (s0 === peg$FAILED) { s0 = peg$parsepluralFormat(); if (s0 === peg$FAILED) { s0 = peg$parseselectOrdinalFormat(); if (s0 === peg$FAILED) { s0 = peg$parseselectFormat(); } } } return s0; } function peg$parsesimpleFormat() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c12) { s1 = peg$c12; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c13); } } if (s1 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c14) { s1 = peg$c14; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c15); } } if (s1 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c16) { s1 = peg$c16; peg$currPos += 4; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c17); } } } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 44) { s4 = peg$c7; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s6 = peg$parsechars(); if (s6 !== peg$FAILED) { s4 = [s4, s5, s6]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 === peg$FAILED) { s3 = null; } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c18(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsepluralFormat() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c19) { s1 = peg$c19; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c20); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c7; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$parsepluralStyle(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c21(s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseselectOrdinalFormat() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.substr(peg$currPos, 13) === peg$c22) { s1 = peg$c22; peg$currPos += 13; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c7; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$parsepluralStyle(); if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c24(s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseselectFormat() { var s0, s1, s2, s3, s4, s5, s6; s0 = peg$currPos; if (input.substr(peg$currPos, 6) === peg$c25) { s1 = peg$c25; peg$currPos += 6; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c26); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c7; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = []; s6 = peg$parseoptionalFormatPattern(); if (s6 !== peg$FAILED) { while (s6 !== peg$FAILED) { s5.push(s6); s6 = peg$parseoptionalFormatPattern(); } } else { s5 = peg$FAILED; } if (s5 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c27(s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseselector() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$currPos; if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c28; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c29); } } if (s2 !== peg$FAILED) { s3 = peg$parsenumber(); if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 !== peg$FAILED) { s0 = input.substring(s0, peg$currPos); } else { s0 = s1; } if (s0 === peg$FAILED) { s0 = peg$parsechars(); } return s0; } function peg$parseoptionalFormatPattern() { var s0, s1, s2, s3, s4, s5, s6, s7, s8; s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { s2 = peg$parseselector(); if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 123) { s4 = peg$c5; peg$currPos++; } else { s4 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s4 !== peg$FAILED) { s5 = peg$parse_(); if (s5 !== peg$FAILED) { s6 = peg$parsemessageFormatPattern(); if (s6 !== peg$FAILED) { s7 = peg$parse_(); if (s7 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 125) { s8 = peg$c9; peg$currPos++; } else { s8 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s8 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c30(s2, s6); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parseoffset() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.substr(peg$currPos, 7) === peg$c31) { s1 = peg$c31; peg$currPos += 7; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parsenumber(); if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c33(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsepluralStyle() { var s0, s1, s2, s3, s4; s0 = peg$currPos; s1 = peg$parseoffset(); if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$parseoptionalFormatPattern(); if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$parseoptionalFormatPattern(); } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c34(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } return s0; } function peg$parsews() { var s0, s1; peg$silentFails++; s0 = []; if (peg$c36.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c37); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c36.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c37); } } } } else { s0 = peg$FAILED; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c35); } } return s0; } function peg$parse_() { var s0, s1, s2; peg$silentFails++; s0 = peg$currPos; s1 = []; s2 = peg$parsews(); while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsews(); } if (s1 !== peg$FAILED) { s0 = input.substring(s0, peg$currPos); } else { s0 = s1; } peg$silentFails--; if (s0 === peg$FAILED) { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c38); } } return s0; } function peg$parsedigit() { var s0; if (peg$c39.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c40); } } return s0; } function peg$parsehexDigit() { var s0; if (peg$c41.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c42); } } return s0; } function peg$parsenumber() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 48) { s1 = peg$c43; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c44); } } if (s1 === peg$FAILED) { s1 = peg$currPos; s2 = peg$currPos; if (peg$c45.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c46); } } if (s3 !== peg$FAILED) { s4 = []; s5 = peg$parsedigit(); while (s5 !== peg$FAILED) { s4.push(s5); s5 = peg$parsedigit(); } if (s4 !== peg$FAILED) { s3 = [s3, s4]; s2 = s3; } else { peg$currPos = s2; s2 = peg$FAILED; } } else { peg$currPos = s2; s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s1 = input.substring(s1, peg$currPos); } else { s1 = s2; } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c47(s1); } s0 = s1; return s0; } function peg$parsechar() { var s0, s1, s2, s3, s4, s5, s6, s7; if (peg$c48.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c49); } } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c50) { s1 = peg$c50; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c51); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c52(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c53) { s1 = peg$c53; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c54); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c55(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c56) { s1 = peg$c56; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c57); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c58(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c59) { s1 = peg$c59; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c60); } } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c61(); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.substr(peg$currPos, 2) === peg$c62) { s1 = peg$c62; peg$currPos += 2; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c63); } } if (s1 !== peg$FAILED) { s2 = peg$currPos; s3 = peg$currPos; s4 = peg$parsehexDigit(); if (s4 !== peg$FAILED) { s5 = peg$parsehexDigit(); if (s5 !== peg$FAILED) { s6 = peg$parsehexDigit(); if (s6 !== peg$FAILED) { s7 = peg$parsehexDigit(); if (s7 !== peg$FAILED) { s4 = [s4, s5, s6, s7]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } if (s3 !== peg$FAILED) { s2 = input.substring(s2, peg$currPos); } else { s2 = s3; } if (s2 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c64(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } } } return s0; } function peg$parsechars() { var s0, s1, s2; s0 = peg$currPos; s1 = []; s2 = peg$parsechar(); if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); s2 = peg$parsechar(); } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { peg$savedPos = s0; s1 = peg$c65(s1); } s0 = s1; return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException( null, peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } return { SyntaxError: peg$SyntaxError, parse: peg$parse }; })(); this['IntlMessageFormatParser'] = src$parser$$default; }).call(this); //# sourceMappingURL=parser.js.map
require('dotenv').config({silent:true}); var feathers = require('feathers'); var bodyParser = require('body-parser'); var rest = require('feathers-rest'); var socketio = require('feathers-socketio'); var fms = require('../lib'); var AutoService = fms.AutoService; const hooks = require('feathers-hooks'); const errorHandler = require('feathers-errors/handler'); const connection = { host : process.env.FILEMAKER_SERVER_ADDRESS, db : 'Test', user: process.env.FILEMAKER_USER, pass: process.env.FILEMAKER_PASS }; const model = { layout : 'Todos', idField : 'id' }; // Create a feathers instance. const app = feathers() .configure(hooks()) // Enable REST services .configure(rest()) // Enable REST services .configure(socketio()) // Turn on JSON parser for REST services .use(bodyParser.json()) // Turn on URL-encoded parser for REST services .use(bodyParser.urlencoded({ extended: true })) .configure( AutoService({ connection, prefix : 'auto' })) .use(errorHandler()); // Create a service with a default page size of 2 items // and a maximum size of 4 app.use('/todos', fms({ connection, model, paginate: { default: 2, max: 4 } })); // Start the server module.exports = app.listen(3030); console.log('Feathers Todo Filemaker service running on 127.0.0.1:3030');
// Math.extend v0.5.0 // Copyright (c) 2008-2009 Laurent Fortin // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Object.extend(Math, { sum: function(list) { var sum = 0; for(var i = 0, len = list.length; i < len; i++) sum += list[i]; return sum; }, mean: function(list) { return list.length ? this.sum(list) / list.length : false; }, median: function(list) { if(!list.length) return false; list = this.sort(list); if(list.length.isEven()) { return this.mean([list[list.length / 2 - 1], list[list.length / 2]]); } else { return list[(list.length / 2).floor()]; } }, variance: function(list) { if(!list.length) return false; var mean = this.mean(list); var dev = []; for(var i = 0, len = list.length; i < len; i++) dev.push(this.pow(list[i] - mean, 2)); return this.mean(dev); }, stdDev: function(list) { return this.sqrt(this.variance(list)); }, sort: function(list, desc) { // we output a clone of the original array return list.clone().sort(function(a, b) { return desc ? b - a : a - b }); }, baseLog: function(n, base) { return this.log(n) / this.log(base || 10); }, factorize: function(n) { if(!n.isNatural(true) || n == 1) return false; if(n.isPrime()) return [n]; var sqrtOfN = this.sqrt(n); for(var i = 2; i <= sqrtOfN; i++) if((n % i).isNull() && i.isPrime()) return [i, this.factorize(n / i)].flatten(); }, sinh: function(n) { return (this.exp(n) - this.exp(-n)) / 2; }, cosh: function(n) { return (this.exp(n) + this.exp(-n)) / 2; }, tanh: function(n) { return this.sinh(n) / this.cosh(n); } }); Object.extend(Number.prototype, { isNaN: function() { return isNaN(this); }, isNull: function() { return this == 0; }, isEven: function() { if(!this.isInteger()) return false; return(this % 2 ? false : true); }, isOdd: function() { if(!this.isInteger()) return false; return(this % 2 ? true : false); }, isInteger: function(excludeZero) { // if this == NaN ... if(this.isNaN()) return false; if(excludeZero && this.isNull()) return false; return (this - this.floor()) ? false : true; }, isNatural: function(excludeZero) { return(this.isInteger(excludeZero) && this >= 0); }, isPrime: function() { var sqrtOfThis = Math.sqrt(this); var somePrimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101]; if(!this.isNatural(true) || sqrtOfThis.isInteger()) { return false; } if(somePrimes.include(this)) return true; for(var i = 0, len = somePrimes.length; i < len; i++) { if(somePrimes[i] > sqrtOfThis) { return true; } if((this % somePrimes[i]).isNull()) { return false; } } for(var i = 103; i <= sqrtOfThis; i += 2) { if((this % i).isNull()) { return false; } } return true; }, compute: function(fn) { return fn(this); } }); Object.extend(Array.prototype, { swap: function(index1, index2) { var swap = this[index1]; this[index1] = this[index2]; this[index2] = swap; return this; }, shuffle: function(inline, times) { var list = (inline != false ? this : this.clone()); for(var i = 0, len = list.length * (times || 4); i < len; i++) { list.swap( (Math.random() * list.length).floor(), (Math.random() * list.length).floor() ); } return list; }, randomDraw: function(items) { items = Number(items) || 1; var list = this.shuffle(false); if (items >= list.length) { return list; } var sample = []; for(var i = 1; i <= items; i++) { if(list.length > 0) { sample.push(list.shift()); } else { return sample; } } return sample; } }); Object.extend(Object, { numericValues: function(object) { return Object.values(object).select(Object.isNumber); } });
module.exports = { dimension: 'overworld', config: { robotName: 'rob', accountName: 'admin', serverIP: '127.0.0.1', serverPort: 8080, tcpPort: 3001, posX: 4, posY: 4, posZ: 4, orient: 0, raw: true, }, internalInventory: { meta: { 'size': 64, 'side': -1, 'selected': 1 }, slots: [ { side: -1, slotNum: 1, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 64 } }, { side: -1, slotNum: 2, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 37 } }, { side: -1, slotNum: 5, contents: { 'damage': 0, 'hasTag': false, 'label': "Stone", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:stone", 'size': 3 } }, { side: -1, slotNum: 7, contents: { 'damage': 0, 'hasTag': false, 'label': "Wooden Sword?", 'maxDamage': 100, 'maxSize': 1, 'name': "minecraft:wooden_sword?", 'size': 1 } }, { side: -1, slotNum: 9, contents: { 'damage': 0, 'hasTag': false, 'label': "Netherrack", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:netherrack", 'size': 23 } } ], }, externalInventory: { meta: { 'size': 27, 'side': 3 }, slots: [ { side: 3, slotNum: 1, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 4 } }, { side: 3, slotNum: 2, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 7 } }, { side: 3, slotNum: 5, contents: { 'damage': 0, 'hasTag': false, 'label': "Stone", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:stone", 'size': 25 } } ], }, map: { [-2]: { 0: { [-2]: { "hardness": .5, "name": "minecraft:dirt", }, } }, [-1]: { 0: { [-1]: { "hardness": .5, "name": "minecraft:dirt", }, } }, 0: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, }, 1: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": 2.5, "name": "minecraft:chest", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, }, 2: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, }, 3: { 0: { 3: { "hardness": .5, "name": "minecraft:dirt", }, } }, 4: { 0: { 4: { "hardness": .5, "name": "minecraft:dirt", }, } }, 5: { 0: { 5: { "hardness": .5, "name": "minecraft:dirt", }, } }, }, components: { '0c9a47e1-d211-4d73-ad9d-f3f88a6d0ee9': 'keyboard', '25945f78-9f94-4bd5-9211-cb37b352ebf7': 'filesystem', '2a2da751-3baa-4feb-9fa1-df76016ff390': 'inventory_controller', '5d48c968-e6f5-474e-865f-524e803678a7': 'filesystem', '5f6a65bd-98c1-4cf5-bbe5-3e0b8b23662d': 'internet', '5fffe6b3-e619-4f4f-bc9f-3ddb028afe02': 'filesystem', '73aedc53-517d-4844-9cb2-645c8d7667fc': 'screen', '8be5872b-9a01-4403-b853-d88fe6f17fc3': 'eeprom', '9d40d271-718e-45cc-9522-dc562320a78b': 'crafting', 'c8181ac9-9cc2-408e-b214-3acbce9fe1c6': 'chunkloader', 'c8fe2fde-acb0-4188-86ef-4340de011e25': 'robot', 'ce229fd1-d63d-4778-9579-33f05fd6af9a': 'gpu', 'fdc85abb-316d-4aca-a1be-b7f947016ba1': 'computer', 'ff1699a6-ae72-4f74-bf1c-88ac6901d56e': 'geolyzer' }, };
/** * general purpose formatters * * @author Tim Golen 2014-02-12 */ define(['rivets'], function(rivets) { /** * casts a value to a number * * @author Tim Golen 2013-10-22 * * @param {mixed} value * * @return {number} */ rivets.formatters.number = function (value) { return +value; }; /** * subtract values * * @author Tim Golen 2014-02-10 * * @param {integer} val1 * @param {integer} val2 * * @return {integer} */ rivets.formatters.minus = function(val1, val2) { return parseInt(val1, 10) - parseInt(val2, 10); }; /** * returns the ith item of an array of items * * @author Tim Golen 2014-02-10 * * @param {Array} arr * @param {String} i index of the item to get * * @return {mixed} */ rivets.formatters.at = function(arr, i) { if (!_.isArray(arr)) { return null; } return arr[parseInt(i, 10)]; }; /** * returns the length of an array * * @author Tim Golen 2014-02-10 * * @param {Array} array * * @return {integer} */ rivets.formatters.length = function (array) { if (!array) { return 0; } return array.length; }; /** * formats the number like a big number eg. 24k * * @author Tim Golen 2013-11-27 * * @param {number} value * * @return {string} */ rivets.formatters.bignumber = function(value) { return formatter.formatBigNumber(value); }; /** * formats a number with commas and such * * @author Tim Golen 2013-11-27 * * @param {number} value * * @return {string} */ rivets.formatters.formattednumber = function(value) { return formatter.formatNumber(value); }; /** * formats a number as a pretty display of bytes * * @author Tim Golen 2014-02-12 * * @param {integer} value * * @return {string} */ rivets.formatters.bytes = function(value) { var bytes = parseInt(value, 10); var aKB = 1024, aMB = aKB * 1024, aGB = aMB * 1024, aTB = aGB * 1024; if (bytes > aTB) return _addDecimalToSingleDigit(bytes / aTB) + ' TB'; if (bytes > aGB) return _addDecimalToSingleDigit(bytes / aGB) + ' GB'; if (bytes > aMB) return _addDecimalToSingleDigit(bytes / aMB) + ' MB'; if (bytes > aKB) return _addDecimalToSingleDigit(bytes / aKB) + ' KB'; return (bytes | 0) + ' B'; }; function _addDecimalToSingleDigit(num){ var ret = num | 0; var split = num.toFixed(1).split('.'); if (Math.abs(ret) < 10 && split.length > 1 && split[1] != '0') { return ret + '.' + split[1]; } return ret; } /** * checks if a value is greater than a number * * @author Tim Golen 2013-11-11 * * @param {number} value * @param {number} num * * @return {boolean} */ rivets.formatters.gt = function(value, num) { return value > num; } /** * casts a value to a boolean * * @author Tim Golen 2013-11-02 * * @param {mixed} value */ rivets.formatters.boolean = function (value) { if (value == false || value == 'false' || value == 0) { return false; } return value == true || value == 'true' || value; }; /** * tests if two values are equal * example usage: * rv-hide="rows.length | number | eq 0" * * @author Tim Golen 2013-10-22 * * @param {mixed} value * @param {string} args * * @return {boolean} */ rivets.formatters.eq = function(value, args) { if (value === true && args === 'true') { return true; } if (value === false && args === 'false') { return true; } return value === args; }; /** * tests if two values are not equal * example usage: * rv-show="rows.length | number | neq 0" * * @author Tim Golen 2013-10-22 * * @param {mixed} value * @param {string} args * * @return {boolean} */ rivets.formatters.neq = function(value, args) { return value !== args; }; /** * returns true or false if the value exists * in a comma separated string * * @author Tim Golen 2014-01-29 * * @param {string} value * @param {string} commaString * * @return {boolean} */ rivets.formatters.in = function(value, commaString) { var array = commaString.split(','); return array.indexOf(value) > -1; } /** * returns true or false if the value is blank * or doesn't exist * * @author Tim Golen 2014-01-29 * * @param {mixed} value * * @return {boolean} */ rivets.formatters.isblank = function(value) { if (!value) { return true; } return value === ''; }; /** * returns a formatted date * * @author Tim Golen 2013-10-23 * * @param {mixed} value * @param {string} format of the date * * @return {string} */ rivets.formatters.date = function(value, format) { if (!value) { return '---'; } return __m.utc(value.toString()).format( (format) ? format : 'lll' ); }; /** * converts some date formats * * @author Tim Golen 2014-01-18 * * @param {string} value in the format of YYYYWW * * @return {string} example: 'Week of Dec 13 2014' */ rivets.formatters.weekToDate = function(value) { var now = __m.utc(value, 'YYYYWW'); return 'Week of '+now.format('ll'); }; /** * converts an array into a comma separated list * * @author Tim Golen 2014-01-18 * * @param {string} value that will be converted to an array * * @return {string} */ rivets.formatters.comma = function(value) { return value.join(','); } /** * tacks some json, and returns a formatted string * * @author Tim Golen 2013-11-07 * * @param {object} obj * * @return {string} */ rivets.formatters.json = function(obj) { if (_.isString(obj) && _.startsWith(obj, '{') && _.endsWith(obj, '}')) { return JSON.stringify(JSON.parse(obj), null, 2); } return JSON.stringify(obj, null, 2); }; /** * removes certain fields from an acs log params object * * @author Tim Golen 2013-11-04 * * @param {object} obj the params attribute of an acs log * @param {string} separator what to do the join with * @param {string} addSpace between the items if === "true" * * @return {object} */ rivets.formatters.separatedList = function(array, separator, addSpace) { if (_.isArray(array) && !_.isEmpty(array)) { return (addSpace === 'true') ? array.join(separator + ' ') : array.join(separator); } return '---'; }; /** * when used with the HTML formatter, this will * display a physical space for a blank value * * @author Tim Golen 2013-11-07 * * @param {mixed} value * * @return {mixed} */ rivets.formatters.showBlankSpace = function(value) { return (value)? value: '&nbsp;'; }; /** * shows dashes instead of a blank field * * @author Tim Golen 2013-11-11 * * @param {mixed} value * * @return {mixed} */ rivets.formatters.showBlankDashes = function(value) { return (value)? value: '---'; }; /** * it's just like showBlankSpace except the non-html version * * @author Tim Golen 2013-11-07 * * @param {mixed} value * * @return {mixed} */ rivets.formatters.empty = function(value) { return (value)? value: ''; }; /** * checks to see if the object is empty or not * * @author Tim Golen 2014-02-13 * * @param {object} object * * @return {boolean} */ rivets.formatters.notempty = function(object) { return !_.isEmpty(object); }; /** * formats an array as a list * * @author Tim Golen 2013-11-11 * * @param {array} array * * @return {string} */ rivets.formatters.list = function(array) { var result = '<ul>'; _.each(array, function(item) { result+= '<li>'+item+'</li>'; }); result += '</ul>' return result; }; /** * formats an array as a linked list * * @author Tim Golen 2013-11-11 * * @param {array} array * * @return {string} */ rivets.formatters.linklist = function(array, urlPattern) { var result = '<ul>'; _.each(array, function(item) { result+= '<li><a href="'+_.sprintf(urlPattern, item)+'">'+item+'</a></li>'; }); result += '</ul>' return result; }; /** * allows for string substitution * * @author Tim Golen 2013-11-12 * * @param {string} val * @param {string} urlPattern * * @return {string} */ rivets.formatters.sprintf = function(val, pattern) { return _.sprintf(pattern, val); }; /** * truncats a string to a certain length * * @author Tim Golen 2014-02-12 * * @param {string} val to truncate * @param {integer} length of string before truncating * @param {string} truncateString the string to truncate with * @param {string} addSpecial a special truncate text for ACS * * @return {string} */ rivets.formatters.truncate = function(val, length, truncateString, addSpecial) { return _.truncate(val, parseInt(length, 10), (addSpecial)? '... Click for full text.': truncateString || '...'); }; /** * returns the minimum value of two numbers * * example usage: * rv-percentwidth="event.percentage | number | min 5" * * @author Tim Golen 2013-11-26 * * @param {number} val from our model * @param {string} min argument passed to formatter * the absolute minimum * * @return {number} */ rivets.formatters.min = function(val, min) { return Math.max(val, +min); }; /** * returns an escaped string that is safe to display * * @author Tim Golen 2013-12-04 * * @param {string} val * * @return {string} */ rivets.formatters.escape = function(val) { return _.escape(val); }; return rivets; });
(function() { 'use strict'; /** * Get the main module (shared for Workout). */ angular.module(appName) /** * Login Controller. */ .controller('ConfirmBookingController', ConfirmBooking); ConfirmBooking.$inject = ['$state', '$filter', '$http', 'config', '$location','CommonService','BookingDataService']; function ConfirmBooking($state, $filter, $http, config, $location, CommonService, BookingDataService) { var BookingVm = this; BookingVm.finalBalance = 0; BookingVm.currentUserDetails = {}; BookingVm.successMessagePopup = false; BookingVm.initialBalance = 0; BookingVm.paymentDetails = {}; // Variable declarations // Function declarations BookingVm.decreaseOpacity = decreaseOpacity; BookingVm.increaseOpacity = increaseOpacity; BookingVm.bookingPayment = bookingPayment; BookingVm.goToLive = goToLive; activate(); function activate() { BookingVm.bookingAmount = (CommonService.getBookingDetails().bookingCount * 157); BookingVm.currentUserDetails = CommonService.getUserDetails(); BookingVm.initialBalance = CommonService.getUserDetails().scutops_money; BookingVm.paymentDetails.order_id = CommonService.getBookingDetails().order_id; BookingVm.paymentDetails.cust_id = CommonService.getUserDetails().id; // To initialize anything before the project starts } function decreaseOpacity(){ document.getElementsByClassName("main-content2")[0].style.opacity="0.5"; } function increaseOpacity(){ document.getElementsByClassName("main-content2")[0].style.opacity="1"; } function bookingPayment(){ var balance = BookingVm.initialBalance - BookingVm.bookingAmount; if(balance >= 0){ BookingVm.currentUserDetails.scutops_money = balance; //updating the user details BookingVm.paymentDetails.newBalance = balance; var paymentDetails = JSON.stringify(BookingVm.paymentDetails);// preparing for passing to the php file //console.log(paymentDetails); BookingDataService.makePayment(paymentDetails).then(function(response){ CommonService.setUserDetails(BookingVm.currentUserDetails);//updating user details in common service BookingVm.finalBalance = balance; decreaseOpacity(); BookingVm.successMessagePopup = true; }); } else alert("Insufficient balance"); } function goToLive(){ $state.go("liveUpdate"); } } })();
"use strict"; var dns = require('dns'), os = require('os'); // Because localtunnel doesn't work reliably enough, // hack the config to point at the local ip. module.exports = function(ctx, done){ if(ctx.environment !== 'development'){ // Only run this hack in dev for real. return done(); } dns.lookup(os.hostname(), function (err, add, fam){ ctx.url = 'http://' + add + ':8080'; done(); }); };
var Message = require('../models/message'); exports.create = function(req, res) { new Message({ senderID: req.body.senderID, senderAlias: req.body.senderAlias, acceptorID: req.body.acceptorID, acceptorAlias: req.body.acceptorAlias, subject: req.body.subject, content: req.body.content }).save(function(err, message) { if (err) { return res.send(400, err); } res.send(message); }); }; exports.list = function(req, res) { Message.find({}, function(err, messages) { if (err) { res.send(500, err); } res.send(messages || []); }); }; exports.remove = function(req, res) { var delFlag = false; var saveFlag = false; Message.findOne({_id: req.params.id}, function(err, doc){ if(doc.senderID == req.user._id){ if(doc.delFromAcceptor == 'true'){ delFlag=true; }else{ doc.delFromSender = true; saveFlag = true; } } if(doc.acceptorID == req.user._id){ if(doc.delFromSender == 'true'){ delFlag = true; }else{ doc.delFromAcceptor = true; saveFlag = true; } } if(saveFlag){ doc.save(function(err, doc){ err ? res.send(500, err) : res.send(''); }) } if(delFlag){ doc.remove(function(err, doc) { err ? res.send(500, err) : res.send(''); }); } }); };
import { createAction, createThunkAction } from 'redux/actions'; import { getShortenUrl } from 'services/bitly'; import { saveAreaOfInterest } from 'components/forms/area-of-interest/actions'; export const setShareData = createAction('setShareData'); export const setShareUrl = createAction('setShareUrl'); export const setShareSelected = createAction('setShareSelected'); export const setShareOpen = createAction('setShareOpen'); export const setShareCopied = createAction('setShareCopied'); export const setShareLoading = createAction('setShareLoading'); export const setShareModal = createThunkAction( 'setShareModal', (params) => (dispatch) => { const { shareUrl } = params; dispatch( setShareData({ ...params, }) ); getShortenUrl(shareUrl) .then((response) => { let shortShareUrl = ''; if (response.status < 400) { shortShareUrl = response.data.link; dispatch(setShareUrl(shortShareUrl)); } else { dispatch(setShareLoading(false)); } }) .catch(() => { dispatch(setShareLoading(false)); }); } ); export const setShareAoi = createThunkAction('shareModalSaveAoi', (params) => (dispatch) => { dispatch(saveAreaOfInterest({ ...params })) });
import React from 'react' const DefaultLayout = ({ children }) => { return ( <div className="layout" style={{ width: '100%', height: '100%' }}> {children} </div> ) } export default DefaultLayout
var connect = require('..'); var assert = require('assert'); var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ res.end(JSON.stringify(req.body)); }); describe('connect.bodyParser()', function(){ it('should default to {}', function(done){ app.request() .post('/') .end(function(res){ res.body.should.equal('{}'); done(); }) }) it('should parse JSON', function(done){ app.request() .post('/') .set('Content-Type', 'application/json') .write('{"user":"tobi"}') .end(function(res){ res.body.should.equal('{"user":"tobi"}'); done(); }); }) it('should parse x-www-form-urlencoded', function(done){ app.request() .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .write('user=tobi') .end(function(res){ res.body.should.equal('{"user":"tobi"}'); done(); }); }) describe('with multipart/form-data', function(){ it('should populate req.body', function(done){ app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="user"\r\n') .write('\r\n') .write('Tobi') .write('\r\n--foo--') .end(function(res){ res.body.should.equal('{"user":"Tobi"}'); done(); }); }) it('should support files', function(done){ var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ assert('Tobi' == req.body.user.name); req.files.text.originalFilename.should.equal('foo.txt'); req.files.text.path.should.include('.txt'); res.end(req.files.text.originalFilename); }); app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="user[name]"\r\n') .write('\r\n') .write('Tobi') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n') .write('\r\n') .write('some text here') .write('\r\n--foo--') .end(function(res){ res.body.should.equal('foo.txt'); done(); }); }) it('should expose options to multiparty', function(done){ var app = connect(); app.use(connect.bodyParser({ keepExtensions: true })); app.use(function(req, res){ assert('Tobi' == req.body.user.name); assert(~req.files.text.path.indexOf('.txt')); res.end(req.files.text.originalFilename); }); app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="user[name]"\r\n') .write('\r\n') .write('Tobi') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n') .write('\r\n') .write('some text here') .write('\r\n--foo--') .end(function(res){ res.body.should.equal('foo.txt'); done(); }); }) it('should work with multiple fields', function(done){ app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="user"\r\n') .write('\r\n') .write('Tobi') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="age"\r\n') .write('\r\n') .write('1') .write('\r\n--foo--') .end(function(res){ res.body.should.equal('{"user":"Tobi","age":"1"}'); done(); }); }) it('should support nesting', function(done){ app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="user[name][first]"\r\n') .write('\r\n') .write('tobi') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="user[name][last]"\r\n') .write('\r\n') .write('holowaychuk') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="user[age]"\r\n') .write('\r\n') .write('1') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="species"\r\n') .write('\r\n') .write('ferret') .write('\r\n--foo--') .end(function(res){ var obj = JSON.parse(res.body); obj.user.age.should.equal('1'); obj.user.name.should.eql({ first: 'tobi', last: 'holowaychuk' }); obj.species.should.equal('ferret'); done(); }); }) it('should support multiple files of the same name', function(done){ var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ req.files.text.should.have.length(2); assert(req.files.text[0]); assert(req.files.text[1]); res.end(); }); app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n') .write('\r\n') .write('some text here') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n') .write('\r\n') .write('some more text stuff') .write('\r\n--foo--') .end(function(res){ res.statusCode.should.equal(200); done(); }); }) it('should support nested files', function(done){ var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ Object.keys(req.files.docs).should.have.length(2); req.files.docs.foo.originalFilename.should.equal('foo.txt'); req.files.docs.bar.originalFilename.should.equal('bar.txt'); res.end(); }); app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-Disposition: form-data; name="docs[foo]"; filename="foo.txt"\r\n') .write('\r\n') .write('some text here') .write('\r\n--foo\r\n') .write('Content-Disposition: form-data; name="docs[bar]"; filename="bar.txt"\r\n') .write('\r\n') .write('some more text stuff') .write('\r\n--foo--') .end(function(res){ res.statusCode.should.equal(200); done(); }); }) it('should next(err) on multipart failure', function(done){ var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ res.end('whoop'); }); app.use(function(err, req, res, next){ err.message.should.equal('parser error, 16 of 28 bytes parsed'); res.statusCode = 500; res.end(); }); app.request() .post('/') .set('Content-Type', 'multipart/form-data; boundary=foo') .write('--foo\r\n') .write('Content-filename="foo.txt"\r\n') .write('\r\n') .write('some text here') .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n') .write('\r\n') .write('some more text stuff') .write('\r\n--foo--') .end(function(res){ res.statusCode.should.equal(500); done(); }); }) }) // I'm too lazy to test this in both `.json()` and `.urlencoded()` describe('verify', function () { it('should throw 403 if verification fails', function (done) { var app = connect(); app.use(connect.bodyParser({ verify: function () { throw new Error(); } })) app.request() .post('/') .set('Content-Type', 'application/json') .write('{"user":"tobi"}') .expect(403, done); }) it('should not throw if verification does not throw', function (done) { var app = connect(); app.use(connect.bodyParser({ verify: function () {} })) app.use(function (req, res, next) { res.statusCode = 204; res.end(); }) app.request() .post('/') .set('Content-Type', 'application/json') .write('{"user":"tobi"}') .expect(204, done); }) }) })
module.exports = exports = require('./lib/rhetorical');
(function() {var implementors = {}; implementors["tokio_fs"] = [{"text":"impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/sys/unix/ext/fs/trait.DirEntryExt.html\" title=\"trait std::sys::unix::ext::fs::DirEntryExt\">DirEntryExt</a> for <a class=\"struct\" href=\"tokio_fs/struct.DirEntry.html\" title=\"struct tokio_fs::DirEntry\">DirEntry</a>","synthetic":false,"types":["tokio_fs::read_dir::DirEntry"]}]; if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
'use strict'; import { Schema } from 'mongoose'; import shortid from 'shortid'; const EntrySchema = new Schema({ _id: { type: String, unique: true, default: shortid.generate }, stepRef: { type: String, ref: 'Step' }, name: String, value: String, dateCreated: { type: Date, default: Date.now }, dateUpdated: { type: Date } }); const Entry = mongoose.model('Entry', EntrySchema); export default Entry;
import { strToEl } from '../utils'; export default class Ripple { constructor() { this.container = strToEl('<div class="ripple"></div>'); } animate() { this.container.classList.remove('animate'); this.container.offsetLeft; this.container.classList.add('animate'); } }
import React from 'react'; import PropTypes from 'prop-types'; import Button from 'components/Button'; Main.propTypes = { showLoginForm: PropTypes.func.isRequired, showSignUpForm: PropTypes.func.isRequired }; export default function Main({ showLoginForm, showSignUpForm }) { return ( <main> <Button color="logoBlue" style={{ display: 'block', fontSize: '2.5rem', padding: '1rem' }} onClick={showLoginForm} > Yes, I have an account </Button> <Button color="pink" style={{ marginTop: '1.5rem', fontSize: '2rem', padding: '1rem' }} onClick={showSignUpForm} > {"No, I'm a new user. Make me a new account, please!"} </Button> </main> ); }
import Reflux from 'Reflux'; import cartActions from '../actions/cartActions.js'; import _ from 'lodash'; // Items to fill onFillCart action let items = [ { title: 'Iphone 12', price: '129', id: 1 }, { title: 'Galaxy S14', price: '119', id: 2 }, { title: 'Siemens A52', price: '197', id: 3 }, { title: 'Nokia 3310', price: '329', id: 4 } ]; // Storage keys to use when stroing let localStorageKeys = ['cart', 'toggles']; // Constructor for toggles object on init let Toggles = () => { let obj = { title: false, price: false, quantity: false } return obj; }; let cartStore = Reflux.createStore ({ // Assign actions listenables: [cartActions], // Initial state getInitialState() { // Load from local Storage or empty array this.data = JSON.parse(localStorage.getItem(localStorageKeys[0])) || new Array; // Load from local Storage or new Toggles object this.toggles = JSON.parse(localStorage.getItem(localStorageKeys[1])) || new Toggles; // return to component state return {items: this.data}; }, // onAdd action onAdd(item) { // Update cart with item this.updateCart(this.addItem(item)); }, //onDelete action onDelete(item) { // delete item from cart this.updateCart(this.deleteItem(item)); }, onFillCart() { // Add each item to cart then pass to anAdd so it updates cart _.map(items, (item) => {this.onAdd(item)}) }, onSortTitle() { // Set other toggles states this.toggles.price = false; this.toggles.quantity = false; // Toggle this state this.toggles.title = !this.toggles.title; // Assign let toggle = this.toggles.title; // Update cart through sortBy() this.updateCart(this.sortBy(toggle, 'title')); }, onSortPrice() { // Set other toggles states this.toggles.title = false; this.toggles.quantity = false; // Toggle this state this.toggles.price = !this.toggles.price; // Assign let toggle = this.toggles.price; // Update cart through sortBy() this.updateCart(this.sortBy(toggle, 'price')); }, onSortQuantity() { // Set other toggles states this.toggles.title = false; this.toggles.price = false; // Toggle this state this.toggles.quantity = !this.toggles.quantity; // Assign let toggle = this.toggles.quantity; // Update cart through sortBy() this.updateCart(this.sortBy(toggle, 'quantity')); // ABOVE NEEDS INCAPSULATION }, onSubmit() { // Dummy ajax post to emulate success $.ajax({ url: 'http://jsonplaceholder.typicode.com/posts', dataType: 'json', type: 'POST', data: {data: this.data}, success: function(data) { UIkit.notify({ message : 'Success!', status : 'success', timeout : 5000, pos : 'top-center' }); this.clearCart(); }.bind(this), error: function(xhr, status, err) { UIkit.notify({ message : 'Error! </br>' + err.toString(), status : 'danger', timeout : 5000, pos : 'top-center' }); console.error(xhr, status, err.toString()); } }); }, sortBy(toggle, key) { let items; // if not sorted if (toggle) { items = _.orderBy(this.data, key, 'asc'); } // if sorted -> reverse if (!toggle) { items = _.orderBy(this.data, key, 'desc'); } // store state of toggles localStorage.setItem(localStorageKeys[1], JSON.stringify(this.toggles)); return items; }, updateCart(items) { // save items to local storage localStorage.setItem(localStorageKeys[0], JSON.stringify(items)); // assign to this object this.data = items; // trigger component state change this.trigger({items}); }, addItem (item) { let found, i; found = false; i = 0; let items = this.data.concat(); // loop through items while (i < items.length) { // if find item with the same id if (item.id === items[i].id) { // increment quantity items[i].quantity++; found = true; break; } i++; } // if not found if (!found) { // add new item with quantity 1 Object.assign(item, {quantity: 1}); items.push(item); } return items; }, deleteItem (item) { let items = this.data.concat(); let i = items.length; // loop through items in reverse while (i--) { // if found item with the same id and quantity more than 1 -> decrement if (item.id === items[i].id && items[i].quantity > 1) { items[i].quantity--; break; }; // if found item with the same id and quantity equals 1 -> remove; if (item.id === items[i].id && items[i].quantity === 1) { items.splice(i, 1); break; }; } return items; }, // clearing cart on successfull submit clearCart() { // clear local Storage _.map(localStorageKeys, (key) => { localStorage.removeItem(key); }) let empty = new Array; // update cart with empty Array this.updateCart(empty); } }); export default cartStore;
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function () { if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd)var e = jQuery.fn.select2.amd; return e.define("select2/i18n/nb", [], function () { return { inputTooLong: function (e) { var t = e.input.length - e.maximum; return "Vennligst fjern " + t + " tegn" }, inputTooShort: function (e) { var t = e.minimum - e.input.length, n = "Vennligst skriv inn "; return t > 1 ? n += " flere tegn" : n += " tegn til", n }, loadingMore: function () { return "Laster flere resultater…" }, maximumSelected: function (e) { return "Du kan velge maks " + e.maximum + " elementer" }, noResults: function () { return "Ingen treff" }, searching: function () { return "Søker…" } } }), {define: e.define, require: e.require} })();
var detector = (function () { function foodCollision(snake, food, ui) { var snakeHeadX = snake.parts[0].getPosition().x; var snakeHeadY = snake.parts[0].getPosition().y; var foodX = food.getPosition().x; var foodY = food.getPosition().y; if(snakeHeadX === foodX && snakeHeadY === foodY){ return true; } } function playFieldCollision(selector, snake, ui) { if(selector instanceof HTMLCanvasElement){ this.canvas = selector; } else if(typeof selector === 'String' || typeof selector === 'string'){ this.canvas = document.querySelector(selector); } var w = this.canvas.width; var h = this.canvas.height; if(snake.parts[0].x >= w){ snake.parts[0].x = 0; ui.updateCollision('Playfield'); ; } if(snake.parts[0].y >= h){ snake.parts[0].y = 0; ui.updateCollision('Playfield'); } if(snake.parts[0].x < 0){ snake.parts[0].x = w - 20; ui.updateCollision('Playfield'); } if(snake.parts[0].y < 0){ snake.parts[0].y = h - 20; ui.updateCollision('Playfield'); } } function tailCollision (snake, ui) { for (var i = 1; i < snake.parts.length; i++) { if(snake.parts[0].x === snake.parts[i].x && snake.parts[0].y === snake.parts[i].y){ snake.parts = snake.parts.slice(0,2); snake.parts[0].x = 0; snake.parts[0].y = 0; snake.direction = 1; ui.scoreValue = 0; ui.updateScore(0); ui.updateCollision('Tail'); console.log('Self Tail Collision') } } } function wallCollision(wallArray, snake, ui) { for (var i = 1; i < wallArray.length; i++) { if(snake.parts[0].x === wallArray[i].x && snake.parts[0].y === wallArray[i].y){ snake.parts = snake.parts.slice(0,2); snake.parts[0].x = 0; snake.parts[0].y = 0; snake.direction = 1; ui.updateCollision('Wall'); ui.scoreValue = 0; ui.updateScore(0); console.log('Wall Collision') } } } return { isFoodCollision: foodCollision, playFieldCollision: playFieldCollision, tailCollision: tailCollision, wallCollision: wallCollision } }());
'use strict'; var ANONYMOUS_USER_ID = "55268521fb9a901e442172f8"; var mongoose = require('mongoose'); //var Promise = require("bluebird"); var dbService = require('@colabo-knalledge/b-storage-mongo'); var mockup = { fb: { authenticate: false }, db: { data: false } }; var accessId = 0; function resSendJsonProtected(res, data) { // http://tobyho.com/2011/01/28/checking-types-in-javascript/ if (data !== null && typeof data === 'object') { // http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript res.set('Content-Type', 'application/json'); // JSON Vulnerability Protection // http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/ // https://docs.angularjs.org/api/ng/service/$http#description_security-considerations_cross-site-request-forgery-protection res.send(")]}',\n" + JSON.stringify(data)); } else if (typeof data === 'string') { // http://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string res.send(data); } else { res.send(data); } }; var dbConnection = dbService.DBConnect(); var KEdgeModel = dbConnection.model('kEdge', global.db.kEdge.Schema); //reguired for requests that return results populated with target or ource nodes: var KNodeModel = dbConnection.model('KNode', global.db.kNode.Schema); // module.exports = KEdgeModel; //then we can use it by: var User = require('./app/models/KEdgeModel'); // curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/kedges/one/5524344b498be1070ccca4f6 // curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/kedges/one/5524344b498be1070ccca4f6 // curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/kedges/one/5524344b498be1070ccca4f6 //curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/kedges/between/551b4366fd64e5552ed19364/551bb2c68f6e4cfc35654f37 //curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/kedges/in_map/552678e69ad190a642ad461c exports.index = function(req, res) { var id = req.params.searchParam; var id2 = req.params.searchParam2; var id3 = req.params.searchParam3; var id4 = req.params.searchParam4; var type = req.params.type; var found = function(err, kEdges) { //console.log("[modules/kEdge.js:index] in found; req.params.type: %s: ", req.params.type); //console.log("kEdges:"+kEdges); if (err) { throw err; var msg = JSON.stringify(err); resSendJsonProtected(res, { data: kEdges, accessId: accessId, message: msg, success: false }); } else { resSendJsonProtected(res, { data: kEdges, accessId: accessId, success: true }); } } console.log("[modules/kEdge.js:index] req.params.searchParam: %s. req.params.searchParam2: %s", req.params.searchParam, req.params.searchParam2); if (mockup && mockup.db && mockup.db.data) { var datas_json = []; //TODO: change data here: datas_json.push({ id: 1, name: "Sun" }); datas_json.push({ id: 2, name: "Earth" }); datas_json.push({ id: 3, name: "Pluto" }); datas_json.push({ id: 4, name: "Venera" }); resSendJsonProtected(res, { data: datas_json, accessId: accessId }); } //TODO: remove (testing) KEdgeModel.find(function(err, kEdges) { //console.log("all data:\n length: %d.\n", kEdges.length); //console.log(kEdges); //resSendJsonProtected(res, {data: {, accessId : accessId, success: true}); }); switch (type) { case 'one': //by edge id: KEdgeModel.findById(req.params.searchParam, found); break; case 'between': //all edges between specific nodes: KEdgeModel.find({ $and: [{ 'sourceId': req.params.searchParam }, { 'targetId': req.params.searchParam2 }] }, found); break; case 'connected': //all edges connected to knode.id KEdgeModel.find({ $or: [{ 'sourceId': req.params.searchParam }, { 'targetId': req.params.searchParam }] }, found); break; case 'in_map': //all edges in specific map KEdgeModel.find({ 'mapId': req.params.searchParam }, found); break; case 'for_map_type_user_w_target_nodes': console.log("for_map_type_user_w_target_nodes: mapId: %s, type: %s", id, id2); var queryObj = { 'mapId': id, 'type': id2}; if(id3 !== null && id3 !== undefined && id3 !== 'null') { console.log('iAmId: ', id3); queryObj['iAmId'] = id3; } else{ console.log('iAmId: is not set as a paremeter - so for all users'); } KEdgeModel.find(queryObj).populate('targetId', '_id name dataContent.humanID').exec(found); break; default: console.log("[modules/kEdge.js:index] unsuported req.params.type: %s", type); resSendJsonProtected(res, { data: [], accessId: accessId, message: 'unsuported req type \'' + req.params.type + '\'', success: false }); } } // curl -v -H "Content-Type: application/json" -X POST -d '{"name":"Hello Edge", "iAmId":5, "type":"contains", "sourceId":"551b4366fd64e5552ed19364", "targetId": "551bb2c68f6e4cfc35654f37", "ideaId":0}' http://127.0.0.1:8888/kedges // curl -v -H "Content-Type: application/json" -X POST -d '{"name":"Hello Edge 3", "iAmId":6, "type":"contains", "ideaId":0}' http://127.0.0.1:8888/kedges exports.create = function(req, res) { console.log("[modules/kEdge.js:create] req.body: %s", JSON.stringify(req.body)); var data = req.body; if (!("iAmId" in data) || data.iAmId == null || data.iAmId == 0) data.iAmId = mongoose.Types.ObjectId(ANONYMOUS_USER_ID); var kEdge = new KEdgeModel(data); //TODO: Should we force existence of node ids? if (data.sourceId) { kEdge.sourceId = mongoose.Types.ObjectId(data.sourceId); } if (data.targetId) { kEdge.targetId = mongoose.Types.ObjectId(data.targetId); } kEdge.save(function(err) { if (err) throw err; console.log("[modules/kEdge.js:create] data (id:%s) created data: %s", kEdge.id, JSON.stringify(kEdge)); resSendJsonProtected(res, { success: true, data: kEdge, accessId: accessId }); }); } //curl -v -H "Content-Type: application/json" -X PUT -d '{"name": "Hello World E1"}' http://127.0.0.1:8888/kedges/one/551bb2c68f6e4cfc35654f37 //curl -v -H "Content-Type: application/json" -X PUT -d '{"mapId": "552678e69ad190a642ad461c", "sourceId": "55268521fb9a901e442172f9", "targetId": "5526855ac4f4db29446bd183"}' http://127.0.0.1:8888/kedges/one/552475525034f70c166bf89c exports.update = function(req, res) { //console.log("[modules/KEdge.js:update] req.body: %s", JSON.stringify(req.body)); var data = req.body; var id = req.params.searchParam; console.log("[modules/KEdge.js:update] id : %s", id); console.log("[modules/KEdge.js:update] data, : %s", JSON.stringify(data)); delete data._id; //TODO: check this: multi (boolean) whether multiple documents should be updated (false) //TODO: fix: numberAffected vraca 0, a raw vraca undefined. pitanje je da li su ispravni parametri callback f-je // KEdgeModel.findByIdAndUpdate(id , data, { /* multi: true */ }, function (err, numberAffected, raw) { // if (err) throw err; // console.log('The number of updated documents was %d', numberAffected); // console.log('The raw response from Mongo was ', raw); // resSendJsonProtected(res, {success: true, data: data, accessId : accessId}); // }); data.updatedAt = new Date(); //TODO: workaround for hook "schema.pre('update',...)" not working KEdgeModel.update({ _id: id }, data, function(err, raw) { if (err) throw err; console.log('The raw response from Mongo was ', raw); data._id = id; resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); } exports.destroy = function(req, res) { var type = req.params.type; var dataId = req.params.searchParam; var dataId2 = req.params.searchParam2; console.log("[modules/kEdge.js::destroy] dataId:%s, type:%s, req.body: %s", dataId, type, JSON.stringify(req.body)); switch (type) { case 'one': //by edge id: console.log("[modules/kEdge.js:destroy] deleting 'one' edge with id = %d", dataId); KEdgeModel.findByIdAndRemove(dataId, function(err) { if (err) throw err; var data = { id: dataId }; resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; case 'connected': //all edges connected to knode.id console.log("[modules/kEdge.js:destroy] deleting 'connected' to %s", dataId); KEdgeModel.remove({ $or: [{ 'sourceId': dataId }, { 'targetId': dataId }] }, function(err) { if (err) { console.log("[modules/kEdge.js:destroy] error:" + err); throw err; } var data = { id: dataId }; console.log("[modules/kEdge.js:destroy] data:" + JSON.stringify(data)); resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; case 'in-map': //all edges in the map console.log("[modules/kEdge.js:destroy] deleting edges in map %s", dataId); KEdgeModel.remove({ 'mapId': dataId }, function(err) { if (err) { console.log("[modules/kEdge.js:destroy] error:" + err); throw err; } var data = { id: dataId }; console.log("[modules/kEdge.js:destroy] data:" + JSON.stringify(data)); resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; // TODO: this currently delete all edges that belongs to the provided mapId case 'by-modification-source': // by source (manual/computer) of modification console.log("[modules/kEdge.js:destroy] deleting edges in map %s", dataId); KEdgeModel.remove({ 'mapId': dataId }, function(err) { if (err) { console.log("[modules/kEdge.js:destroy] error:" + err); throw err; } var data = { id: dataId }; console.log("[modules/kEdge.js:destroy] data:" + JSON.stringify(data)); resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; case 'by-type-n-user': // by type and user //TODO: we must also filter by `mapId` but so far we are sending only 2 parameters! console.log("[modules/kEdge.js:destroy] deleting all edges of type %s by user %s", dataId, dataId2); KEdgeModel.remove({ $and: [{ 'type': dataId }, { 'iAmId': dataId2 }] }, function(err) { if (err) { console.log("[modules/kEdge.js:destroy] error:" + err); throw err; } var data = { id: dataId }; console.log("[modules/kEdge.js:destroy] data:" + JSON.stringify(data)); resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; case 'edges-to-child': // by type and user console.log("[modules/kEdge.js:destroy] deleting all edges with specific tagetId %s", dataId); KEdgeModel.remove({ 'targetId': dataId }, function(err) { if (err) { console.log("[modules/kEdge.js:destroy] error:" + err); throw err; } var data = { id: dataId }; console.log("[modules/kEdge.js:destroy] data:" + JSON.stringify(data)); resSendJsonProtected(res, { success: true, data: data, accessId: accessId }); }); break; default: console.log("[modules/kEdge.js:index] unsuported req.params.type: %s", type); resSendJsonProtected(res, { data: [], accessId: accessId, message: 'unsuported req type \'' + type + '\'', success: false }); } };
function transformPath(decisionPath) { var path = [] for (var i=1; i<decisionPath.length; i++) { var node = { feature: decisionPath[i-1].feature, side: decisionPath[i].side == 'left' ? "<=" : ">", threshold: decisionPath[i-1].threshold.toPrecision(5), featureIdx: decisionPath[i-1].featureIdx, level: i } //copy all properties of decisionPath[i] to node if they won't overide a property for (var attrname in decisionPath[i]) { if (node[attrname] == null) node[attrname] = decisionPath[i][attrname]; } path.push(node) } return path; } var tip_features = { feature: function(d) { return 'Feature: ' + d.feature }, count: function(d) { return d.count + ' samples' }, dataPercentage: function(d) { return d.dataPercentage + '% of the data'}, impurity: function(d) { return 'Impurity: ' + d.impurity} }