code
stringlengths
2
1.05M
// Init express server var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var server = require('http').Server(app); server.listen(3000); console.log("started listenning on port 3000"); // Subscribe to lexa's router stream and update the LED accordingly // var onoff = require('onoff'); // var Gpio = onoff.Gpio; // var led = new Gpio(18, 'out'); var sio = require('socket.io-client'); var socket = sio.connect('http://lexa.tuscale.ro'); // socket.on('message', function(msg) { // console.log('Got a new message from the router:', msg); // var jMsg = JSON.parse(msg); // var newLedState = jMsg.led; // led.writeSync(newLedState); // }); // Init firebase var firebase = require('firebase'); var io = require('socket.io')(server); var firebase_app = firebase.initializeApp({ apiKey: "AIzaSyB3ZvJDuZ2HD-UppgPvY2by-GI0KnessXw", authDomain: "rlexa-9f1ca.firebaseapp.com", databaseURL: "https://rlexa-9f1ca.firebaseio.com", projectId: "rlexa-9f1ca", storageBucket: "rlexa-9f1ca.appspot.com", messagingSenderId: "161670508523" }); var db = firebase.database(); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Init NFC serial link // var SerialPort = require('serialport'); // SerialPort.list(function (err, ports) { // ports.forEach(function (port) { // console.log(port.comName); // }); // }); // var port = new SerialPort('/dev/ttyACM0', { // baudRate: 9600, // parser: SerialPort.parsers.readline("\r\n") // }); // port.on('open', function () { // console.log('open'); // }); // // Monitor NFC activity // port.on('data', function (data) { // var tagID = data.split(' ').join(''); // console.log(data.split(' ')); // tagID = tagID.substring(0, tagID.length - 1); // console.log(tagID + " scanned ..."); // db.ref("card/" + tagID).once("value", function(cardOwnerSnap) { // var cardOwnerName = cardOwnerSnap.child('name').val(); // if (cardOwnerName) { // db.ref('authed').set(cardOwnerName); // } // }); // // Notify our web-clients that a tag was scanned // io.sockets.emit('idscanned', { cardid: tagID }); // }); io.on('connection', function (socket) { console.log('Web client connected.'); }); // Define web-facing endpoints for managing the users app.post('/add_user', function (req, res) { var currentUser = { name: req.body.name, led: req.body.led, id: req.body.id }; var updates = {}; updates['card/' + currentUser.id] = { name: currentUser.name, led: currentUser.led }; updates['users/' + currentUser.name] = currentUser; return firebase.database().ref().update(updates); }); app.get('/get_users', function (req, res) { firebase.database().ref().once('value', function (snap) { var dataUsers = snap.child("users"); res.send(dataUsers); }); }); app.get('/get_authed', function (req, res) { db.ref().once('value', function (snap) { var isUserLogged = snap.child("authed/Mike").val(); console.log(isUserLogged); if (isUserLogged) { var userData = snap.child("users/Mike/led") console.log(parseInt(userData.val())); } }) var name = "BLAH"; name = name.toLowerCase(); name = name.charAt(0).toUpperCase() + name.slice(1); res.send(name); }); // Monitor process termination and do cleanups // process.on('SIGINT', function () { // led.writeSync(0); // led.unexport(); // process.exit(); // }); // db.ref('authed').once('value', function (snap) { // var lastScannedTagOwner = snap.val(); // if (lastScannedTagOwner) { // // Valid tag present // request({ // url: 'http://lexa.tuscale.ro/publish', // method: 'POST', // json: { led: (stateName === "on" ? 1 : 0) } // }, // function (error, response, body) { // if (error) { // return console.error('upload failed:', error); // } // // Delete scanned tag and notify user of successfull op // db.ref('authed').remove(); // that.emit(':tell', 'Hi ' + lastScannedTagOwner + '! Turning ' + stateName + ' the LED!'); // console.log('Upload successful! Server responded with:', body) // } // ); // } else { // that.emit(':tell', 'Please scan your tag and try again.'); // } // });
// fetch() polyfill for making API calls. import 'whatwg-fetch'; // Object.assign() is commonly used with React. // It will use the native implementation if it's present and isn't buggy. import objectAssign from 'object-assign'; Object.assign = objectAssign;
!function e(n,r,t){function o(a,u){if(!r[a]){if(!n[a]){var c="function"==typeof require&&require;if(!u&&c)return c(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var f=r[a]={exports:{}};n[a][0].call(f.exports,function(e){var r=n[a][1][e];return o(r?r:e)},f,f.exports,e,n,r,t)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a<t.length;a++)o(t[a]);return o}({1:[function(e,n,r){!function(e,n,r,t,o,i,a){e.GoogleAnalyticsObject=o,e[o]=e[o]||function(){(e[o].q=e[o].q||[]).push(arguments)},e[o].l=1*new Date,i=n.createElement(r),a=n.getElementsByTagName(r)[0],i.async=1,i.src=t,a.parentNode.insertBefore(i,a)}(window,document,"script","//www.google-analytics.com/analytics.js","ga"),ga("create","UA-67843411-1","auto"),ga("send","pageview")},{}]},{},[1]);
// getPostsParameters gives an object containing the appropriate find and options arguments for the subscriptions's Posts.find() getPostsParameters = function (terms) { var maxLimit = 200; // console.log(terms) // note: using jquery's extend() with "deep" parameter set to true instead of shallow _.extend() // see: http://api.jquery.com/jQuery.extend/ // initialize parameters by extending baseParameters object, to avoid passing it by reference var parameters = deepExtend(true, {}, viewParameters.baseParameters); // if view is not defined, default to "top" var view = !!terms.view ? dashToCamel(terms.view) : 'top'; // get query parameters according to current view if (typeof viewParameters[view] !== 'undefined') parameters = deepExtend(true, parameters, viewParameters[view](terms)); // extend sort to sort posts by _id to break ties deepExtend(true, parameters, {options: {sort: {_id: -1}}}); // if a limit was provided with the terms, add it too (note: limit=0 means "no limit") if (typeof terms.limit !== 'undefined') _.extend(parameters.options, {limit: parseInt(terms.limit)}); // limit to "maxLimit" posts at most when limit is undefined, equal to 0, or superior to maxLimit if(!parameters.options.limit || parameters.options.limit == 0 || parameters.options.limit > maxLimit) { parameters.options.limit = maxLimit; } // hide future scheduled posts unless "showFuture" is set to true or postedAt is already defined if (!parameters.showFuture && !parameters.find.postedAt) parameters.find.postedAt = {$lte: new Date()}; // console.log(parameters); return parameters; }; getUsersParameters = function(filterBy, sortBy, limit) { var find = {}, sort = {createdAt: -1}; switch(filterBy){ case 'invited': // consider admins as invited find = {$or: [{isInvited: true}, adminMongoQuery]}; break; case 'uninvited': find = {$and: [{isInvited: false}, notAdminMongoQuery]}; break; case 'admin': find = adminMongoQuery; break; } switch(sortBy){ case 'username': sort = {username: 1}; break; case 'karma': sort = {karma: -1}; break; case 'postCount': sort = {postCount: -1}; break; case 'commentCount': sort = {commentCount: -1}; case 'invitedCount': sort = {invitedCount: -1}; } return { find: find, options: {sort: sort, limit: limit} }; };
// ==UserScript== // @name Kiss Simple Infobox hider // @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites // @include https://kissanime.ru/Anime/*/* // @include https://kimcartoon.to/Cartoon/*/* // @include https://kissasian.sh/Drama/*/* // @author Playacem // @updateURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js // @downloadURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js // @require https://code.jquery.com/jquery-latest.js // @grant none // @run-at document-end // @version 0.0.11 // ==/UserScript== // do not change var JQ = jQuery; function hideInfobox() { var selector = JQ('#centerDivVideo') /* the div with the video */ .prev() /*a clear2 div*/ .prev() /*dropdown*/ .prev() /*a clear2 div*/ .prev(); /*the actual div*/ selector.remove(); } // load after 2 seconds setTimeout(hideInfobox, 2000);
'use strict'; const fs = require('fs'); const Q = require('q'); const exec = require('child_process').exec; const searchpaths = ["/bin/xset"]; class XSetDriver { constructor(props) { this.name = "Backlight Control"; this.devicePath = "xset"; this.description = "Screensaver control via Xwindows xset command"; this.devices = []; this.driver = {}; //this.depends = []; } probe(props) { searchpaths.forEach(function(p) { if(fs.existsSync(p)) { let stat = fs.lstatSync(p); if (stat.isFile()) { console.log("found xset control at "+p); this.devices.push(new XSetDriver.Channel(this, p, props)); } } }.bind(this)); return this.devices.length>0; } } class XSetChannel { constructor(driver, path, props) { this.value = 1; this.setCommand = path; this.enabled = true; this.display = ":0.0"; this.error = 0; // internal variables this.lastReset = new Date(); } enable() { this.set("on"); } disable() { this.set("off"); } activate() { this.set("activate"); } blank() { this.set("blank"); } reset() { this.set("reset"); this.lastReset=new Date(); } setTimeout(secs) { this.set(""+secs); } set(action) { if(!this.enabled) return false; var ss = this; exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) { if(error) { if(ss.error++ >10) { ss.enabled=false; } console.log("xset error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }.bind(this)); } } XSetDriver.Channel = XSetChannel; module.exports = XSetDriver; /* Treadmill.prototype.init_screensaver = function(action) { this.screensaver = { // config/settings enabled: !simulate, display: ":0.0", error: 0, // internal variables lastReset: new Date(), // screensaver functions enable: function() { this.set("on"); }, disable: function() { this.set("off"); }, activate: function() { this.set("activate"); }, blank: function() { this.set("blank"); }, reset: function() { this.set("reset"); this.lastReset=new Date(); }, timeout: function(secs) { this.set(""+secs); }, // main set() function calls command "xset s <action>" set: function(action) { if(!this.enabled) return false; var ss = this; exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) { if(error) { if(ss.error++ >10) { ss.enabled=false; } console.log("xset error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }); } }; if(simulate) return false; // initialize the screensaver var ss = this.screensaver; exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) { if(error) { ss.enabled = false; console.log("screensaver.conf error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }); this.screensaver.enable(); } */
var fs = require("fs"); var longStr = (new Array(10000)).join("welefen"); while(true){ fs.writeFileSync("1.txt", longStr); }
/** * Copyright (c) 2011 Bruno Jouhier <[email protected]> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var fs = require("fs"); var path = require("path"); var compile = require("./compile"); var registered = false; var _options = {}; /// !doc /// /// # streamline/lib/compiler/register /// /// Streamline `require` handler registration /// /// * `register.register(options)` /// Registers `require` handlers for streamline. /// `options` is a set of default options passed to the `transform` function. exports.register = function(setoptions) { if (registered) return; _options = setoptions || {}; registered = true; var pModule = require('module').prototype; var orig = pModule._compile; pModule._compile = function(content, filename) { content = compile.transformModule(content, filename, _options); return orig.call(this, content, filename); } }; var dirMode = parseInt('777', 8); exports.trackModule = function(m, options) { if (registered) throw new Error("invalid call to require('streamline/module')"); m.filename = m.filename.replace(/\\/g, '/'); var tmp = m.filename.substring(0, m.filename.lastIndexOf('/')); tmp += '/tmp--' + Math.round(Math.random() * 1e9) + path.extname(m.filename); //console.error("WARNING: streamline not registered, re-loading module " + m.filename + " as " + tmp); exports.register({}); fs.writeFileSync(tmp, fs.readFileSync(m.filename, "utf8"), "utf8"); process.on('exit', function() { try { fs.unlinkSync(tmp); } catch (ex) {} }) m.exports = require(tmp); return false; } Object.defineProperty(exports, "options", { enumerable: true, get: function() { return _options; } });
/* * Copyright 2016 Joyent, Inc., All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE */ module.exports = { KeyPair: SDCKeyPair, LockedKeyPair: SDCLockedKeyPair }; var mod_assert = require('assert-plus'); var mod_sshpk = require('sshpk'); var mod_util = require('util'); var mod_httpsig = require('http-signature'); var KeyRing = require('./keyring'); function SDCKeyPair(kr, opts) { mod_assert.object(kr, 'keyring'); mod_assert.ok(kr instanceof KeyRing, 'keyring instanceof KeyRing'); this.skp_kr = kr; mod_assert.object(opts, 'options'); mod_assert.string(opts.plugin, 'options.plugin'); mod_assert.optionalString(opts.source, 'options.source'); this.plugin = opts.plugin; this.source = opts.source; this.comment = ''; if (opts.public !== undefined) { /* * We need a Key of v1,3 or later for defaultHashAlgorithm and * the Signature hashAlgorithm support. */ mod_assert.ok(mod_sshpk.Key.isKey(opts.public, [1, 3]), 'options.public must be a sshpk.Key instance'); this.comment = opts.public.comment; } this.skp_public = opts.public; if (opts.private !== undefined) { mod_assert.ok(mod_sshpk.PrivateKey.isPrivateKey(opts.private), 'options.private must be a sshpk.PrivateKey instance'); } this.skp_private = opts.private; } SDCKeyPair.fromPrivateKey = function (key) { mod_assert.object(key, 'key'); mod_assert.ok(mod_sshpk.PrivateKey.isPrivateKey(key), 'key is a PrivateKey'); var kr = new KeyRing({ plugins: [] }); var kp = new SDCKeyPair(kr, { plugin: 'none', private: key, public: key.toPublic() }); return (kp); }; SDCKeyPair.prototype.canSign = function () { return (this.skp_private !== undefined); }; SDCKeyPair.prototype.createRequestSigner = function (opts) { mod_assert.string(opts.user, 'options.user'); mod_assert.optionalString(opts.subuser, 'options.subuser'); mod_assert.optionalBool(opts.mantaSubUser, 'options.mantaSubUser'); var sign = this.createSign(opts); var user = opts.user; if (opts.subuser) { if (opts.mantaSubUser) user += '/' + opts.subuser; else user += '/users/' + opts.subuser; } var keyId = '/' + user + '/keys/' + this.getKeyId(); function rsign(data, cb) { sign(data, function (err, res) { if (res) res.keyId = keyId; cb(err, res); }); } return (mod_httpsig.createSigner({ sign: rsign })); }; SDCKeyPair.prototype.createSign = function (opts) { mod_assert.object(opts, 'options'); mod_assert.optionalString(opts.algorithm, 'options.algorithm'); mod_assert.optionalString(opts.keyId, 'options.keyId'); mod_assert.string(opts.user, 'options.user'); mod_assert.optionalString(opts.subuser, 'options.subuser'); mod_assert.optionalBool(opts.mantaSubUser, 'options.mantaSubUser'); if (this.skp_private === undefined) { throw (new Error('Private key for this key pair is ' + 'unavailable (because, e.g. only a public key was ' + 'found and no matching private half)')); } var key = this.skp_private; var keyId = this.getKeyId(); var alg = opts.algorithm; var algParts = alg ? alg.toLowerCase().split('-') : []; if (algParts[0] && algParts[0] !== key.type) { throw (new Error('Requested algorithm ' + alg + ' is ' + 'not supported with a key of type ' + key.type)); } var self = this; var cache = this.skp_kr.getSignatureCache(); function sign(data, cb) { if (Buffer.isBuffer(data)) { mod_assert.buffer(data, 'data'); } else { mod_assert.string(data, 'data'); } mod_assert.func(cb, 'callback'); var ck = { key: key, data: data }; if (Buffer.isBuffer(data)) ck.data = data.toString('base64'); if (cache.get(ck, cb)) return; cache.registerPending(ck); /* * We can throw in here if the hash algorithm we were told to * use in 'algorithm' is invalid. Return it as a normal error. */ var signer, sig; try { signer = self.skp_private.createSign(algParts[1]); signer.update(data); sig = signer.sign(); } catch (e) { cache.put(ck, e); cb(e); return; } var res = { algorithm: key.type + '-' + sig.hashAlgorithm, keyId: keyId, signature: sig.toString(), user: opts.user, subuser: opts.subuser }; sign.algorithm = res.algorithm; cache.put(ck, null, res); cb(null, res); } sign.keyId = keyId; sign.user = opts.user; sign.subuser = opts.subuser; sign.getKey = function (cb) { cb(null, self.skp_private); }; return (sign); }; SDCKeyPair.prototype.getKeyId = function () { return (this.skp_public.fingerprint('md5').toString('hex')); }; SDCKeyPair.prototype.getPublicKey = function () { return (this.skp_public); }; SDCKeyPair.prototype.getPrivateKey = function () { return (this.skp_private); }; SDCKeyPair.prototype.isLocked = function () { return (false); }; SDCKeyPair.prototype.unlock = function (passphrase) { throw (new Error('Keypair is not locked')); }; function SDCLockedKeyPair(kr, opts) { SDCKeyPair.call(this, kr, opts); mod_assert.buffer(opts.privateData, 'options.privateData'); this.lkp_privateData = opts.privateData; mod_assert.string(opts.privateFormat, 'options.privateFormat'); this.lkp_privateFormat = opts.privateFormat; this.lkp_locked = true; } mod_util.inherits(SDCLockedKeyPair, SDCKeyPair); SDCLockedKeyPair.prototype.createSign = function (opts) { if (this.lkp_locked) { throw (new Error('SSH private key ' + this.getPublicKey().comment + ' is locked (encrypted/password-protected). It must be ' + 'unlocked before use.')); } return (SDCKeyPair.prototype.createSign.call(this, opts)); }; SDCLockedKeyPair.prototype.createRequestSigner = function (opts) { if (this.lkp_locked) { throw (new Error('SSH private key ' + this.getPublicKey().comment + ' is locked (encrypted/password-protected). It must be ' + 'unlocked before use.')); } return (SDCKeyPair.prototype.createRequestSigner.call(this, opts)); }; SDCLockedKeyPair.prototype.canSign = function () { return (true); }; SDCLockedKeyPair.prototype.getPrivateKey = function () { if (this.lkp_locked) { throw (new Error('SSH private key ' + this.getPublicKey().comment + ' is locked (encrypted/password-protected). It must be ' + 'unlocked before use.')); } return (this.skp_private); }; SDCLockedKeyPair.prototype.isLocked = function () { return (this.lkp_locked); }; SDCLockedKeyPair.prototype.unlock = function (passphrase) { mod_assert.ok(this.lkp_locked); this.skp_private = mod_sshpk.parsePrivateKey(this.lkp_privateData, this.lkp_privateFormat, { passphrase: passphrase }); mod_assert.ok(this.skp_public.fingerprint('sha512').matches( this.skp_private)); this.lkp_locked = false; };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DropdownMenuItemType; (function (DropdownMenuItemType) { DropdownMenuItemType[DropdownMenuItemType["Normal"] = 0] = "Normal"; DropdownMenuItemType[DropdownMenuItemType["Divider"] = 1] = "Divider"; DropdownMenuItemType[DropdownMenuItemType["Header"] = 2] = "Header"; })(DropdownMenuItemType = exports.DropdownMenuItemType || (exports.DropdownMenuItemType = {})); //# sourceMappingURL=Dropdown.Props.js.map
/** * Export exceptions * @type {Object} */ module.exports = { Schema: require('./Schema'), Value: require('./Value') }
// flow-typed signature: da1b0a6922881fd3985864661b7297ce // flow-typed version: <<STUB>>/babel-eslint_v^10.0.3/flow_v0.113.0 /** * This is an autogenerated libdef stub for: * * 'babel-eslint' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-eslint' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-eslint/lib/analyze-scope' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/attachComments' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/convertComments' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/convertTemplateType' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/toAST' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/toToken' { declare module.exports: any; } declare module 'babel-eslint/lib/babylon-to-espree/toTokens' { declare module.exports: any; } declare module 'babel-eslint/lib' { declare module.exports: any; } declare module 'babel-eslint/lib/parse-with-scope' { declare module.exports: any; } declare module 'babel-eslint/lib/parse' { declare module.exports: any; } declare module 'babel-eslint/lib/require-from-eslint' { declare module.exports: any; } declare module 'babel-eslint/lib/visitor-keys' { declare module.exports: any; } // Filename aliases declare module 'babel-eslint/lib/analyze-scope.js' { declare module.exports: $Exports<'babel-eslint/lib/analyze-scope'>; } declare module 'babel-eslint/lib/babylon-to-espree/attachComments.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/attachComments'>; } declare module 'babel-eslint/lib/babylon-to-espree/convertComments.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/convertComments'>; } declare module 'babel-eslint/lib/babylon-to-espree/convertTemplateType.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/convertTemplateType'>; } declare module 'babel-eslint/lib/babylon-to-espree/index' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree'>; } declare module 'babel-eslint/lib/babylon-to-espree/index.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree'>; } declare module 'babel-eslint/lib/babylon-to-espree/toAST.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toAST'>; } declare module 'babel-eslint/lib/babylon-to-espree/toToken.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toToken'>; } declare module 'babel-eslint/lib/babylon-to-espree/toTokens.js' { declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toTokens'>; } declare module 'babel-eslint/lib/index' { declare module.exports: $Exports<'babel-eslint/lib'>; } declare module 'babel-eslint/lib/index.js' { declare module.exports: $Exports<'babel-eslint/lib'>; } declare module 'babel-eslint/lib/parse-with-scope.js' { declare module.exports: $Exports<'babel-eslint/lib/parse-with-scope'>; } declare module 'babel-eslint/lib/parse.js' { declare module.exports: $Exports<'babel-eslint/lib/parse'>; } declare module 'babel-eslint/lib/require-from-eslint.js' { declare module.exports: $Exports<'babel-eslint/lib/require-from-eslint'>; } declare module 'babel-eslint/lib/visitor-keys.js' { declare module.exports: $Exports<'babel-eslint/lib/visitor-keys'>; }
var express = require('express'); var userRouter = express.Router(); var passport = require('passport'); var Model = require('../models/user'); var authenticate = require('./auth'); /* GET all the users */ exports.getAll = function(req, res, next) { Model.Users.forge() .fetch({ columns: ['_id', 'username', 'admin'] }) .then(function(user) { res.json(user); }).catch(function(err) { console.log(err); }); }; /* GET a user given its id */ exports.getUser = function(req, res, next) { var userID = req.params.userID; Model.User.forge({'_id':userID}) .fetch({columns:['_id', 'username', 'admin']}) .then(function (user) { res.json(user); }); }; /* PUT update a user given its id */ exports.updateUser = function(req, res, next) { var userID = req.params.userID; Model.User.forge({'_id':userID}) .fetch({columns:['_id', 'username', 'admin']}) .then(function (user) { res.json(user); }); }; /* GET logout */ exports.signOut = function(req, res){ req.logout(); res.status(200).json({message: 'Login user out'}); }; /* POST login. */ exports.signIn = function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.status(401).json({ err: info }); } return req.logIn(user, function(err) { if (err) { console.log(err); return res.status(500).json({ error: 'Could not log in user' }); } var token = authenticate.getToken(user); res.status(200).json({ status: 'Login successful', succes: true, token: token }); }); })(req, res, next); }; /* POST Register. */ exports.signUp = function(req, res, next) { var userData = req.body; Model.User.forge({ username: userData.username }).fetch() //see if user already exists .then(function(user) { if (user) { return res.status(400).json({ title: 'signup', errorMessage: 'That username already exists' }); } else { //User does not existe, lets add it var signUpUser = Model.User.forge({ username: userData.username, password: userData.password, admin: false }); signUpUser.save() .then(function(user) { var result = 'User ' + user.get('username') + ' created.'; return res.status(200).json({ message: result, user: { id: user.get('id'), username: user.get('username'), } }); }); } }); };
import Float from 'ember-advanced-form/components/float'; export default Float;
document.getElementsByTagName('body')[0].style.overflow = 'hidden'; window.scrollTo(70, 95);
var url = args.url; var limit = args.limitl; var defaultWaitTime = Number(args.wait_time_for_polling) uuid = executeCommand('urlscan-submit-url-command', {'url': url})[0].Contents; uri = executeCommand('urlscan-get-result-page', {'uuid': uuid})[0].Contents; var resStatusCode = 404 var waitedTime = 0 while(resStatusCode == 404 && waitedTime < Number(args.timeout)) { var resStatusCode = executeCommand('urlscan-poll-uri', {'uri': uri})[0].Contents; if (resStatusCode == 200) { break; } wait(defaultWaitTime); waitedTime = waitedTime + defaultWaitTime; } if(resStatusCode == 200) { return executeCommand('urlscan-get-http-transaction-list', {'uuid': uuid, 'url': url, 'limit': limit}); } else { if(waitedTime >= Number(args.timeout)){ return 'Could not get result from UrlScan, please try to increase the timeout.' } else { return 'Could not get result from UrlScan, possible rate-limit issues.' } }
import User from '../models/user.model'; import Post from '../models/post.model'; import UserPost from '../models/users_posts.model'; import fs from 'fs'; import path from 'path'; /** * Load user and append to req. */ function load(req, res, next, id) { User.get(id) .then((user) => { req.user = user; // eslint-disable-line no-param-reassign return next(); }) .catch(e => next(e)); } /** * Get user * @returns {User} */ function get(req, res) { req.user.password = ""; var user = JSON.parse(JSON.stringify(req.user)); Post.count({ userId: req.user._id }).exec() .then(postCount => { user.postCount = postCount; User.count({ following: req.user._id }).exec() .then(followedByCount => { user.followedByCount = followedByCount; return res.json({ data: user, result: 0 }); }) }) .catch(err => { return res.json({ data: err, result: 1 }); }) } /** * Update basic info;firstname lastname profie.bio description title * @returns {User} */ function updateBasicinfo(req, res, next) { var user = req.user; user.firstname = req.body.firstname; user.lastname = req.body.lastname; user.profile.bio = req.body.profile.bio; user.profile.title = req.body.profile.title; user.profile.description = req.body.profile.description; user.save() .then(savedUser => res.json({ data: savedUser, result: 0 })) .catch(e => next(e)); } /** * Update basic info;firstname lastname profie.bio description title * @returns {User} */ function uploadUserimg(req, res, next) { var user = req.user; var file = req.files.file; fs.readFile(file.path, function(err, original_data) { if (err) { next(err); } // save image in db as base64 encoded - this limits the image size // to there should be size checks here and in client var newPath = path.join(__filename, '../../../../public/uploads/avatar/'); fs.writeFile(newPath + user._id + path.extname(file.path), original_data, function(err) { if (err) next(err); console.log("write file" + newPath + user._id + path.extname(file.path)); fs.unlink(file.path, function(err) { if (err) { console.log('failed to delete ' + file.path); } else { console.log('successfully deleted ' + file.path); } }); user.image = '/uploads/avatar/' + user._id + path.extname(file.path); user.save(function(err) { if (err) { next(err); } else { res.json({ data: user, result: 1 }); } }); }); }); } /** * Create new user * @property {string} req.body.username - The username of user. * @property {string} req.body.mobileNumber - The mobileNumber of user. * @returns {User} */ function create(req, res, next) { const user = new User({ username: req.body.username, mobileNumber: req.body.mobileNumber }); user.save() .then(savedUser => res.json(savedUser)) .catch(e => next(e)); } /** * Update existing user * @property {string} req.body.username - The username of user. * @property {string} req.body.mobileNumber - The mobileNumber of user. * @returns {User} */ function update(req, res, next) { const user = req.user; user.username = req.body.username; user.mobileNumber = req.body.mobileNumber; user.save() .then(savedUser => res.json(savedUser)) .catch(e => next(e)); } /** * Get user list. req.params.query : search string req.params. * @returns {User[]} */ function list(req, res, next) { var params = req.query; var condition; if (params.query == "") condition = {}; else { condition = { $or: [{ "firstname": new RegExp(params.query, 'i') }, { "lastname": new RegExp(params.query, 'i') }] }; } User.count(condition).exec() .then(total => { if (params.page * params.item_per_page > total) { params.users = []; throw { data: params, result: 1 }; } params.total = total; return User.find(condition) .sort({ createdAt: -1 }) .skip(params.page * params.item_per_page) .limit(parseInt(params.item_per_page)) .exec(); }) .then(users => { params.users = users; res.json({ data: params, result: 0 }); }) .catch(err => next(err)); } /** * Delete user. * @returns {User} */ function remove(req, res, next) { const user = req.user; user.remove() .then(deletedUser => res.json(deletedUser)) .catch(e => next(e)); } /** * get post of ther user * @returns {User} */ function getPosts(req, res, next) { var user = req.user; Post.find({ userId: user._id }) .sort({ createdAt: -1 }) .populate('userId') .populate({ path: 'comments', // Get friends of friends - populate the 'friends' array for every friend populate: { path: 'author' } }) .exec() .then(posts => { console.log(posts); res.json({ data: posts, result: 0 }) }) .catch(e => next(e)); } /** * get post of ther user * @returns {User} */ function addPost(req, res, next) { var user = req.user; var post = new Post({ userId: user._id, title: req.body.title, content: req.body.content, }); post.save() .then(post => { console.log(post); res.json({ data: post, result: 0 }) }) .catch(e => next(e)); } function followUser(req, res, next) { var user = req.user; User.get(req.body.user_follow_to) .then((user_follow_to) => { if (user.following.indexOf(user_follow_to._id) == -1) user.following.push(user_follow_to._id); user.save() .then(result => { res.json({ result: 0, data: result }); }) .catch(e => next(e)); }) .catch(e => next(e)); } function disconnectUser(req, res, next) { var user = req.user; User.get(req.body.user_disconnect_to) .then(user_disconnect_to => { var index = user.following.indexOf(user_disconnect_to._id) if (index > -1) user.following.splice(index, 1); user.save() .then(result => { res.json({ result: 0, data: result }); }) .catch(e => next(e)); }) .catch(e => next(e)); } function myFeeds(req, res, next) { var user = req.user; Post.find({ userId: { $in: user.following } }) .populate('userId') .populate({ path: 'comments', // Get friends of friends - populate the 'friends' array for every friend populate: { path: 'author' } }) // .populate('likeUsers') .exec() .then(feeds => { res.json({ data: feeds, result: 0 }); }) .catch(e => next(e)); } // function allUsers(req, res, next) { // var user = req.user; // User.find() // .sort({ createdAt: -1 }) // .exec() // .then(users => { // res.json(users) // }) // .catch(e => next(e)); // } //----------------------Like system---------------- function likePost(req, res, next) { // UserPost.find({ // user: req.current_user, // post: req.body.post_id // }) // .exec() // .then(userpost => { // if(userpost.length == 0){ // new UserPost({ // user: req.current_user, // post: req.body.post_id // }).save().then((userpost)=>{ // res.json({ // result:0, // data:userpost // }); // }) // } // else // { // res.json({ // result:0, // data:"You already like it" // }) // } // }) // .catch(e => { // res.json({ // result: 1, // data: e // }) // }); Post.get(req.body.post_id) .then((post) => { if (post.likeUsers.indexOf(req.current_user._id) == -1) post.likeUsers.push(req.current_user._id); post.save() .then(result => { res.json({ result: 0, data: result }); }) .catch(e => next(e)); }) .catch(e => next(e)); } function dislikePost(req, res, next) { // UserPost.remove({ // user: req.current_user, // post: req.body.post_id // }) // .exec() // .then(userpost => { // res.json({ // result:0, // data:userpost // }) // }) // .catch(e => { // res.json({ // result: 1, // data: e.message // }) // }); Post.get(req.body.post_id) .then((post) => { if (post.likeUsers.indexOf(req.current_user._id) != -1) post.likeUsers.splice(post.likeUsers.indexOf(req.current_user._id), 1); post.save() .then(result => { res.json({ result: 0, data: result }); }) .catch(e => next(e)); }) .catch(e => next(e)); } export default { load, get, create, update, list, remove, updateBasicinfo, uploadUserimg, getPosts, addPost, followUser, disconnectUser, myFeeds, likePost, dislikePost };
define(function (require) { require('plugins/timelion/directives/expression_directive'); const module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisParamsController', function ($scope, $rootScope) { $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; $scope.vis.params.interval = $scope.vis.params.interval || '1m'; $scope.search = function () { $rootScope.$broadcast('courier:searchRefresh'); }; }); });
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Cache Status. * * The Initial Developer of the Original Code is * Jason Purdy. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Thanks to the Fasterfox Extension for some pointers * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ function cs_updated_stat( type, aDeviceInfo, prefs ) { var current = round_memory_usage( aDeviceInfo.totalSize/1024/1024 ); var max = round_memory_usage( aDeviceInfo.maximumSize/1024/1024 ); var cs_id = 'cachestatus'; var bool_pref_key = 'auto_clear'; var int_pref_key = 'ac'; var clear_directive; if ( type == 'memory' ) { cs_id += '-ram-label'; bool_pref_key += '_ram'; int_pref_key += 'r_percent'; clear_directive = 'ram'; // this is some sort of random bug workaround if ( current > max && current == 4096 ) { current = 0; } } else if ( type == 'disk' ) { cs_id += '-hd-label'; bool_pref_key += '_disk'; int_pref_key += 'd_percent'; clear_directive = 'disk'; } else { // offline ... or something else we don't manage return; } /* dump( 'type: ' + type + ' - aDeviceInfo' + aDeviceInfo ); // do we need to auto-clear? dump( "evaling if we need to auto_clear...\n" ); dump( bool_pref_key + ": " + prefs.getBoolPref( bool_pref_key ) + " and " + (( current/max )*100) + " > " + prefs.getIntPref( int_pref_key ) + "\n" ); dump( "new min level: " + prefs.getIntPref( int_pref_key )*.01*max + " > 10\n" ); */ /* This is being disabled for now: http://code.google.com/p/cachestatus/issues/detail?id=10 */ /* if ( prefs.getBoolPref( bool_pref_key ) && prefs.getIntPref( int_pref_key )*.01*max > 10 && (( current/max )*100) > prefs.getIntPref( int_pref_key ) ) { //dump( "clearing!\n" ); cs_clear_cache( clear_directive, 1 ); current = 0; } */ // Now, update the status bar label... var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); if (win) { win.document.getElementById(cs_id).setAttribute( 'value', current + " MB / " + max + " MB " ); } } function update_cache_status() { var cache_service = Components.classes["@mozilla.org/network/cache-service;1"] .getService(Components.interfaces.nsICacheService); var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService); var prefs = prefService.getBranch("extensions.cachestatus."); var cache_visitor = { visitEntry: function(a,b) {}, visitDevice: function( device, aDeviceInfo ) { cs_updated_stat( device, aDeviceInfo, prefs ); } } cache_service.visitEntries( cache_visitor ); } /* * This function takes what could be 15.8912576891 and drops it to just * one decimal place. In a future version, I could have the user say * how many decimal places... */ function round_memory_usage( memory ) { memory = parseFloat( memory ); memory *= 10; memory = Math.round(memory)/10; return memory; } // I got the cacheService code from the fasterfox extension // http://www.xulplanet.com/references/xpcomref/ifaces/nsICacheService.html function cs_clear_cache( param, noupdate ) { var cacheService = Components.classes["@mozilla.org/network/cache-service;1"] .getService(Components.interfaces.nsICacheService); if ( param && param == 'ram' ) { cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY); } else if ( param && param == 'disk' ) { cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK); } else { cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK); cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY); } if ( ! noupdate ) { update_cache_status(); } } /* * Grabbed this helpful bit from: * http://kb.mozillazine.org/On_Page_Load * http://developer.mozilla.org/en/docs/Code_snippets:On_page_load */ var csExtension = { onPageLoad: function(aEvent) { update_cache_status(); }, QueryInterface : function (aIID) { if (aIID.equals(Components.interfaces.nsIObserver) || aIID.equals(Components.interfaces.nsISupports) || aIID.equals(Components.interfaces.nsISupportsWeakReference)) return this; throw Components.results.NS_NOINTERFACE; }, register: function() { var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService); this._prefs = prefService.getBranch("extensions.cachestatus."); if ( this._prefs.getBoolPref( 'auto_update' ) ) { var appcontent = document.getElementById( 'appcontent' ); if ( appcontent ) appcontent.addEventListener( "DOMContentLoaded", this.onPageLoad, true ); } this._branch = this._prefs; this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2); this._branch.addObserver("", this, true); this._hbox = this.grabHBox(); this.rebuildPresence( this._prefs.getCharPref( 'presence' ) ); this.welcome(); }, welcome: function () { //Do not show welcome page if user has turned it off from Settings. if (!csExtension._prefs.getBoolPref( 'welcome' )) { return } //Detect Firefox version var version = ""; try { version = (navigator.userAgent.match(/Firefox\/([\d\.]*)/) || navigator.userAgent.match(/Thunderbird\/([\d\.]*)/))[1]; } catch (e) {} function welcome(version) { if (csExtension._prefs.getCharPref( 'version' ) == version) { return; } //Showing welcome screen setTimeout(function () { var newTab = getBrowser().addTab("http://add0n.com/cache-status.html?version=" + version); getBrowser().selectedTab = newTab; }, 5000); csExtension._prefs.setCharPref( 'version', version ); } //FF < 4.* var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"] .getService(Components.interfaces.nsIVersionComparator) .compare(version, "4.0"); if (versionComparator < 0) { var extMan = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager); var addon = extMan.getItemForID("[email protected]"); welcome(addon.version); } //FF > 4.* else { Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getAddonByID("[email protected]", function (addon) { welcome(addon.version); }); } }, grabHBox: function() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); var found_hbox; if (win) { this._doc = win.document; found_hbox = win.document.getElementById("cs_presence"); } //dump( "In grabHBox(): WIN: " + win + " HB: " + found_hbox + "\n" ); return found_hbox; }, observe: function(aSubject, aTopic, aData) { if ( aTopic != 'nsPref:changed' ) return; // aSubject is the nsIPrefBranch we're observing (after appropriate QI) // aData is the name of the pref that's been changed (relative to aSubject) //dump( "pref changed: S: " + aSubject + " T: " + aTopic + " D: " + aData + "\n" ); if ( aData == 'auto_update' ) { var add_event_handler = this._prefs.getBoolPref( 'auto_update' ); if ( add_event_handler ) { window.addEventListener( 'load', this.onPageLoad, true ); } else { window.removeEventListener( 'load', this.onPageLoad, true ); } } else if ( aData == 'presence' ) { var presence = this._prefs.getCharPref( 'presence' ); if ( presence == 'original' || presence == 'icons' ) { this.rebuildPresence( presence ); } else { dump( "Unknown presence value: " + presence + "\n" ); } } }, rebuildPresence: function(presence) { // Take the hbox 'cs_presence' and replace it if ( this._hbox == null ) { this._hbox = this.grabHBox(); } var hbox = this._hbox; var child_node = hbox.firstChild; while( child_node != null ) { hbox.removeChild( child_node ); child_node = hbox.firstChild; } var popupset = this._doc.getElementById( 'cs_popupset' ); var child_node = popupset.firstChild; while( child_node != null ) { popupset.removeChild( child_node ); child_node = popupset.firstChild; } var string_bundle = this._doc.getElementById( 'cache-status-strings' ); if ( presence == 'original' ) { var ram_image = this._doc.createElement( 'image' ); ram_image.setAttribute( 'tooltiptext', string_bundle.getString( 'ramcache' ) ); ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' ); var ram_label = this._doc.createElement( 'label' ); ram_label.setAttribute( 'id', 'cachestatus-ram-label' ); ram_label.setAttribute( 'value', ': ' + string_bundle.getString( 'nly' ) ); ram_label.setAttribute( 'tooltiptext', string_bundle.getString( 'ramcache' ) ); var disk_image = this._doc.createElement( 'image' ); disk_image.setAttribute( 'tooltiptext', string_bundle.getString( 'diskcache' ) ); disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' ); var disk_label = this._doc.createElement( 'label' ); disk_label.setAttribute( 'tooltiptext', string_bundle.getString( 'diskcache' ) ); disk_label.setAttribute( 'id', 'cachestatus-hd-label' ); disk_label.setAttribute( 'value', ': ' + string_bundle.getString( 'nly' ) ); hbox.appendChild( ram_image ); hbox.appendChild( ram_label ); hbox.appendChild( disk_image ); hbox.appendChild( disk_label ); } else if ( presence == 'icons' ) { var ram_tooltip = this._doc.createElement( 'tooltip' ); ram_tooltip.setAttribute( 'id', 'ram_tooltip' ); ram_tooltip.setAttribute( 'orient', 'horizontal' ); var ram_desc_prefix = this._doc.createElement( 'description' ); ram_desc_prefix.setAttribute( 'id', 'cachestatus-ram-prefix' ); ram_desc_prefix.setAttribute( 'value', string_bundle.getString( 'ramcache' ) + ':' ); ram_desc_prefix.setAttribute( 'style', 'font-weight: bold;' ); var ram_desc = this._doc.createElement( 'description' ); ram_desc.setAttribute( 'id', 'cachestatus-ram-label' ); ram_desc.setAttribute( 'value', string_bundle.getString( 'nly' ) ); ram_tooltip.appendChild( ram_desc_prefix ); ram_tooltip.appendChild( ram_desc ); var hd_tooltip = this._doc.createElement( 'tooltip' ); hd_tooltip.setAttribute( 'id', 'hd_tooltip' ); hd_tooltip.setAttribute( 'orient', 'horizontal' ); var hd_desc_prefix = this._doc.createElement( 'description' ); hd_desc_prefix.setAttribute( 'id', 'cachestatus-hd-prefix' ); hd_desc_prefix.setAttribute( 'value', string_bundle.getString( 'diskcache' ) + ':' ); hd_desc_prefix.setAttribute( 'style', 'font-weight: bold;' ); var hd_desc = this._doc.createElement( 'description' ); hd_desc.setAttribute( 'id', 'cachestatus-hd-label' ); hd_desc.setAttribute( 'value', string_bundle.getString( 'nly' ) ); hd_tooltip.appendChild( hd_desc_prefix ); hd_tooltip.appendChild( hd_desc ); popupset.appendChild( ram_tooltip ); popupset.appendChild( hd_tooltip ); hbox.parentNode.insertBefore( popupset, hbox ); var ram_image = this._doc.createElement( 'image' ); ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' ); ram_image.setAttribute( 'tooltip', 'ram_tooltip' ); var disk_image = this._doc.createElement( 'image' ); disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' ); disk_image.setAttribute( 'tooltip', 'hd_tooltip' ); hbox.appendChild( ram_image ); hbox.appendChild( disk_image ); } } } // I can't just call csExtension.register directly b/c the XUL // might not be loaded yet. window.addEventListener( 'load', function() { csExtension.register(); }, false );
(function() { 'use strict'; angular.module('newApp') .controller('newAppCtrl', newAppCtrl); function newAppCtrl() { } })();
let upath = require('upath'), through2 = require('through2'), paths = require('../../project.conf.js').paths, RegexUtil = require('../util/RegexUtil'); module.exports = class StreamReplacer { constructor(replacements = {}) { this.replacements = replacements; } /** * Add a transform to the replacer. A transform is a function that takes a vinyl file from the stream as a * parameter and returns the path to be used as a replacement for that file. * * This function is called for each file present in the stream. * * @param transformFn(file) * * @returns {through2} */ push(transformFn) { let that = this; return through2.obj(function (file, enc, flush) { let dir = upath.dirname(upath.relative(paths.src(), file.path)), ext = upath.extname(file.path), name = upath.basename(file.path, ext); that.replacements[transformFn(file)] = new RegExp(RegexUtil.escape(upath.join(dir, name + ext)).replace(/ /g, '(?: |%20)'), 'g'); this.push(file); flush(); }); } /** * Search and replace all files in the stream with values according to the transforms configured via `push()`. * * @returns {through2} */ replace() { let that = this; return through2.obj(function (file, enc, flush) { Object.keys(that.replacements).forEach((replacement) => { file.contents = new Buffer(String(file.contents).replace(that.replacements[replacement], replacement)); }); this.push(file); flush(); }); } };
/** * WebCLGLVertexFragmentProgram Object * @class * @constructor */ WebCLGLVertexFragmentProgram = function(gl, vertexSource, vertexHeader, fragmentSource, fragmentHeader) { this.gl = gl; var highPrecisionSupport = this.gl.getShaderPrecisionFormat(this.gl.FRAGMENT_SHADER, this.gl.HIGH_FLOAT); this.precision = (highPrecisionSupport.precision != 0) ? 'precision highp float;\n\nprecision highp int;\n\n' : 'precision lowp float;\n\nprecision lowp int;\n\n'; this.utils = new WebCLGLUtils(); this.vertexSource; this.fragmentSource; this.in_vertex_values = []; this.in_fragment_values = []; this.vertexAttributes = []; // {location,value} this.vertexUniforms = []; // {location,value} this.fragmentSamplers = []; // {location,value} this.fragmentUniforms = []; // {location,value} if(vertexSource != undefined) this.setVertexSource(vertexSource, vertexHeader); if(fragmentSource != undefined) this.setFragmentSource(fragmentSource, fragmentHeader); }; /** * Update the vertex source * @type Void * @param {String} vertexSource * @param {String} vertexHeader */ WebCLGLVertexFragmentProgram.prototype.setVertexSource = function(vertexSource, vertexHeader) { this.vertexHead =(vertexHeader!=undefined)?vertexHeader:''; this.in_vertex_values = [];//{value,type,name,idPointer} // value: argument value // type: 'buffer_float4_fromKernel'(4 packet pointer4), 'buffer_float_fromKernel'(1 packet pointer4), 'buffer_float4'(1 pointer4), 'buffer_float'(1 pointer1) // name: argument name // idPointer to: this.vertexAttributes or this.vertexUniforms (according to type) var argumentsSource = vertexSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D" //console.log(argumentsSource); for(var n = 0, f = argumentsSource.length; n < f; n++) { if(argumentsSource[n].match(/\*kernel/gm) != null) { if(argumentsSource[n].match(/float4/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'buffer_float4_fromKernel', name:argumentsSource[n].split('*kernel')[1].trim()}; } else if(argumentsSource[n].match(/float/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'buffer_float_fromKernel', name:argumentsSource[n].split('*kernel')[1].trim()}; } } else if(argumentsSource[n].match(/\*/gm) != null) { if(argumentsSource[n].match(/float4/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'buffer_float4', name:argumentsSource[n].split('*')[1].trim()}; } else if(argumentsSource[n].match(/float/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'buffer_float', name:argumentsSource[n].split('*')[1].trim()}; } } else { if(argumentsSource[n].match(/float4/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'float4', name:argumentsSource[n].split(' ')[1].trim()}; } else if(argumentsSource[n].match(/float/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'float', name:argumentsSource[n].split(' ')[1].trim()}; } else if(argumentsSource[n].match(/mat4/gm) != null) { this.in_vertex_values[n] = {value:undefined, type:'mat4', name:argumentsSource[n].split(' ')[1].trim()}; } } } //console.log(this.in_vertex_values); //console.log('original source: '+vertexSource); this.vertexSource = vertexSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, ''); this.vertexSource = this.vertexSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, ''); //console.log('minified source: '+this.vertexSource); this.vertexSource = this.parseVertexSource(this.vertexSource); if(this.fragmentSource != undefined) this.compileVertexFragmentSource(); }; /** @private **/ WebCLGLVertexFragmentProgram.prototype.parseVertexSource = function(source) { //console.log(source); for(var n = 0, f = this.in_vertex_values.length; n < f; n++) { // for each in_vertex_values (in argument) var regexp = new RegExp(this.in_vertex_values[n].name+'\\[\\w*\\]',"gm"); var varMatches = source.match(regexp);// "Search current "in_vertex_values.name[xxx]" in source and store in array varMatches //console.log(varMatches); if(varMatches != null) { for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]") var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm"); var regexpNativeGLMatches = source.match(regexpNativeGL); if(regexpNativeGLMatches == null) { var name = varMatches[nB].split('[')[0]; var vari = varMatches[nB].split('[')[1].split(']')[0]; var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm"); if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel') source = source.replace(regexp, 'buffer_float4_fromKernel_data('+name+'0,'+name+'1,'+name+'2,'+name+'3)'); if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') source = source.replace(regexp, 'buffer_float_fromKernel_data('+name+'0)'); if(this.in_vertex_values[n].type == 'buffer_float4') source = source.replace(regexp, name); if(this.in_vertex_values[n].type == 'buffer_float') source = source.replace(regexp, name); } } } } source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, ""); //console.log('%c translated source:'+source, "background-color:#000;color:#FFF"); return source; }; /** * Update the fragment source * @type Void * @param {String} fragmentSource * @param {String} fragmentHeader */ WebCLGLVertexFragmentProgram.prototype.setFragmentSource = function(fragmentSource, fragmentHeader) { this.fragmentHead =(fragmentHeader!=undefined)?fragmentHeader:''; this.in_fragment_values = [];//{value,type,name,idPointer} // value: argument value // type: 'buffer_float4'(RGBA channels), 'buffer_float'(Red channel) // name: argument name // idPointer to: this.fragmentSamplers or this.fragmentUniforms (according to type) var argumentsSource = fragmentSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D" //console.log(argumentsSource); for(var n = 0, f = argumentsSource.length; n < f; n++) { if(argumentsSource[n].match(/\*/gm) != null) { if(argumentsSource[n].match(/float4/gm) != null) { this.in_fragment_values[n] = {value:undefined, type:'buffer_float4', name:argumentsSource[n].split('*')[1].trim()}; } else if(argumentsSource[n].match(/float/gm) != null) { this.in_fragment_values[n] = {value:undefined, type:'buffer_float', name:argumentsSource[n].split('*')[1].trim()}; } } else { if(argumentsSource[n].match(/float4/gm) != null) { this.in_fragment_values[n] = {value:undefined, type:'float4', name:argumentsSource[n].split(' ')[1].trim()}; } else if(argumentsSource[n].match(/float/gm) != null) { this.in_fragment_values[n] = {value:undefined, type:'float', name:argumentsSource[n].split(' ')[1].trim()}; } else if(argumentsSource[n].match(/mat4/gm) != null) { this.in_fragment_values[n] = {value:undefined, type:'mat4', name:argumentsSource[n].split(' ')[1].trim()}; } } } //console.log(this.in_fragment_values); //console.log('original source: '+source); this.fragmentSource = fragmentSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, ''); this.fragmentSource = this.fragmentSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, ''); //console.log('minified source: '+this.fragmentSource); this.fragmentSource = this.parseFragmentSource(this.fragmentSource); if(this.vertexSource != undefined) this.compileVertexFragmentSource(); }; /** @private **/ WebCLGLVertexFragmentProgram.prototype.parseFragmentSource = function(source) { //console.log(source); for(var n = 0, f = this.in_fragment_values.length; n < f; n++) { // for each in_fragment_values (in argument) var regexp = new RegExp(this.in_fragment_values[n].name+'\\[\\w*\\]',"gm"); var varMatches = source.match(regexp);// "Search current "in_fragment_values.name[xxx]" in source and store in array varMatches //console.log(varMatches); if(varMatches != null) { for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]") var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm"); var regexpNativeGLMatches = source.match(regexpNativeGL); if(regexpNativeGLMatches == null) { var name = varMatches[nB].split('[')[0]; var vari = varMatches[nB].split('[')[1].split(']')[0]; var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm"); if(this.in_fragment_values[n].type == 'buffer_float4') source = source.replace(regexp, 'buffer_float4_data('+name+','+vari+')'); if(this.in_fragment_values[n].type == 'buffer_float') source = source.replace(regexp, 'buffer_float_data('+name+','+vari+')'); } } } } source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, ""); //console.log('%c translated source:'+source, "background-color:#000;color:#FFF"); return source; }; /** @private **/ WebCLGLVertexFragmentProgram.prototype.compileVertexFragmentSource = function() { lines_vertex_attrs = (function() { str = ''; for(var n = 0, f = this.in_vertex_values.length; n < f; n++) { if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel') { str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n'; str += 'attribute vec4 '+this.in_vertex_values[n].name+'1;\n'; str += 'attribute vec4 '+this.in_vertex_values[n].name+'2;\n'; str += 'attribute vec4 '+this.in_vertex_values[n].name+'3;\n'; } else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') { str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n'; } else if(this.in_vertex_values[n].type == 'buffer_float4') { str += 'attribute vec4 '+this.in_vertex_values[n].name+';\n'; } else if(this.in_vertex_values[n].type == 'buffer_float') { str += 'attribute float '+this.in_vertex_values[n].name+';\n'; } else if(this.in_vertex_values[n].type == 'float') { str += 'uniform float '+this.in_vertex_values[n].name+';\n'; } else if(this.in_vertex_values[n].type == 'float4') { str += 'uniform vec4 '+this.in_vertex_values[n].name+';\n'; } else if(this.in_vertex_values[n].type == 'mat4') { str += 'uniform mat4 '+this.in_vertex_values[n].name+';\n'; } } return str; }).bind(this); lines_fragment_attrs = (function() { str = ''; for(var n = 0, f = this.in_fragment_values.length; n < f; n++) { if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') { str += 'uniform sampler2D '+this.in_fragment_values[n].name+';\n'; } else if(this.in_fragment_values[n].type == 'float') { str += 'uniform float '+this.in_fragment_values[n].name+';\n'; } else if(this.in_fragment_values[n].type == 'float4') { str += 'uniform vec4 '+this.in_fragment_values[n].name+';\n'; } else if(this.in_fragment_values[n].type == 'mat4') { str += 'uniform mat4 '+this.in_fragment_values[n].name+';\n'; } } return str; }).bind(this); var sourceVertex = this.precision+ 'uniform float uOffset;\n'+ lines_vertex_attrs()+ this.utils.unpackGLSLFunctionString()+ 'vec4 buffer_float4_fromKernel_data(vec4 arg0, vec4 arg1, vec4 arg2, vec4 arg3) {\n'+ 'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+ 'float argY = (unpack(arg1)*(uOffset*2.0))-uOffset;\n'+ 'float argZ = (unpack(arg2)*(uOffset*2.0))-uOffset;\n'+ 'float argW = (unpack(arg3)*(uOffset*2.0))-uOffset;\n'+ 'return vec4(argX, argY, argZ, argW);\n'+ '}\n'+ 'float buffer_float_fromKernel_data(vec4 arg0) {\n'+ 'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+ 'return argX;\n'+ '}\n'+ 'vec2 get_global_id() {\n'+ 'return vec2(0.0, 0.0);\n'+ '}\n'+ this.vertexHead+ 'void main(void) {\n'+ this.vertexSource+ '}\n'; //console.log(sourceVertex); var sourceFragment = this.precision+ lines_fragment_attrs()+ 'vec4 buffer_float4_data(sampler2D arg, vec2 coord) {\n'+ 'vec4 textureColor = texture2D(arg, coord);\n'+ 'return textureColor;\n'+ '}\n'+ 'float buffer_float_data(sampler2D arg, vec2 coord) {\n'+ 'vec4 textureColor = texture2D(arg, coord);\n'+ 'return textureColor.x;\n'+ '}\n'+ 'vec2 get_global_id() {\n'+ 'return vec2(0.0, 0.0);\n'+ '}\n'+ this.fragmentHead+ 'void main(void) {\n'+ this.fragmentSource+ '}\n'; //console.log(sourceFragment); this.vertexFragmentProgram = this.gl.createProgram(); this.utils.createShader(this.gl, "WEBCLGL VERTEX FRAGMENT PROGRAM", sourceVertex, sourceFragment, this.vertexFragmentProgram); this.vertexAttributes = []; // {location,value} this.vertexUniforms = []; // {location,value} this.fragmentSamplers = []; // {location,value} this.fragmentUniforms = []; // {location,value} this.uOffset = this.gl.getUniformLocation(this.vertexFragmentProgram, "uOffset"); // vertexAttributes & vertexUniforms for(var n = 0, f = this.in_vertex_values.length; n < f; n++) { if( this.in_vertex_values[n].type == 'buffer_float4_fromKernel') { this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0"), this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"1"), this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"2"), this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"3")], value:this.in_vertex_values[n].value, type: this.in_vertex_values[n].type}); this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1; } else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') { this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0")], value:this.in_vertex_values[n].value, type: this.in_vertex_values[n].type}); this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1; } else if(this.in_vertex_values[n].type == 'buffer_float4' || this.in_vertex_values[n].type == 'buffer_float') { this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)], value:this.in_vertex_values[n].value, type: this.in_vertex_values[n].type}); this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1; } else if(this.in_vertex_values[n].type == 'float' || this.in_vertex_values[n].type == 'float4' || this.in_vertex_values[n].type == 'mat4') { this.vertexUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)], value:this.in_vertex_values[n].value, type: this.in_vertex_values[n].type}); this.in_vertex_values[n].idPointer = this.vertexUniforms.length-1; } } // fragmentSamplers & fragmentUniforms for(var n = 0, f = this.in_fragment_values.length; n < f; n++) { if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') { this.fragmentSamplers.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)], value:this.in_fragment_values[n].value, type: this.in_fragment_values[n].type}); this.in_fragment_values[n].idPointer = this.fragmentSamplers.length-1; } else if(this.in_fragment_values[n].type == 'float' || this.in_fragment_values[n].type == 'float4' || this.in_fragment_values[n].type == 'mat4') { this.fragmentUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)], value:this.in_fragment_values[n].value, type: this.in_fragment_values[n].type}); this.in_fragment_values[n].idPointer = this.fragmentUniforms.length-1; } } return true; }; /** * Bind float, mat4 or a WebCLGLBuffer to a vertex argument * @type Void * @param {Int|String} argument Id of argument or name of this * @param {Float|Int|WebCLGLBuffer} data */ WebCLGLVertexFragmentProgram.prototype.setVertexArg = function(argument, data) { if(data == undefined) alert("Error: setVertexArg("+argument+", undefined)"); var numArg; if(typeof argument != "string") { numArg = argument; } else { for(var n=0, fn = this.in_vertex_values.length; n < fn; n++) { if(this.in_vertex_values[n].name == argument) { numArg = n; break; } } } if(this.in_vertex_values[numArg] == undefined) { console.log("argument "+argument+" not exist in this vertex program"); return; } this.in_vertex_values[numArg].value = data; if( this.in_vertex_values[numArg].type == 'buffer_float4_fromKernel' || this.in_vertex_values[numArg].type == 'buffer_float_fromKernel' || this.in_vertex_values[numArg].type == 'buffer_float4' || this.in_vertex_values[numArg].type == 'buffer_float') { this.vertexAttributes[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value; } else if(this.in_vertex_values[numArg].type == 'float' || this.in_vertex_values[numArg].type == 'float4' || this.in_vertex_values[numArg].type == 'mat4') { this.vertexUniforms[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value; } }; /** * Bind float or a WebCLGLBuffer to a fragment argument * @type Void * @param {Int|String} argument Id of argument or name of this * @param {Float|Int|WebCLGLBuffer} data */ WebCLGLVertexFragmentProgram.prototype.setFragmentArg = function(argument, data) { if(data == undefined) alert("Error: setFragmentArg("+argument+", undefined)"); var numArg; if(typeof argument != "string") { numArg = argument; } else { for(var n=0, fn = this.in_fragment_values.length; n < fn; n++) { if(this.in_fragment_values[n].name == argument) { numArg = n; break; } } } if(this.in_fragment_values[numArg] == undefined) { console.log("argument "+argument+" not exist in this fragment program"); return; } this.in_fragment_values[numArg].value = data; if(this.in_fragment_values[numArg].type == 'buffer_float4' || this.in_fragment_values[numArg].type == 'buffer_float') { this.fragmentSamplers[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value; } else if(this.in_fragment_values[numArg].type == 'float' || this.in_fragment_values[numArg].type == 'float4' || this.in_fragment_values[numArg].type == 'mat4') { this.fragmentUniforms[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value; } };
"use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), interval: 200, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: false, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, es5: true, strict: true, globalstrict: true }, files: { src: ['Gruntfile.js', 'package.json', 'lib/*.js', 'lib/controllers/**/*.js', 'lib/models/**/*.js', 'lib/utils/**/*.js', 'demo/*.js'] } }, watch: { files: ['<%= jshint.files.src %>'], tasks: ['default'] } }); // npm tasks grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task. grunt.registerTask('default', ['jshint']); };
//borrowed from stefanocudini bootstrap-list-filter (function($) { $.fn.btsListFilterContacts = function(inputEl, options) { var searchlist = this, searchlist$ = $(this), inputEl$ = $(inputEl), items$ = searchlist$, callData, callReq; //last callData execution function tmpl(str, data) { return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { return data[key] || ''; }); } function debouncer(func, timeout) { var timeoutID; timeout = timeout || 300; return function () { var scope = this , args = arguments; clearTimeout( timeoutID ); timeoutID = setTimeout( function () { func.apply( scope , Array.prototype.slice.call( args ) ); }, timeout); }; } options = $.extend({ delay: 300, minLength: 1, initial: true, eventKey: 'keyup', resetOnBlur: true, sourceData: null, sourceTmpl: '<a class="list-group-item" href="#"><tr><h3><span>{title}</span></h3></tr></a>', sourceNode: function(data) { return tmpl(options.sourceTmpl, data); }, emptyNode: function(data) { return '<a class="list-group-item well" href="#"><span>No Results</span></a>'; }, itemEl: '.list-group-item', itemChild: null, itemFilter: function(item, val) { //val = val.replace(new RegExp("^[.]$|[\[\]|()*]",'g'),''); //val = val.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); val = val && val.replace(new RegExp("[({[^.$*+?\\\]})]","g"),''); var text = $.trim($(item).text()), i = options.initial ? '^' : '', regSearch = new RegExp(i + val,'i'); return regSearch.test( text ); } }, options); inputEl$.on(options.eventKey, debouncer(function(e) { var val = $(this).val(); console.log(val); if(options.itemEl) items$ = searchlist$.find(options.itemEl); if(options.itemChild) items$ = items$.find(options.itemChild); var contains = items$.filter(function(){ return options.itemFilter.call(searchlist, this, val); }), containsNot = items$.not(contains); if (options.itemChild){ contains = contains.parents(options.itemEl); containsNot = containsNot.parents(options.itemEl).hide(); } if(val!=='' && val.length >= options.minLength) { contains.show(); containsNot.hide(); if($.type(options.sourceData)==='function') { contains.hide(); containsNot.hide(); if(callReq) { if($.isFunction(callReq.abort)) callReq.abort(); else if($.isFunction(callReq.stop)) callReq.stop(); } callReq = options.sourceData.call(searchlist, val, function(data) { callReq = null; contains.hide(); containsNot.hide(); searchlist$.find('.bts-dynamic-item').remove(); if(!data || data.length===0) $( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$); else for(var i in data) $( options.sourceNode.call(searchlist, data[i]) ).addClass('bts-dynamic-item').appendTo(searchlist$); }); } else if(contains.length===0) { $( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$); } } else { contains.show(); containsNot.show(); searchlist$.find('.bts-dynamic-item').remove(); } }, options.delay)); if(options.resetOnBlur) inputEl$.on('blur', function(e) { $(this).val('').trigger(options.eventKey); }); return searchlist$; }; })(jQuery);
/*! * jquery.initialize. An basic element initializer plugin for jQuery. * * Copyright (c) 2014 Barış Güler * http://hwclass.github.io * * Licensed under MIT * http://www.opensource.org/licenses/mit-license.php * * http://docs.jquery.com/Plugins/Authoring * jQuery authoring guidelines * * Launch : July 2014 * Version : 0.1.0 * Released: July 29th, 2014 * * * makes an element initialize for defined events with their names */ (function ($) { $.fn.initialize = function (options) { var currentElement = $(this), opts = options; var getSize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var setEvents = function () { for (var countForEventsObj = 0, len = getSize(opts.events); countForEventsObj < len; countForEventsObj++) { $(this).on(opts.events[countForEventsObj].name, opts.events[countForEventsObj].funcBody) } } if (opts.init) { setEvents(); } return this; } })(jQuery);
/** * utility library */ var basicAuth = require('basic-auth'); var fs = require('fs'); /** * Simple basic auth middleware for use with Express 4.x. * * @example * app.use('/api-requiring-auth', utils.basicAuth('username', 'password')); * * @param {string} username Expected username * @param {string} password Expected password * @returns {function} Express 4 middleware requiring the given credentials */ exports.basicAuth = function(username, password) { return function(req, res, next) { var user = basicAuth(req); if (!user || user.name !== username || user.pass !== password) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); return res.sendStatus(401); } next(); }; }; exports.cpuTemp = function() { var cputemp = Math.round(((parseFloat(fs.readFileSync("/sys/class/thermal/thermal_zone0/temp"))/1000) * (9/5) + 32)*100)/100; return cputemp; }; exports.w1Temp = function(serial) { var temp; var re=/t=(\d+)/; try { var text=fs.readFileSync('/sys/bus/w1/devices/' + serial + '/w1_slave','utf8'); if (typeof(text) != "undefined") { if (text.indexOf("YES") > -1) { var temptext=text.match(re); if (typeof(temptext) != "undefined") { temp = Math.round(((parseFloat(temptext[1])/1000) * (9/5) + 32)*100)/100; } } } } catch (e) { console.log(e); } return temp; };
version https://git-lfs.github.com/spec/v1 oid sha256:5f5740cfcc24e2a730f7ea590ae0dc07d66d256fd183c46facf3fdfeb0bd69d2 size 3654
version https://git-lfs.github.com/spec/v1 oid sha256:467bccdb74ef62e6611ba27f338a0ba0c49ba9a90ef1facb394c14de676318cf size 1150464
version https://git-lfs.github.com/spec/v1 oid sha256:4f8b1998d2048d6a6cabacdfb3689eba7c9cb669d6f81dbbd18156bdb0dbe18f size 1880
import React from 'react' import { FormControl } from 'react-bootstrap' import './@FilterListInput.css' const FilterListInput = ({onFilter, searchValue}) => { let handleFilter = e => { onFilter(e.target.value) } return (<FormControl className='FilterListInput' type='text' defaultValue={searchValue} placeholder='Search within this list...' onChange={handleFilter.bind(this)} />) } export default FilterListInput
/*! * ear-pipe * Pipe audio streams to your ears * Dan Motzenbecker <[email protected]> * MIT Licensed */ "use strict"; var spawn = require('child_process').spawn, util = require('util'), Duplex = require('stream').Duplex, apply = function(obj, method, args) { return obj[method].apply(obj, args); } var EarPipe = function(type, bits, transcode) { var params; if (!(this instanceof EarPipe)) { return new EarPipe(type, bits, transcode); } Duplex.apply(this); params = ['-q', '-b', bits || 16, '-t', type || 'mp3', '-']; if (transcode) { this.process = spawn('sox', params.concat(['-t', typeof transcode === 'string' ? transcode : 'wav', '-'])); } else { this.process = spawn('play', params); } } util.inherits(EarPipe, Duplex); EarPipe.prototype._read = function() { return apply(this.process.stdout, 'read', arguments); } EarPipe.prototype._write = function() { return apply(this.process.stdin, 'write', arguments); } EarPipe.prototype.pipe = function() { return apply(this.process.stdout, 'pipe', arguments); } EarPipe.prototype.end = function() { return apply(this.process.stdin, 'end', arguments); } EarPipe.prototype.kill = function() { return apply(this.process, 'kill', arguments); } module.exports = EarPipe;
/** * @description - The purpose of this model is to lookup various Drinking activities for a user */ var baseModel = require('./base'); var Drink; Drink = baseModel.Model.extend({ tableName: 'drink' }); module.exports = baseModel.model('Drink', Drink);
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module', ecmaFeatures: { 'jsx': true }, }, globals: { enz: true, xhr_calls: true, }, plugins: [ 'react' ], extends: 'react-app', rules: { 'semi': [2, 'never'], // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 2, // allow debugger during development 'no-debugger': 2, 'comma-danglcd e': 0, 'camelcase': 0, 'no-alert': 2, 'space-before-function-paren': 2, 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2, } }
define(['jquery'], function ($) { if (!Array.prototype.reduce) { /** * Array.prototype.reduce polyfill * * @param {Function} callback * @param {Value} [initialValue] * @return {Value} * * @see http://goo.gl/WNriQD */ Array.prototype.reduce = function (callback) { var t = Object(this), len = t.length >>> 0, k = 0, value; if (arguments.length === 2) { value = arguments[1]; } else { while (k < len && !(k in t)) { k++; } if (k >= len) { throw new TypeError('Reduce of empty array with no initial value'); } value = t[k++]; } for (; k < len; k++) { if (k in t) { value = callback(value, t[k], k, t); } } return value; }; } if ('function' !== typeof Array.prototype.filter) { /** * Array.prototype.filter polyfill * * @param {Function} func * @return {Array} * * @see http://goo.gl/T1KFnq */ Array.prototype.filter = function (func) { var t = Object(this), len = t.length >>> 0; var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (func.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } var isSupportAmd = typeof define === 'function' && define.amd; /** * @class core.agent * * Object which check platform and agent * * @singleton * @alternateClassName agent */ var agent = { /** @property {Boolean} [isMac=false] true if this agent is Mac */ isMac: navigator.appVersion.indexOf('Mac') > -1, /** @property {Boolean} [isMSIE=false] true if this agent is a Internet Explorer */ isMSIE: navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1, /** @property {Boolean} [isFF=false] true if this agent is a Firefox */ isFF: navigator.userAgent.indexOf('Firefox') > -1, /** @property {String} jqueryVersion current jQuery version string */ jqueryVersion: parseFloat($.fn.jquery), isSupportAmd: isSupportAmd, isW3CRangeSupport: !!document.createRange }; return agent; });
ml.module('three.scenes.Fog') .requires('three.Three', 'three.core.Color') .defines(function(){ /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ THREE.Fog = function ( hex, near, far ) { this.color = new THREE.Color( hex ); this.near = ( near !== undefined ) ? near : 1; this.far = ( far !== undefined ) ? far : 1000; }; });
/** * @file Generate ico image files. * @memberof module:ci/tasks * @function icoTask * @param grunt * @param {object} config - Task configuration. * @param {function} callback - Callback when done. * */ "use strict"; var ico = require('../../lib/commands/ico'); module.exports = function (grunt, config, callback) { ico(config.src, config.dest, {}, function (err) { if (!err) { grunt.log.writeln('ICO file created: %s', config.dest); callback(err); } }); };
'use strict'; const path = require('path') const webpack = require('webpack') const pkg = require('./package.json') const HtmlWebpackPlugin = require('html-webpack-plugin') const WebpackNotifierPlugin = require('webpack-notifier') var paths = { dist: path.join(__dirname, 'dist'), src: path.join(__dirname, 'src') } const baseAppEntries = [ './src/index.jsx' ]; const devAppEntries = [ 'webpack-dev-server/client', 'webpack/hot/only-dev-server' ]; const appEntries = baseAppEntries .concat(process.env.NODE_ENV === 'development' ? devAppEntries : []); const basePlugins = [ new webpack.DefinePlugin({ __DEV__: process.env.NODE_ENV !== 'production', 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].js'), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'body' }) ]; const devPlugins = [ new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: pkg.name }) ]; const prodPlugins = [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]; const plugins = basePlugins .concat(process.env.NODE_ENV === 'production' ? prodPlugins : []) .concat(process.env.NODE_ENV === 'development' ? devPlugins : []); module.exports = { entry: { app: appEntries, vendor: [ 'es5-shim', 'es6-shim', 'es6-promise', 'react', 'react-dom', 'react-redux', 'redux', 'redux-thunk' ] }, output: { path: paths.dist, filename: '[name].[hash].js', publicPath: '/', sourceMapFilename: '[name].[hash].js.map', chunkFilename: '[id].chunk.js' }, devtool: 'eval-source-map', resolve: { extensions: ['', '.jsx', '.js', '.css'] }, plugins: plugins, // devServer: { // historyApiFallback: { index: '/' }, // proxy: proxy(), // }, module: { preLoaders: [ { test: /\.js$/, loader: "eslint", exclude: /node_modules/ } ], loaders: [{ test: /\.(jsx|js)?$/, loader: 'react-hot!babel', include: paths.src, exclude: /(\.test\.js$)/ }, { test: /\.css$/, loaders: ['style', 'css?modules&localIdentName=[local]---[hash:base64:5]', 'postcss'], include: paths.src }, { test: /\.html$/, loader: 'raw', exclude: /node_modules/ } ] }, postcss: function (webpack) { return [ require("postcss-import")({ addDependencyTo: webpack }), require("postcss-url")(), require("postcss-custom-properties")(), require("postcss-nesting")(), require("postcss-cssnext")(), require("postcss-browser-reporter")(), require("postcss-reporter")() ] } };
var EcommerceProductsEdit = function () { var handleImages = function() { // see http://www.plupload.com/ var uploader = new plupload.Uploader({ runtimes : 'html5,html4', browse_button : document.getElementById('tab_images_uploader_pickfiles'), // you can pass in id... container: document.getElementById('tab_images_uploader_container'), // ... or DOM Element itsel url : "assets/ajax/product-images.php", filters : { max_file_size : '10mb', mime_types: [ {title : "Image files", extensions : "jpg,gif,png"}, ] }, multipart_params: {'oper': "addproductimages"}, // Flash settings flash_swf_url : 'assets/global/plugins/plupload/js/Moxie.swf', // Silverlight settings silverlight_xap_url : 'assets/global/plugins/plupload/js/Moxie.xap', init: { PostInit: function() { $('#tab_images_uploader_filelist').html(""); $('#tab_images_uploader_uploadfiles').click(function() { uploader.start(); return false; }); $('#tab_images_uploader_filelist').on('click', '.added-files .remove', function(){ uploader.removeFile($(this).parent('.added-files').attr("id")); $(this).parent('.added-files').remove(); }); }, BeforeUpload: function(up, file) { }, FilesAdded: function(up, files) { plupload.each(files, function(file) { $('#tab_images_uploader_filelist').append('<div class="alert col-md-6 col-sm-12 alert-warning added-files" id="uploaded_file_' + file.id + '">' + file.name + '(' + plupload.formatSize(file.size) + ') <span class="status label label-info"></span>&nbsp;<a href="javascript:;" style="margin-top:0px" class="remove pull-right btn btn-xs red"><i class="fa fa-times"></i> </a></div>'); }); }, UploadProgress: function(up, file) { $('#uploaded_file_' + file.id + ' > .status').html(file.percent + '%'); }, FileUploaded: function(up, file, response) { var response = $.parseJSON(response.response); if (response.error && response.error == 'no') { var $uplaod_path = "../images/products/"; var newfile = response.newfilename.trim(); // uploaded file's unique name. Here you can collect uploaded file names and submit an jax request to your server side script to process the uploaded files and update the images tabke if(newfile != ""){ $image_names = $("#image-names").val(); $img_lists = new Array(); $img_lists.push(newfile); if($image_names != ""){ $img_lists = $image_names.split("::::"); $img_lists.push(newfile); } $("#image-names").val($img_lists.join("::::")); $('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-success").html('<i class="fa fa-check"></i> Done'); // set successfull upload var imgContaint = '<div class="col-md-3 product-image-div"><div class=mt-overlay-1><div class=item-image><img alt="'+newfile+'"src="'+$uplaod_path+newfile+'"></div><div class=mt-overlay><ul class=mt-info><li><a class="btn btn-outline green" href="'+$uplaod_path+newfile+'"><i class=icon-magnifier></i></a><li><a class="btn btn-outline btn-product-image-delete red" href=javascript:; data-image="'+newfile+'"><i class="fa fa-trash-o"></i></a></ul></div></div></div>'; $('#Product-iamge-list').append(imgContaint); } } else { $('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-danger").html('<i class="fa fa-warning"></i> Failed'); // set failed upload Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'}); } }, Error: function(up, err) { Metronic.alert({type: 'danger', message: err.message, closeInSeconds: 10, icon: 'warning'}); } } }); uploader.init(); // delete images(); //varient image handing var optgroupContainer = $("#optiongroup-containner"); optgroupContainer.on("click", ".option-img-upload", function(e){ e.preventDefault(); $(this).closest('.mt-overlay-1').find(".option-img-upload-input").trigger("click"); }); optgroupContainer.on("change", ".option-img-upload-input", function(e){ e.preventDefault(); var $fileInput = $(this); var fileInputImageContainer = $(this).closest('.mt-overlay-1'); var el = $fileInput.closest(".portlet").children(".portlet-body"); var $oper = 'saveoptionimage'; //over initialization Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); var formData = new FormData(); formData.append('oper', $oper); formData.append('file', $fileInput[0].files[0]); $.ajax({ url: "assets/ajax/ajax1.php", data: formData, method: "post", contentType: false, processData: false, dataType: 'json', success : function(response){ if(response.error == "no"){ var d = new Date(); fileInputImageContainer.find("img").attr('src', "../images/products/"+response.filename+"?"+d.getTime()); fileInputImageContainer.find('input[name^="product-option-img"]').val(response.filename); $fileInput.val(''); }else{ Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'}); } } }); Metronic.unblockUI(el); }); } var initComponents = function(){ var summerEditer = $('#product-description'); summerEditer.summernote({ height: 150, // set editor height minHeight: 100, // set minimum height of editor maxHeight: 300, // set maximum height of editor placeholder: 'Product Description here...', toolbar: [ ['style', ['bold', 'italic', 'underline', 'clear']], ['font', ['superscript', 'subscript']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']] ] }); $('.note-editable').on('blur', function() { if($(summerEditer.summernote('code')).text().length > 20){ $('.summernote-error').hide(); }else{ $('.summernote-error').show(); } }); $.fn.select2.defaults.set("theme", "bootstrap"); $.fn.select2.defaults.set("id", function(object){ return object.text; }); $.fn.select2.defaults.set("tags", true); /*$.fn.select2.defaults.set("createTag", function (params) { return { id: params.term, text: params.term, newOption: true}}); $.fn.select2.defaults.set("createSearchChoice", function(term, data){ if ( $(data).filter( function() { return term.localeCompare(this.text)===0; //even if the this.text is undefined it works }).length===0) { if(confirm("Are you do you want to add item.")){ return {id:term, text:term};} } }) */ // non casesensetive matcher.... $.fn.select2.defaults.set("matcher", function(params, data) { // If there are no search terms, return all of the data if ($.trim(params.term) === '') { return data; } // `params.term` should be the term that is used for searching // `data.text` is the text that is displayed for the data object if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) { return data; } // Return `null` if the term should not be displayed return null; }); // non casesensitive tags creater $.fn.select2.defaults.set("createTag", function(params) { var term = $.trim(params.term); if(term === "") { return null; } var optionsMatch = false; this.$element.find("option").each(function() { // if(this.value.toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare values if($(this).text().toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare option text optionsMatch = true; } }); if(optionsMatch) { return null; } return {id: term, text: term, tag:true}; }); $('#product-category').select2({placeholder:"Select Category"}); $('#product-brand').select2({placeholder:"Select Manufacturer"}); $("#product-collection").select2().on("select2:select", function(e){ if(e.params.data.tag == true){ $this = $(this); var el = $this.closest(".portlet").children(".portlet-body"); Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); $.post("assets/ajax/ajax1.php", {"oper": "saverandomcollection", "collection-name": $.trim(e.params.data.text)}, function(data){ Metronic.unblockUI(el); if(data.error == "no"){ $('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this); } }, "json"); } }); $("#product-tags").select2(); var removeArrayItem = function (array, item){ for(var i in array){ if(array[i]==item){ array.splice(i,1); break; } } } $("#Product-iamge-list").on("click", ".btn-product-image-delete", function(){ var $this = $(this); if(confirm("Are you sure you want to remove image")){ var $image_container = $this.closest(".product-image-div"); var $img_name = $this.data("image"); var el = $(this).closest(".portlet").children(".portlet-body"); Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); $.post( "assets/ajax/product-images.php", {'product-image':$img_name, 'oper':'deleteproductimages'},function(data){ data = jQuery.parseJSON(data); if(data.error =="no"){ $image_container.fadeOut(300, function(){ $(this).remove();}); var $image_names = $("#image-names").val(); var $img_lists = new Array(); if($image_names != ""){ $img_lists = $image_names.split("::::"); removeArrayItem($img_lists, $img_name); } $("#image-names").val($img_lists.join("::::")); } Metronic.unblockUI(el); }); } }); // product attribuets var addCustomAttrVal = function(){ $('select[name^="product-attributes-value"]').select2().on("select2:select", function(e){ $this = $(this); $attribute_id = $.trim($this.data("attribute")); if(e.params.data.tag == true && $attribute_id > 0){ var el = $this.closest(".portlet").children(".portlet-body"); Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); $.post("assets/ajax/ajax1.php", {"oper": "savenewattributevalue", "attribute-value": $.trim(e.params.data.text), "attribute-id":$attribute_id}, function(data){ Metronic.unblockUI(el); if(data.error == "no"){ $('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this); } }, "json"); } }); } $("#product-category").on('change', function(){ $(".categoey-name-span").html($(this).find(":selected").html()); }); $(".categoey-name-span").html($("#product-category").find(":selected").html()); $("#btn-attribute-load").on("click", function(e){ e.preventDefault(); var filled_field = false; $('input[name^="product-attributes-value"]').each(function() { if($.trim($(this).val())){ filled_field = true; return false; } }); var Confirm = true; if(filled_field) Confirm = confirm("Previous specification data will erased. Are you sure want to reload Specification data."); if(Confirm){ var el = $(this).closest(".portlet").children(".portlet-body"); Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); $.post( "assets/ajax/ajax1.php", {'category-id':$("#product-category").val(), 'oper':'getattributebycategory'},function(data){ data = $.parseJSON(data); if(data.error =="no"){ var $_html = ""; if(!$.isEmptyObject(data.attributeCollection)){ $i = 0; $.each(data.attributeCollection, function(index, attributeGroup){ $_html += '<tr><td colspan="2" class="text-danger text-center"><strong>' + attributeGroup.name + '</strong></td></tr>'; $.each(attributeGroup.attributes, function(indexJ, attribute){ $_html += '<tr><td class="text-right"><label class="control-label input-sm">'+attribute.text +' : </label></td><input type="hidden" name="product-attributes-id['+$i+']" value="' + attribute.id + '"/><td>' if(attribute.isfilter > 0){ $_html += '<select data-attribute="' + attribute.id + '" style="width:100%;" name="product-attributes-value['+$i+']" class="form-control input-sm">'; var filterArray = attribute.filters.split(","); $.each(filterArray, function(index, filter){ $_html += '<option value = "'+filter+'">'+filter+'</option>'; }); $_html += "</select>"; }else{ $_html += '<input type="type" name="product-attributes-value['+$i+']" class="form-control input-sm">'; } $_html += '</td></tr>'; $i++; }); }); }else{ $_html = '<tr><td colspan="2" class="text-center">No Attributes Found. </td></tr>'; } $("#attribute-list-table tbody").html($_html); addCustomAttrVal(); } Metronic.unblockUI(el); }); } }); addCustomAttrVal(); $("img", "#Product-iamge-list").error(function() { $this = $(this); $this.error = null; $this.attr("src", "http://placehold.it/400?text=image") }); $('[data-toggle="tooltip"]').tooltip(); // product varients var optiongroupMaster = $("#optiongroupmaster").html(); var optgroupContainer = $("#optiongroup-containner"); var createCombinations = function($elements){ var CombinationArray = {}; var $i = 0; $elements.each(function(index, element){ var SelectedOptGgroup = $(element).select2("data"); if(SelectedOptGgroup.length > 0){ var temp_array = {}; $.each(SelectedOptGgroup, function(index, data){ temp_array[index] = {text:data.text, id:data.id}; }); CombinationArray[$i++] = temp_array; } }); var $totalCombinations = {}; var i=0, k=0; var combinations = []; $.each(CombinationArray, function(index1, varients){ if(i== 0){ //combinations = varients; $.each(varients, function(index, varient){ combinations.push(varient); }); }else{ k = 0; tempCombination = []; $.each(combinations, function(index2, combination){ $.each(varients, function(index3, varient){ tempCombination[k] = []; if(i == 1){ tempCombination[k].push(combination); }else{ $.each(combination, function(index4, subCombination){ tempCombination[k].push(subCombination); }); } tempCombination[k].push(varient); k++; }); }); combinations = tempCombination; } i++; }); return combinations; } var loadCombination = function(){ var $combinations = createCombinations($(".product-options-select2", optgroupContainer)); var $_html = ""; $.each($combinations, function(index, combination){ $_html += '<tr><td class="text-center">'; var combination_id = []; if(Array.isArray(combination)){ combination_length = combination.length; $.each(combination, function(index1, varient){ $_html += '<label class="label label-sm label-success lh2"><strong>'+varient.text+'</strong></label>'; combination_id.push(varient.id); if(index1+1 < combination_length) $_html += " X "; }); }else{ $_html += '<label class="label label-sm label-success lh2"><strong>'+combination.text+'</strong></label>'; combination_id.push(combination.id); } var comb_id_text = combination_id.join("-") $_html += '<input type="hidden" name="combination-id[]" value="'+comb_id_text+'"></td><td><input type="text" name="combination-qty['+comb_id_text+']" placeholder="Quantity" class="form-control input-sm"></td><td><input type="text" name="combination-price['+comb_id_text+']" placeholder="Price" class="form-control input-sm"></td><!---<td><button type="button" class="btn btn-sm red btn-combination-delete">Delete</button></td>---></tr>'; }); $("tbody", "#verient-form-table").html($_html); } var has_img_html = ''; var insertImageDiv = function(id, text){ return '<div class="col-md-3 col-sm-6 text-center" id="selected-option-'+id+'" ><div class="mt-overlay-1"><div class="item-image"><img src="http://placehold.it/400?text='+text+'"></div><div class="mt-overlay"><ul class="mt-info"><li><input type="file" class="option-img-upload-input display-hide"><input type="hidden" name="product-option-img['+id+']"><a class="btn green btn-outline" href="javascript:;"><i class="icon-magnifier"></i></a></li><li><a class="btn yellow btn-outline option-img-upload" href="javascript:;"><i class="fa fa-upload"></i></a></li></ul></div></div><div class="bg-blue label-full">'+text+'</div></div>'; } $(".product-options-select2", optgroupContainer).select2({tags : false}); $("#add_attrbut_btn").on("click", function(){ optgroupContainer.append(optiongroupMaster); var otgrouplength = optgroupContainer.find(".optiongroups").length - 1; var lastOptgroup = optgroupContainer.find(".optiongroups:last"); lastOptgroup.find(".product-options-select2:last").select2({tags: false}) .on("change", function(e) { $this = $(this); e.preventDefault(); loadCombination(); }) .on("select2:select", function(e){ $this = $(this); if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image") $this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text)); }) .on("select2:unselect", function(e){ $this = $(this); $this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove(); }) }); optgroupContainer.find(".product-options-select2").select2() .on("change", function(e) { e.preventDefault(); loadCombination(); }) .on("select2:select", function(e){ $this = $(this); if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image") $this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text)); }) .on("select2:unselect", function(e){ $this = $(this); $this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove(); }); optgroupContainer.on('click', ".optiongroup-delete-btn" , function(){ $(this).closest(".optiongroups").fadeOut(300, function(){ $(this).remove(); loadCombination();}); }); optgroupContainer.on("change", '.product-optgroup-select', function(){ var $this = $(this); $found = false; optgroupContainer.find(".product-optgroup-select").each(function(index, optgroup_select){ if($this.val() == $(optgroup_select).val() && !$this.is($(optgroup_select))){ $found = true; return; } }); if($found){ Metronic.alert({type: 'danger', message: "This varient is already selected", closeInSeconds: 4, icon: 'warning'}); $this.val("").trigger("change"); return; } var optionGroupSelect = $this.closest(".optiongroups").find('.product-options-select2'); optionGroupSelect.select2("val", ""); if($.trim($this.val()) > 0){ $.post("assets/ajax/ajax1.php", {"option-group-id": $this.val(), "oper": "getoptionbyoptiongroup"}, function(data){ data = $.parseJSON(data); if(data.error == "no"){ var $_html = ""; $.each(data.options, function(index, option){ $_html += '<option value="'+option.id+'">'+option.text+'</option>'; }); optionGroupSelect.html($_html); $this.closest(".optiongroups").find(".optgroup-image-div .swatches").html(""); } }); } if($this.find("option:selected").data("type") == "image"){ $this.closest(".optiongroups").find(".optgroup-image-btn").removeClass("display-hide"); $this.closest(".optiongroups").find(".optgroup-image-div").collapse("show"); }else{ $this.closest(".optiongroups").find(".optgroup-image-btn").addClass("display-hide"); $this.closest(".optiongroups").find(".optgroup-image-div").collapse("hide"); } }); $("#verient-form-table tbody").on("click", ".btn-combination-delete",function(){ $(this).closest("tr").fadeOut(300, function(){ $(this).remove()}); }); optgroupContainer.on("click", ".optgroup-image-btn",function(e){ e.preventDefault(); $(this).closest(".optiongroups").find(".optgroup-image-div").collapse("toggle"); }); } var handleForms = function() { $.validator.setDefaults({ highlight: function(element) { $(element).closest('.form-group').addClass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeClass('has-error'); }, errorElement: 'span', errorClass: 'help-block', errorPlacement: function(error, element) { if(element.parent('.input-group').length) { error.insertAfter(element.parent()); } else { error.insertAfter(element); } } }); var product_form_validater = $("#product-form").validate(); $("#tab_images_uploader_pickfiles").on('click', function(){ $(".alert-product-image").hide(); }); $("#product-form").on('submit', function(e){ e.preventDefault(); $(".alert-product-image").hide(); if(product_form_validater.valid() === true){ $this = $(this); var el = $this.closest(".portlet").children(".portlet-body"); image_vals = $("#image-names").val().trim(); $productDescription = $('#product-description').summernote('code'); if($($productDescription).text().length < 20){ // summernote validation.... $('.summernote-error').show(); $('#product-description').summernote('focus'); return false; Metronic.unblockUI(el); } if(image_vals == "" || image_vals.indexOf(".") < 5){ // image valiadation $(".alert-product-image").fadeIn("300").show(); var $target = $('html,body'); $target.animate({scrollTop: $target.height()}, 1000); return false; Metronic.unblockUI(el); } var $data = $this.serializeArray(); // convert form to array $data.push({name: "product-description", value: $productDescription}); var optionGroups = $(".optiongroups", "#optiongroup-containner"); if(optionGroups.length > 0){ optionGroups.each(function(index, optiongroup){ $data.push({name: "product-optgroup["+index+"]", value: $(optiongroup).find(".product-optgroup-select").val()}); $data.push({name: "product-opttype["+index+"]", value: $(optiongroup).find(".product-optgroup-select option:selected").data("type")}); $data.push({name: "product-options["+index+"]", value: $(optiongroup).find(".product-options-select2").select2("val")}); }); } //Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' }); $.post( "assets/ajax/ajax1.php", $data, function(data){ data = jQuery.parseJSON(data); if(data.error =="no"){ var ClickBtnVal = $("[type=submit][clicked=true]", $this).data("value"); if(ClickBtnVal == "save-exit"){ location.href="products.php?Saved=Successfully"; }else{ Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'}); } }else{ Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'}); } Metronic.unblockUI(el); }); } }); $("form button[type=submit], form input[type=submit]").click(function() { $("button[type=submit], input[type=submit]", $(this).parents("form")).removeAttr("clicked"); $(this).attr("clicked", "true"); }); } return { //main function to initiate the module init: function () { handleImages(); initComponents(); handleForms(); } }; }();
var dotBeautify = require('../index.js'); var fs = require('fs'); var chai = require('chai'); var assert = chai.assert; var expect = chai.expect; var setup = 'function start (resp)\ {\ resp.writeHead(200, {"Content-Type": "text/html"\ });\ fs.readFile(filename, "utf8", function(err, data) {\ if (err) throw err;\ resp.write(data);resp.end ();});\ }'; describe('dotbeautify', function() { before(function() { fs.writeFileSync(__dirname + '/data/badFormat.js', setup, 'utf8'); }); it('Beautify the horribly formatted code without a config', function() { dotBeautify.beautify([__dirname + '/data/']); var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8'); var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8'); if(properFormat == badFormat) { return true; } }); it('Beautify the horribly formatted code with a given config', function() { dotBeautify.beautify([__dirname + '/data/'], { indent_size: 8 }); var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8'); var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8'); if(properFormat == badFormat) { return true; } }); it('Should throw an error upon not passing any directories in', function() { expect(function() { dotBeautify.beautify([],{}); }).to.throw(Error); }); });
function Block() { this.isAttacked = false; this.hasShip = false; this.shipType = "NONE"; this.attackable = true; this.shipSize = 0; this.direction = "no" } function Ship(x,y,direction,size){ this.x = x; this.y = y; this.direction = direction; this.size = size; this.win = false; } var bKimage = document.getElementById("OL"); function GameMap(x, y, scale,ctx) { this.x = x; this.y = y; this.ctx =ctx; this.scale = scale; this.length = scale / 11; this.mapGrid = new Array(10); this.mapX = this.x + this.length; this.mapY = this.y + this.length; this.ships = []; this.adjustScale = function(num){ this.scale = num; this.length = this.scale / 11; this.mapX = this.x + this.length; this.mapY = this.y + this.length; } //ship info this.sinkList = new Array(5); for(var i = 0 ; i < 5 ; i++) this.sinkList[i]= false; this.win = function(){ for(var i = 0 ; i < 10 ; i++){ for(var j = 0 ;j < 10 ; j++){ if(this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked){ return false; } } } return true; } this.updateSink = function (){ var count = [0,0,0,0,0]; for(var i = 0 ;i < 10 ; i++){ for(var j = 0 ;j < 10 ; j++){ if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){ if(this.mapGrid[j][i].shipType == AIRCRAFT_CARRIER) count[AIRCRAFT_CARRIER]++; if(this.mapGrid[j][i].shipType == BATTLESHIP) count[BATTLESHIP]++; if(this.mapGrid[j][i].shipType == CRUISER) count[CRUISER]++; if(this.mapGrid[j][i].shipType == SUBMARINE) count[SUBMARINE]++; if(this.mapGrid[j][i].shipType == DESTROYER) count[DESTROYER]++; } } } for(var i = 0 ;i < 5 ; i++){ if(count[AIRCRAFT_CARRIER]==5){ this.sinkList[AIRCRAFT_CARRIER]=true; this.updataAttackable(AIRCRAFT_CARRIER); } if(count[BATTLESHIP]==4){ this.sinkList[BATTLESHIP]=true; this.updataAttackable(BATTLESHIP); } if(count[CRUISER]==3){ this.sinkList[CRUISER]=true; this.updataAttackable(CRUISER); } if(count[SUBMARINE]==3){ this.sinkList[SUBMARINE]=true; this.updataAttackable(SUBMARINE); } if(count[DESTROYER]==2){ this.sinkList[DESTROYER]=true; this.updataAttackable(DESTROYER); } } //console.log(count); } this.updataAttackable = function(type){ for(var b = 0 ;b < 10 ; b++){ for(var a = 0 ;a < 10 ; a++){ if(this.mapGrid[a][b].shipType == type){ if(this.inIndex(a-1,b) && !this.hasShip(a-1,b) && !this.mapGrid[a-1][b].isAttacked) this.mapGrid[a-1][b].attackable = false; if(this.inIndex(a+1,b) && !this.hasShip(a+1,b) && !this.mapGrid[a+1][b].isAttacked) this.mapGrid[a+1][b].attackable = false; if(this.inIndex(a-1,b+1) && !this.hasShip(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked) this.mapGrid[a-1][b+1].attackable = false; if(this.inIndex(a+1,b+1) && !this.hasShip(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked) this.mapGrid[a+1][b+1].attackable = false; if(this.inIndex(a-1,b-1) && !this.hasShip(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked) this.mapGrid[a-1][b-1].attackable = false; if(this.inIndex(a+1,b-1) && !this.hasShip(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked) this.mapGrid[a+1][b-1].attackable = false; if(this.inIndex(a,b+1) && !this.hasShip(a,b+1) && !this.mapGrid[a][b+1].isAttacked) this.mapGrid[a][b+1].attackable = false; if(this.inIndex(a,b-1) && !this.hasShip(a,b-1) && !this.mapGrid[a][b-1].isAttacked) this.mapGrid[a][b-1].attackable = false; } } } } this.inIndex = function(a,b){ if(a < 0 || a > 9 || b < 0 || b >9) return false; return true; } this.resetMap = function() { for (var i = 0; i < 10; i++) { this.mapGrid[i] = new Array(10); } for (var i = 0; i < 10; i++) { for (var j = 0; j < 10; j++) { this.mapGrid[i][j] = new Block(); } } } this.imgBG = document.getElementById("LB"); this.drawMap = function() { this.ctx.font = "" + this.length + "px airborne"; this.ctx.fillStyle = "rgba(221,221,255,0.6)"; this.ctx.drawImage(this.imgBG,10,10,450,450,this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length); this.ctx.fillRect(this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length); this.ctx.strokeRect(this.x, this.y, this.scale, this.scale); this.ctx.fillStyle = "#ddddff"; for (var i = 1; i <= 10; i++) { this.ctx.moveTo(this.x + i * this.length, this.y); this.ctx.lineTo(this.x + i * this.length, this.y + this.scale); this.ctx.stroke(); this.ctx.fillText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10); this.ctx.strokeText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10); } for (var i = 1; i <= 10; i++) { this.ctx.moveTo(this.x, this.y + i * this.length); this.ctx.lineTo(this.x + this.scale, this.y + i * this.length); this.ctx.stroke(); this.ctx.fillText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10); this.ctx.strokeText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10); } } this.drawMark = function(shipOption){ for(var i = 0 ;i < 10 ; i++){ for(var j = 0 ;j < 10 ; j++){ if(shipOption && this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked ){ var a = this.mapX + j*this.length; var b = this.mapY + i*this.length; this.drawShip(a,b); } if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){ var a = this.mapX + j*this.length; var b = this.mapY + i*this.length; this.drawHit(a,b); } if(!this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){ var a = this.mapX + j*this.length; var b = this.mapY + i*this.length; this.drawWave(a,b); } if(!this.mapGrid[j][i].attackable && hintSys){ var a = this.mapX + j*this.length; var b = this.mapY + i*this.length; this.drawHint(a,b); } } } } this.shipAttacked=function(a,b){ if(a>this.mapX && a<this.mapX+10*this.length && b>this.mapY && b<this.mapY+this.length*10){ a=a-this.mapX; b=b-this.mapY; a=Math.floor(a/this.length); b=Math.floor(b/this.length); if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){ return true; } this.mapGrid[a][b].isAttacked = true; console.log(a + ", " + b); this.drawMark(); this.updateSink(); if(this.mapGrid[a][b].hasShip == true){ shipHit(); if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){ this.mapGrid[a+1][b+1].attackable = false; } if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){ this.mapGrid[a+1][b-1].attackable = false; } if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){ this.mapGrid[a-1][b+1].attackable = false; } if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){ this.mapGrid[a-1][b-1].attackable = false; } this.drawMark(); return true; } else{ missedHit(); return false; } } return true; } this.aiAttack = function(a,b){ console.log(a + ", " + b); if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){ return true; } this.mapGrid[a][b].isAttacked = true; this.drawMark(); this.updateSink(); if(this.mapGrid[a][b].hasShip == true){ if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){ this.mapGrid[a+1][b+1].attackable = false; } if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){ this.mapGrid[a+1][b-1].attackable = false; } if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){ this.mapGrid[a-1][b+1].attackable = false; } if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){ this.mapGrid[a-1][b-1].attackable = false; } this.drawMark(); return true; } else{ return false; } return true; } this.drawShip = function(a,b){ var temp = this.ctx.fillStyle; this.ctx.fillStyle = "blue"; this.ctx.fillRect(a,b,this.length,this.length); this.ctx.fillStyle = temp; } this.drawHit = function(a,b){ var temp = this.ctx.fillStyle; this.ctx.fillStyle = "red"; this.ctx.fillRect(a,b,this.length,this.length); this.ctx.fillStyle = temp; } this.drawWave = function(a,b){ var temp = this.ctx.fillStyle; this.ctx.fillStyle = "Grey"; this.ctx.fillRect(a,b,this.length,this.length); this.ctx.fillStyle = temp; } this.drawHint = function(a,b){ var temp = this.ctx.fillStyle; this.ctx.fillStyle = "#DDDDDD"; this.ctx.fillRect(a,b,this.length,this.length); this.ctx.fillStyle = temp; } this.hasShip = function(a,b) { //if out of map , means no ship in there; if(a < 0 || a > 9 || b < 0 || b >9) return false; return this.mapGrid[a][b].hasShip; } //check surrounding this.checkSurrounding = function(a,b){ if(this.hasShip(a-1,b)) return false; if(this.hasShip(a+1,b)) return false; if(this.hasShip(a-1,b+1)) return false; if(this.hasShip(a+1,b+1)) return false; if(this.hasShip(a-1,b-1)) return false; if(this.hasShip(a+1,b-1)) return false; if(this.hasShip(a,b+1)) return false; if(this.hasShip(a,b-1)) return false; return true; } this.isPlaceable = function(a,b,direction,length){ //check this position if(this.hasShip(a,b)) return false; if(!this.checkSurrounding(a,b)){ return false; } if(direction == HORIZONTAL){ for(var i = 1 ; i < length ; i++){ if(a + length - 1 > 9){ return false } if(this.hasShip(a+i,b) || !this.checkSurrounding(a+i,b)) return false; } } else{ for(var i = 1 ; i < length ; i++){ if(b + length - 1 > 9){ return false } if(this.hasShip(a,b+i) || !this.checkSurrounding(a,b+i)) return false; } } return true; } this.randomPlacment = function(){ var direction; var x; var y; do{ direction = Math.floor(Math.random()*2); x = Math.floor(Math.random()*10); y = Math.floor(Math.random()*10); } while(!this.isPlaceable(x,y,direction,5)); this.placeShip(x,y,AIRCRAFT_CARRIER,direction,5); do{ direction = Math.floor(Math.random()*2); x = Math.floor(Math.random()*10); y = Math.floor(Math.random()*10); }while(!this.isPlaceable(x,y,direction,4)); this.placeShip(x,y,BATTLESHIP,direction,4); do{ direction = Math.floor(Math.random()*2); x = Math.floor(Math.random()*10); y = Math.floor(Math.random()*10); }while(!this.isPlaceable(x,y,direction,3)); this.placeShip(x,y,CRUISER,direction,3); do{ direction = Math.floor(Math.random()*2); x = Math.floor(Math.random()*10); y = Math.floor(Math.random()*10); }while(!this.isPlaceable(x,y,direction,3)); this.placeShip(x,y,SUBMARINE,direction,3); do{ direction = Math.floor(Math.random()*2); x = Math.floor(Math.random()*10); y = Math.floor(Math.random()*10); }while(!this.isPlaceable(x,y,direction,2)); this.placeShip(x,y,DESTROYER,direction,2); } this. placeShip = function(x,y,name,direction,size){ if(direction == HORIZONTAL){ for(var i = 0 ; i< size ; i++){ this.mapGrid[x+i][y].hasShip = true; this.mapGrid[x+i][y].shipType = name; this.mapGrid[x+i][y].shipSize = size; this.mapGrid[x+i][y].direction = direction; } } else{ for(var i = 0 ; i< size ; i++){ this.mapGrid[x][y+i].hasShip = true; this.mapGrid[x][y+i].shipType = name; this.mapGrid[x][y+i].shipSize = size; this.mapGrid[x][y+i].direction = direction; } } } }
import Ember from 'ember'; export default Ember.Component.extend({ colorMap: { running: 'green', waiting: 'orange', terminated: 'red' }, getStatusByName(name) { let retval = null; Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => { if (name === containerStatus.name) { retval = containerStatus; return; } }); return retval; }, items: Ember.computed('containers', 'containerStatuses', function() { let items = []; this.get('containers').map((container) => { let status = this.getStatusByName(container.name); let state = Object.keys(status.state)[0], stateLabel = state.capitalize(), stateColor = this.colorMap[state], readyLabel = status.ready ? 'Ready' : 'Not ready', readyColor = status.ready ? 'green': 'orange'; items.push({ container, status, stateLabel, stateColor, readyLabel, readyColor }); }); return items; }) });
define(function() { var TramoView = Backbone.View.extend({ tagName: 'tr', template: _.template($('#tramo-tmpl').html()), events: {}, initialize: function() {}, render: function(index) { $(this.el).html(this.template(this.model.toJSON())) .addClass((index % 2 === 0) ? 'row1' : 'row2'); return this; } }); return TramoView; });
module.exports = { moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'ts', 'tsx'], transform: { '^.+\\.vue$': 'vue-jest', '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '^.+\\.tsx?$': 'ts-jest' }, transformIgnorePatterns: ['/node_modules/'], moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' }, snapshotSerializers: ['jest-serializer-vue'], testMatch: ['**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'], testURL: 'http://localhost/', watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'], globals: { 'ts-jest': { babelConfig: true } } }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.bitcoin = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'bc', bip32: { public: 0x0488b21e, private: 0x0488ade4, }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80, }; exports.regtest = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'bcrt', bip32: { public: 0x043587cf, private: 0x04358394, }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef, }; exports.testnet = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'tb', bip32: { public: 0x043587cf, private: 0x04358394, }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef, };
import React from 'react'; import PropTypes from 'prop-types'; import './index.css'; const TemplateWrapper = ({children}) => <div>{children()}</div>; TemplateWrapper.propTypes = { children: PropTypes.func, }; export default TemplateWrapper;
'use strict'; describe('Purchases E2E Tests:', function () { describe('Test purchases page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3000/purchases'); expect(element.all(by.repeater('purchase in purchases')).count()).toEqual(0); }); }); });
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint()); } if (angle > 360) {angle = 0;} points.map ( function (pt) { return pt.subtract (center); } ).map ( function (pt) { return y_rotate(pt, angle); } )/*.map ( function (pt) { return x_rotate(pt, angle); } )//.map ( function (pt) { return z_rotate(pt,angle); } )/**/.map ( function (pt) { return project (pt,700); } ).map ( function (pt) { return { x: pt['x'] + center.x, y: pt['y'] + center.y, scale: pt['scale'] } } ).forEach ( function (pt) { if (pt.scale < 0) {return;} context.fillStyle = 'rgba(255,255,255,' + pt.scale + ')'; context.beginPath(); context.arc(pt.x, pt.y, 4*pt.scale, 0, Math.PI * 2, true); context.closePath(); context.fill(); } ); angle = angle + 1; } } function randomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomPoint () { return new Point3D ( randomInt (-100,900), randomInt (-100,900), randomInt (-100,900), 1, randomInt (1,10) ); } function init() { console.log ('inited'); var viewport = document.getElementById('viewport'), context = viewport.getContext ('2d'), points = []; context.strokeStyle = '#aaa'; context.lineWidth = 1; setInterval (render (context, points), 50); } document.body.onload = init; }());
version https://git-lfs.github.com/spec/v1 oid sha256:59e6f2fa6c70c504d839d897c45f9a84348faf82342a31fb5818b1deb13861fa size 294301
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('coffee').del() .then(function () { // Inserts seed entries return knex('coffee').insert([ { id: 1, name: 'Three Africas', producer_id: 1, flavor_profile: 'Fruity, radiant, creamy', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 2, name: 'Ethiopia Bulga', producer_id: 2, flavor_profile: 'Cotton Candy, Strawberry, Sugar, Tangerine', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 3, name: 'Columbia Andino', producer_id: 2, flavor_profile: 'Butterscotch Citrus', varieties: 'Bourbon, Caturra, Typica', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 4, name: 'Colombia Popayán Fall Harvest', producer_id: 1, flavor_profile: 'Baking spice, red apple, nougat', varieties: '', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }]) .then(() => { return knex.raw("SELECT setval('coffee_id_seq', (SELECT MAX(id) FROM coffee));"); }); }); };
'use strict'; var express = require('express'), router = express.Router(), Post = require('../models/post'); module.exports = function (app) { app.use('/', router); }; router.get('/', function (req, res, next) { var posts = [new Post({ "title": "dummy posty" }), new Post()]; res.render('index', { title: 'Brian Mitchell', active: {active_home: true}, posts: posts }); });
"use strict"; const express = require('express'); const router = express.Router(); const quoteCtrl = require('../controllers/quote.js'); //returns an array of stocks that potentially match the query string //no result will return an empty string router.get('/quote/:quote', quoteCtrl.quote); module.exports = router;
var Blasticator = function() { var init = function() { registerSettings(); }; var showDialogue = function() { new ModalDialogue({ message:'This will destroy EVERYTHING. FOREVER.', buttons:[{ label:'Keep my data', role:'secondary', autoClose:true },{ label:'BURN IT ALL', role:'primary', autoClose:true, callback:function() { App.persister.clear(); window.location.reload(true); } }] }); }; var registerSettings = function() { App.settings.register([{ section:'Data', label:'Clear data', type:'button', iconClass:'fa-trash', callback:showDialogue }]); }; init(); };
(function () { window.AgidoMockups = window.AgidoMockups || {}; AgidoMockups.icons = AgidoMockups.icons || {}; AgidoMockups.icons.underline = new Kinetic.Group({name: "underlineIcon", width: 18, height: 20}); AgidoMockups.icons.underline.add(new Kinetic.Text({text: "U", fill: '#000', fontSize: 20, fontStyle: 'normal'})); AgidoMockups.icons.underline.add(new Kinetic.Line({ points: [1, 19, 13, 19], stroke: '#000', strokeWidth: 1 })); })();
(function() { var myPromise = new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition((pos) => { resolve(pos); }) }); function parsePosition(pos) { return { lat: pos.coords.latitude, lon: pos.coords.longitude } } function displayMap(pos) { let img = document.getElementById('theImg'); img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + pos.lat + "," + pos.lon + "&zoom=13&size=500x500&sensor=false"; } myPromise .then(parsePosition) .then(console.log) }());
module.exports = function(grunt) { grunt.initConfig({ // package.json is shared by all examples pkg: grunt.file.readJSON('../../package.json'), // Uglify the file at `src/foo.js` and output the result to `dist/foo.min.js` // // It's likely that this task is preceded by a `grunt-contrib-concat` task // to create a single file which is then uglified. uglify: { options: {}, dist: { files: { 'dist/foo.min.js': 'src/foo.js' // destination: source } } } }); // Load libraries used grunt.loadNpmTasks('grunt-contrib-uglify'); // Define tasks grunt.registerTask('default', ['uglify']); };
'use strict'; angular.module('adsApp').controller('AdminTownsController', ['$scope', '$rootScope', 'catalog', 'config', 'notify', function ($scope, $rootScope, catalog, config, notify) { $rootScope.pageTitle = 'Towns'; var usersConfig = config.users; var townsParams = { startPage: usersConfig.startPage, pageSize: usersConfig.pageSize }; $scope.getTowns = function () { $rootScope.loading = true; catalog.get('admin/towns', townsParams).then(function (towns) { $scope.towns = towns; }, function (error) { notify.message('Users filed to load!', error); }).finally(function () { $rootScope.loading = false; }); }; $scope.getTowns(); } ]);
/** * @providesModule Case */ const DOM = require('DOM'); var Case = (function () { /** * A Case is a test against an element. */ function Case (attributes) { return new Case.fn.init(attributes); } // Prototype object of the Case. Case.fn = Case.prototype = { constructor: Case, init: function (attributes) { this.listeners = {}; this.timeout = null; this.attributes = attributes || {}; var that = this; // Dispatch a resolve event if the case is initiated with a status. if (this.attributes.status) { // Delay the status dispatch to the next execution cycle so that the // Case will register listeners in this execution cycle first. setTimeout(function () { that.resolve(); }, 0); } // Set up a time out for this case to resolve within. else { this.attributes.status = 'untested'; this.timeout = setTimeout(function () { that.giveup(); }, 350); } return this; }, // Details of the Case. attributes: null, get: function (attr) { return this.attributes[attr]; }, set: function (attr, value) { var isStatusChanged = false; // Allow an object of attributes to be passed in. if (typeof attr === 'object') { for (var prop in attr) { if (attr.hasOwnProperty(prop)) { if (prop === 'status') { isStatusChanged = true; } this.attributes[prop] = attr[prop]; } } } // Assign a single attribute value. else { if (attr === 'status') { isStatusChanged = true; } this.attributes[attr] = value; } if (isStatusChanged) { this.resolve(); } return this; }, /** * A test that determines if a case has one of a set of statuses. * * @return boolean * A bit that indicates if the case has one of the supplied statuses. */ hasStatus: function (statuses) { // This is a rought test of arrayness. if (typeof statuses !== 'object') { statuses = [statuses]; } var status = this.get('status'); for (var i = 0, il = statuses.length; i < il; ++i) { if (statuses[i] === status) { return true; } } return false; }, /** * Dispatches the resolve event; clears the timeout fallback event. */ resolve: function () { clearTimeout(this.timeout); var el = this.attributes.element; var outerEl; // Get a selector and HTML if an element is provided. if (el && el.nodeType && el.nodeType === 1) { // Allow a test to provide a selector. Programmatically find one if none // is provided. this.attributes.selector = this.defineUniqueSelector(el); // Get a serialized HTML representation of the element the raised the error // if the Test did not provide it. if (!this.attributes.html) { this.attributes.html = ''; // If the element is either the <html> or <body> elements, // just report that. Otherwise we might be returning the entire page // as a string. if (el.nodeName === 'HTML' || el.nodeName === 'BODY') { this.attributes.html = '<' + el.nodeName + '>'; } // Get the parent node in order to get the innerHTML for the selected // element. Trim wrapping whitespace, remove linebreaks and spaces. else if (typeof el.outerHTML === 'string') { outerEl = el.outerHTML.trim().replace(/(\r\n|\n|\r)/gm, '').replace(/>\s+</g, '><'); // Guard against insanely long elements. // @todo, make this length configurable eventually. if (outerEl.length > 200) { outerEl = outerEl.substr(0, 200) + '... [truncated]'; } this.attributes.html = outerEl; } } } this.dispatch('resolve', this); }, /** * Abandons the Case if it not resolved within the timeout period. */ giveup: function () { clearTimeout(this.timeout); // @todo, the set method should really have a 'silent' option. this.attributes.status = 'untested'; this.dispatch('timeout', this); }, // @todo, make this a set of methods that all classes extend. listenTo: function (dispatcher, eventName, handler) { handler = handler.bind(this); dispatcher.registerListener.call(dispatcher, eventName, handler); }, registerListener: function (eventName, handler) { if (!this.listeners[eventName]) { this.listeners[eventName] = []; } this.listeners[eventName].push(handler); }, dispatch: function (eventName) { if (this.listeners[eventName] && this.listeners[eventName].length) { var eventArgs = [].slice.call(arguments); this.listeners[eventName].forEach(function (handler) { // Pass any additional arguments from the event dispatcher to the // handler function. handler.apply(null, eventArgs); }); } }, /** * Creates a page-unique selector for the selected DOM element. * * @param {jQuery} element * An element in a jQuery wrapper. * * @return {string} * A unique selector for this element. */ defineUniqueSelector: function (element) { /** * Indicates whether the selector string represents a unique DOM element. * * @param {string} selector * A string selector that can be used to query a DOM element. * * @return Boolean * Whether or not the selector string represents a unique DOM element. */ function isUniquePath (selector) { return DOM.scry(selector).length === 1; } /** * Creates a selector from the element's id attribute. * * Temporary IDs created by the module that contain "visitorActions" are excluded. * * @param {HTMLElement} element * * @return {string} * An id selector or an empty string. */ function applyID (element) { var selector = ''; var id = element.id || ''; if (id.length > 0) { selector = '#' + id; } return selector; } /** * Creates a selector from classes on the element. * * Classes with known functional components like the word 'active' are * excluded because these often denote state, not identity. * * @param {HTMLElement} element * * @return {string} * A selector of classes or an empty string. */ function applyClasses (element) { var selector = ''; // Try to make a selector from the element's classes. var classes = element.className || ''; if (classes.length > 0) { classes = classes.split(/\s+/); // Filter out classes that might represent state. classes = reject(classes, function (cl) { return (/active|enabled|disabled|first|last|only|collapsed|open|clearfix|processed/).test(cl); }); if (classes.length > 0) { return '.' + classes.join('.'); } } return selector; } /** * Finds attributes on the element and creates a selector from them. * * @param {HTMLElement} element * * @return {string} * A selector of attributes or an empty string. */ function applyAttributes (element) { var selector = ''; // Whitelisted attributes to include in a selector to disambiguate it. var attributes = ['href', 'type', 'title', 'alt']; var value; if (typeof element === 'undefined' || typeof element.attributes === 'undefined' || element.attributes === null) { return selector; } // Try to make a selector from the element's classes. for (var i = 0, len = attributes.length; i < len; i++) { value = element.attributes[attributes[i]] && element.attributes[attributes[i]].value; if (value) { selector += '[' + attributes[i] + '="' + value + '"]'; } } return selector; } /** * Creates a unique selector using id, classes and attributes. * * It is possible that the selector will not be unique if there is no * unique description using only ids, classes and attributes of an * element that exist on the page already. If uniqueness cannot be * determined and is required, you will need to add a unique identifier * to the element through theming development. * * @param {HTMLElement} element * * @return {string} * A unique selector for the element. */ function generateSelector (element) { var selector = ''; var scopeSelector = ''; var pseudoUnique = false; var firstPass = true; do { scopeSelector = ''; // Try to apply an ID. if ((scopeSelector = applyID(element)).length > 0) { selector = scopeSelector + ' ' + selector; // Assume that a selector with an ID in the string is unique. break; } // Try to apply classes. if (!pseudoUnique && (scopeSelector = applyClasses(element)).length > 0) { // If the classes don't create a unique path, tack them on and // continue. selector = scopeSelector + ' ' + selector; // If the classes do create a unique path, mark this selector as // pseudo unique. We will keep attempting to find an ID to really // guarantee uniqueness. if (isUniquePath(selector)) { pseudoUnique = true; } } // Process the original element. if (firstPass) { // Try to add attributes. if ((scopeSelector = applyAttributes(element)).length > 0) { // Do not include a space because the attributes qualify the // element. Append classes if they exist. selector = scopeSelector + selector; } // Add the element nodeName. selector = element.nodeName.toLowerCase() + selector; // The original element has been processed. firstPass = false; } // Try the parent element to apply some scope. element = element.parentNode; } while (element && element.nodeType === 1 && element.nodeName !== 'BODY' && element.nodeName !== 'HTML'); return selector.trim(); } /** * Helper function to filter items from a list that pass the comparator * test. * * @param {Array} list * @param {function} comparator * A function that return a boolean. True means the list item will be * discarded from the list. * @return array * A list of items the excludes items that passed the comparator test. */ function reject (list, comparator) { var keepers = []; for (var i = 0, il = list.length; i < il; i++) { if (!comparator.call(null, list[i])) { keepers.push(list[i]); } } return keepers; } return element && generateSelector(element); }, push: [].push, sort: [].sort, concat: [].concat, splice: [].splice }; // Give the init function the Case prototype. Case.fn.init.prototype = Case.fn; return Case; }()); module.exports = Case;
/*! * Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0) * Copyright 2013-2017 Start Bootstrap * Purchase a license to use this theme at (https://wrapbootstrap.com) */ /*! * Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0) * Copyright 2013-2017 Start Bootstrap * Purchase a license to use this theme at (https://wrapbootstrap.com) */ // Load WOW.js on non-touch devices var isPhoneDevice = "ontouchstart" in document.documentElement; $(document).ready(function() { if (isPhoneDevice) { //mobile } else { //desktop // Initialize WOW.js wow = new WOW({ offset: 50 }) wow.init(); } }); (function($) { "use strict"; // Start of use strict // Collapse the navbar when page is scrolled $(window).scroll(function() { if ($("#mainNav").offset().top > 100) { $("#mainNav").addClass("navbar-shrink"); } else { $("#mainNav").removeClass("navbar-shrink"); } }); // Activate scrollspy to add active class to navbar items on scroll $('body').scrollspy({ target: '#mainNav', offset: 68 }); // Smooth Scrolling: Smooth scrolls to an ID on the current page // To use this feature, add a link on your page that links to an ID, and add the .page-scroll class to the link itself. See the docs for more details. $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 68) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Closes responsive menu when a link is clicked $('.navbar-collapse>ul>li>a, .navbar-brand').click(function() { $('.navbar-collapse').collapse('hide'); }); // Activates floating label headings for the contact form $("body").on("input propertychange", ".floating-label-form-group", function(e) { $(this).toggleClass("floating-label-form-group-with-value", !!$(e.target).val()); }).on("focus", ".floating-label-form-group", function() { $(this).addClass("floating-label-form-group-with-focus"); }).on("blur", ".floating-label-form-group", function() { $(this).removeClass("floating-label-form-group-with-focus"); }); // Owl Carousel Settings $(".team-carousel").owlCarousel({ items: 3, navigation: true, pagination: false, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], }); $(".portfolio-carousel").owlCarousel({ singleItem: true, navigation: true, pagination: false, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], autoHeight: true, mouseDrag: false, touchDrag: false, transitionStyle: "fadeUp" }); $(".testimonials-carousel, .mockup-carousel").owlCarousel({ singleItem: true, navigation: true, pagination: true, autoHeight: true, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], transitionStyle: "backSlide" }); $(".portfolio-gallery").owlCarousel({ items: 3, }); // Magnific Popup jQuery Lightbox Gallery Settings $('.gallery-link').magnificPopup({ type: 'image', gallery: { enabled: true }, image: { titleSrc: 'title' } }); // Magnific Popup Settings $('.mix').magnificPopup({ type: 'image', image: { titleSrc: 'title' } }); // Vide - Video Background Settings $('header.video').vide({ mp4: "mp4/camera.mp4", poster: "img/agency/backgrounds/bg-mobile-fallback.jpg" }, { posterType: 'jpg' }); })(jQuery); // End of use strict
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1) { state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note } } } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => { commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error) }) }, deleteMultipleClient({commit, dispatch}, clients) { HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) } } export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
import "cutaway" import { assert, report } from "tapeless" import createPlayer from "./main.js" const { ok, notOk, equal } = assert try { createPlayer() } catch (e) { ok .describe("will throw sans video input") .test(e, e.message) } const source = document.createElement("video") source.src = "" const { play, stop } = createPlayer(source) equal .describe("play") .test(typeof play, "function") notOk .describe("playing") .test(play()) equal .describe("stop") .test(typeof stop, "function") ok .describe("paused", "will operate") .test(stop()) report()
class dximagetransform_microsoft_maskfilter { constructor() { // Variant Color () {get} {set} this.Color = undefined; } } module.exports = dximagetransform_microsoft_maskfilter;
/** * Calculates the radius of the Hill Sphere, * for a body with mass `m1` * @param {Number} m1 Mass of the lighter body * @param {Number} m2 Mass of the heavier body * @param {Number} a Semi-major axis * @param {Number} e Eccentricity * @return {Number} Hill Sphere radius */ function hillSphere( m1, m2, a, e ) { return a * ( 1 - e ) * Math.pow( ( m1 / ( 3 * m2 ) ), 1/3 ) } module.exports = hillSphere
var httpRequester = (function() { var makeHttpRequest = function(url, type, data) { var deferred = $.Deferred(); $.ajax({ url: url, type: type, contentType: 'application/json', data: data, success: function(resultData) { deferred.resolve(resultData); }, error: function(error) { deferred.reject(error); } }); return deferred; }; var sendRequest = function(url, type, data) { return makeHttpRequest(url, type, data); }; return { sendRequest: sendRequest }; }());
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosCopy extends React.Component { render() { if(this.props.bare) { return <g> <g> <polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon> <g> <path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path> </g> </g> </g>; } return <IconBase> <g> <polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon> <g> <path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path> </g> </g> </IconBase>; } };IosCopy.defaultProps = {bare: false}
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import User from './User'; import Loading from '../../components/Icon/Loading'; import './InterestingPeople.less'; import steemAPI from '../../steemAPI'; class InterestingPeopleWithAPI extends Component { static propTypes = { authenticatedUser: PropTypes.shape({ name: PropTypes.string, }), followingList: PropTypes.arrayOf(PropTypes.string), }; static defaultProps = { authenticatedUser: { name: '', }, followingList: [], }; state = { users: [], loading: true, noUsers: false, }; componentWillMount() { const authenticatedUsername = this.props.authenticatedUser.name; const usernameValidator = window.location.pathname.match(/@(.*)/); const username = usernameValidator ? usernameValidator[1] : authenticatedUsername; this.getBlogAuthors(username); } getBlogAuthors = (username = '') => steemAPI .getBlogAuthorsAsync(username) .then((result) => { const followers = this.props.followingList; const users = _.sortBy(result, user => user[1]) .reverse() .filter(user => !followers.includes(user[0])) .slice(0, 5) .map(user => ({ name: user[0] })); if (users.length > 0) { this.setState({ users, loading: false, noUsers: false, }); } else { this.setState({ noUsers: true, }); } }) .catch(() => { this.setState({ noUsers: true, }); }); render() { const { users, loading, noUsers } = this.state; if (noUsers) { return <div />; } if (loading) { return <Loading />; } return ( <div className="InterestingPeople"> <div className="InterestingPeople__container"> <h4 className="InterestingPeople__title"> <i className="iconfont icon-group InterestingPeople__icon" /> {' '} <FormattedMessage id="interesting_people" defaultMessage="Interesting People" /> </h4> <div className="InterestingPeople__divider" /> {users && users.map(user => <User key={user.name} user={user} />)} <h4 className="InterestingPeople__more"> <Link to={'/latest-comments'}> <FormattedMessage id="discover_more_people" defaultMessage="Discover More People" /> </Link> </h4> </div> </div> ); } } export default InterestingPeopleWithAPI;
var pagerun = require('pagerun'); // set for debug // pagerun.modulesRoot = '../'; pagerun.mode = 'test'; // pagerun.loadNpmPlugin('httpresponse'); pagerun.loadNpmPlugin('httpsummary'); pagerun.loadNpmPlugin('httperror'); pagerun.loadNpmPlugin('htmlhint'); pagerun.loadNpmPlugin('jserror'); pagerun.loadNpmPlugin('pagesummary'); pagerun.loadNpmPlugin('jsunit'); // pagerun.loadNpmPlugin('jscoverage'); process.on('message', function(config) { pagerun.setConfig(config); pagerun.run(function(result){ process.send(result); process.exit(0); }); });
'use strict'; $(function() { $.material.init(); $('#libraries').btsListFilter('#searcher', { itemChild: 'h3', resetOnBlur: false }); $('#searcher').focus(); });
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './storage_mock'; /** * Creates a mock for the `axStorage` injection of a widget. * * @return {AxStorageMock} * a mock of `axStorage` that can be spied and/or mocked with additional items */ export function create() { const globalStorageMock = createGlobalStorageMock(); const namespace = 'mock'; const local = globalStorageMock.getLocalStorage( namespace ); const session = globalStorageMock.getSessionStorage( namespace ); /** * The AxStorageMock provides the same API as AxStorage, with the additional property * {@link #mockBackends} to inspect and/or simulate mock values in the storage backend. * * @name AxStorageMock * @constructor * @extends AxStorage */ return { local, session, /** * Provides access to the backing stores for `local` and `session` storage. * * Contains `local` and `session` store properties. The stores are plain objects whose properties * reflect any setItem/removeItem operations. When properties are set on a store, they are observed * by `getItem` calls on the corresponding axStorage API. * * @memberof AxStorageMock */ mockBackends: { local: globalStorageMock.mockBackends.local[ namespace ].store, session: globalStorageMock.mockBackends.session[ namespace ].store } }; }
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) { let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) { createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } clearText () { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else { this.textIndicator.classList.remove("in"); } } else { this.clearText(); } } }
//= require sencha_touch/sencha-touch //= require_directory ./sencha_touch/app //= require_tree ./sencha_touch/app/models //= require_tree ./sencha_touch/app/stores //= require_tree ./sencha_touch/app/controllers //= require_tree ./sencha_touch/app/views
;(function() { function ToerismeApp(id, parentContainer) { this.API_URL = 'https://datatank.stad.gent/4/toerisme/visitgentevents.json'; this.id = id; this.parentContainer = parentContainer; this.loadData = function() { var that = this; var xhr = new XMLHttpRequest(); xhr.open('get', this.API_URL, true); xhr.responseType = 'json'; xhr.onload = function() { if(xhr.status == 200) { var data = (!xhr.responseType)?JSON.parse(xhr.response):xhr.response; var id = 1; var tempStr = ''; for(i=0; i<20; i++) { var title = data[i].title; var contact = data[i].contact[0]; //var website = contact.website[0]; //var weburl = website.url; var images = data[i].images[0]; var language = data[i].language; var website = ''; if(contact.website){ website = contact.website[0].url; //console.log(website); } if(language == 'nl'){ tempStr += '<div class="row row_events">'; tempStr += '<a href="http://' + website +'" target="_blank";>'; tempStr += '<div class="col-xs-6"><div class="div_image" style="background: url(' + images +') no-repeat center ;background-size:cover;"></div></div>'; tempStr += '<div class="col-xs-6"><h4>' + title + '</h4>'; tempStr += '<p>Adres: ' + contact.street + ' nr ' + contact.number + '<br> Stad: ' + contact.city +'</p>'; tempStr += '</div>'; /* einde adres */ tempStr += '</a>'; tempStr += '<a class="link_heart" id="myDIV'+[i]+'" alt="Add to favorites" title="Add to favorites" onclick="myFunction('+[i]+')" ><span class="glyphicon glyphicon-heart-empty"></span></a>'; tempStr += '</div>';/* einde row */ }else{}; } that.parentContainer.innerHTML = tempStr; } else { console.log('xhr.status'); } } xhr.onerror = function() { console.log('Error'); } xhr.send(); }; this.updateUI = function() { }; this.toString = function() { return `ToerismeApp with id: ${this.id}`; }; }; var ww1 = new ToerismeApp(1, document.querySelector('.sidebar')); ww1.loadData(); console.log(ww1.toString()); })(); function myFunction(id){ document.getElementById("myDIV"+id).classList.toggle("link_heart-select"); }
module.exports = "module-one-A-model";
$(function () { 'use strict'; const notificationType = { success: 'Success', error: 'Error', info: 'Info' }, notificationTypeClass = { success: 'toast-success', info: 'toast-info', error: 'toast-error' }; function initSignalR() { let connection = $.connection, hub = connection.notificationHub; hub.client.toast = (message, dellay, type) => { console.log('CALLEEEEEEEEEEEED') if (type === notificationType.success) { Materialize.toast(message, dellay, notificationTypeClass.success) } else if (type === notificationType.info) { Materialize.toast(message, dellay, notificationTypeClass.info) } else { Materialize.toast(message, dellay, notificationTypeClass.error) } }; connection.hub.start().done(() => hub.server.init()); } initSignalR(); }());
/** * Ensures that the callback pattern is followed properly * with an Error object (or undefined or null) in the first position. */ 'use strict' // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ /** * Determine if a node has a possiblity to be an Error object * @param {ASTNode} node ASTNode to check * @returns {boolean} True if there is a chance it contains an Error obj */ function couldBeError (node) { let exprs switch (node.type) { case 'Identifier': case 'CallExpression': case 'NewExpression': case 'MemberExpression': case 'TaggedTemplateExpression': case 'YieldExpression': return true // possibly an error object. case 'AssignmentExpression': return couldBeError(node.right) case 'SequenceExpression': exprs = node.expressions return exprs.length !== 0 && couldBeError(exprs[exprs.length - 1]) case 'LogicalExpression': return couldBeError(node.left) || couldBeError(node.right) case 'ConditionalExpression': return couldBeError(node.consequent) || couldBeError(node.alternate) default: return node.value === null } } // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = { meta: { type: 'suggestion', docs: { url: 'https://github.com/standard/eslint-plugin-standard#rules-explanations' } }, create: function (context) { const callbackNames = context.options[0] || ['callback', 'cb'] function isCallback (name) { return callbackNames.indexOf(name) > -1 } return { CallExpression: function (node) { const errorArg = node.arguments[0] const calleeName = node.callee.name if (errorArg && !couldBeError(errorArg) && isCallback(calleeName)) { context.report(node, 'Unexpected literal in error position of callback.') } } } } }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > The Date.prototype.getMinutes property "length" has { ReadOnly, DontDelete, DontEnum } attributes es5id: 15.9.5.20_A3_T1 description: Checking ReadOnly attribute ---*/ x = Date.prototype.getMinutes.length; Date.prototype.getMinutes.length = 1; if (Date.prototype.getMinutes.length !== x) { $ERROR('#1: The Date.prototype.getMinutes.length has the attribute ReadOnly'); }
module.exports = function(sails) { var Agenda = require('agenda'), util = require('util'), _ = require('lodash'), os = require("os"), agenda = new Agenda() agenda.sails = sails; var stopServer = function() { agenda.stop(function() { console.log("agenda stopped"); }); }; sails.on("lower", stopServer); sails.on("lowering", stopServer); // return hook return { // expose agenda in sails.hooks.jobs.agenda jobs: agenda, // Defaults config defaults: { jobs: { "globalJobsObjectName": "Jobs", "jobsDirectory": "api/jobs", "db": { "address" : "localhost:27017/jobs", "collection" : "agendaJobs" }, "name": os.hostname() + '-' + process.pid, "processEvery": "1 minutes", "maxConcurrency": 20, "defaultConcurrency": 5, "defaultLockLifetime": 10000, } }, // Runs automatically when the hook initializes initialize: function (cb) { var hook = this , config = sails.config.jobs // init agenda agenda .database(config.db.address, config.db.collection) .name(config.name) .processEvery(config.processEvery) .maxConcurrency(config.maxConcurrency) .defaultConcurrency(config.defaultConcurrency) .defaultLockLifetime(config.defaultLockLifetime) global[config.globalJobsObjectName] = agenda; // Enable jobs using coffeescript try { require('coffee-script/register'); } catch(e0) { try { var path = require('path'); var appPath = sails.config.appPath || process.cwd(); require(path.join(appPath, 'node_modules/coffee-script/register')); } catch(e1) { sails.log.verbose('Please run `npm install coffee-script` to use coffescript (skipping for now)'); } } // Find all jobs var jobs = require('include-all')({ dirname : sails.config.appPath + '/' + config.jobsDirectory, filter : /(.+Job).(?:js|coffee)$/, excludeDirs : /^\.(git|svn)$/, optional : true }); // init jobs hook.initJobs(jobs); // Lets wait on some of the sails core hooks to // finish loading before we load our hook // that talks about cats. var eventsToWaitFor = []; if (sails.hooks.orm) eventsToWaitFor.push('hook:orm:loaded'); if (sails.hooks.pubsub) eventsToWaitFor.push('hook:pubsub:loaded'); sails.after(eventsToWaitFor, function(){ // if (jobs.length > 0) { // start agenda agenda.start(); sails.log.verbose("sails jobs started") // } // Now we will return the callback and our hook // will be usable. return cb(); }); }, /** * Function that initialize jobs */ initJobs: function(jobs, namespace) { var hook = this if (!namespace) namespace = "jobs"; sails.log.verbose("looking for job in " + namespace + "... ") _.forEach(jobs, function(job, name){ if (typeof job === 'function') { var log = "" , _job = job(agenda) , _dn = namespace + "." + name , _name = _job.name || _dn.substr(_dn.indexOf('.') +1); if (_job.disabled) { log += "-> Disabled Job '" + _name + "' found in '" + namespace + "." + name + "'."; } else { var options = (typeof _job.options === 'object')?_job.options:{} , freq = typeof _job.frequency == 'undefined'?sails.config.jobs.processEvery:_job.frequency , error = false; if (typeof _job.run === "function") agenda.define(_name, options, _job.run); log += "-> Job '" + _name + "' found in '" + namespace + "." + name + "', defined in agenda"; if (typeof freq === 'string') { freq = freq.trim().toLowerCase(); if (freq.indexOf('every') == 0) { var interval = freq.substr(6).trim(); agenda.every(interval, _name, _job.data); log += " and will run " + freq; } else if (freq.indexOf('schedule') == 0) { var when = freq.substr(9).trim(); agenda.schedule(when, _name, _job.data); log += " and scheduled " + when; } else if (freq === 'now') { agenda.now(_name, _job.data); log += " and started"; } else { error = true; log += " but frequency is not supported"; } } } log += "."; if (error) sails.log.error(log); else sails.log.verbose(log); } else { hook.initJobs(job, namespace + "." + name); } }) } } };
export class NewForm { update() { } }
var grunt = require('grunt'); var fs = require('fs'); var gruntTextReplace = require('../lib/grunt-match-replace'); var replace = function (settings) { return gruntTextReplace.replace(settings); }; exports.textReplace = { 'Test error handling': { setUp: function (done) { grunt.file.copy('test/text_files/test.txt', 'test/temp/testA.txt'); grunt.file.copy('test/text_files/test.txt', 'test/temp/testB.txt'); done(); }, tearDown: function (done) { fs.unlinkSync('test/temp/testA.txt'); fs.unlinkSync('test/temp/testB.txt'); fs.rmdirSync('test/temp'); done(); }, 'Test no destination found': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test no replacements found': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', dest: 'test/temp/' }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test overwrite failure': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/*', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test destination error': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/*', dest: 'test/temp', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/*', dest: 'test/temp/testA.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 2); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/testB.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 2); test.done(); } } };
var sourceFolder = 'src', destFolder = 'public', configFolder = 'config'; module.exports = { folders: { source: sourceFolder, dest: destFolder }, files: { scripts: [ `${sourceFolder}/js/utils.js`, `${sourceFolder}/js/sprites/weapon.js`, `${sourceFolder}/js/sprites/hook.js`, `${sourceFolder}/js/sprites/enemy.js`, `${sourceFolder}/js/sprites/**/*.js`, `${sourceFolder}/js/map.js`, `${sourceFolder}/js/ui/**/*.js`, `${sourceFolder}/js/states/**/*.js`, `${sourceFolder}/js/**/*.js` ], templates: `${sourceFolder}/templates/**/*.html`, libs: [ 'node_modules/phaser/dist/phaser.js', 'node_modules/stats.js/build/stats.min.js' ], styles: `${sourceFolder}/styles/**/*.css`, images: `${sourceFolder}/images/**/*.*`, sounds: `${sourceFolder}/sounds/**/*.*`, json: `${sourceFolder}/json/**/*.*`, fonts: `${sourceFolder}/fonts/**/*.*`, cname: `${configFolder}/CNAME` }, scripts: { destFolder: `${destFolder}/js`, outFile: 'index.js' }, libs: { destFolder: `${destFolder}/js`, outFile: 'libs.js' }, styles: { destFolder: `${destFolder}/css`, outFile: 'index.css' }, images: { destFolder: `${destFolder}/images` }, sounds: { destFolder: `${destFolder}/sounds` }, json: { destFolder: `${destFolder}/json` }, fonts: { destFolder: `${destFolder}/fonts` }, server: { root: destFolder, livereload: true } };
module.exports = { server: { host: '0.0.0.0', port: 3000 }, database: { host: '158.85.190.240', port: 27017, db: 'hackathon', username: 'administrator', password: 'hunenokGaribaldi9' } };
'use strict'; /* istanbul ignore next */ /* eslint-disable no-console */ /** * Handle failures in the application by terminating. * @param {Exception} err - Exception to handle. */ module.exports = (err) => { console.log(err); console.log(err.stack); process.exit(-1); };
__history = [{"date":"Sun, 30 Mar 2014 19:01:57 GMT","sloc":70,"lloc":24,"functions":1,"deliveredBugs":0.13739293667703853,"maintainability":55.96019418981483,"lintErrors":0,"difficulty":6.375}]
import Omi from 'omi/dist/omi' import { CellsTitle, Cells, CellHeader, CellBody, CellFooter } from '../cell' Omi.makeHTML('CellsTitle', CellsTitle); Omi.makeHTML('Cells', Cells); Omi.makeHTML('CellHeader', CellHeader); Omi.makeHTML('CellBody', CellBody); Omi.makeHTML('CellFooter', CellFooter); export default class List extends Omi.Component{ constructor(data) { super(data); } render(){ return ` <div> <CellsTitle data-title={{title}} /> <Cells slot-index="0"> <div> {{#items}} <{{#link}}a href={{link}} {{/link}}{{^link}}div{{/link}} class="weui-cell {{#link}}weui-cell_access{{/link}}"> {{#imageUrl}} <CellHeader> <img style="width:20px;margin-right:5px;display:block" src={{imageUrl}} /> </CellHeader> {{/imageUrl}} <CellBody slot-index="0" > <p>{{{title}}}</p> </CellBody> <CellFooter slot-index="1"> <span>{{value}}</span> </CellFooter> </{{#link}}a{{/link}}{{^link}}div{{/link}}> {{/items}} </div> </Cells> </div> `; } }
/** @module ember-flexberry-gis */ import Ember from 'ember'; /** Class implementing base stylization for markers. @class BaseMarkerStyle */ export default Ember.Object.extend({ /** Gets default style settings. @method getDefaultStyleSettings @return {Object} Hash containing default style settings. */ getDefaultStyleSettings() { return null; }, /** Applies layer-style to the specified leaflet layer. @method renderOnLeafletMarker @param {Object} options Method options. @param {<a =ref="http://leafletjs.com/reference-1.2.0.html#marker">L.Marker</a>} options.marker Leaflet marker to which marker-style must be applied. @param {Object} options.style Hash containing style settings. */ renderOnLeafletMarker({ marker, style }) { throw `Method 'renderOnLeafletMarker' isn't implemented in 'base' marker-style`; }, /** Renderes layer-style preview on the specified canvas element. @method renderOnCanvas @param {Object} options Method options. @param {<a =ref="https://developer.mozilla.org/ru/docs/Web/HTML/Element/canvas">Canvas</a>} options.canvas Canvas element on which marker-style preview must be rendered. @param {Object} options.style Hash containing style settings. @param {Object} [options.target = 'preview'] Render target ('preview' or 'legend'). */ renderOnCanvas({ canvas, style, target }) { throw `Method 'renderOnCanvas' isn't implemented in 'base' marker-style`; } });
(() => { 'use strict'; angular.module('RestTestApp') .config(($urlRouterProvider, $locationProvider) => { $locationProvider.html5Mode(true); }) .config(function(RestTestStateConfigProvider) { RestTestStateConfigProvider.initialize(); }); })();
/* * * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; angular.module('sample-01', ['adf', 'LocalStorageModule']) .controller('sample01Ctrl', function($scope, localStorageService){ var name = 'sample-01'; var model;// = localStorageService.get(name); if (!model) { // set default model for demo purposes model = { title: "Sample 01", structure: "4-4-4", rows: [{ columns: [{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }, { styleClass: "col-md-4", widgets: [{ type: "Pie" }] },{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }] }] }; } $scope.name = name; $scope.model = model; $scope.collapsible = false; $scope.maximizable = false; $scope.$on('adfDashboardChanged', function (event, name, model) { localStorageService.set(name, model); }); });
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp(); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/modernizr/modernizr.js'); module.exports = app.toTree();
"use strict"; var CropTouch = (function () { function CropTouch(x, y, id) { this.id = id || 0; this.x = x || 0; this.y = y || 0; this.dragHandle = null; } return CropTouch; }()); exports.CropTouch = CropTouch; //# sourceMappingURL=cropTouch.js.map
(function () { 'use strict'; angular .module('Debug', ['pullrefresh']); })();
module.exports = function(knex) { describe('Transactions', function() { it('should be able to commit transactions', function(ok) { var id = null; return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email:'[email protected]', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.commit('Hello world'); }); }).then(function(commitMessage) { expect(commitMessage).to.equal('Hello world'); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.have.length(1); }).otherwise(function(err) { console.log(err); }); }); it('should be able to rollback transactions', function(ok) { var id = null; var err = new Error('error message'); return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email:'[email protected]', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.rollback(err); }); }).otherwise(function(msg) { expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.be.empty; }); }); }); };
var util = require("util"); var choreography = require("temboo/core/choreography"); /* CreateDeployment Create a RightScale Deployment. */ var CreateDeployment = function(session) { /* Create a new instance of the CreateDeployment Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateDeployment" CreateDeployment.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateDeploymentResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateDeploymentInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateDeployment Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateDeploymentInputSet = function() { CreateDeploymentInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentDefaultEC2AvailabilityZone input for this Choreo. ((optional, string) The default EC2 availability zone for this deployment.) */ this.set_DeploymentDefaultEC2AvailabilityZone = function(value) { this.setInput("DeploymentDefaultEC2AvailabilityZone", value); } /* Set the value of the DeploymentDefaultVPCSubnetHref input for this Choreo. ((optional, string) The href of the vpc subnet.) */ this.set_DeploymentDefaultVPCSubnetHref = function(value) { this.setInput("DeploymentDefaultVPCSubnetHref", value); } /* Set the value of the DeploymentDescription input for this Choreo. ((optional, string) The deployment being created.) */ this.set_DeploymentDescription = function(value) { this.setInput("DeploymentDescription", value); } /* Set the value of the DeploymentNickname input for this Choreo. ((required, string) The nickname of the deployment being created.) */ this.set_DeploymentNickname = function(value) { this.setInput("DeploymentNickname", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the CreateDeployment Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateDeploymentResultSet = function(resultStream) { CreateDeploymentResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateDeployment, choreography.Choreography); util.inherits(CreateDeploymentInputSet, choreography.InputSet); util.inherits(CreateDeploymentResultSet, choreography.ResultSet); exports.CreateDeployment = CreateDeployment; /* CreateServer Creates a RightScale server instance. */ var CreateServer = function(session) { /* Create a new instance of the CreateServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServer" CreateServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerInputSet = function() { CreateServerInputSet.super_.call(this); /* Set the value of the AKIImage input for this Choreo. ((optional, string) The URL to the AKI image.) */ this.set_AKIImage = function(value) { this.setInput("AKIImage", value); } /* Set the value of the ARIImage input for this Choreo. ((optional, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((optional, integer) The cloud region identifier. If undefined, the default is 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, string) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((optional, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, string) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, string) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, string) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((optional, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((optional, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((required, string) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((required, string) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((required, string) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The username obtained from RightScale.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((optional, string) The href to the VPC subnet.) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerResultSet = function(resultStream) { CreateServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServer, choreography.Choreography); util.inherits(CreateServerInputSet, choreography.InputSet); util.inherits(CreateServerResultSet, choreography.ResultSet); exports.CreateServer = CreateServer; /* CreateServerXMLInput Creates a RightScale server instance using a given XML template. */ var CreateServerXMLInput = function(session) { /* Create a new instance of the CreateServerXMLInput Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServerXMLInput" CreateServerXMLInput.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerXMLInputResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerXMLInputInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServerXMLInput Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerXMLInputInputSet = function() { CreateServerXMLInputInputSet.super_.call(this); /* Set the value of the ServerParameters input for this Choreo. ((required, xml) The XML file containing the required parameters for the server creation. See documentation for XML schema.) */ this.set_ServerParameters = function(value) { this.setInput("ServerParameters", value); } /* Set the value of the ARIImage input for this Choreo. ((required, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The Account ID obtained from RightScale.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((required, integer) The cloud region identifier. If undefined, the default is: 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, any) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((required, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, any) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, any) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, any) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((required, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((required, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((optional, any) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((optional, any) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((optional, any) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((required, string) The href to the VPC subnet) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServerXMLInput Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerXMLInputResultSet = function(resultStream) { CreateServerXMLInputResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServerXMLInput, choreography.Choreography); util.inherits(CreateServerXMLInputInputSet, choreography.InputSet); util.inherits(CreateServerXMLInputResultSet, choreography.ResultSet); exports.CreateServerXMLInput = CreateServerXMLInput; /* GetArrayIndex Retrieve a list of server assets grouped within a particular RightScale Array. */ var GetArrayIndex = function(session) { /* Create a new instance of the GetArrayIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetArrayIndex" GetArrayIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetArrayIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetArrayIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetArrayIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetArrayIndexInputSet = function() { GetArrayIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetArrayIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetArrayIndexResultSet = function(resultStream) { GetArrayIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetArrayIndex, choreography.Choreography); util.inherits(GetArrayIndexInputSet, choreography.InputSet); util.inherits(GetArrayIndexResultSet, choreography.ResultSet); exports.GetArrayIndex = GetArrayIndex; /* GetServerSettings Retrieve server settings for a specified RightScale Server ID. */ var GetServerSettings = function(session) { /* Create a new instance of the GetServerSettings Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetServerSettings" GetServerSettings.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetServerSettingsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetServerSettingsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetServerSettings Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetServerSettingsInputSet = function() { GetServerSettingsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetServerSettings Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetServerSettingsResultSet = function(resultStream) { GetServerSettingsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetServerSettings, choreography.Choreography); util.inherits(GetServerSettingsInputSet, choreography.InputSet); util.inherits(GetServerSettingsResultSet, choreography.ResultSet); exports.GetServerSettings = GetServerSettings; /* IndexDeployments Retrieve a list of server assets grouped within a particular RightScale Deployment. */ var IndexDeployments = function(session) { /* Create a new instance of the IndexDeployments Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/IndexDeployments" IndexDeployments.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new IndexDeploymentsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new IndexDeploymentsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the IndexDeployments Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var IndexDeploymentsInputSet = function() { IndexDeploymentsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Filter input for this Choreo. ((optional, string) An attributeName=AttributeValue filter pair. For example: nickname=mynick; OR description<>mydesc) */ this.set_Filter = function(value) { this.setInput("Filter", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the inputFile input for this Choreo. () */ } /* A ResultSet with methods tailored to the values returned by the IndexDeployments Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var IndexDeploymentsResultSet = function(resultStream) { IndexDeploymentsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(IndexDeployments, choreography.Choreography); util.inherits(IndexDeploymentsInputSet, choreography.InputSet); util.inherits(IndexDeploymentsResultSet, choreography.ResultSet); exports.IndexDeployments = IndexDeployments; /* LaunchArrayInstance Start an array instance. */ var LaunchArrayInstance = function(session) { /* Create a new instance of the LaunchArrayInstance Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/LaunchArrayInstance" LaunchArrayInstance.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new LaunchArrayInstanceResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new LaunchArrayInstanceInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the LaunchArrayInstance Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var LaunchArrayInstanceInputSet = function() { LaunchArrayInstanceInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the LaunchArrayInstance Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var LaunchArrayInstanceResultSet = function(resultStream) { LaunchArrayInstanceResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(LaunchArrayInstance, choreography.Choreography); util.inherits(LaunchArrayInstanceInputSet, choreography.InputSet); util.inherits(LaunchArrayInstanceResultSet, choreography.ResultSet); exports.LaunchArrayInstance = LaunchArrayInstance; /* ListAllOperationalArrayInstances List all operational instances in an array. */ var ListAllOperationalArrayInstances = function(session) { /* Create a new instance of the ListAllOperationalArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ListAllOperationalArrayInstances" ListAllOperationalArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ListAllOperationalArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ListAllOperationalArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ListAllOperationalArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ListAllOperationalArrayInstancesInputSet = function() { ListAllOperationalArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ListAllOperationalArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ListAllOperationalArrayInstancesResultSet = function(resultStream) { ListAllOperationalArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ListAllOperationalArrayInstances, choreography.Choreography); util.inherits(ListAllOperationalArrayInstancesInputSet, choreography.InputSet); util.inherits(ListAllOperationalArrayInstancesResultSet, choreography.ResultSet); exports.ListAllOperationalArrayInstances = ListAllOperationalArrayInstances; /* RunRightScript Executes a specified RightScript. */ var RunRightScript = function(session) { /* Create a new instance of the RunRightScript Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/RunRightScript" RunRightScript.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new RunRightScriptResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new RunRightScriptInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the RunRightScript Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var RunRightScriptInputSet = function() { RunRightScriptInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the RightScriptID input for this Choreo. ((required, integer) The ID of the RightScript.) */ this.set_RightScriptID = function(value) { this.setInput("RightScriptID", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the RunRightScript Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var RunRightScriptResultSet = function(resultStream) { RunRightScriptResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(RunRightScript, choreography.Choreography); util.inherits(RunRightScriptInputSet, choreography.InputSet); util.inherits(RunRightScriptResultSet, choreography.ResultSet); exports.RunRightScript = RunRightScript; /* ShowArray Display a comrephensive set of information about the querried array such as: server(s) state information, array templates used, array state, etc. */ var ShowArray = function(session) { /* Create a new instance of the ShowArray Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowArray" ShowArray.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowArrayResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowArrayInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowArray Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowArrayInputSet = function() { ShowArrayInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowArray Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowArrayResultSet = function(resultStream) { ShowArrayResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowArray, choreography.Choreography); util.inherits(ShowArrayInputSet, choreography.InputSet); util.inherits(ShowArrayResultSet, choreography.ResultSet); exports.ShowArray = ShowArray; /* ShowDeploymentIndex Retrieve a list of server assets grouped within a particular RightScale Deployment ID. */ var ShowDeploymentIndex = function(session) { /* Create a new instance of the ShowDeploymentIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowDeploymentIndex" ShowDeploymentIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowDeploymentIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowDeploymentIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowDeploymentIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowDeploymentIndexInputSet = function() { ShowDeploymentIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentID input for this Choreo. ((required, integer) The DeploymentID to only list servers in this particular RightScale deployment.) */ this.set_DeploymentID = function(value) { this.setInput("DeploymentID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerSettings input for this Choreo. ((optional, string) Display additional information about this RightScale deployment. Set True to enable.) */ this.set_ServerSettings = function(value) { this.setInput("ServerSettings", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowDeploymentIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowDeploymentIndexResultSet = function(resultStream) { ShowDeploymentIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowDeploymentIndex, choreography.Choreography); util.inherits(ShowDeploymentIndexInputSet, choreography.InputSet); util.inherits(ShowDeploymentIndexResultSet, choreography.ResultSet); exports.ShowDeploymentIndex = ShowDeploymentIndex; /* ShowServer Display a comrephensive set of information about the querried server such as: state information, server templates used, SSH key href, etc. */ var ShowServer = function(session) { /* Create a new instance of the ShowServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServer" ShowServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerInputSet = function() { ShowServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerResultSet = function(resultStream) { ShowServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServer, choreography.Choreography); util.inherits(ShowServerInputSet, choreography.InputSet); util.inherits(ShowServerResultSet, choreography.ResultSet); exports.ShowServer = ShowServer; /* ShowServerIndex Display an index of all servers in a RightScale account. */ var ShowServerIndex = function(session) { /* Create a new instance of the ShowServerIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServerIndex" ShowServerIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServerIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerIndexInputSet = function() { ShowServerIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServerIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerIndexResultSet = function(resultStream) { ShowServerIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServerIndex, choreography.Choreography); util.inherits(ShowServerIndexInputSet, choreography.InputSet); util.inherits(ShowServerIndexResultSet, choreography.ResultSet); exports.ShowServerIndex = ShowServerIndex; /* StartServer Start a server associated with a particular Server ID. Optionally, this Choreo can also poll the startup process and verify server startup. */ var StartServer = function(session) { /* Create a new instance of the StartServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StartServer" StartServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StartServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StartServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StartServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StartServerInputSet = function() { StartServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StartServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StartServerResultSet = function(resultStream) { StartServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StartServer, choreography.Choreography); util.inherits(StartServerInputSet, choreography.InputSet); util.inherits(StartServerResultSet, choreography.ResultSet); exports.StartServer = StartServer; /* StopServer Stop a RightScale server instance. Optionally, this Choreo can also poll the stop process and verify server termination. */ var StopServer = function(session) { /* Create a new instance of the StopServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StopServer" StopServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StopServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StopServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StopServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StopServerInputSet = function() { StopServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StopServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StopServerResultSet = function(resultStream) { StopServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StopServer, choreography.Choreography); util.inherits(StopServerInputSet, choreography.InputSet); util.inherits(StopServerResultSet, choreography.ResultSet); exports.StopServer = StopServer; /* TerminateArrayInstances Terminate an array instance. */ var TerminateArrayInstances = function(session) { /* Create a new instance of the TerminateArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/TerminateArrayInstances" TerminateArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new TerminateArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new TerminateArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the TerminateArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var TerminateArrayInstancesInputSet = function() { TerminateArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the TerminateArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var TerminateArrayInstancesResultSet = function(resultStream) { TerminateArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(TerminateArrayInstances, choreography.Choreography); util.inherits(TerminateArrayInstancesInputSet, choreography.InputSet); util.inherits(TerminateArrayInstancesResultSet, choreography.ResultSet); exports.TerminateArrayInstances = TerminateArrayInstances;
var path = require('path'); var webpack = require('webpack'); var _ = require('lodash'); var baseConfig = require('./base'); // Add needed plugins here var BowerWebpackPlugin = require('bower-webpack-plugin'); var config = _.merge({ entry: [ 'webpack-dev-server/client?http://127.0.0.1:8000', 'webpack/hot/only-dev-server', './src/components/run' ], cache: true, devtool: 'eval', plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BowerWebpackPlugin({ searchResolveModulesDirectories: false }) ] }, baseConfig); // Add needed loaders config.module.loaders.push({ test: /\.(js|jsx)$/, loader: 'react-hot!babel-loader', include: path.join(__dirname, '/../src') }); module.exports = config;
/*eslint-env mocha*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <[email protected]> * * @license MIT */ 'use strict'; var assert = require('assert'); var fs = require('fs'); var run = require('./fixture/run'); var sandbox = require('./fixture/sandbox'); describe('node', function () { it('passes', function (done) { run('passes', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('fails and continues if `it` throws', function (done) { run('fails', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(code, 1); var lines = stdout.trim().split(/\n+/); assert.equal(lines[0], '# node:'); assert.equal(lines[1], 'not ok 1 test fails synchronously'); assert.equal(lines[3], ' Error: Oh noes!'); var p = lines.indexOf('not ok 2 test fails asynchronously'); assert.notEqual(p, -1); assert.equal(lines[p + 2], ' Error: Oh noes!'); p = lines.indexOf('ok 3 test passes synchronously', p + 2); assert.notEqual(p, -1); assert.equal(lines[p + 1], 'ok 4 test passes asynchronously'); assert.equal(lines[p + 2], '# tests 4'); assert.equal(lines[p + 3], '# pass 2'); assert.equal(lines[p + 4], '# fail 2'); assert.equal(lines[p + 5], '1..4'); done(); }); }); it('fails and exits if `describe` throws', function (done) { run('describe-throws', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout.indexOf('# node:'), 0); assert.equal(stdout.indexOf('i should not show up'), -1); assert.equal(code, 1); done(); }); }); it('coverage tap', function (done) { run('passes', ['--node', '--cover', '-R', 'tap'], function (code, stdout, stderr) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(stderr, '# coverage: 8/8 (100.00 %)\n\n'); assert.equal(code, 0); done(); }); }); it('coverage dot', function (done) { run('passes', ['--node', '--cover', '--no-colors', '-R', 'dot'], function (code, stdout, stderr) { var lines = stdout.trim().split(/\n+/); assert.equal(lines[0], '# node:'); assert.equal(lines[1], ' .'); assert.equal(stderr, '# coverage: 8/8 (100.00 %)\n\n'); assert.equal(code, 0); done(); }); }); it('fails if test fails but coverage is fine', function (done) { run('fails', ['--node', '--cover', '-R', 'tap'], function (code) { assert.equal(code, 1); done(); }); }); it('fails cover', function (done) { run('fails-cover', ['--node', '--cover', '-R', 'tap'], function (code, stdout, stderr) { assert.equal(stdout, '# node:\n' + 'ok 1 test does not cover\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); var coverOut = '\n# coverage: 9/10 (90.00 %)\n\nError: Exit 1\n\n'; assert.equal(stderr.substring(stderr.length - coverOut.length), coverOut); assert.equal(code, 1); done(); }); }); it('times out', function (done) { run('timeout', ['--node', '-R', 'tap', '--timeout', '10'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 test times out\n'), 0); assert.equal(code, 1); done(); }); }); it('uses tdd ui', function (done) { run('ui-tdd', ['--node', '-R', 'tap', '--ui', 'tdd'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('enables color', function (done) { run('passes', ['--node', '-R', 'dot', '--colors'], function (code, stdout) { assert.equal(stdout.trim().split('\n')[3], ' \u001b[90m.\u001b[0m'); assert.equal(code, 0); done(); }); }); it('passes transform to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '../transform.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes transform with options to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '[', '../transform.js', '-x', ']'], function (code, stdout) { var lines = stdout.split('\n'); assert(JSON.parse(lines[1]).x); assert.equal(code, 0); done(); }); }); it('passes multiple transforms to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--transform', '../transform.js', '--transform', '../transform.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(lines[2], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes plugin to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '../plugin.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('passes plugin with options to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '[', '../plugin.js', '-x', ']'], function (code, stdout) { var lines = stdout.split('\n'); assert(JSON.parse(lines[1]).x); assert.equal(code, 0); done(); }); }); it('passes multiple plugins to browserify', function (done) { run('passes', ['--node', '-R', 'tap', '--plugin', '../plugin.js', '--plugin', '../plugin.js'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[0], 'passes/test/passes.js'); assert.equal(lines[2], 'passes/test/passes.js'); assert.equal(code, 0); done(); }); }); it('requires file', function (done) { run('require', ['--node', '-R', 'tap', '-r', '../required'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'required'); assert.equal(code, 0); done(); }); }); it('passes extension to browserify', function (done) { run('extension', ['--node', '-R', 'tap', '--extension', '.coffee'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'coffeescript'); assert.equal(code, 0); done(); }); }); it('passes multiple extensions to browserify', function (done) { run('extension-multiple', ['--node', '-R', 'tap', '--extension', '.coffee', '--extension', '.ts'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1], 'coffeescript'); assert.equal(lines[2], 'typescript'); assert.equal(code, 0); done(); }); }); it('passes recursive', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes non-default recursive', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive', 'other'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 other recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes non-default recursive with trailing /*.js', function (done) { run('recursive', ['--node', '-R', 'tap', '--recursive', 'other/*.js'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 other recursive passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('passes browser-field', function (done) { run('browser-field', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 browser-field passes in browser\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('fails browser-field with --browser-field disabled', function (done) { run('browser-field', ['--node', '-R', 'tap', '--no-browser-field'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 browser-field passes in browser\n' + ' Error'), 0); assert.equal(code, 1); done(); }); }); // This test case passes on node 6 but fails on node 8 and 10. The // corresponding chromium test also passes. it.skip('shows unicode diff', function (done) { run('unicode', ['--node', '-R', 'tap'], function (code, stdout) { assert.equal(stdout.indexOf('# node:\n' + 'not ok 1 unicode prints diff\n' + ' AssertionError: \'€\' == \'3\''), 0); assert.equal(code, 1); done(); }); }); it('fails external', function (done) { run('external', ['--node', '-R', 'tap'], function (code, stdout, stderr) { console.log(stderr); assert.notEqual( stderr.indexOf('Cannot find module \'unresolvable\''), -1); assert.equal(code, 1); done(); }); }); it('passes external with --external enabled', function (done) { run('external', ['--node', '-R', 'tap', '--external', 'unresolvable'], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test external\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); }); it('supports --outfile', sandbox(function (done, tmpdir) { var outfile = tmpdir + '/report.txt'; run('passes', ['--node', '-R', 'tap', '--outfile', outfile], function (code, stdout) { assert.equal(code, 0); assert.equal(stdout, ''); assert.equal(fs.readFileSync(outfile, 'utf8'), '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); done(); }); })); it('supports --mocha-path', sandbox(function (done) { var mochaPath = './node_modules/mocha'; run('passes', ['--node', '-R', 'tap', '--mocha-path', mochaPath], function (code, stdout) { assert.equal(stdout, '# node:\n' + 'ok 1 test passes\n' + '# tests 1\n' + '# pass 1\n' + '# fail 0\n' + '1..1\n'); assert.equal(code, 0); done(); }); })); });
var http = require('http') var https = require('https') var corsify = require('corsify') var collect = require('stream-collector') var pump = require('pump') var iterate = require('random-iterate') var limiter = require('size-limit-stream') var eos = require('end-of-stream') var flushHeaders = function (res) { if (res.flushHeaders) { res.flushHeaders() } else { if (!res._header) res._implicitHeader() res._send('') } } module.exports = function (opts) { var channels = {} var maxBroadcasts = (opts && opts.maxBroadcasts) || Infinity var get = function (channel) { if (channels[channel]) return channels[channel] channels[channel] = {name: channel, subscribers: []} return channels[channel] } var cors = corsify({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Headers": "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }) var onRequest = cors(function (req, res) { if (req.url === '/') { res.end(JSON.stringify({name: 'signalhub', version: require('./package').version}, null, 2) + '\n') return } if (req.url.slice(0, 4) !== '/v1/') { res.statusCode = 404 res.end() return } var name = req.url.slice(4).split('?')[0] if (req.method === 'POST') { collect(pump(req, limiter(64 * 1024)), function (err, data) { if (err) return res.end() if (!channels[name]) return res.end() var channel = get(name) server.emit('publish', channel.name, data) data = Buffer.concat(data).toString() var ite = iterate(channel.subscribers) var next var cnt = 0 while ((next = ite()) && cnt++ < maxBroadcasts) { next.write('data: ' + data + '\n\n') } res.end() }) return } if (req.method === 'GET') { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8') var app = name.split('/')[0] var channelNames = name.slice(app.length + 1) channelNames.split(',').forEach(function (channelName) { var channel = get(app + '/' + channelName) server.emit('subscribe', channel.name) channel.subscribers.push(res) eos(res, function () { var i = channel.subscribers.indexOf(res) if (i > -1) channel.subscribers.splice(i, 1) if (!channel.subscribers.length && channel === channels[channel.name]) delete channels[channel.name] }) }) flushHeaders(res) return } res.statusCode = 404 res.end() }) var server = ((opts && opts.key) ? https : http).createServer(opts) server.on('request', onRequest) return server }
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var centers = require('../../app/controllers/centers'); // Centers Routes app.route('/centers') .get(centers.list) app.route('/centers') .get(centers.create) app.route('/centers/:centerId') .get(centers.read) .put(users.requiresLogin, centers.hasAuthorization, centers.update) .delete(users.requiresLogin, centers.hasAuthorization, centers.delete); // Finish by binding the Center middleware app.param('centerId', centers.centerByID); };
(function(){$(document).ready(function(){$(".joindin").each(function(){var e=$(this);var t=e.attr("href");var n=parseInt(t.substr(t.lastIndexOf("/")+1));$.getJSON("https://api.joind.in/v2.1/talks/"+n+"?callback=?",function(t){var n=t.talks[0].average_rating;if(n>0){e.after(' <img src="/images/ji-ratings/rating-'+n+'.gif" />')}})})})})()
const path = require('path') const merge = require('webpack-merge') const webpack = require('webpack') const baseWebpackConfig = require('./webpack.base.config') const ExtractTextPlugin = require("extract-text-webpack-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = merge(baseWebpackConfig, { output: { path: resolve('dist'), filename: '[name].[hash].js' }, plugins: [ // optimize css for production new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), new ExtractTextPlugin('style.[hash].css'), // split vendor js into separate file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // this assumes your vendor imports exist in the node_modules directory return module.context && module.context.indexOf("node_modules") !== -1; } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), ] })
export default { html: ` <p>42</p> <p>42</p> `, async test({ assert, component, target }) { await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateStore(33); assert.htmlEqual(target.innerHTML, '<p>33</p><p>42</p>'); await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); await component.updateVar(33); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>33</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); } };
// extglyde // // Glyde Glue Plugin // (c)2015 by Cylexia, All Rights Reserved // // Version: 1.15.0625 // // MIT License var ExtGlyde = { GLUE_STOP_ACTION: -200, plane: null, // Canvas resources: null, styles: null, buttons: null, keys: null, button_sequence: [], timers: null, timer_manager: null, action: "", action_params: "", resume_label: "", last_action_id: "", window_title: "", window_width: -1, window_height: -1, background_colour: "#fff", _inited: false, init: function( canvas, filemanager ) { "use strict"; if( !ExtGlyde._inited ) { ExtGlyde.plane = canvas; ExtGlyde.reset(); ExtGlyde._inited = true; return true; } return false; }, reset: function() { ExtGlyde.clearUI(); ExtGlyde.resources = null; ExtGlyde.styles = null; ExtGlyde.timers = null; ExtGlyde.last_action_id = ""; ExtGlyde.window_title = ""; ExtGlyde.window_width = -1; ExtGlyde.window_height = -1; ExtGlyde.background_colour = "#fff"; }, setSize: function( w, h ) { ExtGlyde.window_width = w; ExtGlyde.window_height = h; ExtGlyde.plane.width = w;//(w + "px"); ExtGlyde.plane.height = h;//(h + "px"); ExtGlyde._drawRect( ExtGlyde.getBitmap(), { x: 0, y: 0, width: w, height: h, colour: ExtGlyde.background_colour }, true ); }, getWindowTitle: function() { return ExtGlyde.window_title; }, getWindowWidth: function() { return ExtGlyde.window_width; }, getWindowHeight: function() { return ExtGlyde.window_height; }, /** * If set then the script requests that the given action be performed then resumed from * getResumeLabel(). This is cleared once read * @return the action or null */ getAction: function() { var o = ExtGlyde.action; ExtGlyde.action = null; return o; }, getActionParams: function() { return ExtGlyde.action_params; }, /** * Certain actions call back to the runtime host and need to be resumed, resume from this label * This is cleared once read * @return the label */ getResumeLabel: function() { var o = ExtGlyde.resume_label; ExtGlyde.resume_label = null; return o; }, /** * The bitmap the drawing operations use * @return */ getBitmap: function() { return ExtGlyde.plane.getContext( "2d" ); }, /** * Called when this is attached to a {@link com.cylexia.mobile.lib.glue.Glue} instance * * @param g the instance being attached to */ glueAttach: function( f_plugin, f_glue ) { window.addEventListener( "keydown", function( e ) { ExtGlyde._keyDownHandler( f_glue, (e || window.event) ); } ); window.addEventListener( "keypress", function( e ) { ExtGlyde._keyPressHandler( f_glue, (e || window.event) ); } ); }, /** * Called to execute a glue command * * @param w the command line. The command is in "_" * @param vars the current Glue variables map * @return 1 if the command was successful, 0 if it failed or -1 if it didn't belong to this * plugin */ glueCommand: function( glue, w, vars ) { var cmd = Dict.valueOf( w, "_" ); if( cmd && cmd.startsWith( "f." ) ) { var wc = Dict.valueOf( w, cmd ); cmd = cmd.substring( 2 ); if( (cmd == "setwidth") || (cmd == "setviewwidth") ) { return ExtGlyde.setupView( w ); } else if( cmd == "settitle" ) { return ExtGlyde.setTitle( wc, w ); } else if( cmd == "doaction" ) { return ExtGlyde.doAction( wc, w ); } else if( (cmd == "clear") || (cmd == "clearview") ) { ExtGlyde.clearUI(); } else if( cmd == "loadresource" ) { return ExtGlyde.loadResource( glue, wc, Dict.valueOf( w, "as" ) ); } else if( cmd == "removeresource" ) { if( ExtGlyde.resources !== null ) { delete ExtGlyde.resources[wc]; } } else if( cmd == "setstyle" ) { ExtGlyde.setStyle( wc, w ); } else if( cmd == "getlastactionid" ) { Dict.set( vars, Dict.valueOf( w, "into" ), ExtGlyde.last_action_id ); } else if( cmd == "onkey" ) { if( ExtGlyde.keys === null ) { ExtGlyde.keys = Dict.create(); } var ke = Dict.create(); Dict.set( ke, "label", Dict.valueOf( w, "goto" ) ); Dict.set( ke, "id", Dict.valueOf( w, "useid" ) ); Dict.set( ExtGlyde.keys, wc, ke ); } else if( cmd == "starttimer" ) { ExtGlyde._startTimer( glue, wc, Dict.intValueOf( w, "interval" ), Dict.valueOf( w, "ontickgoto" ) ); } else if( cmd == "stoptimer" ) { ExtGlyde._stopTimer( wc ); } else if( cmd == "stopalltimers" ) { ExtGlyde._stopTimer( "" ); } else if( cmd == "drawas" ) { ExtGlyde.drawAs( wc, w ); } else if( cmd == "writeas" ) { // TODO: colour return ExtGlyde.writeAs( wc, w ); } else if( (cmd == "markas") || (cmd == "addbutton") ) { return ExtGlyde.markAs( wc, w ); } else if( cmd == "paintrectas" ) { return ExtGlyde.paintRectAs( wc, w, false ); } else if( cmd == "paintfilledrectas" ) { return ExtGlyde.paintRectAs( wc, w, true ); } else if( cmd == "exit" ) { if( chrome && chrome.app ) { chrome.app.window.current().close(); } else if( window ) { window.close(); } return Glue.PLUGIN_DONE_EXIT_ALL; } else { return -1; } return 1; } return 0; }, getLabelForButtonAt: function( i_x, i_y ) { if( ExtGlyde.buttons !== null ) { for( var i = 0; i < ExtGlyde.button_sequence.length; i++ ) { var id = ExtGlyde.button_sequence[i]; var btn = ExtGlyde.buttons[id]; var r = ExtGlyde.Button.getRect( btn ); if( ExtGlyde.Rect.containsPoint( r, i_x, i_y ) ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( btn ); } } } return null; }, /** * Get the id of the button at the given index * @param index the index of the button * @return the id or null if the index is out of bounds */ getButtonIdAtIndex: function( index ) { if( ExtGlyde.button_sequence.length > 0 ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { return ExtGlyde.button_sequence[index]; } } return null; }, /** * Get the rect of the given indexed button * @param index the button index * @return the rect as ExtGlyde.Rect or null if index is out of bounds */ getButtonRectAtIndex: function( index ) { var id = ExtGlyde.getButtonIdAtIndex( index ); if( id !== null ) { return ExtGlyde.Button.getRect( ExtGlyde.buttons[id] ); } return null; }, /** * Return the label for the given indexed button. Also sets the lastActionId value * @param index the index * @return the label or null if index is out of bounds */ getButtonLabelAtIndex: function( index ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { var id = button_sequence[index]; if( id !== null ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( buttons[id] ); } } return null; }, getButtonCount: function() { return ExtGlyde.button_sequence.length; }, /** * Add a definition to the (lazily created) styles map. Note, the complete string is stored * so beware that keys like "_" and "f.setstyle" are added too * @param name string: the name of the style * @param data map: the complete arguments string */ setStyle: function( name, data ) { if( ExtGlyde.styles === null ) { ExtGlyde.styles = Dict.create(); } Dict.set( ExtGlyde.styles, name, data ); }, setupView: function( w ) { if( Dict.containsKey( w, "backgroundcolour" ) ) { ExtGlyde.background_colour = Dict.valueOf( w, "backgroundcolour" ); } else { this.background = "#fff"; } ExtGlyde.setSize( Dict.intValueOf( w, Dict.valueOf( w, "_" ) ), Dict.intValueOf( w, "height" ) ); return true; }, setTitle: function( wc, w ) { var tb_title = _.e( "tb_title" ); if( tb_title ) { tb_title.removeChild( tb_title.childNodes[0] ); _.at( tb_title, wc ); } if( window ) { window.title = wc; document.title = wc; } _.e( "windowtitlebar" ).style["display"] = (wc ? "block" : "none"); return 1; }, clearUI: function() { ExtGlyde.button_sequence = []; if( ExtGlyde.buttons !== null ) { Dict.delete( ExtGlyde.buttons ); } ExtGlyde.buttons = Dict.create(); if( ExtGlyde.keys !== null ) { Dict.delete( ExtGlyde.keys ); } ExtGlyde.keys = Dict.create(); ExtGlyde.setSize( ExtGlyde.window_width, ExtGlyde.window_height ); }, doAction: function( s_action, d_w ) { "use strict"; ExtGlyde.action = s_action; ExtGlyde.action_params = Dict.valueOf( d_w, "args", Dict.valueOf( d_w, "withargs" ) ); var done_label = Dict.valueOf( d_w, "ondonegoto" ); ExtGlue.resume_label = ( done_label + "\t" + Dict.valueOf( d_w, "onerrorgoto", done_label ) + "\t" + Dict.valueOf( d_w, "onunsupportedgoto", done_label ) ); return ExtFrontEnd.GLUE_STOP_ACTION; // expects labels to be DONE|ERROR|UNSUPPORTED }, // TODO: this should use a rect and alignment options along with colour support writeAs: function( s_id, d_args ) { "use strict"; ExtGlyde.updateFromStyle( d_args ); var text = Dict.valueOf( d_args, "value" ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); var rw = ExtGlyde.Rect.getWidth( rect ); var rh = ExtGlyde.Rect.getHeight( rect ); var size = Dict.intValueOf( d_args, "size", 2 ); var thickness = Dict.intValueOf( d_args, "thickness", 1 ); var tw = (VecText.getGlyphWidth( size, thickness ) * text.length); var th = VecText.getGlyphHeight( size, thickness ); var tx, ty; if( rw > 0 ) { var align = Dict.valueOf( d_args, "align", "2" ); if( (align == "2") || (align == "centre") ) { tx = (x + ((rw - tw) / 2)); } else if( (align == "1" ) || (align == "right") ) { tx = (x + (rw - tw)); } else { tx = x; } } else { rw = tw; tx = x; } if( rh > 0 ) { ty = (y + ((rh - th) / 2)); } else { rh = th; ty = y; } VecText.drawString( ExtGlyde.getBitmap(), text, Dict.valueOf( d_args, "colour", "#000" ), tx, ty, size, thickness, (thickness + 1) ); rect = ExtGlyde.Rect.create( x, y, rw, rh ); // Dict: ExtGlyde.Rect return ExtGlyde.buttonise( s_id, rect, d_args ); }, drawAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var rid = Dict.valueOf( d_args, "id", Dict.valueOf( d_args, "resource" ) ); if( ExtGlyde.resources !== null ) { var b = rid.indexOf( '.' ); if( b > -1 ) { var resid = rid.substring( 0, b ); var imgid = rid.substring( (b + 1) ); var keys = Dict.keys( ExtGlyde.resources ); for( var i = 0; i < keys.length; i++ ) { var imgmap = Dict.valueOf( ExtGlyde.resources, keys[i] ); // imgmap: ExtGlyde.ImageMap var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); if( ExtGlyde.ImageMap.drawToCanvas( imgmap, imgid, ExtGlyde.getBitmap(), x, y ) ) { var maprect = ExtGlyde.ImageMap.getRectWithId( imgmap, imgid ); var imgrect = ExtGlyde.Rect.create( x, y, ExtGlyde.Rect.getWidth( maprect ), ExtGlyde.Rect.getHeight( maprect ) ); return ExtGlyde.buttonise( s_id, imgrect, d_args ); } } } } return false; }, markAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); return ExtGlyde.buttonise( s_id, ExtGlyde.Rect.createFromCommandArgs( d_args ), m_args ); }, paintRectAs: function( s_id, d_args, b_filled ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var d = Dict.create(); Dict.set( d, "rect", rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d, b_filled ); return ExtGlyde.buttonise( s_id, rect, d_args ); }, buttonise: function( s_id, d_rect, d_args ) { "use strict"; if( Dict.containsKey( d_args, "border" ) ) { var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d ); } if( Dict.containsKey( d_args, "onclickgoto" ) ) { return ExtGlyde.addButton( s_id, d_rect, Dict.valueOf( d_args, "onclickgoto" ) ); } else { return true; } }, addButton: function( s_id, d_rect, s_label ) { if( ExtGlyde.buttons === null ) { ExtGlyde.buttons = Dict.create(); ExtGlyde.button_sequence = []; } if( !Dict.containsKey( ExtGlyde.buttons, s_id ) ) { Dict.set( ExtGlyde.buttons, s_id, ExtGlyde.Button.createFromRect( d_rect, s_label ) ); ExtGlyde.button_sequence.push( s_id ); return true; } return false; }, updateFromStyle: function( d_a ) { "use strict"; if( (ExtGlyde.styles === null) || (ExtGlyde.styles.length === 0) ) { return; } if( Dict.containsKey( d_a, "style" ) ) { var style = Dict.valueOf( styles, Dict.valueOf( d_a, "style" ) ); var keys = Dict.keys( style ); for( var i = 0; i < keys.length; i++ ) { var k = keys[i]; if( !Dict.containsKey( d_a, k ) ) { Dict.set( d_a, k, Dict.valueOf( style, keys[i] ) ); } } } }, loadResource: function( o_glue, s_src, s_id ) { if( ExtGlyde.resources === null ) { ExtGlyde.resources = Dict.create(); } if( Dict.containsKey( ExtGlyde.resources, s_id ) ) { // deallocate } // resources can be replaced using the same ids var data = GlueFileManager.readText( s_src ); Dict.set( ExtGlyde.resources, s_id, ExtGlyde.ImageMap.create( data ) ); return true; }, _drawRect: function( o_context, d_def, b_filled ) { "use strict"; var x, y, w, h; if( Dict.containsKey( d_def, "rect" ) ) { var r = Dict.dictValueOf( d_def, "rect" ); x = ExtGlyde.Rect.getLeft( r ); y = ExtGlyde.Rect.getTop( r ); w = ExtGlyde.Rect.getWidth( r ); h = ExtGlyde.Rect.getHeight( r ); } else { x = Dict.intValueOf( d_def, "x" ); y = Dict.intValueOf( d_def, "y" ); w = Dict.intValueOf( d_def, "width" ); h = Dict.intValueOf( d_def, "height" ); } if( b_filled ) { o_context.fillStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.fillRect( x, y, w, h ); } else { o_context.fillStyle = "none"; o_context.strokeStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.lineWidth = 1; o_context.strokeRect( x, y, w, h ); } }, _timerFired: function() { if( ExtGlyde.timers ) { for( var id in ExtGlyde.timers ) { var t = ExtGlyde.timers[id]; t["count"]--; if( t["count"] === 0 ) { t["count"] = t["reset"]; Glue.run( t["glue"], t["label"] ); } } } }, _startTimer: function( o_glue, s_id, i_tenths, s_label ) { if( !ExtGlyde.timers ) { ExtGlyde.timer_manager = window.setInterval( ExtGlyde._timerFired, 100 ); // install our timer ExtGlyde.timers = {}; } var t = { "glue": o_glue, "count": i_tenths, "reset": i_tenths, "label": s_label }; ExtGlyde.timers[s_id] = t; }, _stopTimer: function( s_id ) { if( !ExtGlyde.timers ) { return; } if( s_id ) { if( ExtGlyde.timers[s_id] ) { delete ExtGlyde.timers[s_id]; } if( ExtGlyde.timers.length > 0 ) { return; } } // out of timers or requested that we stop them all if( ExtGlyde.timer_manager ) { window.clearInterval( ExtGlyde.timer_manager ); ExtGlyde.timer_manager = null; } ExtGlyde.timers = null; }, // keyboard handling _keyDownHandler: function( f_glue, e ) { e = (e || window.event); var kmap = { 37: "direction_left", 38: "direction_up", 39: "direction_right", 40: "direction_down", 27: "escape", 9: "tab", 13: "enter", 8: "backspace", 46: "delete", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12" }; if( e.keyCode in kmap ) { if( ExtGlyde._notifyKeyPress( f_glue, kmap[e.keyCode] ) ) { e.preventDefault(); } } }, _keyPressHandler: function( f_glue, e ) { e = (e || window.event ); if( ExtGlyde._notifyKeyPress( f_glue, String.fromCharCode( e.charCode ) ) ) { e.preventDefault(); } }, _notifyKeyPress: function( f_glue, s_key ) { // boolean if( ExtGlyde.keys && (s_key in ExtGlyde.keys) ) { var ke = ExtGlyde.keys[s_key]; ExtGlyde.last_action_id = Dict.valueOf( ke, "id" ); Glue.run( f_glue, Dict.valueOf( ke, "label" ) ); return true; } return false; }, /** * Stores a button */ Button: { create: function( i_x, i_y, i_w, i_h, s_label ) { // Dict: ExtGlyde.Button return Button.createFromRect( ExtGlyde.Rect.create( i_x, i_y, i_w, i_h ), s_label ); }, createFromRect: function( d_rect, s_label ) { // Dict: ExtGlyde.Button var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "label", s_label ); return d; }, getLabel: function( d_button ) { return d_button.label; }, getRect: function( d_button ) { return d_button.rect; } }, /** * Access to a Rect */ Rect: { create: function( i_x, i_y, i_w, i_h ) { // Dict: ExtGlyde.Rect var r = Dict.create(); Dict.set( r, "x", i_x ); Dict.set( r, "y", i_y ); Dict.set( r, "w", i_w ); Dict.set( r, "h", i_h ); return r; }, createFromCommandArgs: function( d_args ) { // Dict: ExtGlyde.Rect "use strict"; var x = Dict.intValueOf( d_args, "x", Dict.intValueOf( d_args, "atx" ) ); var y = Dict.intValueOf( d_args, "y", Dict.intValueOf( d_args, "aty" ) ); var w = Dict.intValueOf( d_args, "width" ); var h = Dict.intValueOf( d_args, "height" ); return ExtGlyde.Rect.create( x, y, w, h ); }, containsPoint: function( d_rect, i_x, i_y ) { var rx = Dict.intValueOf( d_rect, "x" ); var ry = Dict.intValueOf( d_rect, "y" ); if( (i_x >= rx) && (i_y >= ry) ) { if( (i_x < (rx + Dict.intValueOf( d_rect, "w" ))) && (i_y < (ry + Dict.intValueOf( d_rect, "h" ))) ) { return true; } } return false; }, getLeft: function( o_rect ) { return o_rect.x; }, getTop: function( o_rect ) { return o_rect.y; }, getWidth: function( o_rect ) { return o_rect.w; }, getHeight: function( o_rect ) { return o_rect.h; }, getRight: function( o_rect ) { return (o_rect.x + o_rect.w); }, getBottom: function( o_rect ) { return (o_rect.y + o_rect.h); } }, /** * Processes a .map source loading the image named in it or the specified image * @returns a Dict for use with ExtGlyde.ImageMap */ ImageMap: { create: function( s_mapdata ) { // Dict: ImageMap var im = Dict.create(); var im_rects = Dict.create(); var e, i; var key, value; var bmpsrc; while( (i = s_mapdata.indexOf( ";" )) > -1 ) { var line = s_mapdata.substr( 0, i ).trim(); s_mapdata = s_mapdata.substr( (i + 1) ); e = line.indexOf( "=" ); if( e > -1 ) { key = line.substring( 0, e ); value = line.substring( (e + 1) ); if( key.startsWith( "." ) ) { if( key == ".img" ) { if( !bmpsrc ) { bmpsrc = value; } } } else { Dict.set( im_rects, key, ExtGlyde.ImageMap._decodeRect( value ) ); } } } Dict.set( im, "image", ExtGlyde.ImageMap._loadBitmap( bmpsrc ) ); Dict.set( im, "rects", im_rects ); return im; }, getRectWithId: function( o_imap, s_id ) { // Dict: ExtGlyde.Rect var d_rects = Dict.dictValueOf( o_imap, "rects" ); return Dict.dictValueOf( d_rects, s_id ); }, drawToCanvas: function( o_imap, s_id, o_context, i_x, i_y ) { "use strict"; var src = ExtGlyde.ImageMap.getRectWithId( o_imap, s_id ); // Dict: ExtGlyde.Rect if( src !== null ) { var w = ExtGlyde.Rect.getWidth( src ); var h = ExtGlyde.Rect.getHeight( src ); o_context.drawImage( o_imap.image, ExtGlyde.Rect.getLeft( src ), ExtGlyde.Rect.getTop( src ), w, h, i_x, i_y, w, h ); return true; } return false; }, _loadBitmap: function( s_src ) { var data = GlueFileManager.readBinary( s_src ); if( data !== null ) { return data; } // show an error some how return null; }, _decodeRect: function( s_e ) { // Dict if( s_e.charAt( 1 ) == ':' ) { var l = (s_e.charCodeAt( 0 ) - 48); var i = 2, x, y, w, h; x = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; y = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; w = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; h = ExtGlyde.ImageMap.toInt( s_e.substring( i ) ); return ExtGlyde.Rect.create( x, y, w, h ); } return null; }, toInt: function( s_v ) { var n = parseInt( s_v ); if( !isNaN( n ) ) { return n; } return 0; } } };
import React from 'react'; import { applyRouterMiddleware, Router, Route } from 'dva/router'; import { useScroll } from 'react-router-scroll'; import App from '@/app/App'; function RouterConfig({ history }) { return ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}></Route> </Router> ); } export default RouterConfig;