code
stringlengths
2
1.05M
/* * grunt-mailchimp-export-csv * https://github.com/gst1984/gruntmailchimpexportcsv * * Copyright (c) 2015 Gerald Stockinger * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). mailchimp_export_csv: { websubscriber_list: { options : { apiKey : '****', listId : '****', csvFile : 'output.csv' }, }, }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'mailchimp_export_csv', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
'use strict'; angular.module('ps-menu').directive('psMenuItem', [ function () { return { restrict: 'E', require: '^psMenu', transclude: true, templateUrl: '/modules/ps-menu/views/psMenuItemTemplate.html', scope: { label: '@', icon: '@', route: '@' }, link: function (scope, element, attrs, ctrl) { scope.isActive = function () { //console.log(element === ctrl.getActiveElement()); return element === ctrl.getActiveElement(); }; scope.isVertical = function () { //console.log("just invoked .isVertical() from menuItemDirective link func Yo! YO!"); return ctrl.isVertical() || element.parents('.ps-subitem-section').length > 0; }; element.on('click', function (event) { event.stopPropagation(); event.preventDefault(); //we have to use .$apply() to let ng know something is //happening to our scope. Most of this was in Mod2 sec."Menu Item Selection" scope.$apply(function () {//this wasn't working at first because I had passed in 'element' to this func ctrl.setActiveElement(element); ctrl.setRoute(scope.route); }) }); } }; } ]);
/* [email protected] Copyright under The MIT License (MIT) http://opensource.org/licenses/MIT */ jQuery.noConflict(); jQuery( document ).ready(function( $ ) { //Direccion actual var currentDomain = window.location.host; var currentPath = window.location.pathname; //eBay if(currentDomain.indexOf('ebay.com') > -1) { //Tracking number en el historial de compras v2 if(currentPath.indexOf('eBayISAPI') > -1) { var trackingLoopPurchaseHistory = setInterval(function(){ $("div[id^='track_']").each(function() { var trackingNumber = $(this).children('.g-v33:eq(1)').text().trim(); var trackingNext = $(this).next('.seguimientowrap').attr('data-tracking'); $(this).children('.g-v33:eq(1)').next('a').attr('data-tracking', trackingNumber); //if(!$('#seguimientoCorreos_'+trackingNumber).length) { //Dos envios con el mismo número, evitan que se cree uno nuevo al lado de cada número de tracking con esta condición //Si el número de tracking que encontramos a continuación no es el trackign de este loop, entonces creamos el link if(trackingNext != trackingNumber && trackingNumber != '--') { $(this).after(' <div class="seguimientowrap" data-tracking="'+trackingNumber+'"><a href="https://www.correos.cl/web/guest/seguimiento-en-linea?codigos='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en Correos.cl</a></div>'); } }); }, 1000); } //Tracking en el historial de compras v1 //.tracking-label>a.iframe-modal if(currentPath.indexOf('PurchaseHistory') > -1) { var trackingLoopPurchaseHistory = setInterval(function(){ $('.tracking-label>a.iframe-modal').each(function(){ var trackingNumber = $(this).text(); var trackingNext = $(this).next('.seguimientoCorreos').attr('data-tracking'); //Fix Tracking Number trackingNumber = trackingNumber.replace('Tracking number', ''); trackingNumber = trackingNumber.replace('Número de seguimiento', ''); //if(!$('#seguimientoCorreos_'+trackingNumber).length) { //Dos envios con el mismo número, evitan que se cree uno nuevo al lado de cada número de tracking con esta condición //Si el número de tracking que encontramos a continuación no es el trackign de este loop, entonces creamos el link if(trackingNext != trackingNumber) { $(this).after(' // <a href="https://www.correos.cl/web/guest/seguimiento-en-linea?codigos='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en Correos.cl</a>'); } }); }, 1000); } //Tracking number en el detalle de una compra //span data-ng-show="package.deliveryInfo.trackingNumber != null && package.deliveryInfo.trackingNumber != '' if(currentPath.indexOf('FetchOrderDetails') > -1) { var trackingLoopOrderDetails = setInterval(function(){ $('span[data-ng-show*="package.deliveryInfo.trackingNumber"]').each(function(){ var trackingNumber = $(this).text(); var trackingNext = $(this).next('.seguimientoCorreos').attr('data-tracking'); //Fix Tracking Number trackingNumber = trackingNumber.replace('Tracking number', ''); if(!$('#seguimientoCorreos_'+trackingNumber).length) { $(this).after(' // <a href="https://www.correos.cl/web/guest/seguimiento-en-linea?codigos='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en Correos.cl</a>'); } }); }, 1000); } } //AliExpress if(currentDomain.indexOf('aliexpress.com') > -1) { //Tracking number en los detalles de la orden de compra //.shipping-bd>.no if(currentPath.indexOf('order_detail') > -1) { var trackingNumber = $('.shipping-bd>.no').text(); var logisticsName = $('.logistics-name:first').text().toLowerCase(); //Solo correos.cl, NO si: //.logistics-name = dhl, fedex, tnt, ups, aliexpress standard shipping if(logisticsName.indexOf('dhl') == -1 && logisticsName.indexOf('fedex') == -1 && logisticsName.indexOf('tnt') == -1 && logisticsName.indexOf('ups') == -1 && logisticsName.indexOf('aliexpress standard shipping') == -1) { $('.shipping-bd>.no').html(trackingNumber+'<br/><hr/><a href="https://www.correos.cl/web/guest/seguimiento-en-linea?codigos='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en Correos.cl</a>'); } //AliExpress Standard Shipping if(logisticsName.indexOf('aliexpress standard shipping') > -1) { var trackingNumberForCorreos = trackingNumber.toString().trim(); if (trackingNumberForCorreos.match(/^\d/)) { //Begins with a number, let's apply Correos's formatting //Remove the last three chars, then keep the last 12 digits (not including the three we just removed) trackingNumberForCorreos = trackingNumberForCorreos.slice(0, -3); //remove the last three chars //trackingNumberForCorreos = trackingNumberForCorreos.substr(trackingNumberForCorreos.length - 13); //keep the last 12 chars trackingNumberForCorreos = trackingNumberForCorreos.slice(11); //keep the last 12 chars } var trackingCodInput = 'Cod: <input onClick="this.select();" style="width: 70%;"value="'+trackingNumberForCorreos+'" /><br/><hr/>'; trackingNumberForCorreos = trackingNumberForCorreos.trim().replace(/ +/g, '').replace(/(\r\n|\n|\r)/gm, ''); $('.shipping-bd>.no').html(trackingNumber+'<br/><hr/>'+trackingCodInput+'<a href="https://www.correos.cl/web/guest/seguimiento-en-linea?codigos='+trackingNumberForCorreos+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank" title="'+trackingNumberForCorreos+'">Seguimiento en Correos.cl</a>'); } //DHL if(logisticsName.indexOf('dhl') > -1) { $('.shipping-bd>.no').html(trackingNumber+'<br/><hr/><a href="http://www.dhl.cl/content/cl/es/express/rastreo.shtml?brand=DHL&AWB='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en DHL.cl</a>'); } //FedEx if(logisticsName.indexOf('fedex') > -1) { $('.shipping-bd>.no').html(trackingNumber+'<br/><hr/><a href="http://www.fedex.com/fedextrack/html/index.html?tracknumbers='+trackingNumber+'" class="seguimientoCorreos" id="seguimientoCorreos_'+trackingNumber+'" data-tracking="'+trackingNumber+'" target="_blank">Seguimiento en FedEx.com</a>'); } } } });
{ buildEntry(builds[built]) .then(() => { built++; if (built < total) { next(); } }) .catch(logError); }
'use strict'; module.export = { 'env': { 'browser': true, 'node': true, 'jasmine': true, 'protractor': true }, 'extends': [ 'eslint:recommended', 'airbnb-base' ] };
var Game = function(options) { this.options = Utils.merge({ id: 'canvas' }, options); this.canvas = document.getElementById(this.options.id); this.ctx = new ContextWrapper(this.canvas.getContext('2d')); this.resourceManager = new ResourceManager(); this.entityList = new EntityList(this); this.renderer = new Renderer(this, this.entityList); this.eventManager = new EventManager(this); this.input = new Input(this); this.adjustDimensions(); this.previousTime = 0; this.stopped = false; this.started = false; }; Game.debug = false; Game.prototype = { startWithResources: function(resources) { if(resources) { for(var i = resources.length - 1; i >= 0; i--) { this.resourceManager.load(resources[i]); } } this.resourceManager.ready(this.start, this); }, start: function() { if(this.started) { return; } this.started = true; var self = this; this.nextFrame = requestAnimationFrame(function(time) { self.run(time); }); return this; }, run: function(time) { var self = this; if(this.previousTime === 0) { // First frame only gets the time this.previousTime = time; } else { this.renderer.render(this.ctx); // Execute game logic in a callback so that it does not // prevent the animation frame from ending. // http://impactjs.com/forums/impact-engine/misuse-of-requestanimationframe setTimeout(function() { self.entityList.update(time - self.previousTime); }, 0); } // Loop if(!this.stopped) { this.nextFrame = requestAnimationFrame(function(time) { self.run(time); }); } }, stop: function() { this.stopped = true; if(this.nextFrame) { cancelAnimationFrame(this.nextFrame); this.nextFrame = undefined; } return this; }, isRunning: function() { return this.started && !this.stopped; }, register: function(entity) { if(entity.forEach) { entity.forEach(function(e) { this.register(e); }, this); return this; } this.entityList.register(entity); return this; }, /** * Adjusts the size of the game to the size of the canvas. */ adjustDimensions: function() { return this .setWidth(this.canvas.clientWidth) .setHeight(this.canvas.clientHeight); }, /** * Sets the dimensions of the game. * * @param Vector */ setDimensions: function(vec) { return this .setWidth(vec.x) .setHeight(vec.y) ; }, setWidth: function(w) { this.eventManager.handleEvent('width_changed', w); this.canvas.width = this.width = w; return this; }, setHeight: function(h) { this.eventManager.handleEvent('heigth_changed', h); this.canvas.height = this.height = h; return this; }, };
/** * Game Boy Keypad * Set as a single byte of bit-flags for each of the 8 possible keys. * Odd in that it's a high state (1) that represents a button is not pressed. * 1980s technology is notoriously unkind to software developers in the distant * future. */ // Flux import { log } from '../../actions/LogActions.js'; // A byte with each bit representing one of the 8 keys let keys = 0x00; // Map of the keyboard keycodes to the GB Keypad input // TODO: This is where a configurable keyboard would go const keyMap = new Map([ // Right [39, 0x01], // Left [37, 0x02], // Up [38, 0x04], // Down [40, 0x08], // A [90, 0x10], // B [88, 0x20], // Select [32, 0x40], // Start [13, 0x80], ]); // TODO: I'm still not entirely sure why we need this. let colidx = 0; const Keypad = { reset() { keys = 0x00; colidx = 0; setTimeout(log, 1, 'keypad', 'Reset'); }, rb() { switch (colidx) { case 0x10: return keys & 0x0F; case 0x20: return (keys & 0xF0) >> 8; default: return 0x00; } }, wb(v) { colidx = v & 0x30; }, keydown({ keyCode }) { const bit = keyMap.get(keyCode); // Set bit to 0, to show it's pressed if (bit) keys &= ~bit; }, keyup({ keyCode }) { const bit = keyMap.get(keyCode); // Put the bit back to 1, to show it's not pressed if (bit) keys |= bit; }, }; export default Keypad;
/** * A base class that allows for an object to be frozen and thawed to ease issues with passing by reference 'value' objects. */ class Freezable { /** * Constructor. */ constructor() { /** * The frozen flag. * @type {boolean} * @private */ this._frozen = false; } /** * Freezes the object. Any modifications should throw the TypeError. */ freeze() { this._frozen = true; } /** * Thaws the object. Modifications are now allowed. */ thaw() { this._frozen = false; } /** * Throws a TypeError if the object is frozen. Called by sub-classes at the beginning of non-const methods. */ throwIfFrozen() { if (this._frozen) { throw new TypeError('Attempt to modify a frozen object.'); } } } export default Freezable;
// Generated by CoffeeScript 1.8.0 (function() { var Lexer, SourceMap, compile, ext, formatSourcePosition, fs, getSourceMap, helpers, lexer, parser, path, sourceMaps, vm, withPrettyErrors, _base, _i, _len, _ref, __hasProp = {}.hasOwnProperty, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; fs = require('fs'); vm = require('vm'); path = require('path'); Lexer = require('./lexer').Lexer; parser = require('./parser').parser; helpers = require('./helpers'); SourceMap = require('./sourcemap'); exports.VERSION = '1.8.0'; exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md']; exports.helpers = helpers; withPrettyErrors = function(fn) { return function(code, options) { var err; if (options == null) { options = {}; } try { return fn.call(this, code, options); } catch (_error) { err = _error; throw helpers.updateSyntaxError(err, code, options.filename); } }; }; exports.compile = compile = withPrettyErrors(function(code, options) { var answer, currentColumn, currentLine, extend, fragment, fragments, header, js, map, merge, newLines, token, tokens, _i, _len; merge = helpers.merge, extend = helpers.extend; options = extend({}, options); if (options.sourceMap) { map = new SourceMap; } tokens = lexer.tokenize(code, options); options.referencedVars = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = tokens.length; _i < _len; _i++) { token = tokens[_i]; if (token.variable && token[1].charAt(0) === '_') { _results.push(token[1]); } } return _results; })(); fragments = parser.parse(tokens).compileToFragments(options); currentLine = 0; if (options.header) { currentLine += 1; } if (options.shiftLine) { currentLine += 1; } currentColumn = 0; js = ""; for (_i = 0, _len = fragments.length; _i < _len; _i++) { fragment = fragments[_i]; if (options.sourceMap) { if (fragment.locationData) { map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], { noReplace: true }); } newLines = helpers.count(fragment.code, "\n"); currentLine += newLines; if (newLines) { currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1); } else { currentColumn += fragment.code.length; } } js += fragment.code; } if (options.header) { header = "Generated by CoffeeScript " + this.VERSION; js = "// " + header + "\n" + js; } if (options.sourceMap) { answer = { js: js }; answer.sourceMap = map; answer.v3SourceMap = map.generate(options, code); return answer; } else { return js; } }); exports.tokens = withPrettyErrors(function(code, options) { return lexer.tokenize(code, options); }); exports.nodes = withPrettyErrors(function(source, options) { if (typeof source === 'string') { return parser.parse(lexer.tokenize(source, options)); } else { return parser.parse(source); } }); exports.run = function(code, options) { var answer, dir, mainModule, _ref; if (options == null) { options = {}; } mainModule = require.main; mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.'; mainModule.moduleCache && (mainModule.moduleCache = {}); dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.'); mainModule.paths = require('module')._nodeModulePaths(dir); if (!helpers.isCoffee(mainModule.filename) || require.extensions) { answer = compile(code, options); code = (_ref = answer.js) != null ? _ref : answer; } return mainModule._compile(code, mainModule.filename); }; exports["eval"] = function(code, options) { var Module, createContext, isContext, js, k, o, r, sandbox, v, _i, _len, _module, _ref, _ref1, _ref2, _ref3, _require; if (options == null) { options = {}; } if (!(code = code.trim())) { return; } createContext = (_ref = vm.Script.createContext) != null ? _ref : vm.createContext; isContext = (_ref1 = vm.isContext) != null ? _ref1 : function(ctx) { return options.sandbox instanceof createContext().constructor; }; if (createContext) { if (options.sandbox != null) { if (isContext(options.sandbox)) { sandbox = options.sandbox; } else { sandbox = createContext(); _ref2 = options.sandbox; for (k in _ref2) { if (!__hasProp.call(_ref2, k)) continue; v = _ref2[k]; sandbox[k] = v; } } sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox; } else { sandbox = global; } sandbox.__filename = options.filename || 'eval'; sandbox.__dirname = path.dirname(sandbox.__filename); if (!(sandbox !== global || sandbox.module || sandbox.require)) { Module = require('module'); sandbox.module = _module = new Module(options.modulename || 'eval'); sandbox.require = _require = function(path) { return Module._load(path, _module, true); }; _module.filename = sandbox.__filename; _ref3 = Object.getOwnPropertyNames(require); for (_i = 0, _len = _ref3.length; _i < _len; _i++) { r = _ref3[_i]; if (r !== 'paths') { _require[r] = require[r]; } } _require.paths = _module.paths = Module._nodeModulePaths(process.cwd()); _require.resolve = function(request) { return Module._resolveFilename(request, _module); }; } } o = {}; for (k in options) { if (!__hasProp.call(options, k)) continue; v = options[k]; o[k] = v; } o.bare = true; js = compile(code, o); if (sandbox === global) { return vm.runInThisContext(js); } else { return vm.runInContext(js, sandbox); } }; exports.register = function() { return require('./register'); }; if (require.extensions) { _ref = this.FILE_EXTENSIONS; for (_i = 0, _len = _ref.length; _i < _len; _i++) { ext = _ref[_i]; if ((_base = require.extensions)[ext] == null) { _base[ext] = function() { throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files."); }; } } } exports._compileFile = function(filename, sourceMap) { var answer, err, raw, stripped; if (sourceMap == null) { sourceMap = false; } raw = fs.readFileSync(filename, 'utf8'); stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw; try { answer = compile(stripped, { filename: filename, sourceMap: sourceMap, literate: helpers.isLiterate(filename) }); } catch (_error) { err = _error; throw helpers.updateSyntaxError(err, stripped, filename); } return answer; }; lexer = new Lexer; parser.lexer = { lex: function() { var tag, token; token = this.tokens[this.pos++]; if (token) { tag = token[0], this.yytext = token[1], this.yylloc = token[2]; this.errorToken = token.origin || token; this.yylineno = this.yylloc.first_line; } else { tag = ''; } return tag; }, setInput: function(_at_tokens) { this.tokens = _at_tokens; return this.pos = 0; }, upcomingInput: function() { return ""; } }; parser.yy = require('./nodes'); parser.yy.parseError = function(message, _arg) { var errorLoc, errorTag, errorText, errorToken, token, tokens, _ref1; token = _arg.token; _ref1 = parser.lexer, errorToken = _ref1.errorToken, tokens = _ref1.tokens; errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2]; errorText = errorToken === tokens[tokens.length - 1] ? 'end of input' : errorTag === 'INDENT' || errorTag === 'OUTDENT' ? 'indentation' : helpers.nameWhitespaceCharacter(errorText); return helpers.throwSyntaxError("unexpected " + errorText, errorLoc); }; formatSourcePosition = function(frame, getSourceMapping) { var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName; fileName = void 0; fileLocation = ''; if (frame.isNative()) { fileLocation = "native"; } else { if (frame.isEval()) { fileName = frame.getScriptNameOrSourceURL(); if (!fileName) { fileLocation = (frame.getEvalOrigin()) + ", "; } } else { fileName = frame.getFileName(); } fileName || (fileName = "<anonymous>"); line = frame.getLineNumber(); column = frame.getColumnNumber(); source = getSourceMapping(fileName, line, column); fileLocation = source ? fileName + ":" + source[0] + ":" + source[1] : fileName + ":" + line + ":" + column; } functionName = frame.getFunctionName(); isConstructor = frame.isConstructor(); isMethodCall = !(frame.isToplevel() || isConstructor); if (isMethodCall) { methodName = frame.getMethodName(); typeName = frame.getTypeName(); if (functionName) { tp = as = ''; if (typeName && functionName.indexOf(typeName)) { tp = typeName + "."; } if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) { as = " [as " + methodName + "]"; } return "" + tp + functionName + as + " (" + fileLocation + ")"; } else { return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")"; } } else if (isConstructor) { return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")"; } else if (functionName) { return functionName + " (" + fileLocation + ")"; } else { return fileLocation; } }; sourceMaps = {}; getSourceMap = function(filename) { var answer, _ref1; if (sourceMaps[filename]) { return sourceMaps[filename]; } if (_ref1 = path != null ? path.extname(filename) : void 0, __indexOf.call(exports.FILE_EXTENSIONS, _ref1) < 0) { return; } answer = exports._compileFile(filename, true); return sourceMaps[filename] = answer.sourceMap; }; Error.prepareStackTrace = function(err, stack) { var frame, frames, getSourceMapping; getSourceMapping = function(filename, line, column) { var answer, sourceMap; sourceMap = getSourceMap(filename); if (sourceMap) { answer = sourceMap.sourceLocation([line - 1, column - 1]); } if (answer) { return [answer[0] + 1, answer[1] + 1]; } else { return null; } }; frames = (function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = stack.length; _j < _len1; _j++) { frame = stack[_j]; if (frame.getFunction() === exports.run) { break; } _results.push(" at " + (formatSourcePosition(frame, getSourceMapping))); } return _results; })(); return (err.toString()) + "\n" + (frames.join('\n')) + "\n"; }; }).call(this);
function init() { console.log("Tiles background page started"); chrome.windows.getLastFocused({ populate: true }, function(window) { updateWindow(window); }); migrateStorage(); // Set the version if not done already storageVersionExists(function(exists) { if (!exists) { setStorageVersion(getExtensionVersion()); } }); writeUserStylesheet(); } chrome.tabs.onActivated.addListener(function(info) { chrome.tabs.get(info.tabId, function(tab) { updateTab(tab); }); }); chrome.tabs.onUpdated.addListener(function(tabID, changeInfo, tab) { if (tab.active) { updateTab(tab); } }); chrome.windows.onFocusChanged.addListener(function(windowID) { if (windowID == -1) { return; } chrome.windows.get(windowID, { populate: true }, function(window) { updateWindow(window); }); }); chrome.contextMenus.removeAll(function() { chrome.contextMenus.create({ "title": "Tiles Options", "documentUrlPatterns": [chrome.extension.getURL("/") + "*"], "contexts": ["page", "link"], "onclick" : function() { goToOptionsPage(true) } }); }); function goToOptionsPage(newTab) { var optionsURL = chrome.extension.getURL("/TILES_VERSION_ID_/options/options.html"); if (newTab) { chrome.tabs.create({ url: optionsURL }); } else { chrome.tabs.getCurrent(function(tab) { chrome.tabs.update(tab.id, { url : optionsURL }) }); } } chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { console.log('Message received: ' + request.message); if (request.message == "getUrl") { getFocusedTab(function(tab) { if (tab) { sendResponse({ url: tab.url }); console.log('Sent URL - ' + tab.url); } }); } else if (request.message == "getAbbreviation") { getFocusedTab(function(tab) { if (tab) { getSiteAbbreviationForURL(tab.url, function(abbreviation) { sendResponse({ abbreviation: abbreviation }); console.log('Sent abbreviation - ' + abbreviation); }); } }); } else if (request.message == "setAbbreviation") { getFocusedTab(function(tab) { if (tab) { getIDForURL(tab.url, function(id) { updateSiteAbbreviation(id, request.abbreviation, function(response) { sendResponse({ message: "success" }); console.log('Setting abbreviation of ' + tab.url + ' to ' + request.abbreviation); updateAllWindows(); }); }); } }); } else if (request.message == "delete") { console.log('Deleting...'); getFocusedTab(function(tab) { if (!tab) { return; } function deleteSiteCallback() { if (!request.url) { setPopup(true, false, tab.id); changeIcon(false, null, tab.id); } sendResponse({ message: "deleted" }); console.log('Sent deleted'); updateAllWindows(); } if (request.url == undefined) { console.log("Deleting site " + tab.url); getIDForURL(tab.url, function(id) { removeSites([id], deleteSiteCallback); }); } else { console.log("Deleting site " + request.url); getIDForURL(request.url, function(id) { removeSites([id], deleteSiteCallback); }); } }); } else if (request.message == "save") { console.log('Saving...'); getFocusedTab(function(tab) { createSite(tab.url, request.abbreviation, null, function(site) { addSites([site], function() { updateAllWindows(); sendResponse({ message: "saved" }); console.log('Sent saved'); }); }); }); } else if (request.message == "openTab") { chrome.tabs.create({ url: request.url }); sendResponse({ message: "opened" }); } else if (request.message == SITES_ADDED_MESSAGE || request.message == SITES_REMOVED_MESSAGE) { writeUserStylesheet(); } return true; }); function getFocusedTab(callback) { chrome.windows.getLastFocused({ populate: true }, function(window) { if (window && window.type != 'normal') { return callback(null); } var tabs = window.tabs; for (var j = 0; j < tabs.length; j++) { if (tabs[j].active) { return callback(tabs[j]); } } }); } function setPopup(save, error, tabID) { var details = {}; if (error) { details.popup = '/TILES_VERSION_ID_/browser_action/error.html'; } else { if (save) { details.popup = '/TILES_VERSION_ID_/browser_action/save.html'; } else { details.popup = '/TILES_VERSION_ID_/browser_action/delete.html'; } } details.tabId = tabID; chrome.browserAction.setPopup(details); } /** * Updates all of the windows. */ function updateAllWindows() { chrome.windows.getAll({ populate: true }, function(windows) { console.log('Updating all windows...'); for (var i = 0; i < windows.length; i++) { updateWindow(windows[i]); } }); } /** * Updates all of the tabs in a window. * @param {Window} window The window to update all of its tabs. */ function updateWindow(window) { if (window && window.type == 'normal') { var tabs = window.tabs; for (var i = 0; i < tabs.length; i++) { if (tabs[i].active) { updateTab(tabs[i]); break; } } } } /** * Sets the appropriate popup and icon for the tab. * @param {Tab} tab The tab to update its popup and icon. */ function updateTab(tab) { if (isChromeURL(tab.url)) { setPopup(false, true, tab.id); changeIcon(false, null, tab.id); } else { siteExistsWithURL(tab.url, function(exists) { setPopup(!exists, false, tab.id); changeIcon(exists, null, tab.id); }); } } /** * Sets the icon for the browser action in the chrome toolbar. * @param {boolean} color If {true}, icon will be set to color * version, else icon will be set to grayscale version. * @param callback The callback to call after the icon has * been set. * @param tabID The related tab ID. */ function changeIcon(color, callback, tabID) { var details = {}; if (color) { details.path = '/TILES_VERSION_ID_/icons/icon-bitty.png'; } else { details.path = '/TILES_VERSION_ID_/icons/icon-bitty-gray.png'; } details.tabId = tabID; chrome.browserAction.setIcon(details, callback); } init();
Template.GameEdit.rendered = function() { var currentGame; // adding a date field renders the proper date in this field // when page loads, without it, the wrong date populates $('.date-time-picker').datetimepicker('11/18/2015'); // when template loads find the boolean value of homeTeam currentGame = Games.findOne({ _id: Session.get('sGameId') }); // if true if (currentGame.homeTeam) { // check the box $('.home-team-chkbox').prop('checked', true); } }; Template.GameEdit.helpers({ // if there is a team return false // so we can hide the add team form cGame: function() { if (Meteor.user()) { return Games.findOne({ _id: Session.get('sGameId') }); } }, sGameId: function() { return Session.get('sGameId') }, sGameNew: function() { return Session.get('sGameNew'); }, sLeagueId: function() { return Session.get('sLeagueId'); }, cMyLeagues: function() { return Leagues.find(); }, sSeasonId: function() { return Session.get('sSeasonId'); }, sFormationChosen: function() { return Session.get('sFormationChosen'); }, cMySeasons: function() { return Seasons.find({ leagueId: Session.get('sLeagueId') }); } }); Template.GameEdit.events({ // need this event here for when game appears on 'add game' click // also need it in render when template loads 'click .date-time-picker': function(evt, template) { $('.date-time-picker').datetimepicker(); }, 'submit form#edit-game-form': function(evt, template) { var currentGameId, frmDateTime, convertedDate, gameProperties; evt.preventDefault(); currentGameId = Session.get('sGameId'); // convert the string date to an ISO String // which is required by moment frmDateTime = $(evt.target).find('[name=gameDateTime]').val(); convertedDate = new Date(frmDateTime); gameProperties = { gameDateTime: convertedDate, leagueName: $(evt.target).find('[name=leagueName]').val(), seasonName: $(evt.target).find('[name=seasonName]').val(), opponentName: $(evt.target).find('[name=opponentName]').val(), fieldName: $(evt.target).find('[name=fieldName]').val(), fieldUrl: $(evt.target).find('[name=fieldUrl]').val(), myFormation: $('select.formation-choice-select option:selected').val(), homeTeam: isHomeChecked() }; Games.update(currentGameId, { $set: gameProperties }, function(error, id) { if (error) { return throwError(error.reason); } Router.go('GameEdit', { _id: currentGameId }); }); } });
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(6); /***/ }, /* 1 */, /* 2 */, /* 3 */ /***/ function(module, exports) { module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, scopeId, cssModules ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } // inject cssModules if (cssModules) { var computed = options.computed || (options.computed = {}) Object.keys(cssModules).forEach(function (key) { var module = cssModules[key] computed[key] = function () { return module } }) } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }, /* 4 */, /* 5 */, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _autocomplete = __webpack_require__(7); var _autocomplete2 = _interopRequireDefault(_autocomplete); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* istanbul ignore next */ _autocomplete2.default.install = function (Vue) { Vue.component(_autocomplete2.default.name, _autocomplete2.default); }; exports.default = _autocomplete2.default; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(8), /* template */ __webpack_require__(16), /* scopeId */ null, /* cssModules */ null ) module.exports = Component.exports /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _input = __webpack_require__(9); var _input2 = _interopRequireDefault(_input); var _clickoutside = __webpack_require__(10); var _clickoutside2 = _interopRequireDefault(_clickoutside); var _autocompleteSuggestions = __webpack_require__(11); var _autocompleteSuggestions2 = _interopRequireDefault(_autocompleteSuggestions); var _emitter = __webpack_require__(14); var _emitter2 = _interopRequireDefault(_emitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // exports.default = { name: 'ElAutocomplete', mixins: [_emitter2.default], componentName: 'ElAutocomplete', components: { ElInput: _input2.default, ElAutocompleteSuggestions: _autocompleteSuggestions2.default }, directives: { Clickoutside: _clickoutside2.default }, props: { popperClass: String, placeholder: String, disabled: Boolean, name: String, size: String, value: String, autofocus: Boolean, fetchSuggestions: Function, triggerOnFocus: { type: Boolean, default: true }, customItem: String, icon: String, onIconClick: Function }, data: function data() { return { isFocus: false, suggestions: [], loading: false, highlightedIndex: -1 }; }, computed: { suggestionVisible: function suggestionVisible() { var suggestions = this.suggestions; var isValidData = Array.isArray(suggestions) && suggestions.length > 0; return (isValidData || this.loading) && this.isFocus; } }, watch: { suggestionVisible: function suggestionVisible(val) { this.broadcast('ElAutocompleteSuggestions', 'visible', [val, this.$refs.input.$refs.input.offsetWidth]); } }, methods: { getData: function getData(queryString) { var _this = this; this.loading = true; this.fetchSuggestions(queryString, function (suggestions) { _this.loading = false; if (Array.isArray(suggestions)) { _this.suggestions = suggestions; } else { console.error('autocomplete suggestions must be an array'); } }); }, handleChange: function handleChange(value) { this.$emit('input', value); if (!this.triggerOnFocus && !value) { this.suggestions = []; return; } this.getData(value); }, handleFocus: function handleFocus() { this.isFocus = true; if (this.triggerOnFocus) { this.getData(this.value); } }, handleBlur: function handleBlur() { var _this2 = this; // 因为 blur 事件处理优先于 select 事件执行 setTimeout(function (_) { _this2.isFocus = false; }, 100); }, handleKeyEnter: function handleKeyEnter() { if (this.suggestionVisible && this.highlightedIndex >= 0 && this.highlightedIndex < this.suggestions.length) { this.select(this.suggestions[this.highlightedIndex]); } }, handleClickoutside: function handleClickoutside() { this.isFocus = false; }, select: function select(item) { var _this3 = this; this.$emit('input', item.value); this.$emit('select', item); this.$nextTick(function (_) { _this3.suggestions = []; }); }, highlight: function highlight(index) { if (!this.suggestionVisible || this.loading) { return; } if (index < 0) index = 0; if (index >= this.suggestions.length) { index = this.suggestions.length - 1; } var suggestion = this.$refs.suggestions.$el.querySelector('.el-autocomplete-suggestion__wrap'); var suggestionList = suggestion.querySelectorAll('.el-autocomplete-suggestion__list li'); var highlightItem = suggestionList[index]; var scrollTop = suggestion.scrollTop; var offsetTop = highlightItem.offsetTop; if (offsetTop + highlightItem.scrollHeight > scrollTop + suggestion.clientHeight) { suggestion.scrollTop += highlightItem.scrollHeight; } if (offsetTop < scrollTop) { suggestion.scrollTop -= highlightItem.scrollHeight; } this.highlightedIndex = index; } }, mounted: function mounted() { var _this4 = this; this.$on('item-click', function (item) { _this4.select(item); }); }, beforeDestroy: function beforeDestroy() { this.$refs.suggestions.$destroy(); } }; /***/ }, /* 9 */ /***/ function(module, exports) { module.exports = require("element-ui/lib/input"); /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = require("element-ui/lib/utils/clickoutside"); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(12), /* template */ __webpack_require__(15), /* scopeId */ null, /* cssModules */ null ) module.exports = Component.exports /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _vuePopper = __webpack_require__(13); var _vuePopper2 = _interopRequireDefault(_vuePopper); var _emitter = __webpack_require__(14); var _emitter2 = _interopRequireDefault(_emitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // exports.default = { mixins: [_vuePopper2.default, _emitter2.default], componentName: 'ElAutocompleteSuggestions', data: function data() { return { parent: this.$parent, dropdownWidth: '' }; }, props: { suggestions: Array, options: { default: function _default() { return { forceAbsolute: true, gpuAcceleration: false }; } } }, methods: { select: function select(item) { this.dispatch('ElAutocomplete', 'item-click', item); } }, updated: function updated() { var _this = this; this.$nextTick(function (_) { _this.updatePopper(); }); }, mounted: function mounted() { this.popperElm = this.$el; this.referenceElm = this.$parent.$refs.input.$refs.input; }, created: function created() { var _this2 = this; this.$on('visible', function (val, inputWidth) { _this2.dropdownWidth = inputWidth + 'px'; _this2.showPopper = val; }); } }; /***/ }, /* 13 */ /***/ function(module, exports) { module.exports = require("element-ui/lib/utils/vue-popper"); /***/ }, /* 14 */ /***/ function(module, exports) { module.exports = require("element-ui/lib/mixins/emitter"); /***/ }, /* 15 */ /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('transition', { attrs: { "name": "el-zoom-in-top" }, on: { "after-leave": _vm.doDestroy } }, [_c('div', { directives: [{ name: "show", rawName: "v-show", value: (_vm.showPopper), expression: "showPopper" }], staticClass: "el-autocomplete-suggestion", class: { 'is-loading': _vm.parent.loading }, style: ({ width: _vm.dropdownWidth }) }, [_c('el-scrollbar', { attrs: { "tag": "ul", "wrap-class": "el-autocomplete-suggestion__wrap", "view-class": "el-autocomplete-suggestion__list" } }, [(_vm.parent.loading) ? _c('li', [_c('i', { staticClass: "el-icon-loading" })]) : _vm._l((_vm.suggestions), function(item, index) { return [(!_vm.parent.customItem) ? _c('li', { class: { 'highlighted': _vm.parent.highlightedIndex === index }, on: { "click": function($event) { _vm.select(item) } } }, [_vm._v("\n " + _vm._s(item.value) + "\n ")]) : _c(_vm.parent.customItem, { tag: "component", class: { 'highlighted': _vm.parent.highlightedIndex === index }, attrs: { "item": item, "index": index }, on: { "click": function($event) { _vm.select(item) } } })] })], 2)], 1)]) },staticRenderFns: []} /***/ }, /* 16 */ /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { directives: [{ name: "clickoutside", rawName: "v-clickoutside", value: (_vm.handleClickoutside), expression: "handleClickoutside" }], staticClass: "el-autocomplete" }, [_c('el-input', { ref: "input", attrs: { "value": _vm.value, "disabled": _vm.disabled, "placeholder": _vm.placeholder, "name": _vm.name, "size": _vm.size, "icon": _vm.icon, "on-icon-click": _vm.onIconClick }, on: { "change": _vm.handleChange, "focus": _vm.handleFocus, "blur": _vm.handleBlur }, nativeOn: { "keydown": [function($event) { if (_vm._k($event.keyCode, "up", 38)) { return; } $event.preventDefault(); _vm.highlight(_vm.highlightedIndex - 1) }, function($event) { if (_vm._k($event.keyCode, "down", 40)) { return; } $event.preventDefault(); _vm.highlight(_vm.highlightedIndex + 1) }, function($event) { if (_vm._k($event.keyCode, "enter", 13)) { return; } $event.stopPropagation(); _vm.handleKeyEnter($event) }] } }, [(_vm.$slots.prepend) ? _c('template', { slot: "prepend" }, [_vm._t("prepend")], 2) : _vm._e(), (_vm.$slots.append) ? _c('template', { slot: "append" }, [_vm._t("append")], 2) : _vm._e()], 2), _c('el-autocomplete-suggestions', { ref: "suggestions", class: [_vm.popperClass ? _vm.popperClass : ''], attrs: { "suggestions": _vm.suggestions } })], 1) },staticRenderFns: []} /***/ } /******/ ]);
/** * rtchart.js : Real Time Graph * @depends on d3.min.js */ /** * Graph Area Object */ var RTchart = (function() { var VERSION = 0.2; /* constructor */ var RTchart = function(id, tag) { this.axisAreaSize = [10, 20, 30, 0]; this.div = d3.select('#' + id); this.svg = this.div.append('svg'); this.socket = io.connect(); this.startFlag = true; this.dataset = []; this.timeRange = 60000; // [msec] this.init(tag || id); }; var p = RTchart.prototype; p.init = function(tag) { var self = this /* set callback for getting data from server */ self.socket.on('rtchart:' + tag, function(data) { if (! self.startFlag) { return; } if (data.value.length > self.dataset.length) { var buf = self.dataset.length; for (var i = 0; i < data.value.length - buf; i++) { self.dataset.push(new RTchart.TimeSeriesData().setTimeRange(self.timeRange)); } } for (var i = 0; i < data.value.length; i++) { self.dataset[i].push(data.timestamp, data.value[i]); } self.drawLine(); }); self.resizeWindow(); /* set callback for resizing the window */ window.addEventListener('resize', function() { self.resizeWindow(); self.drawLine(); }, false); return self; }; p.getDivColor = function() { var element = this.div[0][0]; if (element === undefined) return '#000000'; var style = element.currentStyle || document.defaultView.getComputedStyle(element, ''); var color = style.color; if (color === undefined) { return '#000000'; } color = color.toString().replace('rgb\(',''); color = color.replace('\)',''); color = color.split(','); return '#' + parseInt(color[0]).toString(16) + parseInt(color[1]).toString(16) + parseInt(color[2]).toString(16); } p.isHeightUndefined = false; p.getDivSize = function() { var element = this.div[0][0]; if (element === undefined) return {width: 0, height: 0}; var style = element.currentStyle || document.defaultView.getComputedStyle(element, ''); var width = parseFloat(style.width); if (width === undefined) { width = parseFloat(element.clientWidth); } var height = 0; if (this.isHeightUndefined) { height = width; } else { height = parseFloat(style.height); if (height === undefined) { height = parseFloat(element.clientHeight); } if (height === 0) { this.isHeightUndefined = true; height = width; } } return {width: width, height: height}; } p.resizeWindow = function() { var size = this.getDivSize(); this.svg.attr('width', size.width); this.svg.attr('height', size.height); /* after resizing, re-draw */ this.drawLine(); return this; } /** * change graph properties */ p.addLegend = function(legend) { // TODO return this; }; p.isDrawAxis = false; p.setDrawAxis = function(isDrawAxis) { this.isDrawAxis = isDrawAxis; return this; }; p.setTimeRange = function(timeRange) { this.timeRange = timeRange; for (var i = 0; i < this.dataset.length; i++) { this.dataset[i].setTimeRange(timeRange); } return this; }; p.isValueRangeFixed = false; p.setValueRange = function(value1, value2) { this.isValueRangeFixed = true; this.valueRange = [value1, value2]; return this; } p.getValue = function(num) { if (this.dataset.length <= num) return 0; return this.dataset[num].getLastDatum().value; } p.drawLine = function() { var self = this; var axisAreaSize = self.isDrawAxis ? self.axisAreaSize : [0, 0, 0, 0]; /* remove line & axis */ self.svg.selectAll('path').remove(); self.svg.selectAll('g').remove(); /* deep copy dataset */ var now = 0; if (self.dataset[0] === undefined) now = new Date().getTime(); else now = self.dataset[0].data[self.dataset[0].data.length - 1].timestamp; var t0 = now - self.timeRange; var dataset = new Array(self.dataset.length); for (var i = 0; i < self.dataset.length; i++) { dataset[i] = self.dataset[i].deepCopyData(); if ((dataset[i][0].timestamp < t0) && (t0 < dataset[i][1].timestamp)) { /* set the dummy value at t0 */ var v0 = (dataset[i][1].value - dataset[i][0].value) / (dataset[i][1].timestamp - dataset[i][0].timestamp) * (t0 - dataset[i][0].timestamp) + dataset[i][0].value; dataset[i][0] = { timestamp: t0, value: v0, }; } } /* calc domain & range */ var xDomain = [t0, now]; var yDomain = [0, 0]; if (this.isValueRangeFixed) { yDomain = this.valueRange; } else { for (var i = 0; i < dataset.length; i++) { var extent = d3.extent(dataset[i], function(d) { return d.value; }); if (extent[0] > extent[1]) { continue; } if (i == 0) { yDomain = extent; } else { yDomain[0] = (yDomain[0] > extent[0]) ? extent[0] : yDomain[0]; yDomain[1] = (yDomain[1] < extent[1]) ? extent[1] : yDomain[1]; } } } var xRange = [axisAreaSize[2], self.svg.attr('width') - axisAreaSize[3]]; var yRange = [self.svg.attr('height') - axisAreaSize[1], axisAreaSize[0]]; self.xScale = d3.time.scale().domain(xDomain).range(xRange); self.yScale = d3.scale.linear().domain(yDomain).range(yRange); /* draw axis */ if (self.isDrawAxis) { self.xAxis = d3.svg.axis() .scale(self.xScale) .ticks(5) .orient('bottom'); self.yAxis = d3.svg.axis() .scale(self.yScale) .ticks(3) .orient('left'); var axisColor = self.getDivColor(); var xAxisArea = self.svg.append('g') .attr({ 'class': 'x axis', 'transform': 'translate(0, ' + (self.svg.attr('height') - axisAreaSize[1]) + ')', }) .call(self.xAxis) xAxisArea.selectAll('path,line') .attr({ 'fill': 'none', 'stroke': axisColor, 'shape-rendering': 'crispEdges' }) xAxisArea.selectAll('text') .attr('fill', axisColor); var yAxisArea = self.svg.append('g') .attr({ 'class': 'y axis', 'transform': 'translate(' + axisAreaSize[2] + ', 0)', }) .call(self.yAxis) yAxisArea.selectAll('path,line') .attr({ 'fill': 'none', 'stroke': axisColor, 'shape-rendering': 'crispEdges', }); yAxisArea.selectAll('text') .attr('fill', axisColor); } /* draw line */ var colors = d3.scale.category10(); self.line = new Array(dataset.length); for (var i = 0; i < dataset.length; i++) { self.line[i] = d3.svg.line() .x(function(d) { return self.xScale(d.timestamp); }) .y(function(d) { return self.yScale(d.value); }) .interpolate('linear'); self.svg.append('path') .datum(dataset[i]) .attr({ 'class': 'line', 'd': self.line[i], 'stroke': colors(i), 'fill': 'none', }); } return this; }; p.start = function() { this.startFlag = true; return this; }; p.stop = function() { this.startFlag = false; return this; }; return RTchart; })(); RTchart.TimeSeriesData = (function() { /** * Graph Area Object */ var TimeSeriesData = function() { this.data = []; this.setTimeRange(1000); }; var p = TimeSeriesData.prototype; p.setTimeRange = function(timeRange) { this.data = new Array(); this.timeRange = timeRange; return this; }; p.push = function(timestamp, value) { var data = this.data; data.push({ 'timestamp': timestamp, 'value': value, }); var now = data[data.length - 1].timestamp; var t0 = now - this.timeRange; /** * 1. At least two data are necessary. * 2. old data are deleted all except for one of them. */ while ((data.length > 2) && (data[0].timestamp < t0) && (data[1].timestamp <= t0)) { data.shift(); } return this; }; p.getLastDatum = function() { var data = this.data; return data[data.length - 1]; } p.deepCopyData = function() { var data = this.data; var d = new Array(data.length); for (var i = 0; i < data.length; i++) { d[i] = { timestamp: data[i].timestamp, value: data[i].value, }; } return d; } return TimeSeriesData; })();
import React,{Component} from 'react' import {observer} from 'mobx-react' import {inject} from '../../store/index' import { StyleSheet, View,WebView} from 'react-native'; import {NavBar} from '../../component/index' class PhoneValidate extends Component { constructor(props){ super(props) this.state = { url:null } } componentWillMount(){ this.props.user.phoneValidate().then((ulr)=>{ if(ulr){ this.setState({ url:ulr }) } }) } render() { const {goBack} = this.props.navigation return ( <View style={[styles.container]}> <NavBar title='手机认证' leftIcon='angle-left' leftPress={()=>goBack()} /> {this.state.url&& <WebView style={styles.webView} source={{url:this.state.url}} /> } </View> ); } } export default inject('user')(observer(PhoneValidate)) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, webView:{ flex:1 } });
$.getJSON("http://192.168.1.120:8080/todo-server/todo/1", function(data){ $('#Name1').append(data.name); $('#Description1').append(data.description); $('#Importance1').append(data.importance); $('#Owner1').append(data.owner); $('#DateCreated1').append(data.dateCreated); $('#DateDue1').append(data.dateDue); });
'use strict'; var util = require('util'); function ConstraintError(message) { this.name = this.constructor.name; this.message = message !== undefined ? message : ' A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.'; if (Error.captureStackTrace) { Error.captureStackTrace(this, ConstraintError); } } util.inherits(ConstraintError, Error); module.exports = ConstraintError;
module.exports = { componentPaths: ["src/components"], ignore: [/\.test.js$/], publicPath: "public", globalImports: ["assets/base.css", "assets/MyFontsWebfontsKit.css"], containerQuerySelector: "#root", webpackConfigPath: "./config/webpack.config.dev.js", hostname: process.env.COSMOS_HOST || "localhost" };
var ObjectId, Schema, TagModule, TagSchema, mongoose; mongoose = require('mongoose'); Schema = mongoose.Schema; ObjectId = Schema.Types.ObjectId; TagSchema = new Schema({ nickname: { unique: true, type: String }, encode: { unique: true, type: String } }); TagModule = mongoose.model('Tag', TagSchema); module.exports = TagModule;
/** * Set up the configuration handling for ##BUNDLE_NAME## * @type {Object} */ module.exports = { getName() => { return '##BUNDLE_NAME##'; } };
const path = require('path') const webpack = require('webpack') module.exports = (options) => ({ entry: options.entry, output: Object.assign({ path: path.resolve(process.cwd(), 'dist'), publicPath: '/' }, options.output), module: { rules: [{ test: /\.js?$/, exclude: /node_modules/, loader: 'babel-loader', options: { compact: false, presets: [ ["es2015", { modules: false }], "stage-2", "react" ], plugins: [ "transform-node-env-inline" ] } }, { test: /\.(eot|ico|png|svg|ttf|woff|woff2)$/, loader: 'file-loader?name=[name].[ext]' }].concat(options.module.rules) }, plugins: options.plugins.concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), WEATHER_API: JSON.stringify(process.env.WEATHER_API) } }), new webpack.NamedModulesPlugin() ]), devtool: options.devtool, target: 'web', performance: options.performance || {} });
'use strict' var zeptrionDeviceScanner = require('./zeptrionDeviceScanner') module.exports = { zeptrionDeviceScanner: zeptrionDeviceScanner }
export MenuItem from './MenuItem'; export Menu from './Menu';
'use strict' const path = require('path') const webpack = require('webpack') const config = require('./config') const utils = require('./utils') const NODE_ENV = process.env.NODE_ENV || 'production' module.exports = { entry: { app: './resources/assets/js/index', editor: './resources/assets/js/editor', }, output: { path: config[NODE_ENV].assetsRoot, publicPath: config[NODE_ENV].assetsPublicPath, filename: '[name].js', }, resolve: { extensions: ['.js', '.vue', '.styl'], alias: { js: path.resolve(__dirname, '../js'), Components: path.resolve(__dirname, '../js/Components'), vue$: 'vue/dist/vue.common.js', }, }, module: { rules: [ { test: /\.vue$/, use: { loader: 'vue-loader', options: { loaders: utils.cssLoaders({ extract: NODE_ENV === 'production', sourceMap: config[NODE_ENV].sourceMap, }), }, }, }, { test: /\.js$/, use: { loader: 'babel-loader', options: { cacheDirectory: true, }, }, include: path.resolve(__dirname, '../'), exclude: /node_modules/, }, { test: /\.y$/, use: { loader: 'raw-loader', }, }, { test: /\.html$/, use: { loader: 'vue-html-loader', }, }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: { loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]'), }, }, }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, use: { loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]'), }, }, }, { test: require.resolve('jquery'), use: [ { loader: 'expose-loader', options: 'jQuery', }, { loader: 'expose-loader', options: '$', }, ], }, { test: require.resolve(path.join(__dirname, '../js/Parser')), use: [ { loader: 'expose-loader', options: 'Parser', }, { loader: 'babel-loader', }, ], }, { test: require.resolve('brace'), loader: 'expose-loader', options: 'ace', }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': config[NODE_ENV].env, }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), ], node: { fs: 'empty', }, }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require angular //= require angular-animate //= require angular-sanitize //= require angular-toastr //= require angular-touch //= require angular-ui-router //= require ./angularjs/core/templates //= require_tree .
// @flow import type { TextSubject, XpathSubject } from './typedefs'; import TextContent from './textcontent'; import Finder from './finder'; import TextFinder from './textfinder'; import XpathFinder from './xpathfinder'; /** * Construct appropriate `Finder`-derived class for a given subject * * @param {TextContent} content - reference to `TextContent` holding a text representation of the * document * @param {TextSubject | XpathSubject} subject - subject to find; can be of `string` or `RegExp` * type * * @returns {Finder} finder instance ready for use */ function finder(content: TextContent, subject: TextSubject | XpathSubject): Finder { // FIXME: employ more robust check below that doesn't assume Xpath finder by default return TextFinder.isSubject(subject) ? new TextFinder(content, (subject: any)) : new XpathFinder(content, (subject: any)); } export { finder };
//var canvas = document.getElementById("myCanvas").getContext("2d"); var FPS = 30; var CANVAS_WIDTH = 512; var CANVAS_HEIGHT = 256; var cursorX; var cursorY; var gameMode = 1; // 0 - Show enter screen // 1 - play normal function update() { switch(gameMode) { case 0: if(ispressed.enter == true) { gameMode = 1; player.isDieing = false; player.isDead = false; } break; case 1: // check if keys are pressed if(player.isDieing) { player.die(); if(player.isDead) { gameMode = 0; } else { return; } } if (ispressed.d) { if(player.isTouchingSolidWall(1) != 1) { Camera.move( 10, 0); } } if (ispressed.a) { if(player.isTouchingSolidWall(0) != 1) { Camera.move(-10, 0); } } player.jump(); player.updateGravity(); break; default: break; } } // this is the main drawing function function draw() { switch(gameMode) { case 0: canvas.clearRect(0, 0, 512, 256); // clear the canvas canvas.fillStyle="#000000"; canvas.fillRect(0,0,512,256); renderMap(); canvas.fillStyle="#232323"; canvas.fillRect(50,50,(CANVAS_WIDTH - 100),(CANVAS_HEIGHT - 100)); canvas.strokeStyle = "#777777"; canvas.rect(50,50,(CANVAS_WIDTH - 100),(CANVAS_HEIGHT - 100)); canvas.stroke(); canvas.fillStyle = "white"; canvas.font = "20px Bungee Shade"; canvas.fillText("Canvas Test",60,70); canvas.font = "15px Bungee Shade"; canvas.fillText("Enter the game by pressing enter.",60,90); canvas.fillText("The game controls are A, D, and space.",60,110); break; case 1: canvas.clearRect(0, 0, 512, 256); // clear the canvas canvas.fillStyle="#000000"; canvas.fillRect(0,0,512,256); renderMap(); player.draw(); break; default: break; } } // setup the normal drawing functions setInterval(function() { update(); draw(); }, 1000/FPS);
/*global module:false*/ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-compress'); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ["dist", "temp"], concat: { dist: { // 默认为中文语言包 src: ['src/core.js', 'src/lang.js', 'src/main.js', 'xheditor_lang/zh-cn.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { dist: { options: { banner: "/*! xhEditor v<%= pkg.version %> | (c) 2009, 2013 xheditor.com.\r\nLicence: http://xheditor.com/license/lgpl.txt */\n", beautify: { ascii_only: true } }, files: { 'dist/<%= pkg.name %>-<%= pkg.version %>.min.js': ['<%= concat.dist.dest %>'] } } }, copy: { dist: { options: { processContentExclude: ['**/*.gif','**/*.png','**/*.swf'], processContent: function(content, filename){ var pkg = grunt.config( "pkg" ); if(/\.min\.js$/i.test(filename)){ content = content.replace(/@VERSION/g,pkg.version); content = content.replace(/@BUILDDATE/g,grunt.template.today("yymmdd")); } else if(/\.html$/i.test(filename)){ content = content.replace(/xheditor\.js"/g, pkg.name + '-' + pkg.version + '.min.js"'); } return content; } }, files: [ {src:['jquery/**'], dest: 'dist/'}, {src:['xheditor_lang/**'], dest: 'dist/'}, {src:['xheditor_skin/**'], dest: 'dist/'}, {src:['xheditor_emot/**'], dest: 'dist/'}, {src:['xheditor_plugins/**'], dest: 'dist/'}, {src:['CHANGE.md', 'LGPL-LICENSE.txt', 'README.md', 'THANKS.md', 'TODO.md', 'wizard.html'], dest: 'dist/'} ] }, release: { options: { processContentExclude: ['**/*.gif','**/*.png','**/*.swf'], processContent: function(content, filename){ var pkg = grunt.config( "pkg" ); if(/\.min\.js$/i.test(filename)){ content = content.replace(/@VERSION/g,pkg.version); content = content.replace(/@BUILDDATE/g,grunt.template.today("yymmdd")); } else if(/\.html$/i.test(filename)){ content = content.replace(/xheditor\.js"/g, pkg.name + '-' + pkg.version + '.min.js"'); } return content; } }, files: [ {src: ['dist/<%= pkg.name %>-<%= pkg.version %>.min.js'], dest: 'temp/xheditor-<%= pkg.version %>/<%= pkg.name %>-<%= pkg.version %>.min.js'}, {src:['xheditor_lang/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['xheditor_skin/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['xheditor_emot/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['xheditor_plugins/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['demos/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['jquery/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['serverscript/**'], dest: 'temp/xheditor-<%= pkg.version %>/'}, {src:['CHANGE.md', 'LGPL-LICENSE.txt', 'README.md', 'THANKS.md', 'TODO.md', 'wizard.html'], dest: 'temp/xheditor-<%= pkg.version %>/'} ] } }, compress: { 'zip': { options: { archive: 'release/<%= pkg.name %>-<%= pkg.version %>.zip' }, files: [ {expand:true, cwd: 'temp', src: ['xheditor-<%= pkg.version %>/**'], dest: '/'}, ] } } }); // Default task. grunt.registerTask('default', ['clean', 'concat', 'uglify', 'copy', 'compress',]); };
// ES6 operations via Babel.js // Require the 'NET' node module... import net from 'net'; import moment from 'moment'; // capture arg(s)... let port = process.argv[2]; const server = net.createServer((socket) => { socket.on('data', (data) => { let now = moment(); console.log(now.format("YYYY-MM-DD hh:mm") + "\n"); socket.end(now.format("YYYY-MM-DD hh:mm") + "\n"); }); }); server.listen(port);
export const scatterplotGenerator = (num) => { const arr = []; const datapoints = num || 40; // Number of dummy data points const maxRange = Math.random() * 1000; // Max range of new values for (let i = 0; i < datapoints; i++) { const newNumber1 = Math.floor(Math.random() * maxRange); // New random integer const newNumber2 = Math.floor(Math.random() * maxRange); // New random integer arr.push([newNumber1, newNumber2]); } return arr; };
/** * @fileOverview 负责文件上传相关。 */ define([ '../base', '../uploader', '../file', '../lib/transport', './widget' ], function( Base, Uploader, WUFile, Transport ) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend( Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: null /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [method='POST'] * @namespace options * @for Uploader * @description 文件上传方式,`POST`或者`GET`。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile( file, chunkSize ) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1, start = 0, index = 0, len; while ( index < chunks ) { len = Math.min( chunkSize, total - start ); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++ }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return { file: file, has: function() { return !!pending.length; }, fetch: function() { return pending.shift(); } }; } Uploader.register({ 'start-upload': 'start', 'stop-upload': 'stop', 'skip-file': 'skipFile', 'is-in-progress': 'isInProgress' }, { init: function() { var owner = this.owner; this.runing = false; // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn( this._tick, this ); owner.on( 'uploadComplete', function( file ) { // 把其他块取消了。 file.blocks && $.each( file.blocks, function( _, v ) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * @grammar upload() => undefined * @method upload * @for Uploader */ start: function() { var me = this; // 移出invalid的文件 $.each( me.request( 'get-files', Status.INVALID ), function() { me.request( 'remove-file', this ); }); if ( me.runing ) { return; } me.runing = true; // 如果有暂停的,则续传 $.each( me.pool, function( _, v ) { var file = v.file; if ( file.getStatus() === Status.INTERRUPT ) { file.setStatus( Status.PROGRESS ); me._trigged = false; v.transport && v.transport.send(); } }); me._trigged = false; me.owner.trigger('startUpload'); Base.nextTick( me.__tick ); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @method stop * @for Uploader */ stop: function( interrupt ) { var me = this; if ( me.runing === false ) { return; } me.runing = false; interrupt && $.each( me.pool, function( _, v ) { v.transport && v.transport.abort(); v.file.setStatus( Status.INTERRUPT ); }); me.owner.trigger('stopUpload'); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function() { return !!this.runing; }, getStats: function() { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function( file, status ) { file = this.request( 'get-file', file ); file.setStatus( status || Status.COMPLETE ); file.skipped = true; // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger( 'uploadSkip', file ); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function() { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if ( me._promise ) { return me._promise.always( me.__tick ); } // 还有位置,且还有文件要处理的话。 if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) { me._trigged = false; fn = function( val ) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend( val ); Base.nextTick( me.__tick ); }; me._promise = isPromise( val ) ? val.always( fn ) : fn( val ); // 没有要上传的了,且没有正在传输的了。 } else if ( !me.remaning && !me.getStats().numOfQueue ) { me.runing = false; me._trigged || Base.nextTick(function() { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _nextBlock: function() { var me = this, act = me._act, opts = me.options, next, done; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ( act && act.has() && act.file.getStatus() === Status.PROGRESS ) { // 是否提前准备下一个文件 if ( opts.prepareNextFile && !me.pending.length ) { me._prepareNextFile(); } return act.fetch(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if ( me.runing ) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if ( !me.pending.length && me.getStats().numOfQueue ) { me._prepareNextFile(); } next = me.pending.shift(); done = function( file ) { if ( !file ) { return null; } act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 ); me._act = act; return act.fetch(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 return isPromise( next ) ? next[ next.pipe ? 'pipe' : 'then' ]( done ) : done( next ); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function() { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if ( file ) { promise = me.request( 'before-send-file', file, function() { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if ( file.getStatus() === Status.QUEUED ) { me.owner.trigger( 'uploadStart', file ); file.setStatus( Status.PROGRESS ); return file; } return me._finishFile( file ); }); // 如果还在pending中,则替换成文件本身。 promise.done(function() { var idx = $.inArray( promise, pending ); ~idx && pending.splice( idx, 1, file ); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function( reason ) { file.setStatus( Status.ERROR, reason ); me.owner.trigger( 'uploadError', file, reason ); me.owner.trigger( 'uploadComplete', file ); }); pending.push( promise ); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function( block ) { var idx = $.inArray( block, this.pool ); this.pool.splice( idx, 1 ); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function( block ) { var me = this, file = block.file, promise; me.pool.push( block ); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice( block.start, block.end ); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request( 'before-send', block, function() { // 有可能文件已经上传出错了,所以不需要再传输了。 if ( file.getStatus() === Status.PROGRESS ) { me._doSend( block ); } else { me._popBlock( block ); Base.nextTick( me.__tick ); } }); // 如果为fail了,则跳过此分片。 promise.fail(function() { if ( file.remaning === 1 ) { me._finishFile( file ).always(function() { block.percentage = 1; me._popBlock( block ); me.owner.trigger( 'uploadComplete', file ); Base.nextTick( me.__tick ); }); } else { block.percentage = 1; me._popBlock( block ); Base.nextTick( me.__tick ); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function( block ) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport( opts ), data = $.extend({}, opts.formData ), headers = $.extend({}, opts.headers ), requestAccept, ret; block.transport = tr; tr.on( 'destroy', function() { delete block.transport; me._popBlock( block ); Base.nextTick( me.__tick ); }); // 广播上传进度。以文件为单位。 tr.on( 'progress', function( percentage ) { var totalPercent = 0, uploaded = 0; // 可能没有abort掉,progress还是执行进来了。 // if ( !file.blocks ) { // return; // } totalPercent = block.percentage = percentage; if ( block.chunks > 1 ) { // 计算文件的整体速度。 $.each( file.blocks, function( _, v ) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; } owner.trigger( 'uploadProgress', file, totalPercent || 0 ); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function( reject ) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function( value ) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on( 'error', function( type, flag ) { block.retried = block.retried || 0; // 自动重试 if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) && block.retried < opts.chunkRetry ) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if ( !flag && type === 'server' ) { type = requestAccept( type ); } file.setStatus( Status.ERROR, type ); owner.trigger( 'uploadError', file, type ); owner.trigger( 'uploadComplete', file ); } }); // 上传成功 tr.on( 'load', function() { var reason; // 如果非预期,转向上传出错。 if ( (reason = requestAccept()) ) { tr.trigger( 'error', reason, true ); return; } // 全部上传完成。 if ( file.remaning === 1 ) { me._finishFile( file, ret ); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend( data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend( data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger( 'uploadBeforeSend', block, data, headers ); // 开始发送。 tr.appendBlob( opts.fileVal, block.blob, file.name ); tr.append( data ); tr.setRequestHeader( headers ); tr.send(); }, // 完成上传。 _finishFile: function( file, ret, hds ) { var owner = this.owner; return owner .request( 'after-send-file', arguments, function() { file.setStatus( Status.COMPLETE ); owner.trigger( 'uploadSuccess', file, ret, hds ); }) .fail(function( reason ) { // 如果外部已经标记为invalid什么的,不再改状态。 if ( file.getStatus() === Status.PROGRESS ) { file.setStatus( Status.ERROR, reason ); } owner.trigger( 'uploadError', file, reason ); }) .always(function() { owner.trigger( 'uploadComplete', file ); }); } }); });
goog.provide('annotorious.mediatypes.openlayers.Viewer'); goog.require('goog.events.MouseWheelHandler'); /** * The OpenLayers viewer wraps an OpenLayers Box Marker layer to display annotations inside * of Box markers. * @param {Object} map the OpenLayers map * @param {annotorious.mediatypes.openlayers.OpenLayersAnnotator} annotator reference to the annotator * @constructor */ annotorious.mediatypes.openlayers.Viewer = function(map, annotator) { /** @private **/ this._map = map; /** @private **/ this._annotator = annotator; /** @private **/ this._map_bounds = goog.style.getBounds(annotator.element); /** @private **/ this._popup = annotator.popup; goog.style.setStyle(this._popup.element, 'z-index', 99000); /** @private **/ this._overlays = []; /** @private **/ this._shapes = []; /** @private **/ this._currentlyHighlightedOverlay; /** @private **/ this._lastHoveredOverlay; /** @private **/ this._boxesLayer = new OpenLayers.Layer.Boxes('Annotorious'); // TODO make configurable this._map.addLayer(this._boxesLayer); var self = this; this._map.events.register('move', this._map, function() { if (self._currentlyHighlightedOverlay) self._place_popup(); }); annotator.addHandler(annotorious.events.EventType.BEFORE_POPUP_HIDE, function() { if (self._lastHoveredOverlay == self._currentlyHighlightedOverlay) self._popup.clearHideTimer(); else self._updateHighlight(self._lastHoveredOverlay, self._currentlyHighlightedOverlay); }); } annotorious.mediatypes.openlayers.Viewer.prototype.destroy = function() { this._boxesLayer.destroy(); } /** * Resets the position of the popup, without changing the annotation. */ annotorious.mediatypes.openlayers.Viewer.prototype._place_popup = function() { // Compute correct annotation bounds, relative to map var annotation_div = this._currentlyHighlightedOverlay.marker.div; var annotation_dim = goog.style.getBounds(annotation_div); var annotation_pos = goog.style.getRelativePosition(annotation_div, this._map.div); var annotation_bounds = { top: annotation_pos.y, left: annotation_pos.x, width: annotation_dim.width, height: annotation_dim.height }; // Popup width & height var popup_bounds = goog.style.getBounds(this._popup.element); var popup_pos = { y: annotation_bounds.top + annotation_bounds.height + 5 }; if (annotation_bounds.left + popup_bounds.width > this._map_bounds.width) { goog.dom.classes.addRemove(this._popup.element, 'top-left', 'top-right'); popup_pos.x = (annotation_bounds.left + annotation_bounds.width) - popup_bounds.width; } else { goog.dom.classes.addRemove(this._popup.element, 'top-right', 'top-left'); popup_pos.x = annotation_bounds.left; } if (popup_pos.x < 0) popup_pos.x = 0; if (popup_pos.x + popup_bounds.width > this._map_bounds.width) popup_pos.x = this._map_bounds.width - popup_bounds.width; if (popup_pos.y + popup_bounds.height > this._map_bounds.height) popup_pos.y = this._map_bounds.height - popup_bounds.height; this._popup.setPosition(popup_pos); } /** * Shows the popup with a new annotation. * @param {annotorious.Annotation} annotation the annotation */ annotorious.mediatypes.openlayers.Viewer.prototype._show_popup = function(annotation) { this._popup.setAnnotation(annotation); this._place_popup(); this._popup.show(); } /** * @param {Object=} new_highlight the overlay to highlight * @param {Object=} previous_highlight the overlay previously highlighted */ annotorious.mediatypes.openlayers.Viewer.prototype._updateHighlight = function(new_highlight, previous_highlight) { if (new_highlight) { var pos = goog.style.getRelativePosition(new_highlight.marker.div, this._map.div); var height = parseInt(goog.style.getStyle(new_highlight.marker.div, 'height'), 10); goog.style.setStyle(new_highlight.inner, 'border-color', '#fff000'); this._currentlyHighlightedOverlay = new_highlight; this._show_popup(new_highlight.annotation); } else { delete this._currentlyHighlightedOverlay; } if (previous_highlight) { goog.style.setStyle(previous_highlight.inner, 'border-color', '#fff'); } } /** * Adds an annotation to the viewer. * @param {annotorious.Annotation} annotation the annotation */ annotorious.mediatypes.openlayers.Viewer.prototype.addAnnotation = function(annotation) { var geometry = annotation.shapes[0].geometry; var marker = new OpenLayers.Marker.Box(new OpenLayers.Bounds(geometry.x, geometry.y, geometry.x + geometry.width, geometry.y + geometry.height)); goog.dom.classes.add(marker.div, 'annotorious-ol-boxmarker-outer'); goog.style.setStyle(marker.div, 'border', null); var inner = goog.dom.createDom('div', 'annotorious-ol-boxmarker-inner'); goog.style.setSize(inner, '100%', '100%'); goog.dom.appendChild(marker.div, inner); var overlay = {annotation: annotation, marker: marker, inner: inner}; var self = this; goog.events.listen(inner, goog.events.EventType.MOUSEOVER, function(event) { if (!self._currentlyHighlightedOverlay) self._updateHighlight(overlay); self._lastHoveredOverlay = overlay; }); goog.events.listen(inner, goog.events.EventType.MOUSEOUT, function(event) { delete self._lastHoveredOverlay; self._popup.startHideTimer(); }); this._overlays.push(overlay); // The viewer always operates in pixel coordinates for efficiency reasons var shape = annotation.shapes[0]; if (shape.units == annotorious.shape.Units.PIXEL) { this._shapes[annotorious.shape.hashCode(annotation.shapes[0])] = shape; } else { var viewportShape = annotorious.shape.transform(shape, function(xy) { return self._annotator.fromItemCoordinates(xy); }); this._shapes[annotorious.shape.hashCode(annotation.shapes[0])] = viewportShape; } goog.array.sort(this._overlays, function(a, b) { var shapeA = a.annotation.shapes[0]; var shapeB = b.annotation.shapes[0]; return annotorious.shape.getSize(shapeB) - annotorious.shape.getSize(shapeA); }); var zIndex = 10000; goog.array.forEach(this._overlays, function(overlay) { goog.style.setStyle(overlay.marker.div, 'z-index', zIndex); zIndex++; }); this._boxesLayer.addMarker(marker); } /** * Removes an annotation from the viewer. * @param {annotorious.Annotation} annotation the annotation */ annotorious.mediatypes.openlayers.Viewer.prototype.removeAnnotation = function(annotation) { var overlay = goog.array.find(this._overlays, function(overlay) { return overlay.annotation == annotation; }); if (overlay) { goog.array.remove(this._overlays, overlay); this._boxesLayer.removeMarker(overlay.marker); } } /** * Returns all annotations in this viewer. * @return {Array.<annotorious.Annotation>} the annotations */ annotorious.mediatypes.openlayers.Viewer.prototype.getAnnotations = function() { return goog.array.map(this._overlays, function(overlay) { return overlay.annotation; }); } /** * Highlights a particular annotation in the viewer, or de-highlights (if that's a * word...) all, if no annotation is passed to the method. * @param {annotorious.Annotation | undefined} opt_annotation the annotation */ annotorious.mediatypes.openlayers.Viewer.prototype.highlightAnnotation = function(opt_annotation) { if (opt_annotation) { // TODO } else { this._popup.startHideTimer(); } } /** * Convenience method returing only the top-most annotation at the specified coordinates. * @param {number} px the X coordinate * @param {number} py the Y coordinates */ annotorious.mediatypes.openlayers.Viewer.prototype.topAnnotationAt = function(px, py) { var annotations = this.getAnnotationsAt(px, py); if (annotations.length > 0) { return annotations[0]; } else { return undefined; } } /** * Returns the annotations at the specified X/Y coordinates. * @param {number} px the X coordinate * @param {number} py the Y coordinate * @return {Array.<annotorious.Annotation>} the annotations sorted by size, smallest first */ annotorious.mediatypes.openlayers.Viewer.prototype.getAnnotationsAt = function(px, py) { // TODO for large numbers of annotations, we can optimize this // using a tree- or grid-like data structure instead of a list var intersectedAnnotations = []; var self = this; goog.array.forEach(this._overlays, function(overlay) { var annotation = overlay.annotation; if (annotorious.shape.intersects(self._shapes[annotorious.shape.hashCode(annotation.shapes[0])], px, py)) { intersectedAnnotations.push(annotation); } }); goog.array.sort(intersectedAnnotations, function(a, b) { var shape_a = self._shapes[annotorious.shape.hashCode(a.shapes[0])]; var shape_b = self._shapes[annotorious.shape.hashCode(b.shapes[0])]; return annotorious.shape.getSize(shape_a) - annotorious.shape.getSize(shape_b); }); return intersectedAnnotations; }
import R from 'ramda' /** Draws state.keys.response commands. */ export default (layout) => payload => { const { changes } = payload const each = R.map(change => `{cyan-fg}${change.path}{/}{|}{white-fg}${change.value}{/}`, changes) const message = R.join('\n', each) layout.stateWatchBox.setContent(message) layout.screen.render() }
define ( function module ( ) { "use strict"; const _0_0_ = 0; const _1_0_ = 3; const _2_0_ = 6; const _0_1_ = 1; const _1_1_ = 4; const _2_1_ = 7; const _0_2_ = 2; const _1_2_ = 5; const _2_2_ = 8; class mat3 extends Float32Array { constructor ( ) { super( 9 ); this.makeIdentity(); } static set ( outM3, inM3 ) { return mat3.prototype.set.call( outM3 ); } set ( inM3 ) { this[_0_0_] = inM3[_0_0_]; this[_0_1_] = inM3[_0_1_]; this[_0_2_] = inM3[_0_2_]; this[_1_0_] = inM3[_1_0_]; this[_1_1_] = inM3[_1_1_]; this[_1_2_] = inM3[_1_2_]; this[_2_0_] = inM3[_2_0_]; this[_2_1_] = inM3[_2_1_]; this[_2_2_] = inM3[_2_2_]; return this; } static setValues ( outM3, s_0_0, s_0_1, s_0_2, s_1_0, s_1_1, s_1_2, s_2_0, s_2_1, s_2_2 ) { return mat3.prototype.setValues.call( outM3, s_0_0, s_0_1, s_0_2, s_1_0, s_1_1, s_1_2, s_2_0, s_2_1, s_2_2 ); } setValues ( s_0_0, s_0_1, s_0_2, s_1_0, s_1_1, s_1_2, s_2_0, s_2_1, s_2_2 ) { this[_0_0_] = s_0_0; this[_0_1_] = s_0_1; this[_0_2_] = s_0_2; this[_1_0_] = s_1_0; this[_1_1_] = s_1_1; this[_1_2_] = s_1_2; this[_2_0_] = s_2_0; this[_2_1_] = s_2_1; this[_2_2_] = s_2_2; return this; } static transpose ( outM3 ) { return mat3.prototype.transpose.call( outM3 ); } transpose ( inM3 ) { if ( inM3 === undefined ) inM3 = CACHE_MAT3.set( this ); this[_0_0_] = inM3[_0_0_]; this[_0_1_] = inM3[_1_0_]; this[_0_2_] = inM3[_2_0_]; this[_1_0_] = inM3[_0_1_]; this[_1_1_] = inM3[_1_1_]; this[_1_2_] = inM3[_2_1_]; this[_2_0_] = inM3[_0_2_]; this[_2_1_] = inM3[_1_2_]; this[_2_2_] = inM3[_2_2_]; return this; } static add ( outM3, inM3 ) { return mat3.prototype.add.call( outM3, inM3 ); } add ( inM3_a, inM3_b ) { if ( inM3_b === undefined ) inM3_b = this; this[_0_0_] = inM3_a[_0_0_] + inM3_b[_0_0_]; this[_0_1_] = inM3_a[_0_1_] + inM3_b[_0_1_]; this[_0_2_] = inM3_a[_0_2_] + inM3_b[_0_2_]; this[_1_0_] = inM3_a[_1_0_] + inM3_b[_1_0_]; this[_1_1_] = inM3_a[_1_1_] + inM3_b[_1_1_]; this[_1_2_] = inM3_a[_1_2_] + inM3_b[_1_2_]; this[_2_0_] = inM3_a[_2_0_] + inM3_b[_2_0_]; this[_2_1_] = inM3_a[_2_1_] + inM3_b[_2_1_]; this[_2_2_] = inM3_a[_2_2_] + inM3_b[_2_2_]; return this; } static multiply ( outM3, inM3 ) { return mat3.prototype.multiply.call( outM3, inM3 ); } multiply ( inM3_a, inM3_b ) { if ( inM3_b === undefined ) inM3_b = CACHE_MAT3.set( this ); let a = inM3_a; let b = inM3_b; this[_0_0_] = a[_0_0_] * b[_0_0_] + a[_0_1_] * b[_1_0_] + a[_0_2_] * b[_2_0_]; this[_0_1_] = a[_0_0_] * b[_0_1_] + a[_0_1_] * b[_1_1_] + a[_0_2_] * b[_2_1_]; this[_0_2_] = a[_0_0_] * b[_0_2_] + a[_0_1_] * b[_1_2_] + a[_0_2_] * b[_2_2_]; this[_1_0_] = a[_1_0_] * b[_0_0_] + a[_1_1_] * b[_1_0_] + a[_1_2_] * b[_2_0_]; this[_1_1_] = a[_1_0_] * b[_0_1_] + a[_1_1_] * b[_1_1_] + a[_1_2_] * b[_2_1_]; this[_1_2_] = a[_1_0_] * b[_0_2_] + a[_1_1_] * b[_1_2_] + a[_1_2_] * b[_2_2_]; this[_2_0_] = a[_2_0_] * b[_0_0_] + a[_2_1_] * b[_1_0_] + a[_2_2_] * b[_2_0_]; this[_2_1_] = a[_2_0_] * b[_0_1_] + a[_2_1_] * b[_1_1_] + a[_2_2_] * b[_2_1_]; this[_2_2_] = a[_2_0_] * b[_0_2_] + a[_2_1_] * b[_1_2_] + a[_2_2_] * b[_2_2_]; return this; } static addScalar ( outM3, s ) { return mat3.prototype.addScalar.call( outM3, s ); } addScalar ( s, inM3 ) { if ( inM3 === undefined ) inM3 = this; this[_0_0_] = inM3[_0_0_] + s; this[_0_1_] = inM3[_0_1_] + s; this[_0_2_] = inM3[_0_2_] + s; this[_1_0_] = inM3[_1_0_] + s; this[_1_1_] = inM3[_1_1_] + s; this[_1_2_] = inM3[_1_2_] + s; this[_2_0_] = inM3[_2_0_] + s; this[_2_1_] = inM3[_2_1_] + s; this[_2_2_] = inM3[_2_2_] + s; return this; } static multiplyScalar ( outM3, s ) { return mat3.prototype.multiplyScalar.call( outM3, s ); } multiplyScalar ( s, inM3 ) { if ( inM3 === undefined ) inM3 = this; this[_0_0_] = inM3[_0_0_] * s; this[_0_1_] = inM3[_0_1_] * s; this[_0_2_] = inM3[_0_2_] * s; this[_1_0_] = inM3[_1_0_] * s; this[_1_1_] = inM3[_1_1_] * s; this[_1_2_] = inM3[_1_2_] * s; this[_2_0_] = inM3[_2_0_] * s; this[_2_1_] = inM3[_2_1_] * s; this[_2_2_] = inM3[_2_2_] * s; return this; } static makeIdentity ( outM3 ) { return mat3.prototype.makeIdentity.call( outM3 ); } makeIdentity ( ) { this[_0_0_] = 1; this[_0_1_] = 0; this[_0_2_] = 0; this[_1_0_] = 0; this[_1_1_] = 1; this[_1_2_] = 0; this[_2_0_] = 0; this[_2_1_] = 0; this[_2_2_] = 1; return this; } static makeTranslation ( outM3, sX, sY, sZ ) { return mat3.prototype.makeTranslation.call( outM3, sX, sY, sZ ); } makeTranslation ( sX, sY, sZ ) { if ( sX === undefined ) sX = 0; if ( sY === undefined ) sY = 0; if ( sZ === undefined ) sZ = 0; this[_0_0_] = 1; this[_0_1_] = 0; this[_0_2_] = 0; this[_1_0_] = 0; this[_1_1_] = 1; this[_1_2_] = 0; this[_2_0_] = sX; this[_2_1_] = sY; this[_2_2_] = sZ; return this; } static makeScale ( outM3, sX, sY, sZ ) { return mat3.prototype.makeScale.call( outM3, sX, sY, sZ ); } makeScale ( sX, sY, sZ ) { if ( sX === undefined ) sX = 1; if ( sY === undefined ) sY = sX; if ( sZ === undefined ) sZ = sX; this[_0_0_] = sX; this[_0_1_] = 0; this[_0_2_] = 0; this[_1_0_] = 0; this[_1_1_] = sY; this[_1_2_] = 0; this[_2_0_] = 0; this[_2_1_] = 0; this[_2_2_] = sZ; } static makeRotationX ( outM3, sDeg ) { return mat3.prototype.makeRotationX.call( outM3, sDeg ); } makeRotationX( sDeg ) { if ( sDeg === undefined ) sDeg = 0; let c = Math.cos( sDeg / 180 * Math.PI ); let s = Math.sin( sDeg / 180 * Math.PI ); this[_0_0_] = 1; this[_0_1_] = 0; this[_0_2_] = 0; this[_1_0_] = 0; this[_1_1_] = c; this[_1_2_] = -s; this[_2_0_] = 0; this[_2_1_] = s; this[_2_2_] = c; return this; } static makeRotationY ( outM3, sDeg ) { return mat3.prototype.makeRotationY.call( outM3, sDeg ); } makeRotationY ( sDeg ) { if ( sDeg === undefined ) sDeg = 0; let c = Math.cos( sDeg / 180 * Math.PI ); let s = Math.sin( sDeg / 180 * Math.PI ); this[_0_0_] = c; this[_0_1_] = 0; this[_0_2_] = s; this[_1_0_] = 0; this[_1_1_] = 0; this[_1_2_] = 1; this[_2_0_] = -s; this[_2_1_] = 0; this[_2_2_] = c; return this; } static makeRotationZ ( outM3, sDeg ) { return mat3.prototype.makeRotationZ.call( outM3, sDeg ); } makeRotationZ ( sDeg ) { if ( sDeg === undefined ) sDeg = 0; let c = Math.cos( sDeg / 180 * Math.PI ); let s = Math.sin( sDeg / 180 * Math.PI ); this[_0_0_] = c; this[_0_1_] = -s; this[_0_2_] = 0; this[_1_0_] = s; this[_1_1_] = c; this[_1_2_] = 0; this[_2_0_] = 0; this[_2_1_] = 0; this[_2_2_] = 1; return this; } } const CACHE_MAT3 = new mat3; return mat3; });
var debugvar = ""; var AuthenticablePrincipal = { SelectedUser: { name : "", enabled : false, localLogonEnabled: false, id: "", alternativeNames: [] }, ResetUserModalValues: function () { $('#authPrincipalUpn').val(''); $('#authPrincipalEnabled').val(''); $('#localLogonEnabled').val(''); AuthenticablePrincipal.AlternativeUpnActionModalSelect2.val(null).trigger("change"); }, GetUpdatedUserData: function () { return { id: AuthenticablePrincipal.TargetUserId.val(), name: $('#principalName.modal-input').val(), enabled: $("#userEnabled.modal-input").is(":checked"), localLogonEnabled: $("#userLocalLogonEnabled.modal-input").is(":checked"), alternativeNames: UiGlobal.GetSelectedOptions(AuthenticablePrincipal.AlternativeUpnActionModalSelect2) } }, ShowAddUserModal: function () { AuthenticablePrincipal.ResetUserModalValues(); AuthenticablePrincipal.TargetUserId.val(""); AuthenticablePrincipal.InitializeAlternativeUpnActionModalSelect2(); AuthenticablePrincipal.SetCommitOnClick("Add"); AuthenticablePrincipal.UserModal.modal("show"); }, ShowEditUserModal: function (data) { AuthenticablePrincipal.ResetUserModalValues(); AuthenticablePrincipal.LoadEditAuthPrincipalModalData(data); AuthenticablePrincipal.SetCommitOnClick("Edit"); AuthenticablePrincipal.UserModal.modal("show"); }, SetCommitOnClick(eventType) { switch (eventType) { case "Add": AuthenticablePrincipal.CommitUserButton.attr("onclick", "AuthenticablePrincipal.AddAuthPrincipal();"); break; case "Edit": AuthenticablePrincipal.CommitUserButton.attr("onclick", "AuthenticablePrincipal.EditAuthPrincipal();"); break; default: AuthenticablePrincipal.CommitUserButton.attr("onclick", "AuthenticablePrincipal.AddAuthPrincipal();"); } }, LoadEditAuthPrincipalModalData: function (data) { AuthenticablePrincipal.TargetUserId.val(data.id); $('#principalName').val(data.name); $('#userEnabled.modal-input').attr("checked", data.enabled); $('#userLocalLogonEnabled.modal-input').attr("checked", data.localLogonEnabled); AuthenticablePrincipal.InitializeAlternativeUpnActionModalSelect2(data); }, EditAuthPrincipal: function () { var data = AuthenticablePrincipal.GetUpdatedUserData(); //$.extend(client, { // name: $("#authPrincipalUpn").val(), // enabled: $("#authPrincipalEnabled").is(":checked"), // localLogonEnabled: $("#localLogonEnabled").is(":checked"), // alternativeNames: UiGlobal.GetSelectedOptions(AuthenticablePrincipal.AlternativeUpnActionModalSelect2) //}); //debugvar = client; AuthenticablePrincipal.Grid.jsGrid("updateItem", data); //$("#authenticablePrincipalActionModal").modal("hide"); }, AddAuthPrincipal: function () { var data = AuthenticablePrincipal.GetUpdatedUserData(); //$.extend(client, { // name: $("#authPrincipalUpn").val(), // enabled: $("#authPrincipalEnabled").is(":checked"), // localLogonEnabled: $("#localLogonEnabled").is(":checked"), // alternativeNames: UiGlobal.GetSelectedOptions(AuthenticablePrincipal.AlternativeUpnActionModalSelect2) //}); AuthenticablePrincipal.Grid.jsGrid("insertItem", data); //$("#authenticablePrincipalActionModal").modal("hide"); }, InitializeGrid: function () { AuthenticablePrincipal.Grid = $("#authenticablePrincipalTable"); AuthenticablePrincipal.Grid.jsGrid({ height: "auto", width: "100%", rowClick: function (args) { AuthenticablePrincipal.ShowEditUserModal(args.item); //AuthenticablePrincipal.ShowAuthenticablePrincipalActionModal("Edit", args.item); }, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this external identity source?", controller: AuthenticablePrincipal.Controller, //rowClick: function (args) { // AuthenticablePrincipal.ShowAuthenticablePrincipalActionModal("Edit", args.item); //}, fields: [ { name: "name", type: "text", title: "Name" }, { name: "alternativeNames", title: "Alternative UPN", itemTemplate: function (value, item) { var altUpnSelect = $("<select style='width:100%' class='alternativeupn-select2' multiple='multiple'>"); if (item.alternativeNames != null) { item.alternativeNames.forEach(function (option) { altUpnSelect.append($('<option>', { value: option, text: option }).attr('selected', true)); }); } altUpnSelect = altUpnSelect.attr('disabled', true); return altUpnSelect; } }, { name: "localLogonEnabled", type: "checkbox", title: "LocalLogonEnabled", width: 40 }, { name: "enabled", type: "checkbox", title: "Enabled", sorting: false, width: 25 }, { title: "Action", width: 15, itemTemplate: function (value, item) { var btn = $("<i>"); btn.addClass("fa fa-key"); btn.attr('cm-id', item.id); btn.attr('cm-upn', item.name); return btn.on("click", function (event) { var id = event.target.attributes["cm-id"].value var upn = event.target.attributes["cm-upn"].value AuthenticablePrincipal.ResetPasswordButtonClick(id, upn); return false; }); } }, { width: 25, type: "control", editButton: false, headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { AuthenticablePrincipal.ShowAddUserModal(); }); } } ], onRefreshed: function (args) { AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, onItemUpdated: function (args) { AuthenticablePrincipal.Grid.jsGrid("render"); AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, onItemEditing: function (args) { AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, onItemInserting: function (args) { UiGlobal.ResetAlertState(); }, onItemUpdating: function (args) { UiGlobal.ResetAlertState(); AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, onItemDeleting: function (args) { UiGlobal.ResetAlertState(); }, onDataLoading: function (args) { AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, onDataLoaded: function (args) { AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); } }); AuthenticablePrincipal.InitializeAlternativeUpnSelect2(); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/security/authenticable-principals", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { $.ajax({ type: "POST", url: "/security/authenticable-principal", data: item }).fail(function (xhr, ajaxOptions, thrownError) { AuthenticablePrincipal.HandleError(xhr.responseJSON.message, AuthenticablePrincipal.Grid); }); }, updateItem: function (item) { var d = $.Deferred(); $.ajax({ type: "PUT", url: "/security/authenticable-principal", dataType: "json", data: item }).fail(function (xhr, ajaxOptions, thrownError) { AuthenticablePrincipal.HandleError(xhr.responseJSON.message, AuthenticablePrincipal.Grid); }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/security/authenticable-principal", data: item }).fail(function (xhr, ajaxOptions, thrownError) { AuthenticablePrincipal.HandleError(xhr.responseJSON.message, AuthenticablePrincipal.Grid); }); }, onItemInserting: function (args) { AuthenticablePrincipal.ResetErrorState(); }, onItemUpdating: function (args) { AuthenticablePrincipal.ResetErrorState(); }, onItemDeleting: function (args) { AuthenticablePrincipal.ResetErrorState(); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (msg, grid) { grid.jsGrid("render"); UiGlobal.ShowError(msg); }, InitializeSelect: function () { CmOptions.ActiveDirectoryMetadataType.forEach(function (item) { $('#eisType').append($('<option>', { value: item.Name, text: item.Name })); }); }, ImportUserSelections: [], InitializeUserSearchSelect: function () { $('.idp-select').select2({ data: CmOptions.ActiveDirectoryMetadatas }); AuthenticablePrincipal.ImportUserSelect = $(".user-search-select"); AuthenticablePrincipal.ImportUserSelect.select2({ dropdownAutoWidth: true, placeholder: 'search for an ad object', ajax: { url: ("/identity-source/external/query/users"), dataType: 'json', type: 'get', delay: 30, data: function (params) { return { query: params.term, // search term page: params.page }; }, processResults: function (data, params) { // parse the results into the format expected by Select2 // since we are using custom formatting functions we do not need to // alter the remote JSON data, except to indicate that infinite // scrolling can be used params.page = params.page || 1; return { results: data.payload, //pagination: { // more: (params.page * 30) < data.total_count //} }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 2, templateResult: AuthenticablePrincipal.formatRepo, // omitted for brevity, see the source of this page templateSelection: AuthenticablePrincipal.formatRepoSelection // omitted for brevity, see the source of this page }); AuthenticablePrincipal.ImportUserSelect.on("select2:selecting", function (e) { AuthenticablePrincipal.ImportUserSelections.push(e.params.args.data); }); }, formatRepo: function (repo) { var markup = '<div class="user-select-container">' markup = markup + '<div class="user-select-title">' + repo.samAccountName + ' ; ' + repo.name + ' ; ' + repo.displayName + '</div>'; markup = markup + '<div class="user-select-details">UserPrincipalName: <span class="user-select-details-value">' + repo.name + '</span></div>'; markup = markup + '<div class="user-select-details">Domain: <span class="user-select-details-value">' + repo.domain + '</span></div>'; markup = markup + '</div>'; //var markup = repo.text; return markup; }, formatRepoSelection: function (repo) { return repo.samAccountName; //return repo.name || repo.text; //return repo.text; }, FormatExistingUserMergeRepository: function (repo) { return repo.name; }, FormatExistingUserMergeSelection: function (repo) { return repo.name; }, ImportSelectedUsers: function () { UiGlobal.ResetAlertState(); if (AuthenticablePrincipal.MergeOnImport) { var data = { users: AuthenticablePrincipal.ImportUserSelections, mergeWith: AuthenticablePrincipal.ExistingUserMergeSelect2().val(), merge: AuthenticablePrincipal.MergeOnImport }; } else { var data = { users: AuthenticablePrincipal.ImportUserSelections, merge: AuthenticablePrincipal.MergeOnImport }; } Services.ImportUsersFromActiveDirectoryMetadata(data, AuthenticablePrincipal.ImportSelectedUsersSuccessCallback, AuthenticablePrincipal.ImportSelectedUsersErrorCallback); }, ImportSelectedUsersSuccessCallback: function () { AuthenticablePrincipal.ImportUserSelections = []; AuthenticablePrincipal.ResetUserSelect(); UiGlobal.RefreshGrid(AuthenticablePrincipal.Grid); UiGlobal.ShowSuccess("Successfully imported the selected users"); }, ImportSelectedUsersErrorCallback: function (e) { AuthenticablePrincipal.ImportUserSelections = []; AuthenticablePrincipal.ResetUserSelect(); UiGlobal.ShowError("Error while importing users: " + e.responseJSON.message); }, ResetUserSelect: function () { AuthenticablePrincipal.ImportUserSelect.select2('val', 'All'); }, AlternativeUpnSelect2: function () { return $('.alternativeupn-select2'); }, InitializeAlternativeUpnActionModalSelect2: function (client) { AuthenticablePrincipal.ResetUserModalValues(); if (client != null) { if (client.alternativeNames != null) { client.alternativeNames.forEach(function (option) { if (!AuthenticablePrincipal.AlternativeUpnActionModalSelect2.val().includes(option)) { AuthenticablePrincipal.AlternativeUpnActionModalSelect2.append($('<option>', { value: option, text: option }).attr('selected', true)); } }); } } AuthenticablePrincipal.AlternativeUpnActionModalSelect2.select2({ width: '100%', tags: true }); }, InitializeAlternativeUpnSelect2: function () { AuthenticablePrincipal.AlternativeUpnSelect2().select2({ width: '100%' }); }, RegisterModalCloseEvent: function () { $('#authenticablePrincipalActionModal').on('hidden.bs.modal', function () { AuthenticablePrincipal.ResetUserModalValues(); }); }, RegisterImportUserModalCloseEvent: function () { $('#importUsersModal').on('hidden.bs.modal', function () { $('#authPrincipalUpn').val(''); $('#authPrincipalEnabled').val(''); $('#localLogonEnabled').val(''); AuthenticablePrincipal.AlternativeUpnActionModalSelect2ClearOptions(); }); }, PageLoad: function () { AuthenticablePrincipal.InitializeGrid(); AuthenticablePrincipal.InitializeUserSearchSelect(); //AuthenticablePrincipal.RegisterModalCloseEvent(); AuthenticablePrincipal.RegisterMergeCheckboxEvent(); AuthenticablePrincipal.InitializeExistingUserMergeSelect2(); AuthenticablePrincipal.CommitUserButton = $('#commitAuthenticablePrincipalButton'); AuthenticablePrincipal.UserModal = $("#authenticablePrincipalActionModal"); AuthenticablePrincipal.TargetUserId = $('#targetUserId'); AuthenticablePrincipal.AlternativeUpnActionModalSelect2 = $('#alternativeUpn'); }, MergeOnImport: false, ShowMergeExistingUserSelect: function () { $('.existingUserSelect').show(); }, HideMergeExistingUserSelect: function () { $('.existingUserSelect').hide(); }, RegisterMergeCheckboxEvent: function () { $('#mergeCheckbox').change(function () { if ($(this).is(":checked")) { AuthenticablePrincipal.MergeOnImport = true; AuthenticablePrincipal.ShowMergeExistingUserSelect(); } else { AuthenticablePrincipal.MergeOnImport = false; AuthenticablePrincipal.HideMergeExistingUserSelect(); } }); }, ExistingUserMergeSelect2: function () { return $('#existingUserSelect'); }, InitializeExistingUserMergeSelect2: function () { AuthenticablePrincipal.ExistingUserMergeSelect2().select2({ dropdownAutoWidth: true, width: '100%', placeholder: 'Search for a Certificate Manager user', ajax: { url: ("/security/authenticable-principals"), dataType: 'json', type: 'get', delay: 30, //data: function (params) { // return { // query: params.term, // search term // page: params.page // }; //}, processResults: function (data, params) { params.page = params.page || 1; return { results: data.payload, }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, //minimumInputLength: 2, templateResult: AuthenticablePrincipal.FormatExistingUserMergeRepository, templateSelection: AuthenticablePrincipal.FormatExistingUserMergeSelection }); }, ResetPasswordButtonClick: function (id, upn) { //console.log('reset password button click'); //console.log(id); //console.log(upn); $('#reset-pwd-id').val(id) $('#reset-pwd-upn').val(upn); $("#resetUserPasswordModal").modal("show"); return false; }, ResetUserPassword: function () { var id = $('#reset-pwd-id').val(); var newPassword = $('#reset-pwd-password').val(); var data = { id: id, newPassword: newPassword }; $('#reset-pwd-password').val(''); Services.ResetUserPassword(data, UiGlobal.ShowSuccess, UiGlobal.ShowError); }, CommitUserButton: null, UserModal: null, Grid: null, ImportUserSelect: null, TargetUserId: null, AlternativeUpnActionModalSelect2: null } var CmOptions = { hashAlgorithmOptions: [ { Name: "SHA1", Id: 0, Display: "SHA1 (Insecure)" }, { Name: "SHA256", Id: 1, Display: "SHA256 (Recommended)", Primary: true }, { Name: "SHA512", Id: 2, Display: "SHA512 (Most Secure)" } ], cipherOptions: [ { Name: "RSA", Id: 0, Display: "RSA (TLS / More Support)", Primary: true }, { Name: "ECDH", Id: 1, Display: "ECDH (TLS / Most Secure)" }, { Name: "ECDSA", Id: 2, Display: "ECDSA (Uncommon)" } ], keyUsageOptions: [ { Name: "None", Id: 0, Primitive: true, Display: "None" }, { Name: "ServerAuthentication", Id: 1, Primitive: true, Display: "ServerAuthentication", Primary: true }, { Name: "ClientAuthentication", Id: 2, Primitive: true, Display: "ClientAuthentication" }, { Name: "ServerAuthentication, ClientAuthentication", Id: 3, Primitive: false, Display: "ServerAuthentication, ClientAuthentication" }, { Name: "DocumentEncryption", Id: 4, Primitive: true, Display: "DocumentEncryption" }, { Name: "CodeSigning", Id: 8, Primitive: true, Display: "CodeSigning" }, { Name: "CertificateAuthority", Id: 16, Primitive: true, Display: "CertificateAuthority" }, { Name: "Undetermined", Id: 32, Primitive: true, Display: "Undetermined" } ], windowsApiOptions: [ { Name: "Cng", Id: 1, Display: "CryptoApi Next Generation (Most Secure)", Primary: true }, { Name: "CryptoApi", Id: 0, Display: "CryptoApi (More Support)" } ], //windowsApiOptions: ["Cng", "CryptoApi"], authenticationTypeOptions: [ { Name: "UsernamePassword", Id: 0, Display: "basic", Primary: true }, { Name: "WindowsKerberos", Id: 1, Display: "kerberos" } ], ActiveDirectoryMetadataType: [ { Name: "ActiveDirectoryIwa", Id: 0, Display: "ActiveDirectoryIwa" }, { Name: "ActiveDirectoryBasic", Id: 1, Display: "ActiveDirectoryBasic" }, ], LocalIdentityProviderId: "02abeb4c-e0b6-4231-b836-268aa40c3f1c" } var Nodes = { PageLoad: function () { Nodes.Grid = $('#nodeTable'); Nodes.Modal = $('#addNodeModal'); Nodes.CommitButton = $('#addButton'); Nodes.CredentialSelect = $('#credential'); Nodes.InitializeGrid(); Nodes.InitializeIdpSelect(); }, InitializeIdpSelect: function () { Services.GetActiveDirectoryIdentityProviders(Nodes.InitializeIdpSelectSuccessCallback, null); }, InitializeIdpSelectSuccessCallback: function (data) { var primarySet = false; var appendData = {}; data.forEach(function (item) { if (primarySet) { appendData = { value: item.id, text: item.name }; } else { appendData = { value: item.id, text: item.name, selected: "selected" }; primarySet = true; } Nodes.CredentialSelect.append($('<option>', appendData)); }); }, CredentialSelect: null, Grid: null, Modal: null, ShowAddModal: function () { Nodes.ResetModalState(); Nodes.Modal.modal("show"); Nodes.SetCommitOnClick("Add"); }, CommitButton: null, ResetModalState: function () { $('#hostname').val(''); $('#credential').val(''); }, Add: function () { Nodes.Grid.jsGrid("insertItem", Nodes.GetData()); }, Edit: function () { }, GetData: function () { return { hostName: $('#hostname').val(), credentialId: $('#credential').val() }; }, SetCommitOnClick: function(eventType) { switch (eventType) { case "Add": Nodes.CommitButton.attr("onclick", "Nodes.Add();"); break; case "Edit": Nodes.CommitButton.attr("onclick", "Nodes.Edit();"); break; default: Nodes.CommitButton.attr("onclick", "Nodes.Add();"); } }, ViewNode: function (item) { document.location = "/view/node/" + item.id; }, InitializeGrid: function () { Nodes.Grid.jsGrid({ height: "auto", width: "100%", editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, rowClick: function (args) { Nodes.ViewNode(args.item); }, deleteConfirm: "Do you really want to delete this node?", controller: Nodes.Controller, fields: [ { name: "hostname", type: "text", title: "Hostname" }, { name: "credential", type: "text", title: "Credential" }, { name: "lastCommunication", type: "text", title: "LastCommunication" }, { name: "communicationSuccess", type: "text", title: "CommunicationSuccess" }, { name: "details", title: "Action", width: 50, itemTemplate: function (value, item) { var $link = $("<a>").attr("href", '/view/node/' + item.id).text("View"); return $("<div>").append($link); } }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { Nodes.ShowAddModal(); }); } } ], onItemInserting: function (args) { Nodes.ResetErrorState(); }, onItemUpdating: function (args) { Nodes.ResetErrorState(); }, onItemDeleting: function (args) { Nodes.ResetErrorState(); } }); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/nodes", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { var d = $.Deferred(); $.ajax({ type: "POST", url: "/node", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { Nodes.HandleError(xhr.responseJSON.message, Nodes.Table); }); return d.promise(); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/node", data: item }).fail(function (xhr, ajaxOptions, thrownError) { Nodes.HandleError(xhr.responseJSON.message, Nodes.Table); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/node", data: item }).fail(function (xhr, ajaxOptions, thrownError) { Nodes.HandleError(xhr.responseJSON.message, Nodes.Table); }); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus.responseJSON.message); }, InitializeSelect: function () { CmOptions.ActiveDirectoryMetadataType.forEach(function (item) { $('#eisType').append($('<option>', { value: item.Name, text: item.Name })); }); } } function openTab(evt, tabName) { // Declare all variables var i, tabcontent, tablinks; location.hash = tabName; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current tab, and add an "active" class to the button that opened the tab document.getElementById(tabName).style.display = "block"; $('.' + tabName).addClass("active"); }; var UIDefaults = { GetEnumMap: function () { if (localStorage.getItem("uiEnumMap") === null) { Services.GetEnumMapping(); while (localStorage.getItem("uiEnumMap") === null) { } return JSON.parse(localStorage.getItem("uiEnumMap")); } else { return JSON.parse(localStorage.getItem("uiEnumMap")); } } }; var UiGlobal = { GetRowClass: function (item, itemIndex) { if (item.eventCategory == "CertificateIssuance" && item.eventResult == "Success" ) { return 'event-primary'; } if (item.eventCategory == "LogCleared") { return 'warning'; } if (item.eventResult == "Error") { return 'error'; } }, GetWindowsApiDisplay: function (name) { var displayName = "unknown"; CmOptions.windowsApiOptions.forEach(function (item) { if (item.Name == name) { displayName = item.Display; } }); return displayName; }, GetShortDateTime: function (value, item) { var date = new Date(value) return date.toDateString(); }, RefreshGrid: function (grid) { grid.jsGrid("render"); }, ResetAlertState: function () { UiGlobal.HideError(); UiGlobal.HideSuccess(); UiGlobal.HideWarning(); }, ShowSuccess: function (msg) { $('#success-alert').text(msg) $('#success-alert').show(); }, HideSuccess: function (msg) { $('#success-alert').hide(); }, ShowError: function (msg) { $('#error-alert').text(msg) $('#error-alert').show(); }, ShowWarning: function (msg) { $('#warning-alert').text(msg); $('#warning-alert').show(); }, HideError: function () { $('#error-alert').hide(); }, HideWarning: function () { $('#warning-alert').hide(); }, ShowCurrentTab: function () { if (location.hash === "" || location.hash === null) { $('#defaultOpen').click(); } else { var currentTab = location.hash.replace("#", ""); $("." + currentTab).click(); } }, ShowModal: function (id) { $("#" + id).modal("show"); }, GetSelectedOptions: function (obj) { var selectedArray = []; var selected = obj.find(":selected"); for (i = 0; i < selected.length; i++) { selectedArray.push(selected[i].value); } return selectedArray; }, GetDateString(arg) { return (new Date(arg)).toDateString(); }, GetFormRowDiv: function () { return $('<div>').addClass('form-group row'); }, GetFormColLabel: function (displayText) { return $('<div>').addClass('col-sm-6').text(displayText); }, GetFormCheckbox: function (inputId, isChecked) { var input = $('<input>').addClass('form-check-input scope').attr('type', 'checkbox').attr('id', inputId).attr("checked", isChecked); var label = $('<label>').addClass('form-check-label'); var inputDiv = $('<div>').addClass('form-check'); var inputCol = $('<div>').addClass('col-sm-4'); return inputCol.append(inputDiv.append(label.append(input))); }, GetButton: function (onclick) { return $('<button>') .attr('type', 'button') .addClass('btn btn-primary') .attr('onclick', onclick) .text('Save'); } } var CmScripts = { PageLoad: function () { CmScripts.Grid = $('#table'); CmScripts.Modal = $('#addModal'); CmScripts.CommitButton = $('#addButton'); //CmScripts.CredentialSelect = $('#credential'); CmScripts.InitializeGrid(); //CmScripts.InitializeIdpSelect(); }, InitializeIdpSelect: function () { Services.GetActiveDirectoryIdentityProviders(CmScripts.InitializeIdpSelectSuccessCallback, null); }, InitializeIdpSelectSuccessCallback: function (data) { var primarySet = false; var appendData = {}; data.forEach(function (item) { if (primarySet) { appendData = { value: item.id, text: item.name }; } else { appendData = { value: item.id, text: item.name, selected: "selected" }; primarySet = true; } CmScripts.CredentialSelect.append($('<option>', appendData)); }); }, CredentialSelect: null, Grid: null, Modal: null, ShowAddModal: function () { CmScripts.ResetModalState(); CmScripts.Modal.modal("show"); CmScripts.SetCommitOnClick("Add"); }, CommitButton: null, ResetModalState: function () { $('#name').val(''); $('#code').val(''); }, Add: function () { CmScripts.Grid.jsGrid("insertItem", CmScripts.GetData()); }, Edit: function () { }, GetData: function () { return { name: $('#name').val(), code: $('#code').val() }; }, SetCommitOnClick: function(eventType) { switch (eventType) { case "Add": CmScripts.CommitButton.attr("onclick", "CmScripts.Add();"); break; case "Edit": CmScripts.CommitButton.attr("onclick", "CmScripts.Edit();"); break; default: CmScripts.CommitButton.attr("onclick", "CmScripts.Add();"); } }, InitializeGrid: function () { CmScripts.Grid.jsGrid({ height: "auto", width: "100%", editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this script?", controller: CmScripts.Controller, fields: [ { name: "name", type: "text", title: "name" }, { name: "id", type: "text", title: "id" }, { name: "details", title: "Action", width: 50, itemTemplate: function (value, item) { var $link = $("<a>").attr("href", '/view/script/' + item.id).text("View"); return $("<div>").append($link); } }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { CmScripts.ShowAddModal(); }); } } ], onItemInserting: function (args) { CmScripts.ResetErrorState(); }, onItemUpdating: function (args) { CmScripts.ResetErrorState(); }, onItemDeleting: function (args) { CmScripts.ResetErrorState(); } }); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/scripts", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { var d = $.Deferred(); $.ajax({ type: "POST", url: "/script", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { CmScripts.HandleError(xhr.responseJSON.message, CmScripts.Table); }); return d.promise(); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/script", data: item }).fail(function (xhr, ajaxOptions, thrownError) { CmScripts.HandleError(xhr.responseJSON.message, CmScripts.Table); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/script", data: item }).fail(function (xhr, ajaxOptions, thrownError) { CmScripts.HandleError(xhr.responseJSON.message, CmScripts.Table); }); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus.responseJSON.message); }, InitializeSelect: function () { CmOptions.ActiveDirectoryMetadataType.forEach(function (item) { $('#eisType').append($('<option>', { value: item.Name, text: item.Name })); }); } } var certSearchResult = null; var Services = { Post: function (uri, data, successCallback, errorCallback) { $.ajax({ url: uri, type: 'post', data: data, cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, Put: function (uri, data, successCallback, errorCallback) { $.ajax({ url: uri, type: 'put', data: data, cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, Get: function (uri, successCallback, errorCallback) { $.ajax({ url: uri, type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback('Error while retrieving data'); } }); }, Delete: function (uri, successCallback, errorCallback) { $.ajax({ url: uri, type: 'delete', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data); }, error: function (x, t, m) { errorCallback('Error while retrieving data'); } }); }, GetNode: function (id, successCallback, errorCallback) { $.ajax({ url: "/node/" + id, type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SaveSettings: function (requestData, successCallback, errorCallback) { $.ajax({ url: "/general-config/settings", type: 'put', data: requestData, cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, GetActiveDirectoryIdentityProviders: function (successCallback, errorCallback) { $.ajax({ url: "/cm-config/external-identity-sources", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, GetSettings: function (successCallback, errorCallback) { $.ajax({ url: "/app-config", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SetAuditConfig: function (requestData, successCallback, errorCallback) { $.ajax({ url: "/general-config/audit-config", type: 'put', data: requestData, cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, CreateCertificate: function (request, successCallback, errorCallback) { $.ajax({ url: "/ca/private/certificate/request/includeprivatekey", type: 'post', data: { SubjectCommonName: request.SubjectCommonName, SubjectDepartment: request.SubjectDepartment, SubjectOrganization: request.SubjectOrganization, SubjectCity: request.SubjectCity, SubjectState: request.SubjectState, SubjectCountry: request.SubjectCountry, SubjectAlternativeNamesRaw: request.SubjectAlternativeNamesRaw, CipherAlgorithm: request.CipherAlgorithm, Provider: request.Provider, HashAlgorithm: request.HashAlgorithm, KeySize: request.KeySize, KeyUsage: request.KeyUsage }, cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, ResetCertificatePassword: function (id, successCallback, errorCallback) { $.ajax({ url: "/certificate/" + id + "/password", type: 'put', cache: false, async: true, success: function (data) { successCallback(); }, error: function (x, t, m) { errorCallback(); } }); }, GetCertificatePassword: function (id, successCallback, errorCallback) { $.ajax({ url: "/certificate/" + id + "/password", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, IssuePendingCertificate: function (id, successCallback, errorCallback) { $.ajax({ url: "/ca/private/certificate/request/issue-pending/" + id, type: 'post', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, GetCertificateDetails: function (id, successCallback, errorCallback) { $.ajax({ url: "/certificate/" + id, type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SearchCertificates: function (query, successCallback, errorCallback) { $.ajax({ url: "/certificates/search", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { certSearchResult = data; //successCallback(data); }, error: function (x, t, m) { //errorCallback(x, t, m); } }); }, GetAdcsTemplates: function (successCallback, errorCallback) { $.ajax({ url: "/pki-config/templates", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data); }, error: function (x, t, m) { } }); }, GetPendingCertificates: function (successCallback, errorCallback) { $.ajax({ url: "/certificate/request/pending", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data.payload); }, error: function (x, t, m) { } }); }, GetEnumMapping: async function () { const response = await axios.get("/view/enum-mapping"); localStorage.setItem("uiEnumMap", JSON.stringify(response.data)); }, GetSecurityRoleDetails: function (id, successCallback, errorCallback) { $.ajax({ url: "/security/role/" + id, type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, ImportUsersFromActiveDirectoryMetadata: function (data, successCallback, errorCallback) { $.ajax({ url: "/security/authenticable-principal/import", type: 'post', cache: false, async: true, dataType: "json", data: data, success: function (data) { successCallback(data); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, GetAppConfig: function (successCallback, errorCallback) { $.ajax({ url: "/config", type: 'get', cache: false, async: true, dataType: "json", success: function (data) { successCallback(data); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SetAppConfig: function (data, successCallback, errorCallback) { $.ajax({ url: "/config", type: 'put', cache: false, async: true, data: data, dataType: "json", success: function (data) { successCallback(); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, ResetUserPassword: function (data, successCallback, errorCallback) { $.ajax({ url: "/security/authenticable-principal/password", type: 'put', cache: false, async: true, data: data, dataType: "json", success: function (response) { successCallback("Successfully reset password"); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SetLocalAppConfig: function (data, successCallback, errorCallback) { $.ajax({ url: "/config/local", type: 'put', cache: false, async: true, data: data, dataType: "json", success: function (data) { successCallback(); }, error: function (x, t, m) { errorCallback(x, t, m); } }); }, SetRoleScopes: function (roleId, scopes, successCallback, errorCallback) { UiGlobal.ResetAlertState(); $.ajax({ url: "/security/role/" + roleId + "/scopes", type: 'put', cache: false, async: true, data: JSON.stringify( { scopes: scopes } ), dataType: "json", contentType: "application/json", success: function (data) { successCallback(); }, error: function (x, t, m) { errorCallback(x.responseJSON.message); //errorCallback(x, t, m); } }); } } var ActiveDirectoryMetadatas = { ShowAuthApiActionModal: function (dialogType, client) { if (dialogType === "Add") { $('#commitAuthApiEntity').click(function () { ActiveDirectoryMetadatas.AddAuthApiCertificate(client); }); } else { } $("#authApiActionModal").modal("show"); }, ShowAddActiveDirectoryMetadataModal: function (dialogType, client) { $('#commitAuthApiEntity').click(function () { ActiveDirectoryMetadatas.AddEis(client, "Add"); }); $("#addActiveDirectoryMetadataModal").modal("show"); }, AddEis: function (client, isNew) { $.extend(client, { name: $("#eisName").val(), domain: $("#eisDomain").val(), username: $("#eisUsername").val(), password: $("#eisPassword").val(), enabled: $("#eisEnabled").val(), searchBase: $("#eisSearchBase").val(), }); $("#ActiveDirectoryMetadatasTable").jsGrid(isNew ? "insertItem" : "updateItem", client); $("#addActiveDirectoryMetadataModal").modal("hide"); }, AddAuthApiCertificate: function (client) { $.extend(client, { id: $("#thumbprint").val(), primary: $("#primary").is(":checked") }); $("#authApiSigningCertificatesTable").jsGrid("insertItem", client); $("#authApiActionModal").modal("hide"); }, InitializeAuthApiGrid: function () { $('#authApiSigningCertificatesTable').jsGrid({ height: "auto", width: "100%", //filtering: true, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this external identity source?", controller: ActiveDirectoryMetadatas.AuthApiController, fields: [ { name: "displayName", type: "text", title: "DisplayName" }, { name: "thumbprint", type: "text", title: "Thumbprint" }, { name: "hasPrivateKey", type: "checkbox", title: "HasPrivateKey", sorting: false }, { name: "primary", type: "checkbox", title: "Primary", sorting: false }, { type: "control", editButton: false, headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { ActiveDirectoryMetadatas.ShowAuthApiActionModal("Add", {}); }); } } ] }); }, InitializeGrid: function () { $("#ActiveDirectoryMetadatasTable").jsGrid({ height: "auto", width: "100%", //filtering: true, editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this external identity source?", controller: ActiveDirectoryMetadatas.Controller, fields: [ { name: "name", type: "text", title: "Name" }, { name: "domain", type: "text", title: "Domain" }, { name: "searchBase", type: "text", title: "SearchBase" }, { name: "activeDirectoryMetadataType", type: "select", items: CmOptions.ActiveDirectoryMetadataType, valueType: "string", valueField: "Name", textField: "Name", title: "Type" }, { name: "username", type: "text", title: "Username" }, { name: "password", type: "text", readOnly: true, title: "password" }, { name: "enabled", type: "checkbox", title: "Enabled", sorting: false }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { ActiveDirectoryMetadatas.ShowAddActiveDirectoryMetadataModal("Add", {}); }); } } ] }); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/cm-config/external-identity-sources", dataType: "json" }).done(function (response) { d.resolve(response); }); return d.promise(); }, insertItem: function (item) { $.ajax({ type: "POST", url: "/cm-config/external-identity-source", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#ActiveDirectoryMetadatasTable")); }); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/cm-config/external-identity-source", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#ActiveDirectoryMetadatasTable")); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/cm-config/external-identity-source", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#ActiveDirectoryMetadatasTable")); }); }, onItemInserting: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); }, onItemUpdating: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); }, onItemDeleting: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); } }, AuthApiController: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/identity-sources/local-authapi/trustedcertificates", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { $.ajax({ type: "POST", url: "/identity-sources/local-authapi/trustedcertificate", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#authApiSigningCertificatesTable")); }); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/identity-sources/local-authapi/trustedcertificate", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#authApiSigningCertificatesTable")); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/identity-sources/local-authapi/trustedcertificate", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ActiveDirectoryMetadatas.HandleError(xhr.responseJSON.message, $("#authApiSigningCertificatesTable")); }); }, onItemInserting: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); }, onItemUpdating: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); }, onItemDeleting: function (args) { ActiveDirectoryMetadatas.ResetErrorState(); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus.responseJSON.message); }, InitializeSelect: function () { CmOptions.ActiveDirectoryMetadataType.forEach(function (item) { $('#eisType').append($('<option>', { value: item.Name, text: item.Name })); }); }, CertificateSelect2: null, InitializeCertificateSelect2: function () { ActiveDirectoryMetadatas.CertificateSelect2.select2({ width: '100%', placeholder: 'Search for a certificate', ajax: { url: ("/certificates/search/summary"), dataType: 'json', type: 'get', delay: 30, //data: function (params) { // return { // query: params.term // }; //}, processResults: function (data, params) { //params.page = params.page || 1; return { results: data.payload, }; }, cache: false }, escapeMarkup: function (markup) { return markup; }, templateResult: ActiveDirectoryMetadatas.FormatCertificate, templateSelection: ActiveDirectoryMetadatas.FormatCertificateSelection, }); }, FormatCertificate: function (repo) { var markup = '<div class="user-select-container">' markup = markup + '<div class="cert-select-title"><b>' + repo.displayName + '</b></div>'; markup = markup + '<div class="cert-select-details">Thumbprint: <span class="cert-select-details-value">' + repo.thumbprint + '</span></div>'; markup = markup + '<div class="cert-select-details">Expires: <span class="cert-select-details-value">' + UiGlobal.GetDateString(repo.expiry) + '</span></div>'; //markup = markup + '<div class="user-select-details">Domain: <span class="user-select-details-value">' + repo.domain + '</span></div>'; markup = markup + '</div>'; //var markup = repo.text; return markup; }, FormatCertificateSelection: function (repo) { return repo.thumbprint; }, GetAppConfigSuccessCallback: function (data) { $('#jwtValidityPeriod').val(data.payload.jwtValidityPeriod); $('#localIdpIdentifier').val(data.payload.localIdpIdentifier); $('#allowWindowsAuth').prop('checked', data.payload.windowsAuthEnabled); $('#allowLocalAuthentication').prop('checked', data.payload.localLogonEnabled); $('#allowEmergencyAccess').prop('checked', data.payload.emergencyAccessEnabled); }, SaveAppConfigSuccessCallback: function () { UiGlobal.ShowSuccess("Successfully saved app configuration"); }, PageLoad: function () { ActiveDirectoryMetadatas.InitializeSelect(); ActiveDirectoryMetadatas.InitializeGrid(); ActiveDirectoryMetadatas.CertificateSelect2 = $('#thumbprint'); ActiveDirectoryMetadatas.InitializeCertificateSelect2(); ActiveDirectoryMetadatas.InitializeAuthApiGrid(); Services.GetAppConfig(ActiveDirectoryMetadatas.GetAppConfigSuccessCallback, null); UiGlobal.ShowCurrentTab(); }, SetAppConfig: function() { UiGlobal.ResetAlertState(); var data = { jwtValidityPeriod: $('#jwtValidityPeriod').val(), localIdpIdentifier: $('#localIdpIdentifier').val() } Services.SetAppConfig(data, ActiveDirectoryMetadatas.SaveAppConfigSuccessCallback, null); }, SetLocalAppConfig: function () { UiGlobal.ResetAlertState(); var data = { localLogonEnabled: $('#allowLocalAuthentication').prop('checked'), emergencyAccessEnabled: $('#allowEmergencyAccess').prop('checked'), windowsAuthEnabled: $('#allowWindowsAuth').prop('checked') } Services.SetLocalAppConfig(data, ActiveDirectoryMetadatas.SaveAppConfigSuccessCallback, null); } } var GeneralConfig = { SecurityAuditingRadio: null, OperationsLoggingRadio: null, ClearAuditConfigCurrentState: function () { $('input:radio[name="securityAuditingState"]').removeAttr('checked'); $('input:radio[name="operationsLoggingState"]').removeAttr('checked'); }, GetAuditConfigCurrentState: function () { return { securityAuditingState: $('input:radio[name="securityAuditingState"]:checked').val(), operationsLoggingState: $('input:radio[name="operationsLoggingState"]:checked').val() } }, GetSettingsCurrentState: function () { return { cachePeriod: $('#cachePeriod').val() }; }, GetSettings: function () { GeneralConfig.ClearAuditConfigCurrentState(); Services.GetSettings(GeneralConfig.GetSettingsSuccessCallback, GeneralConfig.ErrorCallback) }, SaveSettings: function () { UiGlobal.ResetAlertState(); var data = GeneralConfig.GetSettingsCurrentState(); Services.SaveSettings(data, GeneralConfig.SaveSettingsSuccessCallback, GeneralConfig.ErrorCallback); }, SaveAuditConfig: function () { UiGlobal.ResetAlertState(); var data = GeneralConfig.GetAuditConfigCurrentState(); Services.SetAuditConfig(data, GeneralConfig.SaveAuditConfigSuccessCallback, GeneralConfig.ErrorCallback); }, SaveSettingsSuccessCallback: function () { UiGlobal.ShowSuccess("Settings were saved successfully"); }, ErrorCallback: function (x) { UiGlobal.ShowError(x.message); }, GetSettingsSuccessCallback: function (data) { $("input[name=operationsLoggingState][value=" + data.operationsLoggingState + "]").attr('checked', 'checked'); $("input[name=securityAuditingState][value=" + data.securityAuditingState + "]").attr('checked', 'checked'); $('#cachePeriod').val(data.cachePeriod); }, SaveAuditConfigSuccessCallback: function () { UiGlobal.ShowSuccess("Auditing configuration was saved successfully"); }, PageLoad: function () { //GeneralConfig.SecurityAuditingRadio = $('input[name=securityAuditingRadio]:checked'); //GeneralConfig.OperationsLoggingRadio = $('input[name=operationsLoggingRadio]:checked'); GeneralConfig.GetSettings(); UiGlobal.ShowCurrentTab(); } } var Login = { PageLoad: function () { Login.ShowErrorIfUnsuccessful(); Login.InitializeAlternativeLoginOptions(); Login.ConfigureAuthBypass(); Login.InitializeDomainSelect(); }, ShowErrorIfUnsuccessful: function () { if (Login.IsAuthFailure()) { UiGlobal.ShowError(); } }, ConfigureAuthBypass: function () { //controlled by form post }, InitializeAlternativeLoginOptions: function () { $('#altLoginMethodCheckbox').change(function () { if ($(this).is(":checked")) { $('.alt-login-btn').show(); } else { $('.alt-login-btn').hide(); } }); }, InitializeDomainSelect: function () { CmOptions.ActiveDirectoryMetadatas.forEach(function (item) { if (item.enabled) { var element = $('#domain'); element.append($('<option>', { value: item.id, text: item.name })); } }); if (CmOptions.LocalAuthenticationEnabled) { var element = $('#domain'); element.append($('<option>', { value: CmOptions.LocalIdentityProviderId, text: 'Local' })); } }, IsAuthFailure: function () { if (document.URL.indexOf("authentication_failure") > -1) { return true; } else { return false; } } } var Logs = { Grid: null, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/logs", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); } }, ShowDetailsModal: function (data) { $('#eventTime').val(data.time); $('#eventResult').val(data.eventResult); $('#eventCategory').val(data.eventCategory); $('#contextUserId').val(data.userId); $('#contextUser').val(data.userDisplay); $('#targetId').val(data.target); $('#message').text(data.message); UiGlobal.ShowModal('LogDetailsModal'); }, InitializeGrid: function () { Logs.Grid.jsGrid({ height: "auto", width: "100%", rowClick: function (args) { Logs.ShowDetailsModal(args.item); }, rowClass: function (item, itemIndex) { return UiGlobal.GetRowClass(item, itemIndex); }, editing: false, sorting: true, paging: true, autoload: true, pageSize: 30, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this log?", controller: Logs.Controller, fields: [ { name: "target", type: "text", title: "Target" }, //{ name: "targetDescription", type: "text", title: "Description" }, { name: "userDisplay", type: "text", title: "UserDisplay" }, { name: "userId", type: "text", title: "UserId" }, { name: "eventResult", type: "text", title: "EventResult" }, { name: "eventCategory", type: "text", title: "EventCategory" }, { name: "time", type: "text", title: "Time" } ] }); }, PageLoad: function () { Logs.Grid = $('#logsTable'); Logs.InitializeGrid(); }, Clear: function () { Services.Delete('/logs', Logs.ClearLogsCallbackSuccess, null); }, ClearLogsCallbackSuccess: function (data) { location.reload(); } } var NodeDetails = { Id: null, CredentialId: null, Credential: null, Hostname: null, Node: null, ManagedCertificatesTable: null, PageLoad: function () { UiGlobal.ShowCurrentTab(); NodeDetails.Id = $('#id'); NodeDetails.Credential = $('#credential'); NodeDetails.CredentialId = $('#credentialId'); NodeDetails.Hostname = $('#hostname'); NodeDetails.ManagedCertificatesTable = $('#managedCertificatesTable'); NodeDetails.GetNode(NodeDetails.Id.val()); }, ShowSelectedTable: function () { }, GetNode: function (id) { Services.GetNode(id, NodeDetails.GetNodeSuccessCallback, null); }, RenewManagedCertificateSucessCallback: function () { UiGlobal.ShowSuccess("Certificate renewal job has started. Check the logs for result."); }, RenewManagedCertificateErrorCallback: function () { UiGlobal.ShowError("Certificate renewal failed. Check the logs for more details."); }, RenewManagedCertificate: function (id) { var uri = "/node/" + NodeDetails.Node.id + "/renew/" + id; Services.Post(uri, null, NodeDetails.RenewManagedCertificateSucessCallback, NodeDetails.RenewManagedCertificateErrorCallback) }, InitManagedCertificatesTable: function () { NodeDetails.ManagedCertificatesTable.bootstrapTable({ data: NodeDetails.Node.managedCertificates, columns: [{ align: 'left' }, { align: 'left'}, { field: 'operate', title: 'Action', align: 'left', valign: 'middle', clickToSelect: false, formatter: function (value, row, index) { return '<button class="btn btn-primary btn-sm" onclick="NodeDetails.RenewManagedCertificate(' + " '" + row.id + "' " + ')" >Renew</button> '; } }] }); }, GetNodeSuccessCallback: function (data) { NodeDetails.Node = data; NodeDetails.CredentialId.val(data.credentialId); NodeDetails.Hostname.val(data.hostname); NodeDetails.Credential.val(data.credentialDisplayName); NodeDetails.InitManagedCertificatesTable(); }, InvokeCertificateDiscovery: function () { UiGlobal.ResetAlertState(); Services.Post("/node/" + NodeDetails.Id.val() + "/discovery/iis", null, NodeDetails.InvokeCertificateDiscoverySuccessCallback, NodeDetails.InvokeCertificateDiscoveryErrorCallback); }, InvokeCertificateDiscoverySuccessCallback: function () { UiGlobal.ShowSuccess("Certificate discovery has started for this node. Reviews logs for results."); }, InvokeCertificateDiscoveryErrorCallback: function () { UiGlobal.ShowError("Failed to start certificate discovery"); }, ResetManagedCertificatesState: function () { var uri = "/node/" + NodeDetails.Id.val() + "/managedcertificates"; Services.Delete(uri, NodeDetails.ResetManagedCertificatesStateSuccessCallback, NodeDetails.ResetManagedCertificatesStateErrorCallback) }, ResetManagedCertificatesStateSuccessCallback: function () { UiGlobal.ShowSuccess("Successfully reset the state of all managed certificates for this node."); }, ResetManagedCertificatesStateErrorCallback: function () { UiGlobal.ShowError("Failed to reset state of managed certificates"); } } var OidcIdentityProvider = { PageLoad: function () { OidcIdentityProvider.InitGrid(); OidcIdentityProvider.OidcIdpModal = $('#oidcIdpModal'); OidcIdentityProvider.CommitOidcIdpButton = $('#commitOidcIdpButton'); }, InitModal: function () { OidcIdentityProvider.CommitOidcIdpButton('#commitOidcIdpButton'); }, InitGrid: function () { OidcIdentityProvider.Grid = $("#openIdConfigTable"); $("#openIdConfigTable").jsGrid({ height: "auto", width: "100%", editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this identity provider?", controller: OidcIdentityProvider.Controller, fields: [ { name: "name", type: "text", title: "Name" }, { name: "authority", type: "text", title: "Authority" }, { name: "clientId", type: "text", title: "ClientId" }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { OidcIdentityProvider.ShowAddOidcIdpModal(); }); } } ] }); }, GetOidcIdpData: function () { return { name: $('#oidcIdpName').val(), clientId: $('#oidcIdpClientId').val(), authority: $('#oidcIdpAuthority').val() }; }, AddOidcIdp: function () { OidcIdentityProvider.Grid.jsGrid("insertItem", OidcIdentityProvider.GetOidcIdpData()); }, ShowAddOidcIdpModal: function () { OidcIdentityProvider.ResetAddOidcModalState(); OidcIdentityProvider.OidcIdpModal.modal("show"); OidcIdentityProvider.SetCommitOnClick("Add"); }, SetCommitOnClick(eventType) { switch (eventType) { case "Add": OidcIdentityProvider.CommitOidcIdpButton.attr("onclick", "OidcIdentityProvider.AddOidcIdp();"); break; case "Edit": OidcIdentityProvider.CommitOidcIdpButton.attr("onclick", "OidcIdentityProvider.EditOidcIdp();"); break; default: OidcIdentityProvider.CommitOidcIdpButton.attr("onclick", "OidcIdentityProvider.AddOidcIdp();"); } }, ResetAddOidcModalState: function () { $('#oidcIdpName').val(''); $('#oidcIdpAuthority').val(''); $('#oidcIdpClientId').val(''); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/cm-config/oidc-idp", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { $.ajax({ type: "POST", url: "/cm-config/oidc-idp", data: item }).fail(function (xhr, ajaxOptions, thrownError) { OidcIdentityProvider.HandleError(xhr.responseJSON.message); }); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/cm-config/oidc-idp", data: item }).fail(function (xhr, ajaxOptions, thrownError) { OidcIdentityProvider.HandleError(xhr.responseJSON.message); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/cm-config/oidc-idp", data: item }).fail(function (xhr, ajaxOptions, thrownError) { OidcIdentityProvider.HandleError(xhr.responseJSON.message); }); }, onItemInserting: function (args) { OidcIdentityProvider.ResetErrorState(); }, onItemUpdating: function (args) { OidcIdentityProvider.ResetErrorState(); }, onItemDeleting: function (args) { OidcIdentityProvider.ResetErrorState(); } }, HandleError: function (msg) { OidcIdentityProvider.Grid.jsGrid("render"); UiGlobal.ShowError(msg); }, ResetErrorState: function () { UiGlobal.HideError(); }, OidcIdpModal: null, CommitOidcIdpButton: null, Grid: null } var PendingCertificates = { PageLoad: function () { PendingCertificates.Grid = $('#allPendingCertificates'); PendingCertificates.InitializeGrid(); }, Grid: null, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/certificate/request/pending", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/certificate/request/pending/" + item.id //data: item }).fail(function (xhr, ajaxOptions, thrownError) { ViewAllCertificates.HandleError(xhr.responseJSON.message, ViewAllCertificates.Grid); }); } }, InitializeGrid: function () { PendingCertificates.Grid.jsGrid({ height: "auto", width: "100%", //filtering: true, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you want to deny this certificate request?", controller: PendingCertificates.Controller, fields: [ { title: "CommonName", name: "subjectCommonName", type: "text" }, { title: "RequestDate", name: "requestDate", type: "text" }, { title: "Cipher", name: "cipherAlgorithm", type: "text" }, { title: "Hash", name: "hashAlgorithm", type: "text" }, { title: "RequestType", name: "pendingCertificateRequestType", type: "text" }, { title: "KeyUsage", name: "keyUsage", type: "text" }, { title: "Action", width: 15, itemTemplate: function (value, item) { var btn = $("<i>"); btn.addClass("fa fa-check"); btn.attr('req-id', item.id); btn.on('click', function (event) { UiGlobal.ShowWarning("Please wait, the certificate request is processing"); var id = event.target.attributes["req-id"].value; Services.IssuePendingCertificate(id, PendingCertificates.IssueCertificateSuccessCallback, PendingCertificates.IssueCertificateErrorCallback); return false; }); return btn; } }, { type: "control", editButton: false, width: 10 } ] //onItemInserting: function (args) { SecurityRoles.ResetErrorState(); }, //onItemUpdating: function (args) { SecurityRoles.ResetErrorState(); }, //onItemDeleting: function (args) { SecurityRoles.ResetErrorState(); } }); }, IssueCertificateSuccessCallback: function (data) { UiGlobal.HideWarning(); window.location.replace("/view/certificate/" + data.id); }, IssueCertificateErrorCallback: function (x, t, m) { UiGlobal.HideWarning(); UiGlobal.ShowError("Could not issue the pending certificate."); } } var debugData = ""; var PkiConfig = { ResolveIdpName: function (value, item) { var idpDisplayName = ""; CmOptions.ActiveDirectoryMetadatas.forEach(function (idp) { if (idp.id == item.identityProviderId) { idpDisplayName = idp.name } }); if (idpDisplayName === "") { idpDisplayName = "none"; } return idpDisplayName; }, InitializeSelect: function () { CmOptions.hashAlgorithmOptions.forEach(function (item) { var caHash = $('#caHash'); var element = $('#adcsTemplateHash'); element.append($('<option>', { value: item.Name, text: item.Name })); caHash.append($('<option>', { value: item.Name, text: item.Name })); if (item.Primary === true) { caHash.val(item.Name); element.val(item.Name); } }); CmOptions.cipherOptions.forEach(function (item) { $('#adcsTemplateCipher').append($('<option>', { value: item.Name, text: item.Name, })); }); CmOptions.keyUsageOptions.forEach(function (item) { $('#adcsTemplateKeyUsage').append($('<option>', { value: item.Name, text: item.Name })); }); CmOptions.windowsApiOptions.forEach(function (item) { $('#adcsTemplateWindowsApi').append($('<option>', { value: item.Name, text: item.Name })); }); }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus); }, GetUpdatedTemplateData: function () { var allowedToIssueList = ""; $('#adcsTemplateAllowedToIssue').val().forEach(function (item) { if (allowedToIssueList === "") { allowedToIssueList = item; } else { allowedToIssueList = allowedToIssueList + ';' + item; } }); return { id: $('#selected-template-id').val(), name: $('#adcsTemplateName').val(), cipher: $("#adcsTemplateCipher").val(), keyUsage: $("#adcsTemplateKeyUsage").val(), windowsApi: $("#adcsTemplateWindowsApi").val(), rolesAllowedToIssue: allowedToIssueList } }, EditTemplate: function () { var data = PkiConfig.GetUpdatedTemplateData(); $("#adcsTemplatesTable").jsGrid("updateItem", data); }, LoadEditTemplateModalData: function (data) { var roleIds = new Array(); for (var key in data.rolesAllowedToIssueSelectView) { roleIds.push(data.rolesAllowedToIssueSelectView[key].id); } $('#selected-template-id').val(data.id); $("#adcsTemplateName").val(data.name); $("#adcsTemplateCipher").val(data.cipher); $("#adcsTemplateKeyUsage").val(data.keyUsage); $("#adcsTemplateWindowsApi").val(data.windowsApi); var roleSelect = document.getElementById('adcsTemplateAllowedToIssue'); for (i = 0; i < roleSelect.children.length; i++) { var option = roleSelect.children[i]; if (roleIds.includes(option.value)) { option.selected = true; } else { option.selected = false; } } }, AddTemplate: function () { var data = PkiConfig.GetUpdatedTemplateData(); $("#adcsTemplatesTable").jsGrid("insertItem", data); }, ShowAddTemplateModal: function () { PkiConfig.ResetErrorState(); PkiConfig.SetCommitOnClick("Add"); PkiConfig.InitializeSelect2(); UiGlobal.ShowModal("addAdcsTemplateModal"); }, ShowEditTemplateModal: function (data) { PkiConfig.ResetErrorState(); PkiConfig.LoadEditTemplateModalData(data); PkiConfig.InitializeSelect2(); PkiConfig.SetCommitOnClick("Edit"); UiGlobal.ShowModal("addAdcsTemplateModal"); }, ShowAddPrivateCaModal: function (client) { PkiConfig.InitializePrivateCaIdentityProviderSelect2(); $('#commitPrivateCaButton').click(function () { PkiConfig.AddPrivateCa(client); }); $("#privateCaActionModal").modal("show"); }, ShowEditPrivateCaModal: function (client) { debugData = client; $('#privateCaId').val(client.id); $('#caServerName').val(client.serverName); $('#caCommonName').val(client.commonName); $('#caHash').val(client.hashAlgorithm); PkiConfig.InitializePrivateCaIdentityProviderSelect2(); $('#commitPrivateCaButton').click(function () { PkiConfig.ChangePrivateCa(client); }); $("#privateCaActionModal").modal("show"); }, AddPrivateCa: function (client, isNew) { $.extend(client, { serverName: $("#caServerName").val(), commonName: $("#caCommonName").val(), hashAlgorithm: $("#caHash").val(), authenticationRealm: $("#caAuthenticationRealm").val(), authenticationType: $("#caAuthenticationType").val(), username: $("#caUsername").val(), password: $("#caPassword").val() }); $("#privateCaTable").jsGrid("insertItem", client); $("#privateCaActionModal").modal("hide"); }, ChangePrivateCa: function (client) { $.extend(client, { id: $('#privateCaId').val(), serverName: $("#caServerName").val(), commonName: $("#caCommonName").val(), hashAlgorithm: $("#caHash").val(), identityProviderId: $('#caIdentityProvider').val() }); $("#privateCaTable").jsGrid("updateItem", client); $("#privateCaActionModal").modal("hide"); }, PrivateCertificateAuthoritiesController: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/pki-config/certificate-authorities/private", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { $.ajax({ type: "POST", url: "/pki-config/certificate-authority/private", data: item }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#privateCaTable")); }); }, updateItem: function (item) { var d = $.Deferred(); $.ajax({ type: "PUT", url: "/pki-config/certificate-authority/private", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#privateCaTable")); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/pki-config/certificate-authority/private", data: item }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#privateCaTable")); }); } }, AdcsTemplateController: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/pki-config/templates", //data: filter, dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { var d = $.Deferred(); $.ajax({ type: "POST", url: "/pki-config/template", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#adcsTemplatesTable")); }); return d.promise(); //$.ajax({ // type: "POST", // url: "/pki-config/template", // data: item //}).fail(function (xhr, ajaxOptions, thrownError) { // PkiConfig.HandleError(xhr.responseJSON.message, $("#adcsTemplatesTable")); //}); }, updateItem: function (item) { var d = $.Deferred(); $.ajax({ type: "PUT", url: "/pki-config/template", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#adcsTemplatesTable")); }); return d.promise(); //var d = $.Deferred(); //$.ajax({ // type: "PUT", // url: "/pki-config/template", // data: item //}).fail(function (xhr, ajaxOptions, thrownError) { // PkiConfig.HandleError(xhr.responseJSON.message, $("#adcsTemplatesTable")); //}); //return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/pki-config/template", data: item }).fail(function (xhr, ajaxOptions, thrownError) { PkiConfig.HandleError(xhr.responseJSON.message, $("#adcsTemplatesTable")); }); } }, InitializePkiConfigGrids: function () { PkiConfig.TemplateGrid = $("#adcsTemplatesTable"); PkiConfig.TemplateGrid.jsGrid({ height: "auto", width: "100%", //filtering: true, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this template?", controller: PkiConfig.AdcsTemplateController, rowClick: function (args) { PkiConfig.ShowEditTemplateModal(args.item); }, fields: [ { title: "Template Name", name: "name", type: "text", validate: { validator: "rangeLength", param: [1, 100] }, width: 80 }, //{ title: "Server Name", name: "hash", type: "select", items: CmOptions.hashAlgorithmOptions, valueType: "string", valueField: "Name", textField: "Name", width: 30 }, { title: "Cipher", name: "cipher", type: "select", items: CmOptions.cipherOptions, valueField: "Name", textField: "Name", width: 30 }, { title: "Key Usage", name: "keyUsage", type: "select", items: CmOptions.keyUsageOptions, valueField: "Name", textField: "Name" }, { title: "WindowsApi", name: "windowsApi", type: "select", items: CmOptions.windowsApiOptions, valueField: "Name", textField: "Name", width: 40 }, { title: "Roles Allowed To Issue This Template", name: "rolesAllowedToIssue", itemTemplate: function (value, item) { var roleSelect = $("<select style='width:100%' class='security-roles-adcs-select2' multiple='multiple'>"); item.rolesAllowedToIssueSelectView.forEach(function (option) { roleSelect.append($('<option>', { value: option.id, text: option.name }).attr('selected', true)); }); roleSelect = roleSelect.attr('disabled', true); return roleSelect; //return $("<div>").append(roleSelect); } }, { width:25, editButton: false, type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { PkiConfig.ShowAddTemplateModal(); }); } } ], onItemInserted: function (args) { PkiConfig.TemplateGrid.jsGrid("render"); }, onRefreshed: function (args) { PkiConfig.InitializeSelect2(); }, onItemUpdated: function (args) { PkiConfig.TemplateGrid.jsGrid("render"); PkiConfig.InitializeSelect2(); }, onItemEditing: function (args) { PkiConfig.InitializeSelect2(); }, onItemInserting: function (args) { PkiConfig.ResetErrorState(); }, onItemUpdating: function (args) { PkiConfig.ResetErrorState(); PkiConfig.InitializeSelect2(); }, onItemDeleting: function (args) { PkiConfig.ResetErrorState(); }, onDataLoading: function (args) { PkiConfig.InitializeSelect2();}, onDataLoaded: function (args) { PkiConfig.InitializeSelect2();} }); $("#privateCaTable").jsGrid({ height: "auto", width: "100%", //filtering: true, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this certificate authority?", controller: PkiConfig.PrivateCertificateAuthoritiesController, rowClick: function (args) { PkiConfig.ShowEditPrivateCaModal(args.item); }, fields: [ { title: "Server Name", name: "serverName", type: "text" }, { title: "Common Name", name: "commonName", type: "text" }, { title: "Hash", name: "hashAlgorithm", type: "select", items: CmOptions.hashAlgorithmOptions, valueType: "string", valueField: "Name", textField: "Name" }, { title: "Identity Provider", name: "identityProviderId", itemTemplate: function (value, item) { return PkiConfig.ResolveIdpName(value, item); } }, { type: "control", editButton: false, headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { PkiConfig.ShowAddPrivateCaModal({}); }); } } ], onItemInserting: function (args) { PkiConfig.ResetErrorState(); }, onItemUpdating: function (args) { PkiConfig.ResetErrorState(); }, onItemDeleting: function (args) { PkiConfig.ResetErrorState(); } }); var editableAllowedToIssue = $('.security-roles-adcs-select2-editable'); CmOptions.SecurityRoles.forEach(function (option) { editableAllowedToIssue.append($('<option>', { //value: item.Name, //text: item.Name, value: option.Id, text: option.Name })) }); }, InitializePrivateCaIdentityProviderSelect2: function () { $('#caIdentityProvider').select2({ data: CmOptions.ActiveDirectoryMetadatas, width: '100%' }); }, InitializeSelect2: function () { $('.security-roles-adcs-select2').select2({ width: '100%' }); }, SetCommitOnClick(eventType) { switch (eventType) { case "Add": PkiConfig.CommitTemplateButton.attr("onclick", "PkiConfig.AddTemplate();"); break; case "Edit": PkiConfig.CommitTemplateButton.attr("onclick", "PkiConfig.EditTemplate();"); break; default: PkiConfig.CommitTemplateButton.attr("onclick", "PkiConfig.AddTemplate();"); } }, CommitTemplateButton: null, TemplateGrid: null, PageLoad: function () { PkiConfig.CommitTemplateButton = $('#addAdcsTemplateButton'); PkiConfig.InitializeSelect(); UiGlobal.ShowCurrentTab(); PkiConfig.InitializePkiConfigGrids(); } } function WriteError(msg) { $('#error-alert').text(msg); $('#error-alert').show(); } function DisplayCertificateDetails(data) { $("#displayName").text(data.displayName); $('#hashAlgorithm').text(data.hashAlgorithm); $('#thumbprint').text(data.thumbprint); $('#certificate-id').text(data.id); $('#cipherAlgorithm').text(data.cipherAlgorithm); $('#hasPrivateKey').text(data.hasPrivateKey); $('#expires').text(data.validTo); $('#keySize').text(data.keySize); $('#storageFormat').text(data.certificateStorageFormat); $('#windowsApi').text(data.windowsApi); } function GetPrivateCertificateRequestData() { var request = { SubjectCommonName: $('#commonName').val(), SubjectDepartment: $('#department').val(), SubjectOrganization: $('#organization').val(), SubjectCity: $('#city').val(), SubjectState: $('#state').val(), SubjectCountry: $('#country').val(), SubjectAlternativeNamesRaw: $('#sancsv').val(), CipherAlgorithm: $('#cipherAlgorithm').val(), Provider: $('#windowsApi').val(), HashAlgorithm: $('#hashAlgorithm').val(), KeySize: $('#keySize').val(), KeyUsage: $('#keyUsage').val() } return request; } function ValidateNewPrivateCertificate(request) { //var spinner = StartSpinner(); var keysize = request.KeySize; var provider = request.Provider; var cipheralg = request.CipherAlgorithm; var validRsaKeySizes = ["2048", "4096", "8192", "16384"] var keyusage = request.KeyUsage; //var role = $('#role').val(); //0 is RSA if (cipheralg == "0") { if (validRsaKeySizes.indexOf(keysize) != 0) { var msg = "Rsa keysize is invalid. Rsa only supports 2048, 4096, 8192, or 16384. Choose 2048 if you are unsure."; WriteError(msg) return false; } } //1 is EC if (cipheralg == "1") { if (provider != "1") { var msg = "Elliptic Curve only supports the provider Cng (CryptoApi Next Generation)"; WriteError(msg); return false; } if (keysize != 256) { var msg = "Elliptic Curve only supports a keysize of 256bits"; WriteError(msg); return false; } } if ($("#SubjectCommonName").val() != "") { var result = Services.ValidateDnsName($("#SubjectCommonName").val()) if (result["Status"] != "valid") { WriteError("Invalid subject common name provided") return false; } } else { WriteError("You must specify a subject common name"); return false; } if ($("#SubjectAlternativeNamesRaw").val() != "") { var result = Services.ValidateDnsSan($("#SubjectAlternativeNamesRaw").val()) if (result["Status"] != "valid") { WriteError("Invalid subject alternative name. Either remove the subject alternative name, or specify the san with correct comma separated format. ") return false; } } if (keyusage == null) { WriteError("Key Usage must be specified. If you're not an Admin, you won't be able to select anything except 'Server'") return false; } if (!keyusage.constructor == Array) { WriteError("Key Usage must be specified. If you're not an Admin, you won't be able to select anything except 'Server'") return false; } if (keyusage.length < 1 || keyusage.length > 3) { WriteError("Key Usage must be specified. If you're not an Admin, you won't be able to select anything except 'Server'") return false; } //if (role != "Admin" && keyusage != 1) { // $(".modal-body").text("Key Usage must be specified. If you're not an Admin, you won't be able to select anything except 'Server'"); // $('#msgModal').modal('show'); // return false; //} return true; //$('#formSubmitButtonHidden').click(); } var PrivateCertificateAuthority = { CreateCertificateSuccessCallback: function (data) { if (data.status == "Success") { window.sessionStorage.setItem("certificateId", data.id); $('#create-private-certificate-btn').prop('disabled', false); window.location.replace("/view/certificate/" + data.id); } else if(data.status == "Pending") { window.location.replace('/view/certificate/request/pending'); } else { //error thing } }, CreateCertificateErrorCallback: function (x, t, m) { WriteError(x.responseJSON.message); $('#create-private-certificate-btn').prop('disabled', false); }, GetCertificateErrorCallback: function (x, t, m) { //WriteError(x.responseJSON.message); //$('#create-private-certificate-btn').prop('disabled', false); }, GetCertificateSuccessCallback: function (data) { DisplayCertificateDetails(data); }, GetCertificateDetails: function () { //var id = window.location.pathname.replace('/views/certificate/', ''); var id = window.sessionStorage.getItem("certificateId"); Services.GetCertificateDetails(id, this.GetCertificateSuccessCallback, this.GetCertificateErrorCallback); }, RegisterCreateCertificateButtonEvent: function () { $('#create-private-certificate-btn').click(function () { $('#error-alert').hide(); $('#success-alert').hide(); $('#create-private-certificate-btn').prop('disabled', true); var request = GetPrivateCertificateRequestData(); //if (!ValidateNewPrivateCertificate(request)) //{ // $('#create-private-certificate-btn').prop('disabled', false); // return false; //} Services.CreateCertificate(request, PrivateCertificateAuthority.CreateCertificateSuccessCallback, PrivateCertificateAuthority.CreateCertificateErrorCallback); }); }, InitializeUi: function () { CmOptions.hashAlgorithmOptions.forEach(function (item) { var element = $('#hashAlgorithm'); element.append($('<option>', { value: item.Name, text: item.Name })); if (item.Primary) { element.val(item.Name); } }); CmOptions.cipherOptions.forEach(function (item) { $('#cipherAlgorithm').append($('<option>', { value: item.Name, text: item.Display })); }); CmOptions.keyUsageOptions.forEach(function (item) { if (item.Primitive) { if (item.Primary) { $('#keyUsage').append($('<option>', { value: item.Name, text: item.Display, selected: "selected" })); } else { $('#keyUsage').append($('<option>', { value: item.Name, text: item.Display })); } } }); $('#keyUsage').select2({ width: '100%' }); CmOptions.windowsApiOptions.forEach(function (item) { $('#windowsApi').append($('<option>', { value: item.Name, text: item.Display })); }); }, PageLoad: function () { PrivateCertificateAuthority.InitializeUi(); PrivateCertificateAuthority.RegisterCreateCertificateButtonEvent(); } }; var ScriptDetails = { Uri: '/script', Id: null, Name: null, Code: null, PageLoad: function () { ScriptDetails.Id = $('#id'); ScriptDetails.Name = $('#name'); ScriptDetails.Code = $('#code'); ScriptDetails.Get(ScriptDetails.Id.val()); }, Get: function (id) { var uri = ScriptDetails.Uri + '/' + ScriptDetails.Id.val(); Services.Get(uri, ScriptDetails.GetSuccessCallback, ScriptDetails.ErrorCallback) }, GetSuccessCallback: function (data) { ScriptDetails.Name.val(data.name); ScriptDetails.Code.val(data.code); }, GetSaveData: function () { data = { id: ScriptDetails.Id.val(), name: ScriptDetails.Name.val(), code: ScriptDetails.Code.val() } return data; }, SaveSuccessCallback: function () { UiGlobal.ResetAlertState(); UiGlobal.ShowSuccess(); }, ErrorCallback: function (msg) { UiGlobal.ResetAlertState(); UiGlobal.ShowError('Error while parsing the script'); }, Save: function () { UiGlobal.ResetAlertState(); Services.Put(ScriptDetails.Uri, ScriptDetails.GetSaveData(), ScriptDetails.SaveSuccessCallback, ScriptDetails.ErrorCallback); } } var debugvar = ""; var SecurityRoleDetails = { GetScopesForRole: function () { var selectedScopes = []; CmOptions.Scopes.forEach(function (item) { var selector = "#" + item.Id + ".scope"; if ($(selector).is(":checked")) { selectedScopes.push(item.Id); } }); return selectedScopes; }, SaveScopes: function () { var selectedScopes = SecurityRoleDetails.GetScopesForRole(); Services.SetRoleScopes(SecurityRoleDetails.Role.id, selectedScopes, UiGlobal.ShowSuccess, UiGlobal.ShowError); }, ShowAddRoleMemberModal: function (dialogType, client) { $('#addSecurityRoleMemberButton').click(function () { SecurityRoleDetails.AddSecurityRoleMember(client, dialogType === "Add"); }); $("#addSecurityRoleMemberModal").modal("show"); }, AddSecurityRoleMember: function (client, isNew) { $.extend(client, { memberId: SecurityRoleDetails.UserAddRoleMemberSelect.val(), roleId: $('#roleId').text() }); $("#roleMembersTable").jsGrid(isNew ? "insertItem" : "updateItem", client); $("#addSecurityRoleMemberModal").modal("hide"); }, RenderScopes: function () { CmOptions.Scopes.forEach(function (item) { var formRow = UiGlobal.GetFormRowDiv(); formRow.append(UiGlobal.GetFormColLabel(item.Name)); if (SecurityRoleDetails.Role.scopes == null) { var checked = false; } else { var checked = SecurityRoleDetails.Role.scopes.indexOf(item.Id) >= 0; } formRow.append(UiGlobal.GetFormCheckbox(item.Id, checked)); SecurityRoleDetails.ScopesTab.append(formRow); }); SecurityRoleDetails.ScopesTab.append(UiGlobal.GetButton('SecurityRoleDetails.SaveScopes()')); }, RenderViewData: function (data) { SecurityRoleDetails.Role = data.payload; $('#roleName').text(data.payload.name); SecurityRoleDetails.RenderScopes(); }, InitializeGrid: function () { $("#roleMembersTable").jsGrid({ height: "auto", width: "100%", sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this external identity source?", controller: SecurityRoleDetails.MembersController, fields: [ { name: "name", type: "text", title: "Name", editing: false }, { name: "enabled", type: "checkbox", title: "Enabled", sorting: false, editing: false }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { SecurityRoleDetails.ShowAddRoleMemberModal("Add", {}); }); } } ], onItemInserting: function (args) { SecurityRoleDetails.ResetErrorState(); }, onItemUpdating: function (args) { SecurityRoleDetails.ResetErrorState(); }, onItemDeleting: function (args) { SecurityRoleDetails.ResetErrorState(); } }); }, UserAddRoleMemberSelect: null, InitializeUserAddRoleMemberSelect: function () { SecurityRoleDetails.UserAddRoleMemberSelect = $("#user-select"); SecurityRoleDetails.UserAddRoleMemberSelect.select2({ placeholder: 'search for a certificate manager user', ajax: { url: ("/security/authenticable-principals/search"), dataType: 'json', type: 'get', delay: 30, data: function (params) { return { query: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.payload, }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 2, templateResult: SecurityRoleDetails.UserSelectFormatRepo, // omitted for brevity, see the source of this page templateSelection: SecurityRoleDetails.UserSelectFormatRepoSelection // omitted for brevity, see the source of this page }); }, UserSelectFormatRepo: function (repo) { return repo.name; }, UserSelectFormatRepoSelection: function (repo) { return repo.name; }, MembersController: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/security/role/" + $('#roleId').text() + "/members", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { //MembersController.onItemInserting(); var d = $.Deferred(); $.ajax({ type: "POST", url: "/security/role/" + $('#roleId').text() + "/member/" + SecurityRoleDetails.UserAddRoleMemberSelect.val() }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { SecurityRoleDetails.HandleError(xhr.responseJSON.message, $("#roleMembersTable")); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/security/role/" + $('#roleId').text() + "/member/" + item.id }).fail(function (xhr, ajaxOptions, thrownError) { SecurityRoleDetails.HandleError(xhr.responseJSON.message, $("#roleMembersTable")); }); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus); }, PageLoad: function () { UiGlobal.ShowCurrentTab(); SecurityRoleDetails.ScopesTab = $('#roleScopes.tabcontent'); Services.GetSecurityRoleDetails($('#roleId').text(), SecurityRoleDetails.RenderViewData, null); SecurityRoleDetails.InitializeGrid(); SecurityRoleDetails.InitializeUserAddRoleMemberSelect(); //SecurityRoleDetails.RegisterAddRoleMemberSelectHandler(); }, Role: null, ScopesTab: null } var SecurityRoles = { ShowAddSecurityRoleModal: function (dialogType, client) { //$("#eisName").val(client.name); //$("#eisDomain").val(client.hash); //$("#eis").val(client.cipher); //$("#adcsTemplateKeyUsage").val(client.keyUsage); //$("#adcsTemplateWindowsApi").val(client.windowsApi); $('#AddSecurityRoleButton').click(function () { SecurityRoles.AddRole(client, dialogType === "Add"); }); $("#addSecurityRoleModal").modal("show"); }, AddRole: function (client, isNew) { $.extend(client, { name: $("#secRoleName").val(), enabled: $("#secRoleEnabled").is(":checked") }); $("#securityRolesTable").jsGrid(isNew ? "insertItem" : "updateItem", client); $("#addSecurityRoleModal").modal("hide"); }, InitializeGrid: function () { $("#securityRolesTable").jsGrid({ height: "auto", width: "100%", //filtering: true, editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete this external identity source?", controller: SecurityRoles.Controller, fields: [ { name: "name", type: "text", title: "name" }, //{ name: "domain", type: "text", title: "Domain" }, //{ name: "searchBase", type: "text", title: "SearchBase" }, //{ name: "ActiveDirectoryMetadataType", type: "select", items: CmOptions.ActiveDirectoryMetadataType, valueType: "string", valueField: "Name", textField: "Name", title: "Type" }, //{ name: "username", type: "text", title: "Username" }, //{ name: "password", type: "text", readOnly: true, title: "password" }, { name: "enabled", type: "checkbox", title: "Enabled", sorting: false }, { //css: "security-roles-select2", name: "details", title: "Action", width: 50, itemTemplate: function (value, item) { //var $text = $("<p>").text(item.MyField); var $link = $("<a>").attr("href", '/view/security/role/' + item.id).text("View"); return $("<div>").append($link); } }, { type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { SecurityRoles.ShowAddSecurityRoleModal("Add", {}); }); } } ], onItemInserting: function (args) { SecurityRoles.ResetErrorState(); }, onItemUpdating: function (args) { SecurityRoles.ResetErrorState(); }, onItemDeleting: function (args) { SecurityRoles.ResetErrorState(); } }); }, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/security/roles", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, insertItem: function (item) { var d = $.Deferred(); $.ajax({ type: "POST", url: "/security/role", data: item }).done(function (response) { d.resolve(response.payload); }).fail(function (xhr, ajaxOptions, thrownError) { SecurityRoles.HandleError(xhr.responseJSON.message, $("#securityRolesTable")); }); return d.promise(); }, updateItem: function (item) { $.ajax({ type: "PUT", url: "/security/role", data: item }).fail(function (xhr, ajaxOptions, thrownError) { SecurityRoles.HandleError(xhr.responseJSON.message, $("#securityRolesTable")); }); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/security/role", data: item }).fail(function (xhr, ajaxOptions, thrownError) { SecurityRoles.HandleError(xhr.responseJSON.message, $("#securityRolesTable")); }); } }, ResetErrorState: function () { UiGlobal.HideError(); }, HandleError: function (textStatus, grid) { grid.jsGrid("render"); UiGlobal.ShowError(textStatus.responseJSON.message); }, InitializeSelect: function () { CmOptions.ActiveDirectoryMetadataType.forEach(function (item) { $('#eisType').append($('<option>', { value: item.Name, text: item.Name })); }); } } var ViewAllCertificates = { PageLoad: function () { ViewAllCertificates.Grid = $('#allCertificatesTable'); ViewAllCertificates.InitializeGrid(); }, Grid: null, Controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/certificates", dataType: "json" }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/certificate", data: item }).fail(function (xhr, ajaxOptions, thrownError) { ViewAllCertificates.HandleError(xhr.responseJSON.message, ViewAllCertificates.Grid); }); } }, ViewCertificate: function (item) { document.location = "/view/certificate/" + item.id; }, InitializeGrid: function () { ViewAllCertificates.Grid.jsGrid({ height: "auto", width: "100%", //filtering: true, editing: false, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, rowClick: function (args) { ViewAllCertificates.ViewCertificate(args.item); }, deleteConfirm: "Do you really want to delete this certificate?", controller: ViewAllCertificates.Controller, fields: [ { title: "Display Name", name: "displayName", type: "text" }, { title: "Hash", name: "hashAlgorithm", type: "text", width: 25 }, { title: "Cipher", name: "cipherAlgorithm", type: "text", width: 25 }, { title: "Expires", name: "validTo", type: "text", width: 40, itemTemplate: function (value, item) { return UiGlobal.GetDateString(value); } }, { title: "Thumbprint", name: "thumbprint", type: "text" }, //{ // name: "details", // title: "Action", // width: 20, // itemTemplate: function (value, item) { // //var $text = $("<p>").text(item.MyField); // var $link = $("<a>").attr("href", '/view/certificate/' + item.id).text("View"); // return $("<div>").append($link); // } //}, { type: "control", editButton: false, width: 10 } ] }); } } ViewCertificate = { PageLoad: function () { document.getElementById("defaultOpen").click(); UiGlobal.ShowCurrentTab(); ViewCertificate.SubjectAlternativeNameTable = $('#subjectAlternativeNameTable'); ViewCertificate.AclTable = $('#certificateAclTable'); ViewCertificate.InitialzeAclTable(); ViewCertificate.CertificateAceModal = $('#addCertificateAceModal'); Services.GetCertificateDetails(ViewCertificate.GetCertificateId(), ViewCertificate.GetCertificateSuccessCallback, ViewCertificate.GetCertificateErrorCallback); ViewCertificate.InitializeDownloadUx(); ViewCertificate.InitializeShowPassword(); ViewCertificate.InitializeResetPassword(); ViewCertificate.InitializeSelects(); ViewCertificate.NodeSelect = $("#nodeSelect"); ViewCertificate.InitializeNodeSelect(); ViewCertificate.InitializeNodeSelect(); }, ShowDeployCertificateModal: function () { UiGlobal.ShowModal('deployCertificateModal'); }, DeployToNode: function () { }, GetCertificateId: function () { return $('#certificate-id-hidden').val(); }, InitializeSelects: function () { ViewCertificate.AceTypeChangeAceSelect = $('#aceType'); ViewCertificate.IdentityTypeChangeAceSelect = $('#aceIdentityType'); ViewCertificate.AceIdentitySelect = $('#identity-select'); CmOptions.AceTypes.forEach(function (item) { ViewCertificate.AceTypeChangeAceSelect.append( $('<option>', { value: item, text: item }) ); }); CmOptions.IdentityTypes.forEach(function (item) { ViewCertificate.IdentityTypeChangeAceSelect.append( $('<option>', { value: item, text: item }) ); }); ViewCertificate.AceIdentitySelect.select2({ width: 'resolve', dropdownAutoWidth: true, placeholder: 'search for a certificate manager security principal', ajax: { url: ("/security/principals"), dataType: 'json', type: 'get', delay: 30, data: function (params) { return { query: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.payload, }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 2, templateResult: ViewCertificate.FormatSelectResults, // omitted for brevity, see the source of this page templateSelection: ViewCertificate.FormatSelection // omitted for brevity, see the source of this page }); }, FormatSelectResults: function (repo) { var markup = '<div class="user-select-container">' markup = markup + '<div class="user-select-title">' + repo.name + '</div>'; markup = markup + '<div class="user-select-details">Type: <span class="user-select-details-value">' + repo.identityType + '</span></div>'; markup = markup + '</div>'; return markup; }, FormatSelection: function (repo) { return repo.name; }, AceIdentitySelect: null, AceTypeChangeAceSelect: null, IdentityTypeChangeAceSelect: null, CertificateData: null, SubjectAlternativeNameTable: null, AclTable: null, CertificateAceModal: null, NodeSelect: null, GetCertificateSuccessCallback: function (data) { CertificateData = data; $('#displayName').text(data.displayName); $('#thumbprint').text(data.thumbprint); $('#hashAlgorithm').text(data.hashAlgorithm); $('#cipherAlgorithm').text(data.cipherAlgorithm); $('#hasPrivateKey').text(data.hasPrivateKey); $('#expires').text(UiGlobal.GetDateString(data.expires)); $('#windowsApi').text(UiGlobal.GetWindowsApiDisplay(data.windowsApi)); $('#keySize').text(data.keySize); $('#storageFormat').text(data.certificateStorageFormat); ViewCertificate.InitializeSubjectAlternativeNamesTable(ViewCertificate.SubjectAlternativeNameTable, data.subject.subjectAlternativeName); //ViewCertificate.InitialzeAclTable(ViewCertificate.AclTable, data.acl); }, GetCertificateErrorCallback: function () { UiGlobal.ShowError(); }, ShowAddCertificateAceModal: function () { ViewCertificate.CertificateAceModal.modal("show"); }, InitializeDownloadUx: function () { $('#showCertificateDownloadOptionsButton').click(function () { $('#certificateDownloadOptionsModal').modal('show'); }); $('#cer-radio').change(function () { $("#download-certificate-button").prop('disabled', false); $("#download-cer-option-der").prop('disabled', false); $("#download-cer-option-b64").prop('disabled', false); $("#download-cer-option-b64").prop('checked', true); $("#cer-background").css("background-color", "#b0c4de"); $("#pfx-background").css("background-color", "#f5f5f5"); }); $('#pfx-radio').change(function () { $("#download-certificate-button").prop('disabled', false); $("#download-pfx-includechain").prop('disabled', false); $("#download-cer-option-b64").prop('disabled', true); $("#download-cer-option-der").prop('disabled', true); $("#pfx-background").css("background-color", "#b0c4de"); $("#cer-background").css("background-color", "#f5f5f5"); }); $('#download-certificate-button').click(function (e) { var type; var encoding; if ($("#cer-radio").prop("checked")) { if ($("#download-cer-option-b64").prop('checked')) { type = "certb64"; } else { type = "certbinary"; } type = "certbinary"; } else if ($("#pfx-radio").prop("checked")) { type = "pfx"; } else { type = ""; } if ($('#include-chain-checkbox').prop('checked')) { type = type + "chain" } var downloadUri = "/certificate/" + $('#certificate-id').text(); switch (type) { case "certbinarychain": downloadUri = downloadUri + "/download/cer/binary/includechain"; break; case "certbinary": downloadUri = downloadUri + "/download/cer/binary/nochain"; break; case "certb64chain": downloadUri = downloadUri + "/download/cer/base64/includechain"; break; case "certb64": downloadUri = downloadUri + "/download/cer/base64/nochain"; break; case "pfxchain": downloadUri = downloadUri + "/download/pfx/includechain"; break; case "pfx": downloadUri = downloadUri + "/download/pfx/nochain"; break; default: downloadUri = downloadUri + "/download/cer/binary/nochain"; } e.preventDefault(); window.location.href = downloadUri; }); }, InitializeSubjectAlternativeNamesTable: function (table, sanList) { table.jsGrid({ width: "100%", paging: true, autoload: true, pageLoading: true, controller: { loadData: function () { return { data: sanList } } }, fields: [ { title: "Subject Alternative Name", itemTemplate: function (value, item) { return item; } } ] }); }, ChangeList: function () { }, InitialzeAclTable: function (table) { ViewCertificate.AclTable.jsGrid({ width: "100%", paging: true, autoload: true, //pageLoading: true, deleteConfirm: "Are you sure you want to remove this ACE from the Access Control List?", //"certificate/{certId:guid}/acl/{aceId:guid}" controller: { loadData: function (filter) { var d = $.Deferred(); $.ajax({ type: "GET", url: "/certificate/" + ViewCertificate.GetCertificateId(), dataType: "json" }).done(function (response) { d.resolve(response.payload.acl); }); return d.promise(); }, //loadData: function () { // return { data: acl } //}, insertItem: function (item) { var d = $.Deferred(); $.ajax({ type: "PUT", url: "/certificate/" + item.id + "/acl", dataType: "json", contentType: 'application/json; charset=UTF-8', data: JSON.stringify({ identityType: item.identityType, aceType: item.aceType, identity: item.identity }) }).done(function (response) { d.resolve(response.payload); }); return d.promise(); }, deleteItem: function (item) { $.ajax({ type: "DELETE", url: "/certificate/" + ViewCertificate.GetCertificateId() + "/acl/" + item.id }).fail(function (xhr, ajaxOptions, thrownError) { ViewCertificate.HandleError(xhr.responseJSON.message, AuthenticablePrincipal.Grid); }); } }, fields: [ { title: "Identity", name: "identityDisplayName", type: "text" }, { title: "IdentityType", name: "identityType", type: "text" }, { title: "AceType", name: "aceType", type: "text" }, { width: 25, editButton: false, type: "control", headerTemplate: function () { return $("<button>").attr("type", "button").text("Add") .on("click", function () { ViewCertificate.ShowAddCertificateAceModal("Add", {}); }); } } ] }); }, InitializeShowPassword: function () { $('#showPasswordButton').click(function () { $('#password').empty(); Services.GetCertificatePassword(ViewCertificate.GetCertificateId(), ViewCertificate.GetCertificatePasswordSuccessCallback, ViewCertificate.GetCertificatePasswordErrorCallback); }); }, InitializeResetPassword: function () { $('#resetPasswordButton').click(function () { UiGlobal.ResetAlertState(); Services.ResetCertificatePassword(ViewCertificate.GetCertificateId(), ViewCertificate.ResetCertificatePasswordSuccessCallback, ViewCertificate.ResetCertificatePasswordErrorCallback); }); }, ResetCertificatePasswordSuccessCallback: function () { UiGlobal.ShowSuccess("Certificate password was reset successfully"); }, ResetCertificatePasswordErrorCallback: function () { UiGlobal.ShowError("Could not process certificate password reset request"); }, GetCertificatePasswordSuccessCallback: function (data) { $('#password').text(data.decryptedPassword); }, GetCertificatePasswordErrorCallback: function (x, t, m) { $('#password').text("Could not retrieved password, access denied."); $('#password').css("color", "red"); }, AddCertificateAce: function () { var data = { id: ViewCertificate.GetCertificateId(), identity: ViewCertificate.AceIdentitySelect.val(), identityType: $('#aceIdentityType').val(), aceType: $('#aceType').val() }; ViewCertificate.AclTable.jsGrid("insertItem", data); }, InitializeNodeSelect: function () { ViewCertificate.NodeSelect.select2({ placeholder: 'search for a certificate manager user', ajax: { url: ("/nodes"), dataType: 'json', type: 'get', delay: 30, data: function (params) { return { query: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.payload, }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 2, templateResult: ViewCertificate.NodeSelectFormatRepo, // omitted for brevity, see the source of this page templateSelection: ViewCertificate.NodeSelectFormatRepoSelection // omitted for brevity, see the source of this page }); }, NodeSelectFormatRepo: function (repo) { return repo.hostname; }, NodeSelectFormatRepoSelection: function (repo) { return repo.hostname; }, DeployToNode: function () { var uri = '/node/' + ViewCertificate.NodeSelect.val() + '/deploy/' + ViewCertificate.GetCertificateId(); Services.Post(uri, null, ViewCertificate.DeployCertSuccessCallback, null); }, DeployCertSuccessCallback: function (payload) { UiGlobal.ShowSuccess('Certificate successfully deployed to node'); } }
export default function initProgressHover() { const $progressHover = document.querySelectorAll('.js-progress-hover'); if ($progressHover === null) { return false; } function showMe(event) { document.querySelector('.js-progress-more-info p').textContent = event.target.dataset.moreInfo; } function hideMe() { document.querySelector('.js-progress-more-info p').textContent = ''; } $progressHover.forEach(button => button.addEventListener( 'mouseleave', hideMe, false, )); return $progressHover.forEach(button => button.addEventListener( 'mouseover', showMe, false, )); }
vantage_webpackJsonp([1], { 29: function(t, i, n) { "use strict"; Object.defineProperty(i, "__esModule", { value: !0 }); var e = n(10), s = n(9), r = n.n(s); e.a.config.productionTip = !1, new e.a({ el: "#sapp", template: "<App/>", components: { App: r.a } }) }, 30: function(t, i, n) { "use strict"; n.d(i, "b", function() { return e }), n.d(i, "a", function() { return r }); var e = function(t) { return "$" + Number(t).toLocaleString() }, s = function(t, i, n) { return i.split(".").reduce(function(t, i) { return null === t ? null : t[i] }, t) || n }, r = function(t, i, n) { var e = void 0, r = void 0; /^(\w+(?:\.\w+)*)+\.(\w+)$/.test(i) ? (e = s(t, RegExp.$1), r = RegExp.$2) : (e = t, r = i), e && (e[r] = n) } }, 31: function(t, i, n) { "use strict"; Object.defineProperty(i, "__esModule", { value: !0 }); var e = n(11), s = n.n(e), r = n(41), a = n.n(r); i.default = { name: "sapp", components: { Listing: a.a }, data: function() { return { errorText: "", listings: [] } }, mounted: function() { window.loadCompanyListings = this.loadCompanyListings, window.loadAgentListings = this.loadAgentListings }, methods: { loadListings: function(t) { var i = this; s.a.get("https://cms.prop.cards/api/" + t).then(function(t) { var n = t.data; n.error && (i.errorText = "error: " + n.error), i.listings = n.records }).catch(function(t) { console.log("error", t), i.errorText = t }) }, loadAgentListings: function(t, i, n) { if (!t) throw new Error("Agent ID was not provided"); var e = i || "portfolio", s = n || "1"; this.loadListings("agent_listings/" + t + "/" + e + "/" + s) }, loadCompanyListings: function(t, i, n) { var e = t || 8, s = i || window.MWA_MLS_STATUS || "portfolio", r = n || window.MWA_MLS_SORT || "1"; this.loadListings("company_listings/" + e + "/" + s + "/" + r) } } } }, 32: function(t, i, n) { "use strict"; Object.defineProperty(i, "__esModule", { value: !0 }); var e = n(30); i.default = { name: "listing", props: { details: Object }, data: function() { return {} }, computed: {}, mounted: function() { if (this.details.imageurl) { var t = this.getDomElement(".Listing-photo"); n.i(e.a)(t, "style.backgroundImage", 'url("' + this.details.imageurl + '")') } }, methods: { getDomElement: function(t) { return this.$el.querySelector(t || {}) }, formatCurrency: e.b, onClick: function(t) { "" === this.details.href && t.preventDefault() } } } }, 35: function(t, i) {}, 36: function(t, i) {}, 37: function(t, i) {}, 41: function(t, i, n) { n(37); var e = n(7)(n(32), n(43), null, null); t.exports = e.exports }, 42: function(t, i) { t.exports = { render: function() { var t = this, i = t.$createElement, n = t._self._c || i; return n("div", { staticClass: "ListingList swiper-container swiper-container--sold-listings", attrs: { id: "sapp" } }, [n("div", { staticClass: "listing-list swiper-wrapper swiper-wrapper-prop-row" }, t._l(t.listings, function(t) { return n("listing", { key: t.id, attrs: { details: t } }) })), t._v(" "), "" !== t.errorText ? n("p", [t._v("\n " + t._s(t.errorText) + "\n ")]) : t._e(), t._v(" "), n("div", { staticClass: "swiper-button-prev arrow-bg" }), t._v(" "), n("div", { staticClass: "swiper-button-next arrow-bg" }), t._v(" "), n("div", { staticClass: "swiper-pagination swiper-pagination-h" })]) }, staticRenderFns: [] } }, 43: function(t, i) { t.exports = { render: function() { var t = this, i = t.$createElement, n = t._self._c || i; return n("a", { staticClass: "Listing swiper-slide", attrs: { href: t.details.href, target: "_blank" }, on: { click: function(i) { t.onClick(i) } } }, [n("div", { staticClass: "Listing-photo" }, [t.details.price ? n("div", { staticClass: "Listing-price" }, [t._v("\n " + t._s(t.formatCurrency(t.details.price)) + "\n ")]) : t._e()]), t._v(" "), n("div", { staticClass: "Listing-details" }, [n("strong", { staticClass: "Listing-addr" }, [t._v("\n " + t._s(t.details.title || t.details.addr) + "\n ")]), t._v(" "), n("em", { staticClass: "Listing-city" }, [t._v("\n " + t._s(t.details.location || t.details.city) + "\n ")]), t._v(" "), n("em", { staticClass: "Listing-attribs" }, [t._v("\n " + t._s(t.details.beds) + "\n beds \xa0 " + t._s(t.details.baths) + "\n baths \xa0 " + t._s(t.details.sqft) + "\n sqft " + "\n ")])]), t._v(" "), n("div", { staticClass: "prop-row-gradient" })]) }, staticRenderFns: [] } }, 9: function(t, i, n) { n(35), n(36); var e = n(7)(n(31), n(42), null, null); t.exports = e.exports } }, [29]);
var secrets = require('../config/secrets'); /** * GET /contact * Contact form page. */ exports.getContact = function(req, res) { res.render('contact', { title: 'Contact' }); }; /** * POST /contact * Send a contact form via SendGrid. * @param {string} email * @param {string} name * @param {string} message */ exports.postContact = function(req, res) { req.assert('name', 'Name cannot be blank').notEmpty(); req.assert('email', 'Email cannot be blank').notEmpty(); req.assert('email', 'Email is not valid').isEmail(); req.assert('message', 'Message cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/contact'); } var from = req.body.email; var name = req.body.name; var body = req.body.message; var to = '[email protected]'; var subject = 'Contact Form'; req.flash('success', { msg: 'Email has been sent successfully!' }); res.redirect('/contact'); };
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['md-dialog-container'], click() { this.sendAction('outsideClicked'); } });
'use strict'; var shimmer = require('../../util/shimmer') , logger = require('../../util/logger').child('parsers.wrappers.node-cassandra-cql') , record = require('../../metrics/recorders/cache_storage.js')('Cassandra') ; var WRAP_METHODS = [ 'execute', 'executeAsPrepared', 'executeBatch' ]; module.exports = function initialize(agent, cassandracql) { var tracer = agent.tracer; WRAP_METHODS.forEach(function cb_forEach(operation) { if ( ! (cassandracql && cassandracql.Client && cassandracql.Client.prototype) ) return; shimmer.wrapMethod(cassandracql.Client.prototype, 'node-cassandra-cql.Client.prototype', operation, function wrapper(cmd) { return tracer.segmentProxy(function wrapped() { if (!tracer.getAction() || arguments.length < 1) return cmd.apply(this, arguments); var action = tracer.getAction(); var args = tracer.slice(arguments); var name = 'Cassandra/NULL/' + operation; var segment_info = { metric_name : name, call_url : "", call_count : 1, class_name : 'node-cassandra-cql.Client', method_name : operation, params : {} } var segment = tracer.addSegment(segment_info, record); var position = args.length - 1; var last = args[position]; segment.port = this.port; segment.host = this.host; function proxy(cb) { return function wrap() { segment.end(); return cb.apply(this, arguments); }; } if (typeof last === 'function') { args[position] = tracer.callbackProxy(proxy(last)); } else if (Array.isArray(last) && typeof last[last.length - 1] === 'function') { var callback = proxy(last[last.length - 1]); last[last.length - 1] = tracer.callbackProxy(callback); } else { args.push(function cb() { segment.end(); }); } return cmd.apply(this, args); }); }); }); };
/* * NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io) * Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved. * * Distributed under the MIT license * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code * * @link https://github.com/kusanagi/katana-sdk-node * @license http://www.opensource.org/licenses/mit-license.php MIT License * @copyright Copyright (c) 2016-2018 KUSANAGI S.L. (http://kusanagi.io) */ 'use strict'; const expect = require('chai').expect; const Relation = require('./relation'); describe('Relation', () => { it('should create an instance', () => { const relation = new Relation(null, null, null, null); expect(relation).to.be.an.instanceOf(Relation); }); describe('getAddress()', () => { it('should return the address of the service', () => { const relation = new Relation('test', null, null, null); expect(relation.getAddress()).to.equal('test'); }); }); describe('getName()', () => { it('should return the name of the service', () => { const relation = new Relation(null, 'test', null, null); expect(relation.getName()).to.equal('test'); }); }); describe('getPrimaryKey()', () => { it('should return the primary key', () => { const relation = new Relation(null, null, 'test', null); expect(relation.getPrimaryKey()).to.equal('test'); }); }); describe('getForeignRelations()', () => { it('should return the foreign relations', () => { const relation = new Relation(null, null, null, []); expect(relation.getForeignRelations()).to.eql([]); }); }); });
import React, {PropTypes} from 'react'; import {render} from 'react-dom'; import styled from 'styled-components'; import {Map, Marker, Popup, TileLayer} from 'react-leaflet'; const Wrapper = styled.div ` .leaflet-container { height: 400px; width: 100%; } ` const position = [4.36, -74.04]; class HumboldtMap extends React.Component { constructor(props) { super(props); } render() { return ( <Wrapper> <Map center={position} zoom={5}> <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'/> </Map> </Wrapper> ) } } export default HumboldtMap;
function contains(context, element, text, message) { var matches = context.$(element).text().match(new RegExp(text)); message = message || `${element} should contain "${text}"`; this.push(!!matches, matches, text, message); } export default contains;
/*! * jQuery Simulate v@VERSION - simulate browser mouse and keyboard events * https://github.com/jquery/jquery-simulate * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: @DATE */ ;(function( $, undefined ) { var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/; $.fn.simulate = function( type, options ) { return this.each(function() { new $.simulate( this, type, options ); }); }; $.simulate = function( elem, type, options ) { var method = $.camelCase( "simulate-" + type ); this.target = elem; this.options = options; if ( this[ method ] ) { this[ method ](); } else { this.simulateEvent( elem, type, options ); } }; $.extend( $.simulate, { keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 }, buttonCode: { LEFT: 0, MIDDLE: 1, RIGHT: 2 } }); $.extend( $.simulate.prototype, { simulateEvent: function( elem, type, options ) { var event = this.createEvent( type, options ); this.dispatchEvent( elem, type, event, options ); }, createEvent: function( type, options ) { if ( rkeyEvent.test( type ) ) { return this.keyEvent( type, options ); } if ( rmouseEvent.test( type ) ) { return this.mouseEvent( type, options ); } }, mouseEvent: function( type, options ) { var event, eventDoc, doc, body; options = $.extend({ bubbles: true, cancelable: (type !== "mousemove"), view: window, detail: 0, screenX: 0, screenY: 0, clientX: 1, clientY: 1, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, relatedTarget: undefined }, options ); if ( document.createEvent ) { event = document.createEvent( "MouseEvents" ); event.initMouseEvent( type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || document.body.parentNode ); // IE 9+ creates events with pageX and pageY set to 0. // Trying to modify the properties throws an error, // so we define getters to return the correct values. if ( event.pageX === 0 && event.pageY === 0 && Object.defineProperty ) { eventDoc = event.relatedTarget.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; Object.defineProperty( event, "pageX", { get: function() { return options.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); } }); Object.defineProperty( event, "pageY", { get: function() { return options.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } }); } } else if ( document.createEventObject ) { event = document.createEventObject(); $.extend( event, options ); // standards event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ff974877(v=vs.85).aspx // old IE event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ms533544(v=vs.85).aspx // so we actually need to map the standard back to oldIE event.button = { 0: 1, 1: 4, 2: 2 }[ event.button ] || ( event.button === -1 ? 0 : event.button ); } return event; }, keyEvent: function( type, options ) { var event; options = $.extend({ bubbles: true, cancelable: true, view: window, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: undefined }, options ); if ( document.createEvent ) { try { event = document.createEvent( "KeyEvents" ); event.initKeyEvent( type, options.bubbles, options.cancelable, options.view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode ); // initKeyEvent throws an exception in WebKit // see: http://stackoverflow.com/questions/6406784/initkeyevent-keypress-only-works-in-firefox-need-a-cross-browser-solution // and also https://bugs.webkit.org/show_bug.cgi?id=13368 // fall back to a generic event until we decide to implement initKeyboardEvent } catch( err ) { event = document.createEvent( "Events" ); event.initEvent( type, options.bubbles, options.cancelable ); $.extend( event, { view: options.view, ctrlKey: options.ctrlKey, altKey: options.altKey, shiftKey: options.shiftKey, metaKey: options.metaKey, keyCode: options.keyCode, charCode: options.charCode }); } } else if ( document.createEventObject ) { event = document.createEventObject(); $.extend( event, options ); } if ( !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ) || (({}).toString.call( window.opera ) === "[object Opera]") ) { event.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode; event.charCode = undefined; } return event; }, dispatchEvent: function( elem, type, event ) { if ( elem.dispatchEvent ) { elem.dispatchEvent( event ); } else if ( type === "click" && elem.click && elem.nodeName.toLowerCase() === "input" ) { elem.click(); } else if ( elem.fireEvent ) { elem.fireEvent( "on" + type, event ); } }, simulateFocus: function() { var focusinEvent, triggered = false, element = $( this.target ); function trigger() { triggered = true; } element.bind( "focus", trigger ); element[ 0 ].focus(); if ( !triggered ) { focusinEvent = $.Event( "focusin" ); focusinEvent.preventDefault(); element.trigger( focusinEvent ); element.triggerHandler( "focus" ); } element.unbind( "focus", trigger ); }, simulateBlur: function() { var focusoutEvent, triggered = false, element = $( this.target ); function trigger() { triggered = true; } element.bind( "blur", trigger ); element[ 0 ].blur(); // blur events are async in IE setTimeout(function() { // IE won't let the blur occur if the window is inactive if ( element[ 0 ].ownerDocument.activeElement === element[ 0 ] ) { element[ 0 ].ownerDocument.body.focus(); } // Firefox won't trigger events if the window is inactive // IE doesn't trigger events if we had to manually focus the body if ( !triggered ) { focusoutEvent = $.Event( "focusout" ); focusoutEvent.preventDefault(); element.trigger( focusoutEvent ); element.triggerHandler( "blur" ); } element.unbind( "blur", trigger ); }, 1 ); } }); /** complex events **/ function findCenter( elem ) { var offset, document = $( elem.ownerDocument ); elem = $( elem ); offset = elem.offset(); return { x: offset.left + elem.outerWidth() / 2 - document.scrollLeft(), y: offset.top + elem.outerHeight() / 2 - document.scrollTop() }; } function findCorner( elem ) { var offset, document = $( elem.ownerDocument ); elem = $( elem ); offset = elem.offset(); return { x: offset.left - document.scrollLeft(), y: offset.top - document.scrollTop() }; } $.extend( $.simulate.prototype, { simulateDrag: function() { var i = 0, target = this.target, eventDoc = target.ownerDocument, options = this.options, center = options.handle === "corner" ? findCorner( target ) : findCenter( target ), x = Math.floor( center.x ), y = Math.floor( center.y ), coord = { clientX: x, clientY: y }, dx = options.dx || ( options.x !== undefined ? options.x - x : 0 ), dy = options.dy || ( options.y !== undefined ? options.y - y : 0 ), moves = options.moves || 3; this.simulateEvent( target, "mousedown", coord ); for ( ; i < moves ; i++ ) { x += dx / moves; y += dy / moves; coord = { clientX: Math.round( x ), clientY: Math.round( y ) }; this.simulateEvent( eventDoc, "mousemove", coord ); } if ( $.contains( eventDoc, target ) ) { this.simulateEvent( target, "mouseup", coord ); this.simulateEvent( target, "click", coord ); } else { this.simulateEvent( eventDoc, "mouseup", coord ); } } }); })( jQuery );
UI.Assets = (function(){ // generates and caches frequently used UI assets var me = {}; var assets = {}; me.preLoad = function(next){ var spriteMap; var spriteSheet; var baseUrl = Host.getBaseUrl(); var useVersion = Host.useUrlParams; function assetUrl(url){ url = baseUrl + url; if (useVersion) url += ("?v=" + App.buildNumber); return url; } var createSprites = function(){ if (spriteMap && spriteSheet){ spriteMap.forEach(function(spriteData){ spriteData.img = spriteSheet; Y.sprites[spriteData.name] = Y.sprite(spriteData); }); if (next) next(); } }; FetchService.json(assetUrl("skin/spritemap_v4.json"),function(data){ spriteMap = data; createSprites(); }); Y.loadImage(assetUrl("skin/spritesheet_v4.png"),function(img){ spriteSheet = img; createSprites(); }) }; me.buttonLightScale9 = { left: 2, top:2, right: 4, bottom: 4 }; me.buttonLightHoverScale9 = { left: 2, top:2, right: 4, bottom: 4 }; me.buttonDarkScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkBlueScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkRedScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkRedHoverScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkGreenScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkActiveBlueScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkGreenHoverScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkGreenActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkRedActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkBlueActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonDarkYellowActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.panelMainScale9 = { left:2, top:2, right:3, bottom: 3 }; me.panelDarkScale9 = { left:3, top:3, right:3, bottom: 2 }; me.panelDarkHoverScale9 = { left:3, top:3, right:3, bottom: 2 }; me.panelDarkGreyScale9 = { left:3, top:3, right:3, bottom: 2 }; me.panelDarkGreyBlueScale9 = { left:3, top:3, right:3, bottom: 2 }; me.panelTransScale9 = { left:3, top:3, right:3, bottom: 2 }; me.panelInsetScale9 = { left:2, top:2, right:2, bottom: 2 }; me.panelDarkInsetScale9 = { left:2, top:2, right:2, bottom: 2 }; me.buttonKeyScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonKeyHoverScale9 = { left: 5, top:5, right: 5, bottom: 5 }; me.buttonKeyActiveScale9 = { left: 5, top:5, right: 5, bottom: 5 }; var assetsInfo = { button20_20:{ generate:function(andCache){ var result; var scale = me.panelDarkScale9; //result = UI.scale9Panel(0,0,20,20,scale); result = UI.button(0,0,20,20); result.setProperties({ background: scale, hoverBackground: me.panelDarkHoverScale9, textAlign: "center", font: window.fontMed, paddingTop: 2 }); if (andCache){ assets["buttonUp20_20"] = result; }else{ return result; } } }, button30_30:{ generate:function(andCache){ var result; var scale = me.buttonLightScale9; result = UI.scale9Panel(0,0,30,30,scale); if (andCache){ assets["buttonUp30_30"] = result; }else{ return result; } } }, buttonLight:{ generate:function(andCache){ var result; var scale = me.buttonLightScale9; result = UI.button(); result.setProperties({ background: scale, hoverBackground: me.buttonLightHoverScale9, textAlign: "center", font: window.fontMed }); if (andCache){ assets["buttonLight"] = result; }else{ return result; } } }, buttonDark:{ generate:function(andCache){ var result; var scale = me.buttonDarkScale9; result = UI.button(0,0,20,20); result.setProperties({ background: scale, hoverBackground:UI.Assets.buttonDarkBlueActiveScale9, activeBackground:UI.Assets.buttonDarkActiveScale9, isActive:false, textAlign: "center", font: window.fontMed }); if (andCache){ assets["buttonDark"] = result; }else{ return result; } } }, buttonDarkBlue:{ generate:function(andCache){ var result; result = UI.button(0,0,20,20); result.setProperties({ background: me.buttonDarkBlueScale9, activeBackground:UI.Assets.buttonDarkBlueActiveScale9, isActive:false, textAlign: "center", font: window.fontMed }); if (andCache){ assets["buttonDarkBlue"] = result; }else{ return result; } } }, buttonDarkRed:{ generate:function(andCache){ var result; result = UI.button(0,0,20,20); result.setProperties({ background: me.buttonDarkRedScale9, hoverBackground:UI.Assets.buttonDarkRedHoverScale9, activeBackground:UI.Assets.buttonDarkRedActiveScale9, isActive:false, textAlign: "center", font: window.fontMed }); if (andCache){ assets["buttonDarkRed"] = result; }else{ return result; } } }, buttonDarkGreen:{ generate:function(andCache){ var result; result = UI.button(0,0,20,20); result.setProperties({ background: me.buttonDarkGreenScale9, hoverBackground:UI.Assets.buttonDarkGreenHoverScale9, activeBackground:UI.Assets.buttonDarkGreenActiveScale9, isActive:false, textAlign: "center", font: window.fontMed }); if (andCache){ assets["buttonDarkGreen"] = result; }else{ return result; } } }, buttonKey:{ generate:function(andCache){ var result; result = UI.button(0,0,20,20); result.setProperties({ background: me.buttonKeyScale9, hoverBackground:UI.Assets.buttonKeyHoverScale9, activeBackground:UI.Assets.buttonKeyActiveScale9, isActive:false, textAlign: "center", font: window.fontDark }); if (andCache){ assets["buttonKey"] = result; }else{ return result; } } } }; me.init = function(){ // should be executed when all image assets have been loaded: me.buttonLightScale9.img = Y.getImage("button_light"); me.buttonLightHoverScale9.img = Y.getImage("button_light_hover"); me.buttonDarkScale9.img = Y.getImage("button_inlay"); me.buttonDarkBlueScale9.img = Y.getImage("button_inlay_blue"); me.buttonDarkRedScale9.img = Y.getImage("button_inlay_red"); me.buttonDarkRedHoverScale9.img = Y.getImage("button_inlay_red_hover"); me.buttonDarkGreenScale9.img = Y.getImage("button_inlay_green"); me.buttonDarkGreenHoverScale9.img = Y.getImage("button_hover_green"); me.buttonDarkActiveScale9.img = Y.getImage("button_inlay_active"); me.buttonDarkGreenActiveScale9.img = Y.getImage("button_inlay_green_active"); me.buttonDarkRedActiveScale9.img = Y.getImage("button_inlay_red_active"); me.buttonDarkBlueActiveScale9.img = Y.getImage("button_inlay_blue_active"); me.buttonDarkYellowActiveScale9.img = Y.getImage("button_inlay_yellow_active"); me.panelMainScale9.img = Y.getImage("background"); me.panelDarkScale9.img = Y.getImage("bar"); me.panelDarkHoverScale9.img = Y.getImage("bar_hover"); me.panelDarkGreyScale9.img = Y.getImage("panel_dark_greyish"); me.panelDarkGreyBlueScale9.img = Y.getImage("panel_dark_blueish"); me.panelTransScale9.img = Y.getImage("panel_trans"); me.panelInsetScale9.img = Y.getImage("panel_inset"); me.panelDarkInsetScale9.img = Y.getImage("panel_dark"); me.buttonKeyScale9.img = Y.getImage("keybutton"); me.buttonKeyHoverScale9.img = Y.getImage("keybutton_hover"); me.buttonKeyActiveScale9.img = Y.getImage("keybutton_highlight3"); console.log("Assets init done"); }; me.get = function(name){ var result = assets[name]; if (result){ return result; }else{ var asset = assetsInfo[name]; if (asset){ if (asset.isLoading){ console.log("Asset " + name + " is not ready yet, still loading"); return undefined; }else{ asset.isLoading = true; asset.generate(true); } }else{ console.error("Error: asset " + name + " is not defined"); return undefined; } } }; me.put = function(name,asset){ assets[name] = asset; }; me.generate = function(name){ if (assetsInfo[name]){ return assetsInfo[name].generate(); }else{ console.error("Error: asset " + name + " is not defined"); return undefined; } }; return me; }());
const _ = require('./util'); const userList = []; const socketMap = {}; /** * 处理socket连接 */ let handle = (io, socket) => { // 缓存当前用户的信息 let user = { id: null, name: null, typing: null, color: null, private: 0 }; let refreshUserList = _.boardcast(io, 'refresh userList');//刷新用户列表 let userJoin = _.boardcast(io, 'user join');//用户加入 let userLeave = _.boardcast(io, 'user leave');//用户离开 let privateChat = _.notifyone('chat message');//发送私信给某人 let chatMessage = _.notifyother(socket, 'chat message');//发送消息给其他人 let chatImage = _.notifyother(socket, 'chat image');//发送图片给其他人 let addUserSuccess = _.notifyself(socket, 'add user success');//用户添加成功 let notifyself = _.notifyself(socket, 'notify self');//系统通知自己 // 初始化在线用户列表 refreshUserList(userList); /** * 接受客户端的聊天信息 */ socket.on('chat message', (_msg) => { if(_.isPrivate(_msg)){ let {id, name, msg} = _.getPrivateInfo(_msg); let targetSocket = socketMap[id]; if(targetSocket){ privateChat(targetSocket, user.name, msg); }else{//已下线 notifyself(`${name} 已下线,消息未送达...`); } }else{ let msg = `${user.name}:${_msg}`; chatMessage(msg); } }); /** * 接受客户端的图片信息 */ socket.on('chat image', (name, img) => { chatImage(name, img); }); /** * 新建用户 */ socket.on('add user', (name) => { let id = _.getRamId(); let color = _.getRamColor(); Object.assign(user, {id, name, color}); socketMap[id] = socket; userList.push(user); addUserSuccess(name); refreshUserList(userList); userJoin(user); _.log(`☆☆☆ current users count: ${userList.length} ☆☆☆`); }); /** * 客户端断开连接 */ socket.on('disconnect', () => { if(!user.id){ return false; } userList.forEach((u, index) => { if(u.id === user.id){ userList.splice(index, 1); } }); userLeave(user); refreshUserList(userList); delete socketMap[user.id]; user = undefined; }); /** * 客户端正在输入 */ socket.on('user typing', () => { user.typing = true; refreshUserList(userList); }); /** * 客户端停止输入 */ socket.on('user not typing', () => { user.typing = false; refreshUserList(userList); }); } module.exports = handle;
// flow-typed signature: f02713dde41238d69fd77a94ef0c2340 // flow-typed version: <<STUB>>/@knit/logger_vfile:src/packages/@knit/logger/flow_v0.108.0 /** * This is an autogenerated libdef stub for: * * '@knit/logger' * * 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 '@knit/logger' { 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. */ // Filename aliases declare module '@knit/logger/index' { declare module.exports: $Exports<'@knit/logger'>; } declare module '@knit/logger/index.js' { declare module.exports: $Exports<'@knit/logger'>; }
define(['lodash', 'react', './examples.rt', 'text!./samples/hello.code', 'text!./samples/hello.rt', 'text!./samples/todo.code', 'text!./samples/todo.rt', 'text!./samples/rt-if.code', 'text!./samples/rt-if.rt', 'text!./samples/rt-props.code', 'text!./samples/rt-props.rt', 'text!./samples/rt-repeat.code', 'text!./samples/rt-repeat.rt', 'text!./samples/weather.code', 'text!./samples/weather.rt', 'text!./samples/rt-require.rt' ], function (_, React, examplesTemplate, helloCode, helloRT, todoCode, todoRT, rtIfCode, rtIfRT, rtPropsCode, rtPropsRT, rtRepeatCode, rtRepeatRT, weatherCode, weatherRT, rtRequireRT) { 'use strict'; var samples = { hello: [helloCode, helloRT], todo: [todoCode, todoRT], props: [rtPropsCode, rtPropsRT], rtIf: [rtIfCode, rtIfRT], repeat: [rtRepeatCode, rtRepeatRT], weather: [weatherCode, weatherRT] }; //samples = _.map(samples, function (v, k) { // return {name: k, templateProps: _.template(v[0])({name: k}), templateHTML: v[1]}; //}); _.each(samples, function (v, k) { samples[k] = {name: k, templateProps: _.template(v[0])({name: k}), templateHTML: v[1]}; }); return React.createClass({ displayName: 'Examples', mixins: [React.addons.LinkedStateMixin], getInitialState: function () { var codeAmd = window.reactTemplates.convertTemplateToReact(rtRequireRT, {modules: 'amd', name: 'template'}); var codeCJS = window.reactTemplates.convertTemplateToReact(rtRequireRT, {modules: 'commonjs', name: 'template'}); var codeES6 = window.reactTemplates.convertTemplateToReact(rtRequireRT, {modules: 'es6', name: 'template'}); return { rtRequire: {value: rtRequireRT}, amd: {value: codeAmd}, cjs: {value: codeCJS}, es6: {value: codeES6}, samples: samples }; }, render: examplesTemplate }); });
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-0b72ab9 */ goog.provide('ngmaterial.components.toast'); goog.require('ngmaterial.components.button'); goog.require('ngmaterial.core'); /** * @ngdoc module * @name material.components.toast * @description * Toast */ MdToastDirective['$inject'] = ["$mdToast"]; MdToastProvider['$inject'] = ["$$interimElementProvider"]; angular.module('material.components.toast', [ 'material.core', 'material.components.button' ]) .directive('mdToast', MdToastDirective) .provider('$mdToast', MdToastProvider); /* ngInject */ function MdToastDirective($mdToast) { return { restrict: 'E', link: function postLink(scope, element) { element.addClass('_md'); // private md component indicator for styling // When navigation force destroys an interimElement, then // listen and $destroy() that interim instance... scope.$on('$destroy', function() { $mdToast.destroy(); }); } }; } /** * @ngdoc service * @name $mdToast * @module material.components.toast * * @description * `$mdToast` is a service to build a toast notification on any position * on the screen with an optional duration, and provides a simple promise API. * * The toast will be always positioned at the `bottom`, when the screen size is * between `600px` and `959px` (`sm` breakpoint) * * ## Restrictions on custom toasts * - The toast's template must have an outer `<md-toast>` element. * - For a toast action, use element with class `md-action`. * - Add the class `md-capsule` for curved corners. * * ### Custom Presets * Developers are also able to create their own preset, which can be easily used without repeating * their options each time. * * <hljs lang="js"> * $mdToastProvider.addPreset('testPreset', { * options: function() { * return { * template: * '<md-toast>' + * '<div class="md-toast-content">' + * 'This is a custom preset' + * '</div>' + * '</md-toast>', * controllerAs: 'toast', * bindToController: true * }; * } * }); * </hljs> * * After you created your preset at config phase, you can easily access it. * * <hljs lang="js"> * $mdToast.show( * $mdToast.testPreset() * ); * </hljs> * * ## Parent container notes * * The toast is positioned using absolute positioning relative to its first non-static parent * container. Thus, if the requested parent container uses static positioning, we will temporarily * set its positioning to `relative` while the toast is visible and reset it when the toast is * hidden. * * Because of this, it is usually best to ensure that the parent container has a fixed height and * prevents scrolling by setting the `overflow: hidden;` style. Since the position is based off of * the parent's height, the toast may be mispositioned if you allow the parent to scroll. * * You can, however, have a scrollable element inside of the container; just make sure the * container itself does not scroll. * * <hljs lang="html"> * <div layout-fill id="toast-container"> * <md-content> * I can have lots of content and scroll! * </md-content> * </div> * </hljs> * * @usage * <hljs lang="html"> * <div ng-controller="MyController"> * <md-button ng-click="openToast()"> * Open a Toast! * </md-button> * </div> * </hljs> * * <hljs lang="js"> * var app = angular.module('app', ['ngMaterial']); * app.controller('MyController', function($scope, $mdToast) { * $scope.openToast = function($event) { * $mdToast.show($mdToast.simple().textContent('Hello!')); * // Could also do $mdToast.showSimple('Hello'); * }; * }); * </hljs> */ /** * @ngdoc method * @name $mdToast#showSimple * * @param {string} message The message to display inside the toast * @description * Convenience method which builds and shows a simple toast. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. * */ /** * @ngdoc method * @name $mdToast#simple * * @description * Builds a preconfigured toast. * * @returns {obj} a `$mdToastPreset` with the following chainable configuration methods. * * _**Note:** These configuration methods are provided in addition to the methods provided by * the `build()` and `show()` methods below._ * * <table class="md-api-table methods"> * <thead> * <tr> * <th>Method</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>`.textContent(string)`</td> * <td>Sets the toast content to the specified string</td> * </tr> * <tr> * <td>`.action(string)`</td> * <td> * Adds an action button. <br/> * If clicked, the promise (returned from `show()`) * will resolve with the value `'ok'`; otherwise, it is resolved with `true` after a `hideDelay` * timeout * </td> * </tr> * <tr> * <td>`.highlightAction(boolean)`</td> * <td> * Whether or not the action button will have an additional highlight class.<br/> * By default the `accent` color will be applied to the action button. * </td> * </tr> * <tr> * <td>`.highlightClass(string)`</td> * <td> * If set, the given class will be applied to the highlighted action button.<br/> * This allows you to specify the highlight color easily. Highlight classes are `md-primary`, `md-warn` * and `md-accent` * </td> * </tr> * <tr> * <td>`.capsule(boolean)`</td> * <td>Whether or not to add the `md-capsule` class to the toast to provide rounded corners</td> * </tr> * <tr> * <td>`.theme(string)`</td> * <td>Sets the theme on the toast to the requested theme. Default is `$mdThemingProvider`'s default.</td> * </tr> * <tr> * <td>`.toastClass(string)`</td> * <td>Sets a class on the toast element</td> * </tr> * </tbody> * </table> * */ /** * @ngdoc method * @name $mdToast#updateTextContent * * @description * Updates the content of an existing toast. Useful for updating things like counts, etc. * */ /** * @ngdoc method * @name $mdToast#build * * @description * Creates a custom `$mdToastPreset` that you can configure. * * @returns {obj} a `$mdToastPreset` with the chainable configuration methods for shows' options (see below). */ /** * @ngdoc method * @name $mdToast#show * * @description Shows the toast. * * @param {object} optionsOrPreset Either provide an `$mdToastPreset` returned from `simple()` * and `build()`, or an options object with the following properties: * * - `templateUrl` - `{string=}`: The url of an html template file that will * be used as the content of the toast. Restrictions: the template must * have an outer `md-toast` element. * - `template` - `{string=}`: Same as templateUrl, except this is an actual * template string. * - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template content with a * `<div class="md-toast-content">` if one is not provided. Defaults to true. Can be disabled if you provide a * custom toast directive. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope. * This scope will be destroyed when the toast is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `hideDelay` - `{number=}`: How many milliseconds the toast should stay * active before automatically closing. Set to 0 or false to have the toast stay open until * closed manually. Default: 3000. * - `position` - `{string=}`: Sets the position of the toast. <br/> * Available: any combination of `'bottom'`, `'left'`, `'top'`, `'right'`, `'end'` and `'start'`. * The properties `'end'` and `'start'` are dynamic and can be used for RTL support.<br/> * Default combination: `'bottom left'`. * - `toastClass` - `{string=}`: A class to set on the toast element. * - `controller` - `{string=}`: The controller to associate with this toast. * The controller will be injected the local `$mdToast.hide( )`, which is a function * used to hide the toast. * - `locals` - `{string=}`: An object containing key/value pairs. The keys will * be used as names of values to inject into the controller. For example, * `locals: {three: 3}` would inject `three` into the controller with the value * of 3. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values * and the toast will not open until the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the toast to. Defaults to appending * to the root element of the application. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. `$mdToast.hide()` will resolve either with a Boolean * value == 'true' or the value passed as an argument to `$mdToast.hide()`. * And `$mdToast.cancel()` will resolve the promise with a Boolean value == 'false' */ /** * @ngdoc method * @name $mdToast#hide * * @description * Hide an existing toast and resolve the promise returned from `$mdToast.show()`. * * @param {*=} response An argument for the resolved promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM. * The promise is resolved with either a Boolean value == 'true' or the value passed as the * argument to `.hide()`. * */ /** * @ngdoc method * @name $mdToast#cancel * * @description * `DEPRECATED` - The promise returned from opening a toast is used only to notify about the closing of the toast. * As such, there isn't any reason to also allow that promise to be rejected, * since it's not clear what the difference between resolve and reject would be. * * Hide the existing toast and reject the promise returned from * `$mdToast.show()`. * * @param {*=} response An argument for the rejected promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM * The promise is resolved with a Boolean value == 'false'. * */ function MdToastProvider($$interimElementProvider) { // Differentiate promise resolves: hide timeout (value == true) and hide action clicks (value == ok). toastDefaultOptions['$inject'] = ["$animate", "$mdToast", "$mdUtil", "$mdMedia"]; var ACTION_RESOLVE = 'ok'; var activeToastContent; var $mdToast = $$interimElementProvider('$mdToast') .setDefaults({ methods: ['position', 'hideDelay', 'capsule', 'parent', 'position', 'toastClass'], options: toastDefaultOptions }) .addPreset('simple', { argOption: 'textContent', methods: ['textContent', 'content', 'action', 'highlightAction', 'highlightClass', 'theme', 'parent' ], options: /* ngInject */ ["$mdToast", "$mdTheming", function($mdToast, $mdTheming) { return { template: '<md-toast md-theme="{{ toast.theme }}" ng-class="{\'md-capsule\': toast.capsule}">' + ' <div class="md-toast-content">' + ' <span class="md-toast-text" role="alert" aria-relevant="all" aria-atomic="true">' + ' {{ toast.content }}' + ' </span>' + ' <md-button class="md-action" ng-if="toast.action" ng-click="toast.resolve()" ' + ' ng-class="highlightClasses">' + ' {{ toast.action }}' + ' </md-button>' + ' </div>' + '</md-toast>', controller: /* ngInject */ ["$scope", function mdToastCtrl($scope) { var self = this; if (self.highlightAction) { $scope.highlightClasses = [ 'md-highlight', self.highlightClass ] } $scope.$watch(function() { return activeToastContent; }, function() { self.content = activeToastContent; }); this.resolve = function() { $mdToast.hide( ACTION_RESOLVE ); }; }], theme: $mdTheming.defaultTheme(), controllerAs: 'toast', bindToController: true }; }] }) .addMethod('updateTextContent', updateTextContent) .addMethod('updateContent', updateTextContent); function updateTextContent(newContent) { activeToastContent = newContent; } return $mdToast; /* ngInject */ function toastDefaultOptions($animate, $mdToast, $mdUtil, $mdMedia) { var SWIPE_EVENTS = '$md.swipeleft $md.swiperight $md.swipeup $md.swipedown'; return { onShow: onShow, onRemove: onRemove, toastClass: '', position: 'bottom left', themable: true, hideDelay: 3000, autoWrap: true, transformTemplate: function(template, options) { var shouldAddWrapper = options.autoWrap && template && !/md-toast-content/g.test(template); if (shouldAddWrapper) { // Root element of template will be <md-toast>. We need to wrap all of its content inside of // of <div class="md-toast-content">. All templates provided here should be static, developer-controlled // content (meaning we're not attempting to guard against XSS). var templateRoot = document.createElement('md-template'); templateRoot.innerHTML = template; // Iterate through all root children, to detect possible md-toast directives. for (var i = 0; i < templateRoot.children.length; i++) { if (templateRoot.children[i].nodeName === 'MD-TOAST') { var wrapper = angular.element('<div class="md-toast-content">'); // Wrap the children of the `md-toast` directive in jqLite, to be able to append multiple // nodes with the same execution. wrapper.append(angular.element(templateRoot.children[i].childNodes)); // Append the new wrapped element to the `md-toast` directive. templateRoot.children[i].appendChild(wrapper[0]); } } // We have to return the innerHTMl, because we do not want to have the `md-template` element to be // the root element of our interimElement. return templateRoot.innerHTML; } return template || ''; } }; function onShow(scope, element, options) { activeToastContent = options.textContent || options.content; // support deprecated #content method var isSmScreen = !$mdMedia('gt-sm'); element = $mdUtil.extractElementByName(element, 'md-toast', true); options.element = element; options.onSwipe = function(ev, gesture) { //Add the relevant swipe class to the element so it can animate correctly var swipe = ev.type.replace('$md.',''); var direction = swipe.replace('swipe', ''); // If the swipe direction is down/up but the toast came from top/bottom don't fade away // Unless the screen is small, then the toast always on bottom if ((direction === 'down' && options.position.indexOf('top') != -1 && !isSmScreen) || (direction === 'up' && (options.position.indexOf('bottom') != -1 || isSmScreen))) { return; } if ((direction === 'left' || direction === 'right') && isSmScreen) { return; } element.addClass('md-' + swipe); $mdUtil.nextTick($mdToast.cancel); }; options.openClass = toastOpenClass(options.position); element.addClass(options.toastClass); // 'top left' -> 'md-top md-left' options.parent.addClass(options.openClass); // static is the default position if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', 'relative'); } element.on(SWIPE_EVENTS, options.onSwipe); element.addClass(isSmScreen ? 'md-bottom' : options.position.split(' ').map(function(pos) { return 'md-' + pos; }).join(' ')); if (options.parent) options.parent.addClass('md-toast-animating'); return $animate.enter(element, options.parent).then(function() { if (options.parent) options.parent.removeClass('md-toast-animating'); }); } function onRemove(scope, element, options) { element.off(SWIPE_EVENTS, options.onSwipe); if (options.parent) options.parent.addClass('md-toast-animating'); if (options.openClass) options.parent.removeClass(options.openClass); return ((options.$destroy == true) ? element.remove() : $animate.leave(element)) .then(function () { if (options.parent) options.parent.removeClass('md-toast-animating'); if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', ''); } }); } function toastOpenClass(position) { // For mobile, always open full-width on bottom if (!$mdMedia('gt-xs')) { return 'md-toast-open-bottom'; } return 'md-toast-open-' + (position.indexOf('top') > -1 ? 'top' : 'bottom'); } } } ngmaterial.components.toast = angular.module("material.components.toast");
var board = require('./board'); var util = require('./util'); var hold = require('./hold'); function renderSquareTarget(data, cur) { var pos = util.key2pos(cur.over), width = cur.bounds.width, targetWidth = width / 4, squareWidth = width / 8, asWhite = data.orientation === 'white'; var sq = document.createElement('div'); var style = sq.style; var vector = [ (asWhite ? pos[0] - 1 : 8 - pos[0]) * squareWidth, (asWhite ? 8 - pos[1] : pos[1] - 1) * squareWidth ]; style.width = targetWidth + 'px'; style.height = targetWidth + 'px'; style.left = (-0.5 * squareWidth) + 'px'; style.top = (-0.5 * squareWidth) + 'px'; style[util.transformProp()] = util.translate(vector); sq.className = 'cg-square-target'; data.element.appendChild(sq); return sq; } function removeSquareTarget(data) { if (data.element) { var sqs = data.element.getElementsByClassName('cg-square-target'); while (sqs[0]) sqs[0].parentNode.removeChild(sqs[0]); } } function start(data, e) { if (e.touches && e.touches.length > 1) return; // support one finger touch only e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); var previouslySelected = data.selected; var position = util.eventPosition(e); var bounds = data.bounds; var orig = board.getKeyAtDomPos(data, position, bounds); var hadPremove = !!data.premovable.current; var hadPredrop = !!data.predroppable.current.key; board.selectSquare(data, orig); var stillSelected = data.selected === orig; if (data.pieces[orig] && stillSelected && board.isDraggable(data, orig)) { var bpos = util.boardpos(util.key2pos(orig), data.orientation === 'white'); var squareBounds = util.computeSquareBounds(data.orientation, bounds, orig); data.draggable.current = { previouslySelected: previouslySelected, orig: orig, piece: data.pieces[orig], rel: position, epos: position, pos: [0, 0], dec: data.draggable.magnified ? [ position[0] - (bounds.left + (bounds.width * bpos.left / 100) + (bounds.width * 0.25) / 2), position[1] - (bounds.top + bounds.height - (bounds.height * bpos.bottom / 100) + 10) ] : [ position[0] - (squareBounds.left + squareBounds.width / 2), position[1] - (squareBounds.top + squareBounds.height / 2) ], bounds: bounds, started: false, squareTarget: null, draggingPiece: data.element.querySelector('.' + orig + ' > piece'), originTarget: e.target, scheduledAnimationFrame: false }; if (data.draggable.magnified && data.draggable.centerPiece) { data.draggable.current.dec[1] = position[1] - (bounds.top + bounds.height - (bounds.height * bpos.bottom / 100) - (bounds.height * 0.25) / 2); } hold.start(); } else { if (hadPremove) board.unsetPremove(data); if (hadPredrop) board.unsetPredrop(data); } data.renderRAF(); } function processDrag(data) { if (data.draggable.current.scheduledAnimationFrame) return; data.draggable.current.scheduledAnimationFrame = true; requestAnimationFrame(function() { var cur = data.draggable.current; cur.scheduledAnimationFrame = false; if (cur.orig) { // if moving piece is gone, cancel if (data.pieces[cur.orig] !== cur.piece) { cancel(data); return; } // cancel animations while dragging if (data.animation.current.start && Object.keys(data.animation.current.anims).indexOf(cur.orig) !== -1) data.animation.current.start = false; else if (cur.started) { cur.pos = [ cur.epos[0] - cur.rel[0], cur.epos[1] - cur.rel[1] ]; cur.over = board.getKeyAtDomPos(data, cur.epos, cur.bounds); if (cur.over && !cur.squareTarget) { cur.squareTarget = renderSquareTarget(data, cur); } else if (!cur.over && cur.squareTarget) { if (cur.squareTarget.parentNode) cur.squareTarget.parentNode.removeChild(cur.squareTarget); cur.squareTarget = null; } // move piece cur.draggingPiece.style[util.transformProp()] = util.translate([ cur.pos[0] + cur.dec[0], cur.pos[1] + cur.dec[1] ]); // move square target if (cur.over && cur.squareTarget && cur.over !== cur.prevTarget) { var squareWidth = cur.bounds.width / 8, asWhite = data.orientation === 'white', stPos = util.key2pos(cur.over), vector = [ (asWhite ? stPos[0] - 1 : 8 - stPos[0]) * squareWidth, (asWhite ? 8 - stPos[1] : stPos[1] - 1) * squareWidth ]; cur.squareTarget.style[util.transformProp()] = util.translate(vector); cur.prevTarget = cur.over; } } processDrag(data); } }); } function move(data, e) { if (e.touches && e.touches.length > 1) return; // support one finger touch only if (data.draggable.preventDefault) e.preventDefault(); var cur = data.draggable.current; if (cur.orig) { data.draggable.current.epos = util.eventPosition(e); if (!cur.started && util.distance(cur.epos, cur.rel) >= data.draggable.distance) { cur.started = true; cur.draggingPiece.classList.add('dragging'); if (data.draggable.magnified) { cur.draggingPiece.classList.add('magnified'); } cur.draggingPiece.cgDragging = true; processDrag(data); } } } function end(data, e) { if (data.draggable.preventDefault) { e.preventDefault(); } e.stopPropagation(); e.stopImmediatePropagation(); var draggable = data.draggable; var orig = draggable.current ? draggable.current.orig : null; var dest = draggable.current.over; // comparing with the origin target is an easy way to test that the end event // has the same touch origin if (e && e.type === 'touchend' && draggable.current.originTarget !== e.target && !draggable.current.newPiece) { draggable.current = {}; return; } if (!orig) { removeSquareTarget(data); return; } removeSquareTarget(data); board.unsetPremove(data); board.unsetPredrop(data); if (draggable.current.started) { if (draggable.current.newPiece) { board.dropNewPiece(data, orig, dest); } else { if (orig !== dest) data.movable.dropped = [orig, dest]; board.userMove(data, orig, dest); } data.renderRAF(); } else if (draggable.current.previouslySelected === orig) { board.setSelected(data, null); data.renderRAF(); } draggable.current = {}; } function cancel(data) { removeSquareTarget(data); if (data.draggable.current.orig) { data.draggable.current = {}; board.selectSquare(data, null); } } module.exports = { start: start, move: move, end: end, cancel: cancel, processDrag: processDrag // must be exposed for board editors };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM6 10h2v2H6zm0 4h8v2H6zm10 0h2v2h-2zm-6-4h8v2h-8z" /> , 'SubtitlesOutlined');
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/sr",[],(function(){function n(n,e,r,t){return n%10==1&&n%100!=11?e:n%10>=2&&n%10<=4&&(n%100<12||n%100>14)?r:t}return{errorLoading:function(){return"Preuzimanje nije uspelo."},inputTooLong:function(e){var r=e.input.length-e.maximum;return"Obrišite "+r+" simbol"+n(r,"","a","a")},inputTooShort:function(e){var r=e.minimum-e.input.length;return"Ukucajte bar još "+r+" simbol"+n(r,"","a","a")},loadingMore:function(){return"Preuzimanje još rezultata…"},maximumSelected:function(e){return"Možete izabrati samo "+e.maximum+" stavk"+n(e.maximum,"u","e","i")},noResults:function(){return"Ništa nije pronađeno"},searching:function(){return"Pretraga…"},removeAllItems:function(){return"Уклоните све ставке"}}})),n.define,n.require}();
(function () { 'use strict'; var COOKIE_STRING_SLIDE_CALLOUT = 'mos.charts.slideCallout.hide'; /* * ngInject */ function ChartsController($scope, $cookieStore, $q, CartoSQLAPI) { // Initialize $scope.loadingView = true; $scope.currentData = []; $scope.currentAllData = []; $scope.groupedData = []; $scope.hideCallout = $cookieStore.get(COOKIE_STRING_SLIDE_CALLOUT) || false; $scope.calloutClicked = function () { var hide = true; $cookieStore.put(COOKIE_STRING_SLIDE_CALLOUT, hide); $scope.hideCallout = hide; }; var init = function () { // The chart view displays both the data year and the report year (there is a 1-year lag) $scope.dataYear = CartoSQLAPI.getCurrentYear(); $scope.reportYear = $scope.dataYear + 1; $scope.stats = CartoSQLAPI.yearsData()[$scope.dataYear]; var getCurrentAll = CartoSQLAPI.getAllCurrentData().then(function(data) { $scope.currentAllData = data.data.rows; }); var getGrouped = CartoSQLAPI.getGroupedData().then(function(data) { $scope.groupedData = data.data.rows; }); var all = $q.all([getCurrentAll, getGrouped]); // fetch all needed chart data when controller loads all.then(function() { $scope.currentData = CartoSQLAPI.getCurrentData($scope.currentAllData); $scope.loadingView = false; }); }; init(); } angular.module('mos.views.charts') .controller('ChartsController', ChartsController); })();
(function (signalrdashboardMilliman) { signalrdashboardMilliman.ConfidenceStatusComponent = ng.core.Component({ selector: 'confidence-status', templateUrl: '/scripts/app/templates/milliman/ConfidenceStatusComponent.html' }) .Class({ constructor: function() { this.model = new signalrdashboardMilliman.ConfidenceStatus(); this.componentName = 'ConfidenceStatus'; signalrdashboard.dashboard.registerComponent(this); }, ngOnInit: function() { signalrdashboard.dashboard.completeComponentRegistration(); }, setupHub : function(connection) { var hub = connection.confidenceStatus; var model = this.model; // Add a client-side hub method that the server will call hub.client.updateConfidenceStatus = function(stats) { model.updateFromData(stats); }; }, initialiseData: function(connection) { var model = this.model; connection.confidenceStatus.server.getModel().done(function(stats) { model.updateFromData(stats); }); } }); })(window.signalrdashboard.milliman || (window.signalrdashboard.milliman = {}));
import generic from "../core/generic"; /** * Checks whether the specified key is a own enumerable property of the given object or not. * @private * @function * @param {Object} obj * @param {String} key * @returns {Boolean} */ var _isOwnEnumerable = generic(Object.prototype.propertyIsEnumerable); export default _isOwnEnumerable;
/** * @class nodelinux.Service * Manage node.js scripts as native Linux daemons. * var Service = require('node-linux').Service; * * // Create a new service object * var svc = new Service({ * name:'Hello World', * description: 'The nodejs.org example web server.', * script: '/path/to/helloworld.js' * }); * * // Listen for the "install" event, which indicates the * // process is available as a service. * svc.on('install',function(){ * svc.start(); * }); * * svc.install(); * @author Corey Butler * @singleton */ var fs = require('fs'), p = require('path'), exec = require('child_process').exec, wrapper = p.resolve(p.join(__dirname,'./wrapper.js')); var daemon = function(config) { Object.defineProperties(this,{ /** * @cfg {String} [mode] * The type of daemon to create. Defaults to the system's default daemonization utility. * Alternatively, `systemd` can be used. */ mode: { enumerable: true, writable: true, configurable: false, value: config.mode }, /** * @cfg {String} [defaultMode] * Scans the system in order to find out the default mode. * May return either 'systemv' or 'systemd'. */ defaultMode: { enumerable: false, get: function(){ // http://unix.stackexchange.com/questions/18209/detect-init-system-using-the-shell var hasSystemD = function() { return fs.existsSync("/usr/bin/systemctl") || fs.existsSync("/bin/systemctl"); } var hasUpstart = function() { return false; // TODO: Upstart support is not implemented, for now //return fs.existsSync("/sbin/initctl"); } var hasSystemV = function() { return fs.existsSync("/etc/init.d"); } if (hasSystemD()) { return 'systemd'; } else if (hasUpstart()) { return 'upstart'; } else if (hasSystemV()) { return 'systemv'; } else { throw new Error('Could not detect init system'); } } }, /** * @cfg {String} [user=root] * The user to run the service as. Defaults to 'root' */ user: { enumerable: true, writable: false, configurable: false, value: config.user || 'root' }, /** * @cfg {String} [group=root] * The group to run the service as. Defaults to 'root' */ group: { enumerable: true, writable: false, configurable: false, value: config.group || 'root' }, system: { enumerable: false, get: function(){ switch(this.mode){ case 'systemd': return require('./systemd'); default: return require('./systemv'); } } }, /** * @cfg {String} [author='Unknown'] * An optional descriptive header added to the top of the daemon file. Credits * the author of the script. */ author: { enumerable: true, writable: true, configurable: false, value: config.author || 'Unknown' }, /** * @cfg {String} [piddir=/var/run] * The root directory where the PID file is stored. */ piddir: { enumerable: true, writable: true, configurable: false, value: config.piddir || '/var/run' }, /** * @cfg {String} name * The descriptive name of the process, i.e. `My Process`. */ _name: { enumerable: false, writable: true, configurable: false, value: config.name || null }, /** * @property {String} name * The name of the process. */ name: { enumerable: true, get: function(){return this._name;}, set: function(value){this._name = value;} }, label: { enumerable: false, get: function(){ return this.name.replace(/[^a-zA-Z0-9\_]+/gi,'').toLowerCase() } }, outlog: { enumerable: false, get: function(){ return p.join(this.logpath,this.label+'.log'); } }, errlog: { enumerable: false, get: function(){ return p.join(this.logpath,this.label+'-error.log'); } }, /** * @property {Boolean} exists * Indicates that the service exists. * @readonly */ exists: { enumerable: true, value: function(){ return this.generator.exists; } }, /** * @cfg {String} [description=''] * Description of the service. */ description: { enumerable: true, writable: false, configurable: false, value: config.description || '' }, /** * @cfg {String} [cwd] * The absolute path of the current working directory. Defaults to the base directory of #script. */ cwd: { enumerable: false, writable: true, configurable: false, value: config.cwd || p.dirname(config.script) }, /** * @cfg {Array|Object} [env] * An optional array or object used to pass environment variables to the node.js script. * You can do this by setting environment variables in the service config, as shown below: * * var svc = new Service({ * name:'Hello World', * description: 'The nodejs.org example web server.', * script: '/path/to/helloworld.js', * env: { * name: "NODE_ENV", * value: "production" * } * }); * * You can also supply an array to set multiple environment variables: * * var svc = new Service({ * name:'Hello World', * description: 'The nodejs.org example web server.', * script: '/path/to/helloworld.js', * env: [{ * name: "HOME", * value: process.env["USERPROFILE"] // Access the user home directory * },{ * name: "NODE_ENV", * value: "production" * }] * }); */ _ev: { enumerable: false, writable: true, configurable: false, value: config.env || [] }, EnvironmentVariables: { enumerable: false, get: function(){ var ev = [], tmp = {}; if (Object.prototype.toString.call(this._ev) === '[object Array]'){ this._ev.forEach(function(item){ tmp = {}; tmp[item.name] = item.value; ev.push(tmp); }); } else { tmp[this._ev.name] = this._ev.value; ev.push(tmp); } return ev; } }, /** * @cfg {String} script required * The absolute path of the script to launch as a service. */ script: { enumerable: true, writable: true, configurable: false, value: config.script !== undefined ? require('path').resolve(config.script) : null }, /** * @cfg {String} [logpath=/Library/Logs/node-scripts] * The root directory where the log will be stored. */ logpath: { enumerable: true, writable: true, configurable: false, value: config.logpath || '/var/log' }, /** * @cfg {Number} [maxRetries=null] * The maximum number of restart attempts to make before the service is considered non-responsive/faulty. * Ignored by default. */ maxRetries: { enumerable: true, writable: false, configurable: false, value: config.maxRetries || null }, /** * @cfg {Number} [maxRestarts=3] * The maximum number of restarts within a 60 second period before haulting the process. * This cannot be _disabled_, but it can be rendered ineffective by setting a value of `0`. */ maxRestarts: { enumerable: true, writable: false, configurable: false, value: config.maxRestarts || 3 }, /** * @cfg {Boolean} [abortOnError=false] * Setting this to `true` will force the process to exit if it encounters an error that stops the node.js script from running. * This does not mean the process will stop if the script throws an error. It will only abort if the * script throws an error causing the process to exit (i.e. `process.exit(1)`). */ abortOnError: { enumerable: true, writable: false, configurable: false, value: config.abortOnError instanceof Boolean ? config.abortOnError : false }, /** * @cfg {Number} [wait=1] * The initial number of seconds to wait before attempting a restart (after the script stops). */ wait: { enumerable: true, writable: false, configurable: false, value: config.wait || 1 }, /** * @cfg {Number} [grow=.25] * A number between 0-1 representing the percentage growth rate for the #wait interval. * Setting this to anything other than `0` allows the process to increase it's wait period * on every restart attempt. If a process dies fatally, this will prevent the server from * restarting the process too rapidly (and too strenuously). */ grow: { enumerable: true, writable: false, configurable: false, value: config.grow || .25 }, _suspendedEvents: { enumerable: false, writable: true, configurable: false, value: [] }, /** * @method isSuspended * Indicates the specified event is suspended. */ isSuspended: { enumerable: true, writable: false, configurable: false, value: function(eventname){ return this._suspendedEvents.indexOf(eventname) >= 0; } }, /** * @method suspendEvent * Stop firing the specified event. * @param {String} eventname * The event. */ suspendEvent: { enumerable: true, writable: false, configurable: false, value: function(eventname){ if (!this.isSuspended(eventname)){ this._suspendedEvents.push(eventname); } } }, /** * @method resumeEvent * Resume firing the specified event. * @param {String} eventname * The event. */ resumeEvent: { enumerable: true, writable: false, configurable: false, value: function(eventname){ if (this.isSuspended(eventname)){ this._suspendedEvents.splice(this._suspendedEvents.indexOf(eventname),1); } } }, _gen: { enumerable: false, writable: true, configurable: false, value: null }, generator: { enumerable: false, get: function(){ return this._gen; }, set: function(value) { var me = this; this._gen = value; // Handle generator events & bubble accordingly /** * @event install * Fired when the installation completes. */ this._gen.on('install',function(){ !me.isSuspended('install') && me.emit('install'); }); /** * @event uninstall * Fired when the uninstallation/removal completes. */ this._gen.on('uninstall',function(){ !me.isSuspended('uninstall') && me.emit('uninstall'); }); /** * @event enable * Fired when the enabling completes. */ this._gen.on('enable',function(){ !me.isSuspended('enable') && me.emit('enable'); }); /** * @event disable * Fired when the disabling completes. */ this._gen.on('disable',function(){ !me.isSuspended('disable') && me.emit('disable'); }); /** * @event alreadyinstalled * Fired when a duplicate #install is attempted. */ this._gen.on('alreadyinstalled',function(){ !me.isSuspended('alreadyinstalled') && me.emit('alreadyinstalled'); }); /** * @event invalidinstallation * Fired when an invalid installation is detected. */ this._gen.on('invalidinstallation',function(){ !me.isSuspended('invalidinstallation') && me.emit('invalidinstallation'); }); /** * @event start * Fired when the #start method finishes. */ this._gen.on('start',function(){ !me.isSuspended('start') && me.emit('start'); }); /** * @event stop * Fired when the #stop method finishes. */ this._gen.on('stop',function(){ !me.isSuspended('stop') && me.emit('stop'); }); /** * @event error * Fired when an error occurs. The error is passed as a callback to the listener. */ this._gen.on('error',function(err){ !me.isSuspended('error') && me.emit('error',err); }); /** * @event doesnotexist * Fired when an attempt to uninstall the service fails because it does not exist. */ this._gen.on('doesnotexist',function(err){ !me.isSuspended('doesnotexist') && me.emit('doesnotexist'); }); } }, /** * @method install * Install the script as a background process/daemon. * @param {Function} [callback] */ install: { enumerable: true, writable: true, configurable: false, value: function(callback){ // Generate the content this.generator.createProcess(callback||function(){}); } }, /** * @method uninstall * Uninstall an existing background process/daemon. * @param {Function} [callback] * Executed when the process is uninstalled. */ uninstall: { enumerable: true, writable: true, configurable: false, value: function(callback){ var me = this; this.suspendEvent('stop'); this.stop(function(){ me.resumeEvent('stop'); me.generator.removeProcess(function(success){ callback && callback(); }); }); } }, /** * @method enable * Enable the script as a background process/daemon. * @param {Function} [callback] */ enable: { enumerable: true, writable: true, configurable: false, value: function(callback){ // Generate the content this.generator.enable(callback||function(){}); } }, /** * @method disable * Enable the script as a background process/daemon. * @param {Function} [callback] */ disable: { enumerable: true, writable: true, configurable: false, value: function(callback){ // Generate the content this.generator.disable(callback||function(){}); } }, /** * @method start * Start and/or create a daemon. * @param {Function} [callback] */ start:{ enumerable: true, writable: false, configurable: false, value: function(callback){ this.generator.start(callback); } }, /** * @method stop * Stop the process if it is currently running. * @param {Function} [callback] */ stop: { enumerable: true, writable: false, configurable: false, value: function(callback){ this.generator.stop(callback); } }, /** * @method restart * @param {Function} [callback] */ restart: { enumerable: true, writable: true, configurable: false, value: function(callback){ var me = this; this.stop(function(){ me.start(callback); }); } } }); // Do not allow invalid daemonization type if (!this.mode) { this.mode = this.defaultMode; console.log("Using default mode:", this.mode); } else { console.log("Using mode:", this.mode); } if (['systemv','systemd'].indexOf(this.mode) < 0){ console.warn("Invalid mode %s, using systemv instead", this.mode); this.mode = 'systemv'; } // Require a script tag if (!this.script){ throw new Error('Script was not provided as a configuration attribute.'); } // Generate wrapper code arguments var args = [ '-f','"'+this.script.trim()+'"', '-l','"'+this.outlog.trim()+'"', '-e','"'+this.errlog.trim()+'"', '-t','"'+this.label.trim()+'"', '-g',this.grow.toString(), '-w',this.wait.toString(), '-r',this.maxRestarts.toString(), '-a',(this.abortOnError===true?'y':'n') ]; if (this.maxRetries!==null){ args.push('-m'); args.push(this.maxRetries.toString()); } // Add environment variables for (var i=0;i<this.EnvironmentVariables.length;i++){ args.push('--env'); for (var el in this.EnvironmentVariables[i]){ args.push(el+'='+this.EnvironmentVariables[i][el]); } } // Add the CWD environment variable if requested if (this.cwd){ args.push('--env'); args.push('"'+p.resolve(this.cwd)+'"'); } // Create options var opts = {}; for(var attr in this){ if (typeof this[attr] !== 'function'){ opts[attr] = this[attr]; } } opts.name = this.label; opts.description = this.description; opts.author = this.author; opts.env = this.EnvironmentVariables; opts.usewrapper = config.usewrapper; opts.wrappercode = args.join(' '); // Create the generator this.generator = this.generator || new this.system(opts); }; var util = require('util'), EventEmitter = require('events').EventEmitter; // Inherit Events util.inherits(daemon,EventEmitter); module.exports = daemon;
import AbstractService from './AbstractService'; import SearchParameters from '../domain/SearchParameters'; import RoleService from './RoleService'; import TreeNodeService from './TreeNodeService'; /** * Automatic roles administration. * * @author Radek Tomiška */ export default class RoleTreeNodeService extends AbstractService { constructor() { super(); this.roleService = new RoleService(); this.treeNodeService = new TreeNodeService(); } getApiPath() { return '/role-tree-nodes'; } getNiceLabel(entity) { if (!entity) { return ''; } if (!entity._embedded) { if (entity.name) { return entity.name; } return entity.id; } let label = ''; if (entity._embedded.role) { label = `${ this.roleService.getNiceLabel(entity._embedded.role) }`; } if (entity._embedded.treeNode) { if (label !== '') { label += ', '; } label += `${ this.treeNodeService.getNiceLabel(entity._embedded.treeNode) }`; } if (label !== '') { label += ' - '; } label += `${ entity.name ? entity.name : entity.id }`; // return label; } supportsPatch() { return false; } supportsAuthorization() { return true; } getGroupPermission() { return 'ROLETREENODE'; } /** * Returns default searchParameters for current entity type * * @return {object} searchParameters */ getDefaultSearchParameters() { return super.getDefaultSearchParameters().setName(SearchParameters.NAME_QUICK).clearSort().setSort('name', 'asc'); } }
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest' }; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ import Echo from "laravel-echo"; window.Echo = new Echo({ broadcaster: 'pusher', key: Laravel.pusherKey, cluster: Laravel.pusherCluster, encrypted: true });
import React, { PropTypes, Component } from 'react' export default class UploadButton extends Component { static propTypes = { label: PropTypes.string, accept: PropTypes.string, onUpload: PropTypes.func } getRef = (ref) => { this.fileRef = ref } onUpload = () => this.props.onUpload(this.fileRef.files) render () { const { label, accept } = this.props return ( <label className='pt-file-upload pt-fill'> <input type='file' ref={this.getRef} onChange={this.onUpload} accept={accept} /> <span className='pt-file-upload-input'>{label}</span> </label> ) } }
(function() { var Ext = window.Ext4 || window.Ext; Ext.define('Rally.apps.kanban.Settings', { singleton: true, requires: [ 'Rally.apps.kanban.ColumnSettingsField', 'Rally.apps.common.RowSettingsField', 'Rally.ui.combobox.FieldComboBox', 'Rally.ui.CheckboxField', 'Rally.ui.plugin.FieldValidationUi' ], getFields: function(config) { var items = [ { name: 'groupByField', xtype: 'rallyfieldcombobox', model: Ext.identityFn('UserStory'), margin: '10px 0 0 0', fieldLabel: 'Columns', listeners: { select: function(combo) { this.fireEvent('fieldselected', combo.getRecord().get('fieldDefinition')); }, ready: function(combo) { combo.store.filterBy(function(record) { var attr = record.get('fieldDefinition').attributeDefinition; return attr && !attr.ReadOnly && attr.Constrained && attr.AttributeType !== 'OBJECT' && attr.AttributeType !== 'COLLECTION'; }); if (combo.getRecord()) { this.fireEvent('fieldselected', combo.getRecord().get('fieldDefinition')); } } }, bubbleEvents: ['fieldselected', 'fieldready'] }, { name: 'columns', readyEvent: 'ready', fieldLabel: '', margin: '5px 0 0 80px', xtype: 'kanbancolumnsettingsfield', shouldShowColumnLevelFieldPicker: config.shouldShowColumnLevelFieldPicker, defaultCardFields: config.defaultCardFields, handlesEvents: { fieldselected: function(field) { this.refreshWithNewField(field); } }, listeners: { ready: function() { this.fireEvent('columnsettingsready'); } }, bubbleEvents: 'columnsettingsready' } ]; items.push({ name: 'groupHorizontallyByField', xtype: 'rowsettingsfield', fieldLabel: 'Swimlanes', margin: '10 0 0 0', mapsToMultiplePreferenceKeys: ['showRows', 'rowsField'], readyEvent: 'ready', isAllowedFieldFn: function(field) { var attr = field.attributeDefinition; return (attr.Custom && (attr.Constrained || attr.AttributeType.toLowerCase() !== 'string') || attr.Constrained || _.contains(['boolean'], attr.AttributeType.toLowerCase())) && !_.contains(['web_link', 'text', 'date'], attr.AttributeType.toLowerCase()); }, explicitFields: [ {name: 'Sizing', value: 'PlanEstimate'} ] }); items.push( { name: 'hideReleasedCards', xtype: 'rallycheckboxfield', fieldLabel: 'Options', margin: '10 0 0 0', boxLabel: 'Hide cards in last visible column if assigned to a release' }, { type: 'cardage', config: { fieldLabel: '', margin: '5 0 10 80' } }, { type: 'query' }); return items; } }); })();
/** * @class Ext.fx.CubicBezier * @ignore */ Ext.fx.CubicBezier = { cubicBezierAtTime: function(t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; function sampleCurveX(t) { return ((ax * t + bx) * t + cx) * t; } function solve(x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } function solveCurveX(x, epsilon) { var t0, t1, t2, x2, d2, i; for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (Math.abs(x2) < epsilon) { return t2; } d2 = (3 * ax * t2 + 2 * bx) * t2 + cx; if (Math.abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } t0 = 0; t1 = 1; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2); if (Math.abs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) / 2 + t0; } return t2; } return solve(t, 1 / (200 * duration)); }, cubicBezier: function(x1, y1, x2, y2) { var fn = function(pos) { return Ext.fx.CubicBezier.cubicBezierAtTime(pos, x1, y1, x2, y2, 1); }; fn.toCSS3 = function() { return 'cubic-bezier(' + [x1, y1, x2, y2].join(',') + ')'; }; fn.reverse = function() { return Ext.fx.CubicBezier.cubicBezier(1 - x2, 1 - y2, 1 - x1, 1 - y1); }; return fn; } };
export default function validateLambdaStep(conan, context, stepDone) { const conanAwsLambda = context.parameters; if (conanAwsLambda.role() === undefined) { const error = new Error(".role() is a required parameter for a lambda."); stepDone(error); } else if (conanAwsLambda.packages() !== undefined && conan.config.bucket === undefined) { const error = new Error("conan.config.bucket is required to use .packages()."); stepDone(error); } else { stepDone(); } }
function visualize_test_case(input, output, expected, n) { document.getElementById(`input${n}`).innerHTML = `<b>Input</b>: blood type = ${input[0]} (available blood types = ${input[1]}) <br>` document.getElementById(`output${n}`).innerHTML = `<b>Output</b>: survive = ${output[0]} (expected ${expected[0]}) <br>` return }
/* @flow */ import type { L10nsStrings } from '../formatters/buildFormatter' // Swedish const strings: L10nsStrings = { prefixAgo: 'för', prefixFromNow: 'om', suffixAgo: 'sedan', suffixFromNow: '', seconds: 'mindre än en minut', minute: 'ungefär en minut', minutes: '%d minuter', hour: 'ungefär en timme', hours: 'ungefär %d timmar', day: 'en dag', days: '%d dagar', month: 'ungefär en månad', months: '%d månader', year: 'ungefär ett år', years: '%d år', } export default strings
import path from 'path'; const makeFileLoader = function(args) { switch (args) { case 'woff': return { test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' }; case 'ttf': return { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' }; case 'svg': return { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' }; case 'eot': return { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' }; case 'jpg': return { test: /\.(jpe?g|png|gif|svg)$/i, loaders: ['file?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'] }; default: return {}; } }; export const sasslint = { test: /\s[a|c]ss$/, exclude: /node_modules/, loader: 'sasslint' }; export const js = { test: /\.js/, exclude: /node_modules/, loader: 'babel' }; export const scss = { test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader' }; export const css = { test: /\.css$/, loader: 'style-loader!css-loader' }; export const svgLoader = makeFileLoader('svg'); export const eotLoader = makeFileLoader('eot'); export const woffLoader = makeFileLoader('woff'); export const ttfLoader = makeFileLoader('ttf'); export const jpgLoader = makeFileLoader('jpg'); export const loaders = [ scss, js, css, svgLoader, eotLoader, woffLoader, ttfLoader, jpgLoader ];
import { setOnerror, getOnerror, run } from 'ember-metal'; import RSVP from '../../ext/rsvp'; import { isTesting, setTesting } from 'ember-debug'; const ORIGINAL_ONERROR = getOnerror(); QUnit.module('Ember.RSVP', { teardown() { setOnerror(ORIGINAL_ONERROR); } }); QUnit.test('Ensure that errors thrown from within a promise are sent to the console', function() { let error = new Error('Error thrown in a promise for testing purposes.'); try { run(function() { new RSVP.Promise(function(resolve, reject) { throw error; }); }); ok(false, 'expected assertion to be thrown'); } catch (e) { equal(e, error, 'error was re-thrown'); } }); QUnit.test('TransitionAborted errors are not re-thrown', function() { expect(1); let fakeTransitionAbort = { name: 'TransitionAborted' }; run(RSVP, 'reject', fakeTransitionAbort); ok(true, 'did not throw an error when dealing with TransitionAborted'); }); QUnit.test('Can reject with non-Error object', function(assert) { let wasEmberTesting = isTesting(); setTesting(false); expect(1); try { run(RSVP, 'reject', 'foo'); } catch (e) { equal(e, 'foo', 'should throw with rejection message'); } finally { setTesting(wasEmberTesting); } }); QUnit.test('Can reject with no arguments', function(assert) { let wasEmberTesting = isTesting(); setTesting(false); expect(1); try { run(RSVP, 'reject'); } catch (e) { ok(false, 'should not throw'); } finally { setTesting(wasEmberTesting); } ok(true); }); QUnit.test('rejections like jqXHR which have errorThrown property work', function() { expect(2); let wasEmberTesting = isTesting(); let wasOnError = getOnerror(); try { setTesting(false); setOnerror(error => { equal(error, actualError, 'expected the real error on the jqXHR'); equal(error.__reason_with_error_thrown__, jqXHR, 'also retains a helpful reference to the rejection reason'); }); let actualError = new Error('OMG what really happened'); let jqXHR = { errorThrown: actualError }; run(RSVP, 'reject', jqXHR); } finally { setOnerror(wasOnError); setTesting(wasEmberTesting); } }); QUnit.test('rejections where the errorThrown is a string should wrap the sting in an error object', function() { expect(2); let wasEmberTesting = isTesting(); let wasOnError = getOnerror(); try { setTesting(false); setOnerror(error => { equal(error.message, actualError, 'expected the real error on the jqXHR'); equal(error.__reason_with_error_thrown__, jqXHR, 'also retains a helpful reference to the rejection reason'); }); let actualError = 'OMG what really happened'; let jqXHR = { errorThrown: actualError }; run(RSVP, 'reject', jqXHR); } finally { setOnerror(wasOnError); setTesting(wasEmberTesting); } }); QUnit.test('rejections can be serialized to JSON', function (assert) { expect(2); let wasEmberTesting = isTesting(); let wasOnError = getOnerror(); try { setTesting(false); setOnerror(error => { assert.equal(error.message, 'a fail'); assert.ok(JSON.stringify(error), 'Error can be serialized'); }); let jqXHR = { errorThrown: new Error('a fail') }; run(RSVP, 'reject', jqXHR); } finally { setOnerror(wasOnError); setTesting(wasEmberTesting); } }); const reason = 'i failed'; QUnit.module('Ember.test: rejection assertions'); function ajax(something) { return RSVP.Promise(function(resolve) { QUnit.stop(); setTimeout(function() { QUnit.start(); resolve(); }, 0); // fake true / foreign async }); } QUnit.test('unambigiously unhandled rejection', function() { QUnit.throws(function() { run(function() { RSVP.Promise.reject(reason); }); // something is funky, we should likely assert }, reason); }); QUnit.test('sync handled', function() { run(function() { RSVP.Promise.reject(reason).catch(function() { }); }); // handled, we shouldn't need to assert. ok(true, 'reached end of test'); }); QUnit.test('handled within the same micro-task (via Ember.RVP.Promise)', function() { run(function() { let rejection = RSVP.Promise.reject(reason); RSVP.Promise.resolve(1).then(() => rejection.catch(function() { })); }); // handled, we shouldn't need to assert. ok(true, 'reached end of test'); }); QUnit.test('handled within the same micro-task (via direct run-loop)', function() { run(function() { let rejection = RSVP.Promise.reject(reason); run.schedule('afterRender', () => rejection.catch(function() { })); }); // handled, we shouldn't need to assert. ok(true, 'reached end of test'); }); QUnit.test('handled in the next microTask queue flush (run.next)', function() { expect(2); QUnit.throws(function() { run(function() { let rejection = RSVP.Promise.reject(reason); QUnit.stop(); run.next(() => { QUnit.start(); rejection.catch(function() { }); ok(true, 'reached end of test'); }); }); }, reason); // a promise rejection survived a full flush of the run-loop without being handled // this is very likely an issue. }); QUnit.test('handled in the same microTask Queue flush do to data locality', function() { // an ambiguous scenario, this may or may not assert // it depends on the locality of `user#1` let store = { find() { return RSVP.Promise.resolve(1); } }; run(function() { let rejection = RSVP.Promise.reject(reason); store.find('user', 1).then(() => rejection.catch(function() { })); }); ok(true, 'reached end of test'); }); QUnit.test('handled in a different microTask Queue flush do to data locality', function() { // an ambiguous scenario, this may or may not assert // it depends on the locality of `user#1` let store = { find() { return ajax(); } }; QUnit.throws(function() { run(function() { let rejection = RSVP.Promise.reject(reason); store.find('user', 1).then(() => { rejection.catch(function() { }); ok(true, 'reached end of test'); }); }); }, reason); }); QUnit.test('handled in the next microTask queue flush (ajax example)', function() { QUnit.throws(function() { run(function() { let rejection = RSVP.Promise.reject(reason); ajax('/something/').then(() => { rejection.catch(function() {}); ok(true, 'reached end of test'); }); }); }, reason); });
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var uriUtil = require('mongodb-uri'); var Contato = require('./app/models/contatos'); var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }, replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } }; var mongodbUri = 'mongodb://betovieira:[email protected]:27835/heroku_prx51dxr'; var mongooseUri = uriUtil.formatMongoose(mongodbUri); mongoose.connect(mongooseUri, options, function(err) { if (err) { console.log('Erro ao conectar com mongodb: ' + err); } }); /*Conexão com mongodb mongoose.connect('mongodb://heroku_prx51dxr:[email protected]:27835/heroku_prx51dxr', function(err) { if (err) { console.log('Erro ao conectar com mongodb: ' + err); } });*/ app.use(bodyParser()); var port = process.env.PORT || 8080; var router = express.Router(); // Rotas da api router.get('/', function(req, res){ res.json( {message : 'Enviei uma mensagem legal!'} ); }); //Configurando rotas legais! router.route('/contatos') .get(function(req, res){ Contato.find(function(err, rows) { if (err) { res.send('Erro: ' + err); } res.json(rows); }); }) .post(function(req, res){ var model = new Contato(); model.nome = req.body.nome; model.save(function(err) { if (err) { res.send(err); } res.json( { message: 'Cadastrado com suceso!' } ); }); }); router.route('/contatos/:id') .get(function(req, res){ Contato.findById(req.params.id, function(err, row) { if(err) { res.send(err); } res.json(row); }); }) .put(function(req, res){ Contato.findById(req.params.id, function(err, row){ if (err) { res.send(err); } row.nome = req.body.nome; row.save(function(err){ if (err) { res.send(err); } res.json( { message : 'Contato alterado com sucesso!' } ); }); }); }) .delete(function(req,res){ Contato.remove( { _id : req.params.id }, function(err, row) { if (err) { res.send(err); } res.json( {message : 'Contato excluído com sucesso! ' }); }); }); //Registrando nas rotas app.use('/api', router); // Inicia o servidor app.listen(port, function(){ console.log('SERVIDOR RODANDO NA PORTA: ' + port); });
"use strict"; import "whatwg-fetch"; import {uploadLogs} from "./upload"; import {renderLog} from "./components/Log"; document.addEventListener("DOMContentLoaded", () => { const nodes = document.querySelectorAll("a[data-method]"); for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; const method = node.attributes.getNamedItem("data-method").value; node.appendChild(createForm(node.href, method)); node.addEventListener("click", (event) => { event.preventDefault(); const a = event.target; const form = a.querySelector("form"); form.submit(); }); } }); function createForm(href, method) { const form = document.createElement("form"); form.method = "POST"; form.action = href; form.style = "display: none;" const methodField = document.createElement("input"); methodField.type = "hidden"; methodField.name = "_method"; methodField.value = method.toUpperCase(); form.appendChild(methodField); const csrfField = document.createElement("input"); csrfField.type = "hidden"; csrfField.name = "_csrf"; csrfField.value = Tracklog.csrfToken; form.appendChild(csrfField); return form; } document.addEventListener("DOMContentLoaded", () => { const nodes = document.querySelectorAll("form"); for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; node.addEventListener("submit", (event) => { const form = event.target; const csrfField = document.createElement("input"); csrfField.type = "hidden"; csrfField.name = "_csrf"; csrfField.value = Tracklog.csrfToken; form.appendChild(csrfField); }); } }); document.addEventListener("DOMContentLoaded", () => { const nodes = document.querySelectorAll(".logs-upload-button"); for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; const changeButton = ({textAttribute, disabled}) => { node.textContent = node.attributes.getNamedItem(textAttribute).value; node.disabled = disabled; }; node.addEventListener("click", () => { const fileInput = node.nextElementSibling; fileInput.addEventListener("change", (event) => { const input = event.target; const files = input.files; let filesArray = []; for (let i = 0; i < files.length; i++) { filesArray.push(files[i]); } uploadLogs({ files: filesArray, }) .then((results) => { changeButton({ textAttribute: "data-text-upload", disabled: false, }); if (results.length == 1) { const id = results[0].id; window.location = `/logs/${id}`; } else { window.location = "/logs"; } }) .catch((err) => { changeButton({ textAttribute: "data-text-upload", disabled: false, }); alert(err); }); changeButton({ textAttribute: "data-text-uploading", disabled: true, }); }); fileInput.click(); }); } }); window.Tracklog = { renderLog: renderLog, };
define(['jQuery', 'skeleton', './Word', './WordView'], function($, sk, Word, WordView) { var keycodeToReviews = { 49: 30, //Number 1 in keyboard 50: 20, //Number 2 in keyboard 51: 10, //Number 3 in keyboard 52: 0 //Number 4 in keyboard }; var WorkbenchView = sk.View.extend({ vid: 'workbench', templateName: 'workbench', events: { }, configure: function(){ this.listenTo(this.model, 'change:wordId', this.changeWordView, this); this.listenTo(this.model, 'reset', this.resetWordView, this); }, changeWordView: function(model, value, options) { this.removeLastWordView(); if(value){ this.addWordView(value); } }, addWordView: function(wordId){ var word = new Word({id: wordId}); word.fetched = true; var wordView = new WordView({ model: word, renderPlacing: false, prerendered: false }); this.addChild(wordView); word.fetch({ error: function(model, response, options){ console.error(response); }, success: function(model, response, options){ // console.info(model); } }); }, removeLastWordView: function(){ var childView = this.getChild('word-detail'); if(childView){ this.removeChild('word-detail'); childView.destroy(); } }, renderContent: function(){ var childView = this.getChild('word-detail'); if(childView){ childView.doRender(); this.renderChild(childView); } }, resetWordView: function(){ this.removeLastWordView(); }, toReviewWord: function(cmd){ var reviewValue = keycodeToReviews[cmd]; var wordView = this.getChild('word-detail'); if(wordView){ wordView.model.updateReview(reviewValue); } }, afterRender: function() { var me = this; $(document.body).keydown(function(e){ if(e.keyCode==33){ me.model.pageAction(false); } else if(e.keyCode==34){ me.model.pageAction(true); } else if(e.keyCode>=49 && e.keyCode<=52){ me.toReviewWord(e.keyCode); } else{ console.info('key code: ' + e.keyCode); } }); } }); return WorkbenchView; });
import React from 'react'; import ReactDOM, { findDOMNode } from 'react-dom'; import Calendar from '../CalendarPanel'; import { createTestContainer, getDOMNode, getStyle, getDefaultPalette, toRGB, itChrome, inChrome } from '@test/testUtils'; import '../styles/index'; const { H500, H700 } = getDefaultPalette(); describe('Calendar styles', () => { it('MonthToolbar should render correct styles', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar ref={instanceRef} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const monthToolbarDom = dom.querySelector('.rs-calendar-header-month-toolbar'); assert.equal(getStyle(monthToolbarDom, 'float'), 'left'); assert.equal(getStyle(monthToolbarDom, 'display'), 'block'); assert.equal(getStyle(monthToolbarDom, 'textAlign'), 'center'); }); it('TodayButton should render correct styles', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar ref={instanceRef} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const todayButtonDom = dom.querySelector('.rs-calendar-btn-today'); assert.equal(getStyle(todayButtonDom, 'backgroundColor'), toRGB('#f7f7fa')); inChrome && assert.equal(getStyle(todayButtonDom, 'padding'), '8px 12px'); }); it('Selected item should render correct styles', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar ref={instanceRef} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const selectedDom = dom.querySelector( '.rs-calendar-table-cell-selected .rs-calendar-table-cell-content' ); const contentDom = selectedDom.children[0]; inChrome && assert.equal(getStyle(selectedDom, 'borderColor'), H500, 'Selected item border-color'); assert.equal(getStyle(contentDom, 'backgroundColor'), H500, 'Selected item background-color'); assert.equal(getStyle(contentDom, 'color'), toRGB('#fff'), 'Selected item color'); }); it('Click date title button should render correct styles', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar ref={instanceRef} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const dateTitleDom = dom.querySelector('.rs-calendar-header-title-date'); dateTitleDom.click(); const headerBackward = dom.querySelector('.rs-calendar-header-backward'); const headerForward = dom.querySelector('.rs-calendar-header-backward'); const monthDropDown = dom.querySelector('.rs-calendar-month-dropdown'); const yearActiveDom = dom.querySelector('.rs-calendar-month-dropdown-year-active'); const dropdownActiveCellDom = dom.querySelector( '.rs-calendar-month-dropdown-cell-active .rs-calendar-month-dropdown-cell-content' ); assert.equal( getStyle(headerBackward, 'visibility'), 'hidden', 'Header backward button visibility' ); assert.equal( getStyle(headerForward, 'visibility'), 'hidden', 'Header forward button visibility' ); assert.equal(getStyle(monthDropDown, 'display'), 'block', 'MonthDropDown button display'); assert.equal(getStyle(yearActiveDom, 'color'), H700, 'Active year dom font-color'); assert.equal( getStyle(dropdownActiveCellDom, 'color'), toRGB('#fff'), 'DropdownActiveCellDom color' ); inChrome && assert.equal( getStyle(dropdownActiveCellDom, 'borderColor'), H500, 'DropdownActiveCellDom border-color' ); assert.equal( getStyle(dropdownActiveCellDom, 'backgroundColor'), H500, 'DropdownActiveCellDom background-color' ); }); itChrome('Should be bordered on cell', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar bordered ref={instanceRef} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const tableCellDom = dom.querySelector('.rs-calendar-table-cell'); assert.equal( getStyle(tableCellDom, 'borderBottom'), `1px solid ${toRGB('#f2f2f5')}`, 'TableCellDom border' ); }); itChrome('Should be bordered on month row', () => { const instanceRef = React.createRef(); ReactDOM.render( <Calendar calendarState={'DROP_MONTH'} bordered ref={instanceRef} />, createTestContainer() ); const dom = getDOMNode(instanceRef.current); const dropdownRowDom = dom.querySelector('.rs-calendar-month-dropdown-row'); assert.equal( getStyle(dropdownRowDom, 'borderBottom'), `1px dotted ${toRGB('#e5e5ea')}`, 'DropdownRow border' ); }); it('Should render compact calendar', () => { const instanceRef = React.createRef(); ReactDOM.render(<Calendar compact ref={instanceRef} />, createTestContainer()); const tableCellContentDom = getDOMNode(instanceRef.current).querySelector( '.rs-calendar-table-row:not(.rs-calendar-table-header-row) .rs-calendar-table-cell-content' ); assert.equal(getStyle(tableCellContentDom, 'height'), '50px'); }); });
"use strict"; var _ = require('lodash'); var expect = require('expect.js'); var Promises = require('best-promise'); var fs = require('fs-promise'); var expectCalled = require('expect-called'); var autoDeploy = require('../auto-deploy.js'); var assert = require('assert'); describe('auto-deploy', function(){ throw new Error("Not implemented yet"); describe('initialization', function(){ it.skip('must set autoDeploy vars', function(done){ done(); }); }); });
/* global define */ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'buses/event-bus' ], function ($, _, Backbone, Marionette, EventBus) { 'use strict'; var Heartbeat = Backbone.Marionette.Controller.extend({ initialize: function () { $(document).on('heartbeat-tick', this.heartbeatTick.bind(this)); }, heartbeatTick: function (e, data) { var heartbeat = data.b3.live, keys = _.keys(heartbeat); // console.log(data); _.each(keys, function (key) { if (!_.isEmpty(heartbeat[key])) { EventBus.trigger(key, heartbeat[key]); } }); } }); return Heartbeat; });
/* ************************************************************************ */ /* This portion is a child of the search component. It renders the search results. */ var React = require('react'); // Helper for making AJAX requests to our API var helpers = require("./utils/helpers"); var Result = React.createClass({ getInitialState: function() { console.log('RESULT - getInitialState'); return {items: [], count: null} }, componentWillReceiveProps: function(nextProps) { console.log('RESULT - componentWillReceiveProps') if(nextProps.count === 0) this.clearArticles() }, render: function() { return( <div className="row"> <div className="col-sm-12"> <br /> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title"><strong><i className="fa fa-table"></i> Top Articles</strong></h3> </div> {this.renderArticles(this.props.items, this.props.count)} </div> </div> </div> ) }, handleSave: function(article, e) { helpers.saveArticle(article) }, renderArticles: function(items, count) { var articles = items.map(function(article) { var id = 'articleWell-' + article.tagCounter var numberStyle = {margin: "5px"}; return ( <div className="well" id={id} key={article.tagCounter}> <h3><span className="label label-info" style={numberStyle}>{article.tagCounter}</span><strong>{article.headline}</strong></h3> <br /> <h5>{article.byline}</h5> <h5>{article.sectionName}</h5> <h5>{article.pubDate}</h5> <a target="_blank" href={article.webURL}>{article.webURL}</a> <br /> <br /> <form role="form"> <button type="button" className="btn btn-success" id="runSave" onClick={this.handleSave.bind(this, article)}>Save</button> </form> </div> ) }.bind(this)); return ( <div className="panel-body" id="wellSection"> {articles} </div> ) }, clearArticles: function() { return( <div className="row"> <div className="col-sm-12"> <br /> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title"><strong><i className="fa fa-table"></i> Top Articles</strong></h3> </div> <div className="panel-body" id="wellSection"> </div> </div> </div> </div> ) } }); module.exports = Result;
(function () { require({ baseUrl: './content/' }, ['dojo/parser', 'jquery', 'dojo/domReady!'], function (parser) { parser.parse(); }); }());
var gulp = require('gulp'), concat = require('gulp-concat'), sourcemaps = require('gulp-sourcemaps'), minifyCSS = require('gulp-minify-css'), uglify = require('gulp-uglify'), babel = require("gulp-babel"); var paths = { babel: ['src/PodPicker.babel.js'], js : ['dist/PodPicker.js'], css : ['dist/PodPicker.css'] }; // ES6 gulp.task("es6", function () { return gulp.src(paths.babel) .pipe(babel()) .pipe(concat('PodPicker.js')) .pipe(gulp.dest("dist")); }); // Minify JavaScript gulp.task('js', function() { return gulp.src(paths.js) .pipe(sourcemaps.init()) .pipe(uglify({preserveComments: 'some'})) .pipe(concat('PodPicker.min.js')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); // Minify CSS gulp.task('css', function () { return gulp.src(paths.css) .pipe(sourcemaps.init()) .pipe(minifyCSS({keepSpecialComments: 1})) .pipe(concat('PodPicker.min.css')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')) }) // Rerun the task when a file changes gulp.task('watch', function() { gulp.watch(paths.babel, ['es6']) gulp.watch(paths.js, ['js']); gulp.watch(paths.css, ['css']); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['watch', 'es6' , 'js', 'css']);
module.exports = { Botact: require('./lib'), api: require('./lib/api'), compose: require('./lib/compose') }
'use strict'; module['exports'] = { silly: 'rainbow', input: 'grey', verbose: 'cyan', prompt: 'grey', info: 'green', data: 'grey', help: 'cyan', warn: 'yellow', debug: 'blue', error: 'red' }; //# sourceMappingURL=generic-logging-compiled.js.map
/** * @file Scnt_item.js */ /*** initialize ***/ $(function(){ try { Fcnt_itemMenu(); Fcnt_itemConts(); } catch ( e ) { alert( e.stack ); } }); /*** define ***/ var DCNT_ITMCNTID_TTL = "i-itm-ttl"; var DCNT_ITMCNTID_TAG = "i-itm-tag"; var DCNT_ITMCNTID_DAT = "i-itm-dat"; /*** function ***/ function Fcnt_itemMenu() { try { $("#i-cnt-itm").append("<div id='i-itm-mnu'></div>"); $("#i-cnt-itm").append("<div id='i-itm-bar'><i class='fa fa-bars'></i></div>"); $("#i-itm-bar").css( "width" , "32px" ); $("#i-itm-bar").css( "font-size" , "2.3em" ); $("#i-itm-bar").css( "margin" , "5px 0px 0px 10px" ); $("#i-itm-bar").css( "cursor" , "pointer" ); Fcom_loadJs( [ "./src/js/slidemenu", "./src/js/ujarakbtn" ] , function() { try { Fsdm_init("i-itm-mnu"); Fcnt_itemMenuConts(); $( "#i-itm-mnu" ).css( "background" , "rgb(199, 224, 240)" ); Fsdm_setTop( "i-itm-mnu" , 69 ); Fsdm_setWidth( "i-itm-mnu" , 200 ); $("#i-itm-bar").click(function(){ Fsdm_open( "i-itm-mnu" ); }); } catch(e) { alert(e.stack); } } ); } catch ( e ) { alert( e.stack ); } } function Fcnt_itemMenuConts() { try { /* new button */ $("#i-itm-mnu").append( "<div id='i-itmmnu-new'></div>" ); Fujb_init( "i-itmmnu-new" , "New" ); Fujb_setClickEvent( "i-itmmnu-new" , function(){ Fcom_loadJs( ["./src/js/itmmnu"] , function() { try { Fitm_clickNew(); } catch(e) { alert(e.stack); } } ); }); $("#i-itmmnu-new").css( "margin" , "20px 23px 40px 23px" ); Fujb_start( "i-itmmnu-new" ); $("#i-itm-mnu").append( "<div id='i-itmmnu-ttl'></div>" ); Fujb_init( "i-itmmnu-ttl" , "Title" ); Fujb_setCss( "i-itmmnu-ttl" , "min-width" , "199px" ); Fujb_setCss( "i-itmmnu-ttl" , "background" , "rgb(199, 224, 240)" ); //Fujb_setClickEvent( "i-itmmnu-ttl" , function(){ // try { // Fcom_loadJs( // ["./front/get/js?tgt-itemevt"] , // function() { // try { // Sitm_clickView(DITM_VEWTYPE_TITLE); // Fsdm_close( "i-itm-mnu" ); // } catch (e) {alert(e.stack);} // } // ); // }catch(e){ alert( e.stack ); } //}); Fujb_start( "i-itmmnu-ttl" ); $("#i-itm-mnu").append( "<div id='i-itmmnu-tag'></div>" ); Fujb_init( "i-itmmnu-tag" , "Tag" ); Fujb_setCss( "i-itmmnu-tag" , "min-width" , "199px" ); Fujb_setCss( "i-itmmnu-tag" , "background" , "rgb(199, 224, 240)" ); Fujb_setRelaPosi( "i-itmmnu-tag" , "top" , "-1px" ); //Fujb_setClickEvent( "i-itmmnu-tag" , function(){ //try { // Fcom_loadJs( // ["./src/js/itemevt"] , // function() { // try { // Sitm_clickView(DITM_VEWTYPE_TAG); // Fsdm_close( "i-itm-mnu" ); // } catch (e) {alert(e.stack);} // } // ); //}catch(e){ alert( e.stack ); } //}); Fujb_start( "i-itmmnu-tag" ); $("#i-itm-mnu").append( "<div id='i-itmmnu-date'></div>" ); Fujb_init( "i-itmmnu-date" , "Date" ); Fujb_setCss( "i-itmmnu-date" , "min-width" , "199px" ); Fujb_setCss( "i-itmmnu-date" , "background" , "rgb(199, 224, 240)" ); Fujb_setRelaPosi( "i-itmmnu-date" , "top" , "-2px" ); //Fujb_setClickEvent( "i-itmmnu-date" , function(){ //try { // Fcom_loadJs( // ["./src/js/itemevt"] , // function() { // try { // Sitm_clickView(DITM_VEWTYPE_DATE); // Fsdm_close( "i-itm-mnu" ); // } catch (e) {alert(e.stack);} // } // ); //}catch(e){ alert( e.stack ); } //}); Fujb_start( "i-itmmnu-date" ); } catch ( e ) { alert( e.stack ); } } function Fcnt_itemConts() { try { $("#i-cnt-itm").append("<div id='i-itm'></div>"); $("#i-itm").append("<div id='i-itm-ttl'></div>"); $("#i-itm").append("<div id='i-itm-tag'></div>"); $("#i-itm").append("<div id='i-itm-dat'></div>"); $("#i-itm-ttl").css( "display" , "block" ); $("#i-itm-tag").css( "display" , "none" ); $("#i-itm-dat").css( "display" , "none" ); Fcom_loadJs( ["./src/js/evt_itmttl"] , function() { try { Fcom_endLoad( DINI_LOAD_CNT ); } catch (e) {alert(e.stack);} } ); } catch ( e ) { alert( e.stack ); } } /* end of file */
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _request = require('../request'); var _request2 = _interopRequireDefault(_request); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (Request) { var options = { uri: 'forms', method: 'POST' }; form.get = get; return { form: form }; function form(title, fields) { var extra = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (typeof title !== 'string' || !fields) throw new Error('Required parameters missing'); var body = { title: title, fields: fields }; Object.assign(body, extra); return Request(Object.assign({}, { body: body }, options)); } function get(id) { if (typeof id !== 'string') throw new Error('Id parameters missing or not a string'); var options = { uri: 'forms/' + id, method: 'GET' }; return Request(options); } }; /** * @author Alvaro Martinez de Miguel (Demi) [[email protected]] */
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/ustodo', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
(function () { 'use strict'; angular.module('utils.fileSaver', []) .factory('fileSaver', fileSaver); fileSaver.$inject = []; /* @ngInject */ function fileSaver() { return function (blob, filename) { saveAs(blob, filename); }; } })();
// Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with index 1 should return Node(13); "use strict"; function Node(data) { this.data = data; this.next = null; } Node.prototype = { [Symbol.iterator]() { let current = this; return { next() { if (!current) { return { done: true }; } else { let returnNode = current; current = current.next; return { value: returnNode }; } } }; } }; function getNth(nodeList, index) { if (!nodeList) { throw 'Null linked list should throw error.'; } let currentIndex = 0; let nthNode = null; for (node of nodeList) { if (currentIndex === index) { nthNode = node; } currentIndex++; } if (!nthNode) { throw 'Invalid index value should throw error.'; } else { return nthNode; } }
var debug = require('debug')('object-prototoype'); var test = require('tape'); test('### Object.create() ###', function(t) { t.throws(Object.create, TypeError, 'Object.create could only be invoked with null or obj that plays prototype role'); t.end(); }); test('### Object.create(null) ###', function(t) { var v = Object.create(null); t.notOk(Object.getPrototypeOf(v), "the created object has not prototype"); t.end(); }); test('### Object.create(prototype) ###', function(t) { var obj = { prop: "test" } var v = Object.create(obj); t.deepEqual(obj, v.__proto__, "The Object.create() method creates a new object with the specified prototype object and properties."); t.deepEqual(obj, Object.getPrototypeOf(v), "Or use the better way of taking the object's prototype"); t.end(); });
'use strict'; // Use local.env.js for environment variables that grunt will set when the server starts locally. // Use for your api keys, secrets, etc. This file should not be tracked by git. // // You will need to set these on the server you deploy to. module.exports = { DOMAIN: 'http://localhost:9000', SESSION_SECRET: 'budget-secret', FACEBOOK_ID: 'app-id', FACEBOOK_SECRET: 'secret', TWITTER_ID: 'app-id', TWITTER_SECRET: 'secret', GOOGLE_ID: 'app-id', GOOGLE_SECRET: 'secret', // Control debug level for modules using visionmedia/debug DEBUG: '' };
var searchData= [ ['dynamicalsystem_2ehpp',['dynamicalSystem.hpp',['../dynamicalSystem_8hpp.html',1,'']]] ];
import { collection, clickable, create, text } from 'ember-cli-page-object'; const definition = { scope: '[data-test-collapsed-taxonomies]', title: text('[data-test-title]'), expand: clickable('[data-test-title]'), headers: collection('thead th', { title: text(), }), vocabularies: collection('tbody tr', { name: text('td', { at: 0 }), school: text('td', { at: 1 }), terms: text('td', { at: 2 }), }), }; export default definition; export const component = create(definition);
"use strict"; var _chalk = require('chalk'); // Always enable colors, even if not auto-detected var chalk = new _chalk.constructor({ enabled: true }); /** * Identity function for tokens that should not be styled (returns the input string as-is). * See [[Theme]] for an example. */ exports.plain = function (codePart) { return codePart; }; /** * The default theme. It is possible to override just individual keys. */ exports.DEFAULT_THEME = { /** * keyword in a regular Algol-style language */ keyword: chalk.blue, /** * built-in or library object (constant, class, function) */ built_in: chalk.cyan, /** * user-defined type in a language with first-class syntactically significant types, like * Haskell */ type: chalk.cyan.dim, /** * special identifier for a built-in value ("true", "false", "null") */ literal: chalk.blue, /** * number, including units and modifiers, if any. */ number: chalk.green, /** * literal regular expression */ regexp: chalk.red, /** * literal string, character */ string: chalk.red, /** * parsed section inside a literal string */ subst: exports.plain, /** * symbolic constant, interned string, goto label */ symbol: exports.plain, /** * class or class-level declaration (interfaces, traits, modules, etc) */ class: chalk.blue, /** * function or method declaration */ function: chalk.yellow, /** * name of a class or a function at the place of declaration */ title: exports.plain, /** * block of function arguments (parameters) at the place of declaration */ params: exports.plain, /** * comment */ comment: chalk.green, /** * documentation markup within comments */ doctag: chalk.green, /** * flags, modifiers, annotations, processing instructions, preprocessor directive, etc */ meta: chalk.grey, /** * keyword or built-in within meta construct */ 'meta-keyword': exports.plain, /** * string within meta construct */ 'meta-string': exports.plain, /** * heading of a section in a config file, heading in text markup */ section: exports.plain, /** * XML/HTML tag */ tag: chalk.grey, /** * name of an XML tag, the first word in an s-expression */ name: chalk.blue, /** * s-expression name from the language standard library */ 'builtin-name': exports.plain, /** * name of an attribute with no language defined semantics (keys in JSON, setting names in * .ini), also sub-attribute within another highlighted object, like XML tag */ attr: chalk.cyan, /** * name of an attribute followed by a structured value part, like CSS properties */ attribute: exports.plain, /** * variable in a config or a template file, environment var expansion in a script */ variable: exports.plain, /** * list item bullet in text markup */ bullet: exports.plain, /** * code block in text markup */ code: exports.plain, /** * emphasis in text markup */ emphasis: chalk.italic, /** * strong emphasis in text markup */ strong: chalk.bold, /** * mathematical formula in text markup */ formula: exports.plain, /** * hyperlink in text markup */ link: chalk.underline, /** * quotation in text markup */ quote: exports.plain, /** * tag selector in CSS */ 'selector-tag': exports.plain, /** * #id selector in CSS */ 'selector-id': exports.plain, /** * .class selector in CSS */ 'selector-class': exports.plain, /** * [attr] selector in CSS */ 'selector-attr': exports.plain, /** * :pseudo selector in CSS */ 'selector-pseudo': exports.plain, /** * tag of a template language */ 'template-tag': exports.plain, /** * variable in a template language */ 'template-variable': exports.plain, /** * added or changed line in a diff */ addition: chalk.green, /** * deleted line in a diff */ deletion: chalk.red }; /** * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. */ function fromJson(json) { var theme = {}; for (var key in json) { var style = json[key]; if (Array.isArray(style)) { theme[key] = style.reduce(function (prev, curr) { return curr === 'plain' ? exports.plain : prev[curr]; }, chalk); } else { theme[key] = chalk[style]; } } return theme; } exports.fromJson = fromJson; /** * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. */ function toJson(theme) { var jsonTheme = {}; for (var key in jsonTheme) { var style = jsonTheme[key]; jsonTheme[key] = style._styles; } return jsonTheme; } exports.toJson = toJson; /** * Stringifies a [[Theme]] with formatter functions to a JSON string. * * ```ts * import chalk = require('chalk'); * import {stringify} from 'cli-highlight'; * import * as fs from 'fs'; * * const myTheme: Theme = { * keyword: chalk.red.bold, * addition: chalk.green, * deletion: chalk.red.strikethrough, * number: plain * } * const json = stringify(myTheme); * fs.writeFile('mytheme.json', json, (err: any) => { * if (err) throw err; * console.log('Theme saved'); * }); * ``` */ function stringify(theme) { return JSON.stringify(toJson(theme)); } exports.stringify = stringify; /** * Parses a JSON string into a [[Theme]] with formatter functions. * * ```ts * import * as fs from 'fs'; * import {parse, highlight} from 'cli-highlight'; * * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { * if (err) throw err; * const code = highlight('SELECT * FROM table', {theme: parse(json)}); * console.log(code); * }); * ``` */ function parse(json) { return fromJson(JSON.parse(json)); } exports.parse = parse; //# sourceMappingURL=theme.js.map
/** * This is an enormous cube, and the viewer * resides in the interior. */ function Cagebox() { // First, create an enormous cube const size = 500; this.o = new SixSidedPrism( [-size, size, size], [-size,-size, size], [ size,-size, size], [ size, size, size], [-size, size,-size], [-size,-size,-size], [ size,-size,-size], [ size, size,-size]) // Next, set it to 6 images of Nicolas Cage's face .setSixTextures( SKYBOX_TEXTURE_1, SKYBOX_TEXTURE_2, SKYBOX_TEXTURE_3, SKYBOX_TEXTURE_4, SKYBOX_TEXTURE_5, SKYBOX_TEXTURE_0); } Cagebox.prototype.initBuffers = _oInitBuffers; Cagebox.prototype.draw = _oDraw;
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import {XYPlot, XAxis, YAxis, VerticalGridLines, LineSeries} from '../../'; export default class Example extends React.Component { render() { return ( <XYPlot width={300} height={300}> <VerticalGridLines values={[2, 2.3, 2.7]} /> <XAxis /> <YAxis /> <LineSeries data={[ {x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 15} ]}/> </XYPlot> ); } }
var documents = require('../documents.json') var expected = require('../data/idf-stem-rank-facets.json') var options = { idf: true, stem: true, rank: true, facets: true } var inverted = process.env.INVERTED_COV ? require('../../lib-cov/inverted-index') : require('../../') var timehat = require('timehat') var level = require('level')(__dirname + '/../dbs/db-' + timehat()) var async = require('async') var assert = require('assert') var text = inverted(level, options) var index = function(fn){ async.forEach(Object.keys(documents), function(id, fn){ text.index(documents[id].text, id, documents[id].facets, fn) }, fn) } var getAllKeys = function(fn){ var keys = [] level.createKeyStream() .on('error', fn) .on('data', function(key){ keys.push([key, text.parseKey(key, true)]) }) .on('end', function(){ fn(null, keys) }) } module.exports = function(){ before(index) after(function(fn){ level.close(function(err){ fn(err) }) }) describe('index', function(){ it('should save the right keys', function(fn){ fn() // getAllKeys(function(err, keys){ // if(err) return fn(err) // assert(expected.keys.length === (keys.length - 10)) // assert(keys.filter(function(key){ // return expected.keys.indexOf(key[0]) >= 0 // }).length === (keys.length - 10)) // fn() // }) }) }) describe('query', function(){ it('with limit', function(fn){ text.query('Node.js', { limit: 1 }, function(err, result){ assert(!err) assert(result.results.length === 1) var first = result.results[0] text.query({ last: result.last }, { limit: 1 }, function(err, result){ if(err) throw err assert(result.results[0] !== first) assert(result.results.length === 1) fn() }) }) }) it('with ttl', function(fn){ text.query('Node.js', { limit: 1, ttl: 10 }, function(err, result){ assert(!err) setTimeout(function(){ text.query({ last: result.last }, function(err, result){ assert(err) assert(err.type === 'NotFoundError') fn() }) }, 10500) }) }) it('with one facet', function(fn){ text.query('webos', 'article', function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(result.results[0] === '6') assert(result.results[1] === '7') fn() }) }) it('with more than one facet', function(fn){ text.query('node.js', ['library', 'comment'], function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(result.results[0] === '5') assert(result.results[1] === '4') fn() }) }) it('without facets', function(fn){ text.query('webos', function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(result.results[0] === '6') assert(result.results[1] === '7') fn() }) }) it('with options and facets', function(fn){ text.query('webos', 'article', { limit: 1, ttl: 1 }, function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 1) assert(result.results[0] === '6') fn() }) }) }) describe('remove', function(){ it('should remove', function(fn){ text.remove('2', fn) }) it('should not have any keys from removed id', function(fn){ getAllKeys(function(err, keys){ assert(!err) assert(expected.keys.length !== keys.length) assert(keys.filter(function(key){ return key[1].id === '2' }).length === 0) fn() }) }) it('should return 0 results', function(fn){ text.query('vehicula', function(err, result){ assert(!err) assert(!result.results.length) fn() }) }) }) }
//= require <supermodel> SuperModel.Filter = { filterAttributes: function(){ var result = {}; var attributes = this.filter_attributes; if ( !attributes ) attributes = this._class.attributes; for(var i in attributes) { var attr = attributes[i]; result[attr] = this[attr]; } return result; }, filter: function(query){ query = query.toLowerCase(); var attributes = this.filterAttributes(); for (var key in attributes) { if ( !attributes[key] ) continue; var value = (attributes[key] + "").toLowerCase(); if (value.indexOf(query) != -1) return true; }; return false; } };
const createActions = (updateAllowed, deleteAllowed) => ({ update: { allowed: updateAllowed }, delete: { allowed: deleteAllowed }, }); module.exports = { actions: createActions, };
/* VRT - Copyright © 2017 Odd Marthon Lende All Rights Reserved */ import $ from 'jquery'; import {interact} from 'interact'; import {random} from "./random.js"; import * as d3 from 'd3'; import {EventEmitter} from 'events'; import {DialogComponent} from "./dialog.component.js"; var zIndex = 10999; const bindings = []; export function Dialog (classnames, style, options) { var background, interactable, opacity, dialog = this; EventEmitter.call(this); switch(arguments.length) { case 1: if(typeof classnames === 'object') { style = classnames; classnames = null; } break; case 2: if( typeof classnames !== 'string' ) { options = style; style = classnames; classnames = null; } } options = options || {}; style = style || {}; style["z-index"] = ++zIndex; this._components = []; this._options = options; this._style = style; if(options.isModal) { background = d3.select(document.body) .append("div") .classed("dialog-modal", true) .style("z-index", zIndex - 1); d3.select("html").style("pointer-events", "none"); this.destroy = function () { background.remove(); d3.select("html").style("pointer-events", null); return Dialog.prototype.destroy.call(this); } } this.element = (background || d3.select(document.body)) .append(function () { return dialog.element || document.createElement("div"); }) .classed("dialog", true) .attr("id", (this.id = random())); for(var prop in style) { this.element.style(prop, style[prop]); } opacity = this.element.style("opacity"); this.element.style("opacity", 0); this.element.transition() .duration(500) .style("opacity", opacity); if(options.resizable) interactable = interact(this.element.node(), {}) .resizable({ edges: { top : true, left: true, bottom: true, right: true } }) .on("resizemove", function (event) { var r = event.rect; style.width = r.width + 'px'; style.height = r.height + 'px'; refresh(); dialog.emit("resize"); }); if(classnames) this.element.classed(classnames, true); function refresh () { dialog.refresh(); } window.addEventListener("resize", refresh, false); this.on("destroy", function () { if(options.resizable) interactable.unset(); return window.removeEventListener("resize", refresh); }); setTimeout(refresh, 0); } Dialog.prototype = Object.create(EventEmitter.prototype); function insert (cmp, options) { var node, dialog = this.dialog, components = this._components; options = $.extend({}, this._options || (dialog ? dialog._options : {}), options); components.push( typeof cmp === 'function' ? new cmp( options ) : cmp ); (cmp = components.valueOf()[components.length - 1]); this.element.node() .appendChild( (node = this instanceof DialogComponent ? cmp.node() : cmp.element.node()) ); cmp.dialog = dialog || this; cmp.parent = this; d3.select(node).style(cmp._style); if(this instanceof DialogComponent) d3.select(node).classed(cmp.element.attr("class"), true); cmp.parent.emit("insert", cmp); } Dialog.prototype.remove = function (component) { var components = this._components, len = components.length; for(var i = 0; i < len; i++) { var c = components.shift(); if(c !== component) components.push(c); else { var n = c.element.node(); n.parentNode.removeChild(n); } } } Dialog.prototype.node = function () { return this.element.node(); } Dialog.prototype.insert = function (name, options) { var context = this; if(name instanceof DialogComponent) insert.call(this, name, options); else if(typeof name === 'string') { var r = require('./dialog.component.' + name); for(var n in r) { insert.call(context, r[n], options); } } return this; } Dialog.prototype.nest = function () { var components = this._components; return components.valueOf()[components.length - 1]; } Dialog.prototype.add = function (obj, name, type) { var args = Array.prototype.slice.call(arguments, typeof type === 'string' ? 3 : 2), i; switch(arguments.length) { case 0: throw "Minimum 1 argument (object) is required"; case 1: console.debug(" Auto add properties ", obj); for(name in obj) { if( (i = bindings.indexOf(obj)) > -1 && bindings[++i][name]) { console.debug("Property '"+ name + "' has already been added, skipping..."); continue; } this.add(obj, name); } return this; default: if(typeof obj !== 'object' || typeof name !== 'string') throw "Argument(s) has wrong type, must be (object, string)"; } if( (i = bindings.indexOf(obj)) > -1 && bindings[++i][name]) throw "Property '" + name + "' has already been added"; switch(typeof type === "string" ? type : typeof obj[name]) { case 'undefined': throw "Property '" + name + "' does not exist in the given object"; case 'color': this.insert("color", { 'text' : name, 'value' : obj[name] }); break; case 'boolean': this.insert("checkbox", { 'text' : name, 'checked' : obj[name] }); break; case 'string' : switch(args.length) { case 0: this.insert("input", { 'text' : name, 'value' : obj[name] }); break; case 2: case 1: if( !Array.isArray(args[0]) ) throw "No options list provided"; this.insert("select", { 'text' : name, 'records' : args[0], 'value' : obj[name] }); } break; case 'number' : switch(args.length) { case 0: this.insert("input", { 'text' : name, 'value' : obj[name] }); break; case 3: case 2: this.insert("slider", { 'text' : name, 'value' : obj[name], 'min' : args[0], 'max' : args[1], 'step' : args[2] }); break; } break; case 'object' : if(Array.isArray(obj[name])) { this.insert("input", { 'text' : name, 'value' : obj[name] }); break; } case 'function' : return; } this.nest() .on("modified", function () { var callback = args[args.length - 1]; if(typeof callback === "function") { callback.call(this); } else obj[name] = this.valueOf(); this.dialog.emit("modified", this, name, obj); }) .on("update-request", function () { this.set(obj[name]); }) .disabled(!Object.getOwnPropertyDescriptor(obj, name).writable); if( ( i = bindings.indexOf(obj) ) === -1) { for(i = 0, l = bindings.length; i < l; i += 3) { if(bindings[i] === null) { bindings[i] = obj; bindings[i+1] = {}; bindings[i+2] = 0; break; } } if(bindings[i] !== obj) { bindings.push(obj, {}, 0); i = bindings.length - 3; } } bindings[++i][name] = this.nest(); bindings[i+1]++; this.on("destroy", function () { bindings[i][name] = null; if(! --bindings[i+1] ) { bindings[i-1] = null; bindings[i] = null; } }); return this; } Dialog.prototype.set = function () { var obj = this.nest(); return obj.set.apply(obj, arguments); } Dialog.prototype.disabled = function () { var obj = this.nest(); return obj.disabled.apply(obj, arguments); } Dialog.prototype.validate = function () { var obj = this.nest(); return obj.validate.apply(obj, arguments); } Dialog.prototype.destroy = function () { var components = this._components, parent = this.parent, component; while( (component = components.pop()) ) component.destroy(); this.element.remove(); if(parent && (components = parent._components).indexOf(this) > -1) { components.splice(components.indexOf(this), 1); if(parent instanceof Dialog && !components.length) parent.destroy(); } return this.emit("destroy"); } Dialog.prototype.update = function () { var components = this._components; for(var i = 0, len = components.length; i < len; i++) { components[i].update(); } this.emit("update"); return this; } Dialog.prototype.style = function (style) { if(Array.isArray(style) || typeof style !== "object") throw "TypeError: Argument must be an object"; this._style = $.extend(this._style, style); return this.refresh(); } Dialog.prototype.refresh = function refresh () { var components = this._components, component; for(var prop in this._style) this.element.style(prop, this._style[prop]); for(var i = 0, len = components.length; i < len; i++) { components[i].refresh(); refresh.call(components[i]); } this.emit("refresh"); return this; } Dialog.prototype.trigger = function (eventname) { var context = this, e = [eventname]; return function () { context.emit.apply(context, e.concat(Array.prototype.slice.call(arguments))); } } Dialog.prototype.each = function () { var components = this._components, component; for(var i = 0, len = components.length; i < len; i++) { components[i].on.apply(components[i], arguments); } return this; } Dialog.prototype.components = function () { return this._components; } DialogComponent.prototype.trigger = Dialog.prototype.trigger; DialogComponent.prototype.insert = Dialog.prototype.insert; DialogComponent.prototype.add = Dialog.prototype.add; DialogComponent.prototype.nest = Dialog.prototype.nest; DialogComponent.prototype.destroy = Dialog.prototype.destroy; DialogComponent.prototype.each = Dialog.prototype.each; DialogComponent.prototype.components = Dialog.prototype.components; DialogComponent.prototype.refresh = Dialog.prototype.refresh;
import React, { Component } from 'react' import PropTypes from 'prop-types' import { path } from 'ramda' import { firebaseConnect } from 'react-redux-firebase' // Components import { Radio, RadioGroup } from 'react-radio-group' import Questions from './components/Questions/Questions' import styles from './Classic.scss' import { TOURS_PATH, } from 'consts/firebasePaths' @firebaseConnect() class Classic extends Component { static propTypes = { firebase: PropTypes.object, tour: PropTypes.object, tourKey: PropTypes.string, } handleStakesChange = (value) => { const { tourKey } = this.props this.props.firebase.update(`${TOURS_PATH}/${tourKey}/settings`, { stakes: value === 'true', }) } render() { const { tour, tourKey } = this.props const questions = path(['questions'], tour) || {} const stakes = path(['settings', 'stakes'], tour) ? 'true' : 'false' return ( <div> <h4>Классический квиз</h4> <div className={styles.row}> <RadioGroup name={`tour-${tourKey}`} selectedValue={stakes} onChange={this.handleStakesChange} > <label className={styles.label}><Radio value="false"/> Без ставок</label> <label className={styles.label}><Radio value="true"/> Со ставками</label> </RadioGroup> </div> <Questions questions={questions} tourKey={tourKey}/> </div> ) } } export default Classic
window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"AguafinaScript":{"normal":"AguafinaScript-Regular.ttf","bold":"AguafinaScript-Regular.ttf","italics":"AguafinaScript-Regular.ttf","bolditalics":"AguafinaScript-Regular.ttf"}};
var cliSteps = function cliSteps() { var fs = require('fs'); var rimraf = require('rimraf'); var mkdirp = require('mkdirp'); var exec = require('child_process').exec; var baseDir = fs.realpathSync(__dirname + "/../.."); var tmpDir = baseDir + "/tmp/cucumber-js-sandbox"; var cleansingNeeded = true; var lastRun = { error: null, stdout: "", stderr: "" }; function tmpPath(path) { return (tmpDir + "/" + path); }; function cleanseIfNeeded() { if (cleansingNeeded) { try { rimraf.sync(tmpDir); } catch(e) {} lastRun = { error: null, stdout: "", stderr: "" }; cleansingNeeded = false; } }; function isWindowsPlatform() { return (process.platform == 'win32' || process.platform == 'win64'); }; function joinPathSegments(segments) { var pathJoiner = isWindowsPlatform() ? "\\" : '/'; return segments.join(pathJoiner); } this.Given(/^a file named "(.*)" with:$/, function(filePath, fileContent, callback) { cleanseIfNeeded(); var absoluteFilePath = tmpPath(filePath); var filePathSegments = absoluteFilePath.split('/'); var fileName = filePathSegments.pop(); var dirName = joinPathSegments(filePathSegments); mkdirp(dirName, 0755, function(err) { if (err) { throw new Error(err); } fs.writeFile(absoluteFilePath, fileContent, function(err) { if (err) { throw new Error(err); } callback(); }); }); }); this.When(/^I run `cucumber.js(| .+)`$/, function(args, callback) { var initialCwd = process.cwd(); process.chdir(tmpDir); var runtimePath = joinPathSegments([baseDir, 'bin', 'cucumber.js']); var command = "node \"" + runtimePath + "\"" + args; exec(command, function (error, stdout, stderr) { lastRun['error'] = error; lastRun['stdout'] = stdout; lastRun['stderr'] = stderr; process.chdir(initialCwd); cleansingNeeded = true; callback(); }); }); this.Then(/^it passes with:$/, function(expectedOutput, callback) { var actualOutput = lastRun['stdout']; var actualError = lastRun['error']; var actualStderr = lastRun['stderr']; if (actualOutput.indexOf(expectedOutput) == -1) throw new Error("Expected output to match the following:\n'" + expectedOutput + "'\nGot:\n'" + actualOutput + "'.\n" + "Error:\n'" + actualError + "'.\n" + "stderr:\n'" + actualStderr +"'."); callback(); }); this.Then(/^it outputs this json:$/, function(expectedOutput, callback) { var actualOutput = lastRun['stdout']; var actualError = lastRun['error']; var actualStderr = lastRun['stderr']; expectedOutput = expectedOutput.replace(/<current-directory>/g, tmpDir); try { var actualJson = JSON.parse(actualOutput); } catch(err) { throw new Error("Error parsing actual JSON:\n" + actualOutput); } try { var expectedJson = JSON.parse(expectedOutput); } catch(err) { throw new Error("Error parsing expected JSON:\n" + expectedOutput); } neutraliseVariableValuesInJson(actualJson); neutraliseVariableValuesInJson(expectedJson); var actualJsonString = JSON.stringify(actualJson, null, 2); var expectedJsonString = JSON.stringify(expectedJson, null, 2); if (actualJsonString != expectedJsonString) throw new Error("Expected output to match the following:\n'" + expectedJsonString + "'\nGot:\n'" + actualJsonString + "'.\n" + "Error:\n'" + actualError + "'.\n" + "stderr:\n'" + actualStderr +"'."); callback(); }); this.Then(/^I see the version of Cucumber$/, function(callback) { var Cucumber = require('../../lib/cucumber'); var actualOutput = lastRun['stdout']; var expectedOutput = Cucumber.VERSION + "\n"; if (actualOutput.indexOf(expectedOutput) == -1) throw new Error("Expected output to match the following:\n'" + expectedOutput + "'\nGot:\n'" + actualOutput + "'."); callback(); }); this.Then(/^I see the help of Cucumber$/, function(callback) { var actualOutput = lastRun['stdout']; var expectedOutput = "Usage: cucumber.js "; if (actualOutput.indexOf(expectedOutput) == -1) throw new Error("Expected output to match the following:\n'" + expectedOutput + "'\nGot:\n'" + actualOutput + "'."); callback(); }); }; var neutraliseVariableValuesInJson = function neutraliseVariableValuesInJson(report) { report.forEach(function (item) { (item.elements || []).forEach(function (element) { (element['steps'] || []).forEach(function (step) { if ('result' in step) { if ('error_message' in step.result) { step.result.error_message = "<error-message>"; } if ('duration' in step.result) { step.result.duration = "<duration>"; } } }); }); }); }; module.exports = cliSteps;
function Module() { this.sp = null; this.sensorTypes = { ALIVE: 0, DIGITAL: 1, ANALOG: 2, PWM: 3, SERVO_PIN: 4, TONE: 5, PULSEIN: 6, ULTRASONIC: 7, TIMER: 8, METRIX: 9, METRIXCLEAR: 11, METRIXROWCOLCLEAR: 12, METRIXDRAW: 13, NEOPIXEL: 14, NEOPIXELCLEAR: 15, NEOPIXELINIT : 16, NEOPIXELRAINBOW : 17, NEOPIXELEACH : 18, LCDINIT: 19, LCD: 20, LCDCLEAR: 21, }; this.actionTypes = { GET: 1, SET: 2, RESET: 3, }; this.sensorValueSize = { FLOAT: 2, SHORT: 3, }; this.digitalPortTimeList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; this.sensorData = { ULTRASONIC: 0, DIGITAL: { '0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0, '13': 0, }, ANALOG: { '0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, }, PULSEIN: {}, TIMER: 0, }; this.defaultOutput = {}; this.recentCheckData = {}; this.sendBuffers = []; this.lastTime = 0; this.lastSendTime = 0; this.isDraing = false; } var sensorIdx = 0; Module.prototype.init = function(handler, config) {}; Module.prototype.setSerialPort = function(sp) { var self = this; this.sp = sp; }; Module.prototype.requestInitialData = function() { return this.makeSensorReadBuffer(this.sensorTypes.ANALOG, 0); }; Module.prototype.checkInitialData = function(data, config) { return true; // 이후에 체크 로직 개선되면 처리 // var datas = this.getDataByBuffer(data); // var isValidData = datas.some(function (data) { // return (data.length > 4 && data[0] === 255 && data[1] === 85); // }); // return isValidData; }; Module.prototype.afterConnect = function(that, cb) { that.connected = true; if (cb) { cb('connected'); } }; Module.prototype.validateLocalData = function(data) { return true; }; Module.prototype.requestRemoteData = function(handler) { var self = this; if (!self.sensorData) { return; } Object.keys(this.sensorData).forEach(function(key) { if (self.sensorData[key] != undefined) { handler.write(key, self.sensorData[key]); } }); }; Module.prototype.handleRemoteData = function(handler) { var self = this; var getDatas = handler.read('GET'); var setDatas = handler.read('SET') || this.defaultOutput; var time = handler.read('TIME'); var buffer = new Buffer([]); if (getDatas) { var keys = Object.keys(getDatas); keys.forEach(function(key) { var isSend = false; var dataObj = getDatas[key]; if ( typeof dataObj.port === 'string' || typeof dataObj.port === 'number' ) { var time = self.digitalPortTimeList[dataObj.port]; if (dataObj.time > time) { isSend = true; self.digitalPortTimeList[dataObj.port] = dataObj.time; } } else if (Array.isArray(dataObj.port)) { isSend = dataObj.port.every(function(port) { var time = self.digitalPortTimeList[port]; return dataObj.time > time; }); if (isSend) { dataObj.port.forEach(function(port) { self.digitalPortTimeList[port] = dataObj.time; }); } } if (isSend) { if (!self.isRecentData(dataObj.port, key, dataObj.data)) { self.recentCheckData[dataObj.port] = { type: key, data: dataObj.data, }; buffer = Buffer.concat([ buffer, self.makeSensorReadBuffer( key, dataObj.port, dataObj.data ), ]); } } }); } if (setDatas) { var setKeys = Object.keys(setDatas); setKeys.forEach(function(port) { var data = setDatas[port]; if (data) { if (self.digitalPortTimeList[port] < data.time) { self.digitalPortTimeList[port] = data.time; if (!self.isRecentData(port, data.type, data.data)) { self.recentCheckData[port] = { type: data.type, data: data.data, }; buffer = Buffer.concat([ buffer, self.makeOutputBuffer(data.type, port, data.data), ]); } } } }); } if (buffer.length) { this.sendBuffers.push(buffer); } }; Module.prototype.isRecentData = function(port, type, data) { var that = this; var isRecent = false; if(type == this.sensorTypes.ULTRASONIC) { var portString = port.toString(); var isGarbageClear = false; Object.keys(this.recentCheckData).forEach(function (key) { var recent = that.recentCheckData[key]; if(key === portString) { } if(key !== portString && recent.type == that.sensorTypes.ULTRASONIC) { delete that.recentCheckData[key]; isGarbageClear = true; } }); if((port in this.recentCheckData && isGarbageClear) || !(port in this.recentCheckData)) { isRecent = false; } else { isRecent = true; } } else if (port in this.recentCheckData && type != this.sensorTypes.TONE) { if ( this.recentCheckData[port].type === type && this.recentCheckData[port].data === data ) { isRecent = true; } } return isRecent; }; Module.prototype.requestLocalData = function() { var self = this; if (!this.isDraing && this.sendBuffers.length > 0) { this.isDraing = true; this.sp.write(this.sendBuffers.shift(), function() { if (self.sp) { self.sp.drain(function() { self.isDraing = false; }); } }); } return null; }; /* ff 55 idx size data a */ Module.prototype.handleLocalData = function(data) { var self = this; var datas = this.getDataByBuffer(data); datas.forEach(function(data) { if (data.length <= 4 || data[0] !== 255 || data[1] !== 85) { return; } var readData = data.subarray(2, data.length); var value; switch (readData[0]) { case self.sensorValueSize.FLOAT: { value = new Buffer(readData.subarray(1, 5)).readFloatLE(); value = Math.round(value * 100) / 100; break; } case self.sensorValueSize.SHORT: { value = new Buffer(readData.subarray(1, 3)).readInt16LE(); break; } default: { value = 0; break; } } var type = readData[readData.length - 1]; var port = readData[readData.length - 2]; switch (type) { case self.sensorTypes.DIGITAL: { self.sensorData.DIGITAL[port] = value; break; } case self.sensorTypes.ANALOG: { self.sensorData.ANALOG[port] = value; break; } case self.sensorTypes.PULSEIN: { self.sensorData.PULSEIN[port] = value; break; } case self.sensorTypes.ULTRASONIC: { self.sensorData.ULTRASONIC = value; break; } case self.sensorTypes.TIMER: { self.sensorData.TIMER = value; break; } default: { break; } } }); }; /* ff 55 len idx action device port slot data a 0 1 2 3 4 5 6 7 8 */ Module.prototype.makeSensorReadBuffer = function(device, port, data) { var buffer; var dummy = new Buffer([10]); if (device == this.sensorTypes.ULTRASONIC) { buffer = new Buffer([ 255, 85, 6, sensorIdx, this.actionTypes.GET, device, port[0], port[1], 10, ]); } else if (!data) { buffer = new Buffer([ 255, 85, 5, sensorIdx, this.actionTypes.GET, device, port, 10, ]); } else { value = new Buffer(2); value.writeInt16LE(data); buffer = new Buffer([ 255, 85, 7, sensorIdx, this.actionTypes.GET, device, port, 10, ]); buffer = Buffer.concat([buffer, value, dummy]); } sensorIdx++; if (sensorIdx > 254) { sensorIdx = 0; } return buffer; }; //0xff 0x55 0x6 0x0 0x1 0xa 0x9 0x0 0x0 0xa Module.prototype.makeOutputBuffer = function(device, port, data) { var buffer; var value = new Buffer(2); var dummy = new Buffer([10]); switch (device) { case this.sensorTypes.SERVO_PIN: case this.sensorTypes.DIGITAL: case this.sensorTypes.PWM: case this.sensorTypes.METRIXCLEAR: case this.sensorTypes.METRIXDRAW: case this.sensorTypes.NEOPIXELCLEAR: case this.sensorTypes.NEOPIXELRAINBOW: case this.sensorTypes.LCDCLEAR: { value.writeInt16LE(data); buffer = new Buffer([ 255, 85, 6, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, value, dummy]); break; } case this.sensorTypes.METRIX: case this.sensorTypes.METRIXROWCOLCLEAR: { const value1 = new Buffer(2); const value2 = new Buffer(2); if ($.isPlainObject(data)) { value1.writeInt16LE(data.value1); value2.writeInt16LE(data.value2); } else { value1.writeInt16LE(0); value2.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 8, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, value1, value2, dummy]); break; } case this.sensorTypes.NEOPIXELINIT: { const neoCount = new Buffer(2); var bright = new Buffer(2); if ($.isPlainObject(data)) { neoCount.writeInt16LE(data.value1); bright.writeInt16LE(data.value2); } else { neoCount.writeInt16LE(0); bright.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 8, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, neoCount, bright, dummy]); break; } case this.sensorTypes.NEOPIXEL: { //var count_value = new Buffer(2); const rValue = new Buffer(2); const gValue = new Buffer(2); const bValue = new Buffer(2); if ($.isPlainObject(data)) { // count_value.writeInt16LE(data.count); rValue.writeInt16LE(data.R_val); gValue.writeInt16LE(data.G_val); bValue.writeInt16LE(data.B_val); } else { //count_value.writeInt16LE(0); rValue.writeInt16LE(0); gValue.writeInt16LE(0); bValue.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 10, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, rValue, gValue, bValue, dummy]); break; } case this.sensorTypes.NEOPIXELEACH: { const cntValue = new Buffer(2); const rVal = new Buffer(2); const gVal = new Buffer(2); const bVal = new Buffer(2); if ($.isPlainObject(data)) { cntValue.writeInt16LE(data.CNT_val); rVal.writeInt16LE(data.R_val); gVal.writeInt16LE(data.G_val); bVal.writeInt16LE(data.B_val); } else { cntValue.writeInt16LE(0); rVal.writeInt16LE(0); gVal.writeInt16LE(0); bVal.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 10, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, cntValue, rVal, gVal, bVal, dummy]); break; } case this.sensorTypes.LCDINIT: { const listVal = new Buffer(2); if ($.isPlainObject(data)) { listVal.writeInt16LE(data.list); } else { listVal.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 6, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, listVal, dummy]); break; } case this.sensorTypes.LCD: { const rowValue = new Buffer(2); const colValue = new Buffer(2); const val = new Buffer(2); let textLen = 0; let text; if ($.isPlainObject(data)) { textLen = ('' + `${data.value}`).length; text = Buffer.from('' + `${data.value}`, 'ascii'); rowValue.writeInt16LE(data.row); colValue.writeInt16LE(data.col); val.writeInt16LE(textLen); } else { rowValue.writeInt16LE(0); colValue.writeInt16LE(0); textLen = 0; text = Buffer.from('', 'ascii'); val.writeInt16LE(textLen); } buffer = new Buffer([ 255, 85, 10 + textLen, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, rowValue, colValue, val, text, dummy]); break; } case this.sensorTypes.NEOPIXELEACH:{ var cnt_value = new Buffer(2); var r_value = new Buffer(2); var g_value = new Buffer(2); var b_value = new Buffer(2); if ($.isPlainObject(data)) { cnt_value.writeInt16LE(data.CNT_val); r_value.writeInt16LE(data.R_val); g_value.writeInt16LE(data.G_val); b_value.writeInt16LE(data.B_val); } else { cnt_value.writeInt16LE(0); r_value.writeInt16LE(0); g_value.writeInt16LE(0); b_value.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 10, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, cnt_value, r_value, g_value, b_value, dummy]); break; } case this.sensorTypes.TONE: { var time = new Buffer(2); if ($.isPlainObject(data)) { value.writeInt16LE(data.value); time.writeInt16LE(data.duration); } else { value.writeInt16LE(0); time.writeInt16LE(0); } buffer = new Buffer([ 255, 85, 8, sensorIdx, this.actionTypes.SET, device, port, ]); buffer = Buffer.concat([buffer, value, time, dummy]); break; } } return buffer; }; Module.prototype.getDataByBuffer = function(buffer) { var datas = []; var lastIndex = 0; buffer.forEach(function(value, idx) { if (value == 13 && buffer[idx + 1] == 10) { datas.push(buffer.subarray(lastIndex, idx)); lastIndex = idx + 2; } }); return datas; }; Module.prototype.disconnect = function(connect) { var self = this; connect.close(); if (self.sp) { delete self.sp; } }; Module.prototype.reset = function() { this.lastTime = 0; this.lastSendTime = 0; this.sensorData.PULSEIN = {}; }; module.exports = new Module();
module.exports = function(grunt, options){ var projectDev = options.projectDev; var projectDir = options.projectDir; return { options: { outputStyle: 'compressed' }, site: { files: [{ expand: true, cwd: '<%= projectDev %>/scss/', src: ['*.scss'], dest: '<%= projectDir %>/scss/', ext: '.css' }] } }; };
var controllers = require("../controllers"), auth = require('./auth'); module.exports = function(app) { app.post('/api/users', controllers.usersController.createUser); app.put('/api/snippets', auth.isAuthenticated, controllers.snippetsController.create); app.post('/api/snippets/:snippetId', auth.isAuthenticated, controllers.snippetsController.update); app['delete']('/api/snippets/:snippetId', auth.isAuthenticated, controllers.snippetsController['delete']); app.get('/api/snippets/', auth.isAuthenticated, controllers.snippetsController.read); app.get('/api/snippets/:snippetId', auth.isAuthenticated, controllers.snippetsController.read); app.get('/partials/:partialArea/:partialName', function(req, res) { res.render('../../public/app/' + req.params.partialArea + '/' + req.params.partialName); }); app.get('/partials/:partialArea/:partialName', function(req, res) { res.render('../../public/app/' + req.params.partialArea + '/' + req.params.partialName); }); app.post('/login', auth.login); app.post('/logout', auth.logout); app.get('/api/*', function(req, res) { res.status(404); res.end(); }); app.get('*', function(req, res) { res.render('index', {currentUser: req.user}); }); };
import React from 'react' import { Link } from 'react-router-dom' export default ({ children }) => ( <div className='pa3 bg-big-stone'> <div className='flex flex-row items-center'> <Link to='/' data-id='home-link'> <img src='images/logo-peerpad.svg' alt='PeerPad logo' className='mr4' /> </Link> {children} </div> </div> )
export * from './level'