max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
node_modules/fortune/node_modules/array-buffer/lib/index.js
geoapi/crowdclarify
0
4831
module.exports = { toBuffer: toBuffer, toArrayBuffer: toArrayBuffer } // Thanks kraag22. // http://stackoverflow.com/a/17064149/4172219 function toBuffer (arrayBuffer) { if (Buffer.isBuffer(arrayBuffer)) return arrayBuffer return new Buffer(new Uint8Array(arrayBuffer)) } // Thanks <NAME>. // http://stackoverflow.com/a/19544002/4172219 function toArrayBuffer (buffer) { if (buffer instanceof ArrayBuffer) return buffer return new Uint8Array(buffer).buffer }
0.640625
1
src/lib/packet/index.js
alexandref93/workflow
4
4839
// @flow import path from 'path'; import type { TypeLibExternal } from '../../type-definitions'; import { loader } from '../loader'; import { load as loadConfig, getPathRootConfig } from '../configYML'; type TypeLoadPacket = ({libExternal: TypeLibExternal}) => TypeLibExternal; export const loadPacket : TypeLoadPacket = ({libExternal = {}} = {}) => { const config = loadConfig(); config.packet && config.packet.forEach(packet => { const packetLoaded = loader({ pathModule: packet.isLocal ? path.resolve(getPathRootConfig(), packet.path) : '', name: packet.name, isLocal: packet.isLocal, }); if (typeof packetLoaded === 'object') { Object.keys(packetLoaded).forEach(key => { libExternal[key] = packetLoaded[key]; }); } }); return libExternal; };
1.21875
1
Wikimedia/lookup_web_wikidata_match/ui_settings.js
GLAMpipe/nodes
1
4847
var a = document.getElementById('process_lookup_web_wikidata_match_ui') a.href = `/apps/reconciliation/?node=${node._id}` var div = document.getElementById('process_lookup_wikidata_recon_query_value') div.textContent = node.params.in_field
0.75
1
app/index.js
izziaraffaele/silex-app-generator
6
4855
'use strict'; var path = require('path'); var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var Generator = yeoman.generators.Base.extend({ init: function () { this.pkg = yeoman.file.readJSON(path.join(__dirname, '../package.json')); this.on('end', function () { if (!this.options['skip-install']) { this.installDependencies(); this.spawnCommand('composer', ['install']); this.spawnCommand('chmod', ['777','app/cache']); this.spawnCommand('chmod', ['777','app/logs']); } }); }, askFor: function () { var done = this.async(); // have Yeoman greet the user console.log(this.yeoman); // replace it with a short and sweet description of your generator console.log(chalk.magenta('You\'re using A Yeoman Generator for a Silex based web app!!')); var prompts = [{ name: 'project', message: 'What is this project\'s name?' }, { type: 'checkbox', name: 'features', message: 'What more would you like?', choices: [{ name: 'Auth system', value: 'includeAuth', checked: true }, { name: 'Jest for unit tests', value: 'includeJest', checked: true }] }]; this.prompt(prompts, function (answers) { var features = answers.features; this.projectName = answers.project || 'myApp'; function hasFeature(feat) { return features.indexOf(feat) !== -1; } // manually deal with the response, get back and store the results. // we change a bit this way of doing to automatically do this in the self.prompt() method. this.includeJest = hasFeature('includeJest'); this.includeAuth = hasFeature('includeAuth'); done(); }.bind(this)); }, app: function () { // main htaccess this.template('_package.json', 'package.json'); this.template('_gulpfile.js', 'gulpfile.js'); this.template('_bower.json', 'bower.json'); this.template('_composer.json', 'composer.json'); this.copy('bowerrc', '.bowerrc'); this.copy('gitignore', '.gitignore'); this.copy('preprocessor.js', 'preprocessor.js'); this.copy('phpunit.xml.dist', 'phpunit.xml.dist'); // webroot this.mkdir('web'); this.copy('web/htaccess','web/.htaccess'); this.copy('web/index.php','web/index.php'); // silex app this.directory('app','app'); this.mkdir('app/cache'); this.mkdir('app/logs'); // src application directory this.directory('src','src'); this.directory('tests','tests'); // Now lets build assets this.mkdir('assets'); this.directory('assets/images','assets/images'); this.directory('assets/scripts','assets/scripts'); this.mkdir('assets/styles'); this.template('assets/styles/_main.scss', 'assets/styles/_main.scss'); this.copy('assets/styles/auth.scss','assets/styles/auth.scss'); this.copy('assets/styles/errors.scss','assets/styles/errors.scss'); this.copy('assets/favicon.ico','assets/favicon.ico'); this.copy('assets/robots.txt','assets/robots.txt'); var routes = []; // lets start adding features if( this.includeAuth ){ routes.push({ routeName: "login", pattern: "/login", method: ["get"], controller: "WebComposer\\AppBundle\\Controllers\\AuthController:login" }); routes.push({ routeName: "signup", pattern: "/signup", method: ["get"], controller: "WebComposer\\AppBundle\\Controllers\\AuthController:signup" }); } if (this.includeJest) { this.directory('assets/scripts/ui/__tests__','assets/scripts/ui/__tests__'); } this.write('app/config/routes.json', JSON.stringify({'config.routes':routes})); } }); module.exports = Generator;
1.554688
2
scripts/utilities/utils.js
JCGithu/Sinon
0
4863
function copyString(str) { var el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style = { position: 'absolute', left: '-9999px' }; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); console.log('Clipboard updated'); lineBreak(); } function swalColours() { let darkMode = document.getElementById('darkMode'); if (darkMode.checked) { (swalColour.fail = '#232323'), (swalColour.loading = '#2c3e50'), (swalColour.pass = '#<PASSWORD>'); } else { (swalColour.fail = '#ED6A5A'), (swalColour.loading = 'rgba(0,0,0,0.4)'), (swalColour.pass = '#30bced'); } } function lineBreak() { console.log('~=~=~=~=~=~=~=~=~=~=~=~'); } function progressBar(progress, format, targetFiles) { let progressText = document.getElementById('progressText'); if (progress.percent === undefined) { progressText.textContent = progress.timemark.match('dd:dd:dd)'); } else { if (format.indexOf('concat') >= 0) { progress.percent = progress.percent / targetFiles.length; } if (progress.percent >= 100) { progress.percent = 99.9; } if (progressText) { progressText.textContent = (Math.round(progress.percent * 100) / 100).toFixed(1) + '%'; console.log('Processing: ' + Math.floor(progress.percent) + '% done'); let percentage = parseFloat((Math.round(progress.percent) / 100).toFixed(2)); win.setProgressBar(percentage); } } } function docReady(fn) { if (document.readyState === 'complete' || document.readyState === 'interactive') { setTimeout(fn, 1); } else { document.addEventListener('DOMContentLoaded', fn); } } function URLwipe() { if (document.getElementById('urlWipe').checked) { console.log('URL Wipe applied'); document.getElementById('inputURL').value = ''; } } const axios = require('axios'); async function versionChecker() { return axios.get('http://colloquial.studio/sinondata.json').then(async (response) => { let element = document.getElementById('ver'); if (element.innerHTML !== response.data.version) { element.style = 'color:var(--hover)'; let docs = document.getElementById('documentation'); let docText = `<h4 style="color:var(--hover)">// Current version of Sinon is ${response.data.version}</h4>` + docs.innerHTML; docs.innerHTML = docText; } }); } module.exports = { docReady, lineBreak, progressBar, swalColours, copyString, URLwipe, versionChecker };
1.578125
2
src/dashv2.js
ricocai/lab
0
4871
// ---------------------------------------------------------------------------- // You can set the following variables before loading this script: /*global netdataNoDygraphs *//* boolean, disable dygraph charts * (default: false) */ /*global netdataNoSparklines *//* boolean, disable sparkline charts * (default: false) */ /*global netdataNoPeitys *//* boolean, disable peity charts * (default: false) */ /*global netdataNoGoogleCharts *//* boolean, disable google charts * (default: false) */ /*global netdataNoMorris *//* boolean, disable morris charts * (default: false) */ /*global netdataNoEasyPieChart *//* boolean, disable easypiechart charts * (default: false) */ /*global netdataNoGauge *//* boolean, disable gauge.js charts * (default: false) */ /*global netdataNoD3 *//* boolean, disable d3 charts * (default: false) */ /*global netdataNoC3 *//* boolean, disable c3 charts * (default: false) */ /*global netdataNoBootstrap *//* boolean, disable bootstrap - disables help too * (default: false) */ /*global netdataDontStart *//* boolean, do not start the thread to process the charts * (default: false) */ /*global netdataErrorCallback *//* function, callback to be called when the dashboard encounters an error * (default: null) */ /*global netdataRegistry:true *//* boolean, use the netdata registry * (default: false) */ /*global netdataNoRegistry *//* boolean, included only for compatibility with existing custom dashboard * (obsolete - do not use this any more) */ /*global netdataRegistryCallback *//* function, callback that will be invoked with one param: the URLs from the registry * (default: null) */ /*global netdataShowHelp:true *//* boolean, disable charts help * (default: true) */ /*global netdataShowAlarms:true *//* boolean, enable alarms checks and notifications * (default: false) */ /*global netdataRegistryAfterMs:true *//* ms, delay registry use at started * (default: 1500) */ /*global netdataCallback *//* function, callback to be called when netdata is ready to start * (default: null) * netdata will be running while this is called * (call NETDATA.pause to stop it) */ /*global netdataPrepCallback *//* function, callback to be called before netdata does anything else * (default: null) */ /*global netdataServer *//* string, the URL of the netdata server to use * (default: the URL the page is hosted at) */ // ---------------------------------------------------------------------------- // global namespace //import axios from "./node_modules/axios" var NETDATA = window.NETDATA || {}; (function(window, document) { // ------------------------------------------------------------------------ // compatibility fixes // fix IE issue with console if(!window.console) { window.console = { log: function(){} }; } // if string.endsWith is not defined, define it if(typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(s) { if(s.length > this.length) return false; return this.slice(-s.length) === s; }; } // if string.startsWith is not defined, define it if(typeof String.prototype.startsWith !== 'function') { String.prototype.startsWith = function(s) { if(s.length > this.length) return false; return this.slice(s.length) === s; }; } NETDATA.name2id = function(s) { return s .replace(/ /g, '_') .replace(/\(/g, '_') .replace(/\)/g, '_') .replace(/\./g, '_') .replace(/\//g, '_'); }; // ---------------------------------------------------------------------------------------------------------------- // Detect the netdata server // http://stackoverflow.com/questions/984510/what-is-my-script-src-url // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url NETDATA._scriptSource = function() { var script = null; if(typeof document.currentScript !== 'undefined') { script = document.currentScript; } else { var all_scripts = document.getElementsByTagName('script'); script = all_scripts[all_scripts.length - 1]; } if (typeof script.getAttribute.length !== 'undefined') script = script.src; else script = script.getAttribute('src', -1); return script; }; NETDATA.IAMServer = '' NETDATA.OpenAPIServer = '' if(typeof IAMServer !== 'undefined'){ NETDATA.IAMServer = IAMServer; console.log('NETDATA.IAMServer = ', NETDATA.IAMServer) } if(typeof OpenAPIServer !== 'undefined'){ NETDATA.OpenAPIServer = OpenAPIServer; console.log('NETDATA.OpenAPIServer = ', NETDATA.OpenAPIServer) } if(typeof netdataServer !== 'undefined') NETDATA.serverDefault = netdataServer; else { var s = NETDATA._scriptSource(); if(s) NETDATA.serverDefault = s.replace(/\/dash_yunkon.js(\?.*)*$/g, ""); else { console.log('WARNING: Cannot detect the URL of the netdata server.'); NETDATA.serverDefault = null; } } if(NETDATA.serverDefault === null) NETDATA.serverDefault = ''; else if(NETDATA.serverDefault.slice(-1) !== '/') NETDATA.serverDefault += '/'; //NETDATA.serverDefault = 'http://172.16.17.32:8529/_db/api/v1/' console.log('Rico trace in NETDATA.serverDefault = ', NETDATA.serverDefault) NETDATA.instance = axios.create({ baseURL: 'http://172.16.17.32:9110/api/v1/', timeout: 1000, headers: { 'X-Access-Token': '<KEY>' } }); NETDATA.IAM = axios.create({ baseURL: 'http://172.16.17.32:8529/_db/api/v1/', timeout: 1000, headers: { 'X-Access-Token': '<KEY>' } }); // default URLs for all the external files we need // make them RELATIVE so that the whole thing can also be // installed under a web server NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-2.2.4.min.js'; NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity-3.2.0.min.js'; NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline-2.1.2.min.js'; NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart-97b5824.min.js'; NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge-1.3.2.min.js'; NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined-dd74404.js'; NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter-dd74404.js'; NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-2.2.4-min.js'; NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3-0.4.11.min.js'; NETDATA.c3_css = NETDATA.serverDefault + 'css/c3-0.4.11.min.css'; NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3-3.5.17.min.js'; NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris-0.5.1.min.js'; NETDATA.morris_css = NETDATA.serverDefault + 'css/morris-0.5.1.css'; NETDATA.google_js = 'https://www.google.com/jsapi'; //NETDATA.axios = 'https://unpkg.com/axios/dist/axios.min.js' NETDATA.themes = { white: { bootstrap_css: NETDATA.serverDefault + 'css/bootstrap-3.3.7.css', dashboard_css: NETDATA.serverDefault + 'dashboard.css?v20161229-2', background: '#FFFFFF', foreground: '#000000', grid: '#F0F0F0', axis: '#F0F0F0', colors: [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC', '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99', '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ], easypiechart_track: '#f0f0f0', easypiechart_scale: '#dfe0e0', gauge_pointer: '#C0C0C0', gauge_stroke: '#F0F0F0', gauge_gradient: false }, slate: { bootstrap_css: NETDATA.serverDefault + 'css/bootstrap-slate-flat-3.3.7.css?v20161229-1', dashboard_css: NETDATA.serverDefault + 'dashboard.slate.css?v20161229-2', background: '#272b30', foreground: '#C8C8C8', grid: '#283236', axis: '#283236', /* colors: [ '#55bb33', '#ff2222', '#0099C6', '#faa11b', '#adbce0', '#DDDD00', '#4178ba', '#f58122', '#a5cc39', '#f58667', '#f5ef89', '#cf93c0', '#a5d18a', '#b8539d', '#3954a3', '#c8a9cf', '#c7de8a', '#fad20a', '#a6a479', '#a66da8' ], */ colors: [ '#66AA00', '#FE3912', '#3366CC', '#D66300', '#0099C6', '#DDDD00', '#5054e6', '#EE9911', '#BB44CC', '#e45757', '#ef0aef', '#CC7700', '#22AA99', '#109618', '#905bfd', '#f54882', '#4381bf', '#ff3737', '#329262', '#3B3EFF' ], easypiechart_track: '#373b40', easypiechart_scale: '#373b40', gauge_pointer: '#474b50', gauge_stroke: '#373b40', gauge_gradient: false } }; if(typeof netdataTheme !== 'undefined' && typeof NETDATA.themes[netdataTheme] !== 'undefined') NETDATA.themes.current = NETDATA.themes[netdataTheme]; else NETDATA.themes.current = NETDATA.themes.white; NETDATA.colors = NETDATA.themes.current.colors; // these are the colors Google Charts are using // we have them here to attempt emulate their look and feel on the other chart libraries // http://there4.io/2012/05/02/google-chart-color-list/ //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6', // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11', // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ]; // an alternative set // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/ // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray) //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ]; if(typeof netdataShowHelp === 'undefined') netdataShowHelp = true; if(typeof netdataShowAlarms === 'undefined') netdataShowAlarms = false; if(typeof netdataRegistryAfterMs !== 'number' || netdataRegistryAfterMs < 0) netdataRegistryAfterMs = 1500; if(typeof netdataRegistry === 'undefined') { // backward compatibility netdataRegistry = (typeof netdataNoRegistry !== 'undefined' && netdataNoRegistry === false); } if(netdataRegistry === false && typeof netdataRegistryCallback === 'function') netdataRegistry = true; // ---------------------------------------------------------------------------------------------------------------- // detect if this is probably a slow device var isSlowDeviceResult = undefined; var isSlowDevice = function() { if(isSlowDeviceResult !== undefined) return isSlowDeviceResult; try { var ua = navigator.userAgent.toLowerCase(); var iOS = /ipad|iphone|ipod/.test(ua) && !window.MSStream; var android = /android/.test(ua) && !window.MSStream; isSlowDeviceResult = (iOS === true || android === true); } catch (e) { isSlowDeviceResult = false; } return isSlowDeviceResult; }; // ---------------------------------------------------------------------------------------------------------------- // the defaults for all charts // if the user does not specify any of these, the following will be used NETDATA.chartDefaults = { host: NETDATA.serverDefault, // the server to get data from width: '100%', // the chart width - can be null height: '100%', // the chart height - can be null min_width: null, // the chart minimum width - can be null library: 'dygraph', // the graphing library to use method: 'average', // the grouping method before: 0, // panning after: -600, // panning pixels_per_point: 1, // the detail of the chart fill_luminance: 0.8 // luminance of colors in solid areas }; // ---------------------------------------------------------------------------------------------------------------- // global options NETDATA.options = { pauseCallback: null, // a callback when we are really paused pause: false, // when enabled we don't auto-refresh the charts targets: null, // an array of all the state objects that are // currently active (independently of their // viewport visibility) updated_dom: true, // when true, the DOM has been updated with // new elements we have to check. auto_refresher_fast_weight: 0, // this is the current time in ms, spent // rendering charts continuously. // used with .current.fast_render_timeframe page_is_visible: true, // when true, this page is visible auto_refresher_stop_until: 0, // timestamp in ms - used internally, to stop the // auto-refresher for some time (when a chart is // performing pan or zoom, we need to stop refreshing // all other charts, to have the maximum speed for // rendering the chart that is panned or zoomed). // Used with .current.global_pan_sync_time last_page_resize: Date.now(), // the timestamp of the last resize request last_page_scroll: 0, // the timestamp the last time the page was scrolled // the current profile // we may have many... current: { pixels_per_point: isSlowDevice()?5:1, // the minimum pixels per point for all charts // increase this to speed javascript up // each chart library has its own limit too // the max of this and the chart library is used // the final is calculated every time, so a change // here will have immediate effect on the next chart // update idle_between_charts: 100, // ms - how much time to wait between chart updates fast_render_timeframe: 200, // ms - render continuously until this time of continuous // rendering has been reached // this setting is used to make it render e.g. 10 // charts at once, sleep idle_between_charts time // and continue for another 10 charts. idle_between_loops: 500, // ms - if all charts have been updated, wait this // time before starting again. idle_parallel_loops: 100, // ms - the time between parallel refresher updates idle_lost_focus: 500, // ms - when the window does not have focus, check // if focus has been regained, every this time global_pan_sync_time: 1000, // ms - when you pan or zoom a chart, the background // auto-refreshing of charts is paused for this amount // of time sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount // of time before setting up synchronized selections // on hover. sync_selection: true, // enable or disable selection sync pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart sync_pan_and_zoom: true, // enable or disable pan and zoom sync pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming update_only_visible: true, // enable or disable visibility management parallel_refresher: (isSlowDevice() === false), // enable parallel refresh of charts concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts destroy_on_hide: (isSlowDevice() === true), // destroy charts when they are not visible show_help: netdataShowHelp, // when enabled the charts will show some help show_help_delay_show_ms: 500, show_help_delay_hide_ms: 0, eliminate_zero_dimensions: true, // do not show dimensions with just zeros stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap smooth_plot: (isSlowDevice() === false), // enable smooth plot, where possible charts_selection_animation_delay: 50, // delay to animate charts when syncing selection color_fill_opacity_line: 1.0, color_fill_opacity_area: 0.2, color_fill_opacity_stacked: 0.8, pan_and_zoom_factor: 0.25, // the increment when panning and zooming with the toolbox pan_and_zoom_factor_multiplier_control: 2.0, pan_and_zoom_factor_multiplier_shift: 3.0, pan_and_zoom_factor_multiplier_alt: 4.0, abort_ajax_on_scroll: false, // kill pending ajax page scroll async_on_scroll: false, // sync/async onscroll handler onscroll_worker_duration_threshold: 30, // time in ms, to consider slow the onscroll handler retries_on_data_failures: 3, // how many retries to make if we can't fetch chart data from the server setOptionCallback: function() { } }, debug: { show_boxes: false, main_loop: true, focus: false, visibility: false, chart_data_url: false, chart_errors: false, // FIXME: remember to set it to false before merging chart_timing: false, chart_calls: false, libraries: false, dygraph: false } }; NETDATA.statistics = { refreshes_total: 0, refreshes_active: 0, refreshes_active_max: 0 }; // ---------------------------------------------------------------------------------------------------------------- // local storage options NETDATA.localStorage = { default: {}, current: {}, callback: {} // only used for resetting back to defaults }; NETDATA.localStorageTested = -1; NETDATA.localStorageTest = function() { if(NETDATA.localStorageTested !== -1) return NETDATA.localStorageTested; if(typeof Storage !== "undefined" && typeof localStorage === 'object') { var test = 'test'; try { localStorage.setItem(test, test); localStorage.removeItem(test); NETDATA.localStorageTested = true; } catch (e) { NETDATA.localStorageTested = false; } } else NETDATA.localStorageTested = false; return NETDATA.localStorageTested; }; NETDATA.localStorageGet = function(key, def, callback) { var ret = def; if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') { NETDATA.localStorage.default[key.toString()] = def; NETDATA.localStorage.callback[key.toString()] = callback; } if(NETDATA.localStorageTest() === true) { try { // console.log('localStorage: loading "' + key.toString() + '"'); ret = localStorage.getItem(key.toString()); // console.log('netdata loaded: ' + key.toString() + ' = ' + ret.toString()); if(ret === null || ret === 'undefined') { // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"'); localStorage.setItem(key.toString(), JSON.stringify(def)); ret = def; } else { // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"'); ret = JSON.parse(ret); // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret)); } } catch(error) { console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"'); ret = def; } } if(typeof ret === 'undefined' || ret === 'undefined') { console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret)); ret = def; } NETDATA.localStorage.current[key.toString()] = ret; return ret; }; NETDATA.localStorageSet = function(key, value, callback) { if(typeof value === 'undefined' || value === 'undefined') { console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value)); } if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') { NETDATA.localStorage.default[key.toString()] = value; NETDATA.localStorage.current[key.toString()] = value; NETDATA.localStorage.callback[key.toString()] = callback; } if(NETDATA.localStorageTest() === true) { // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"'); try { localStorage.setItem(key.toString(), JSON.stringify(value)); } catch(e) { console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"'); } } NETDATA.localStorage.current[key.toString()] = value; return value; }; NETDATA.localStorageGetRecursive = function(obj, prefix, callback) { var keys = Object.keys(obj); var len = keys.length; while(len--) { var i = keys[len]; if(typeof obj[i] === 'object') { //console.log('object ' + prefix + '.' + i.toString()); NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback); continue; } obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback); } }; NETDATA.setOption = function(key, value) { if(key.toString() === 'setOptionCallback') { if(typeof NETDATA.options.current.setOptionCallback === 'function') { NETDATA.options.current[key.toString()] = value; NETDATA.options.current.setOptionCallback(); } } else if(NETDATA.options.current[key.toString()] !== value) { var name = 'options.' + key.toString(); if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined') console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value); //console.log(NETDATA.localStorage); //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()])); //console.log(NETDATA.options); NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null); if(typeof NETDATA.options.current.setOptionCallback === 'function') NETDATA.options.current.setOptionCallback(); } return true; }; NETDATA.getOption = function(key) { return NETDATA.options.current[key.toString()]; }; // read settings from local storage NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null); // always start with this option enabled. NETDATA.setOption('stop_updates_when_focus_is_lost', true); NETDATA.resetOptions = function() { var keys = Object.keys(NETDATA.localStorage.default); var len = keys.length; while(len--) { var i = keys[len]; var a = i.split('.'); if(a[0] === 'options') { if(a[1] === 'setOptionCallback') continue; if(typeof NETDATA.localStorage.default[i] === 'undefined') continue; if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue; NETDATA.setOption(a[1], NETDATA.localStorage.default[i]); } else if(a[0] === 'chart_heights') { if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') { NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]); } } } }; // ---------------------------------------------------------------------------------------------------------------- if(NETDATA.options.debug.main_loop === true) console.log('welcome to NETDATA'); NETDATA.onresizeCallback = null; NETDATA.onresize = function() { NETDATA.options.last_page_resize = Date.now(); NETDATA.onscroll(); if(typeof NETDATA.onresizeCallback === 'function') NETDATA.onresizeCallback(); }; NETDATA.onscroll_updater_count = 0; NETDATA.onscroll_updater_running = false; NETDATA.onscroll_updater_last_run = 0; NETDATA.onscroll_updater_watchdog = null; NETDATA.onscroll_updater_max_duration = 0; NETDATA.onscroll_updater_above_threshold_count = 0; NETDATA.onscroll_updater = function() { NETDATA.onscroll_updater_running = true; NETDATA.onscroll_updater_count++; var start = Date.now(); var targets = NETDATA.options.targets; var len = targets.length; // when the user scrolls he sees that we have // hidden all the not-visible charts // using this little function we try to switch // the charts back to visible quickly if(NETDATA.options.abort_ajax_on_scroll === true) { // we have to cancel pending requests too while (len--) { if (targets[len]._updating === true) { if (typeof targets[len].xhr !== 'undefined') { targets[len].xhr.abort(); targets[len].running = false; targets[len]._updating = false; } targets[len].isVisible(); } } } else { // just find which chart is visible while (len--) targets[len].isVisible(); } var end = Date.now(); // console.log('scroll No ' + NETDATA.onscroll_updater_count + ' calculation took ' + (end - start).toString() + ' ms'); if(NETDATA.options.current.async_on_scroll === false) { var dt = end - start; if(dt > NETDATA.onscroll_updater_max_duration) { // console.log('max onscroll event handler duration increased to ' + dt); NETDATA.onscroll_updater_max_duration = dt; } if(dt > NETDATA.options.current.onscroll_worker_duration_threshold) { // console.log('slow: ' + dt); NETDATA.onscroll_updater_above_threshold_count++; if(NETDATA.onscroll_updater_above_threshold_count > 2 && NETDATA.onscroll_updater_above_threshold_count * 100 / NETDATA.onscroll_updater_count > 2) { NETDATA.setOption('async_on_scroll', true); console.log('NETDATA: your browser is slow - enabling asynchronous onscroll event handler.'); } } } NETDATA.onscroll_updater_last_run = start; NETDATA.onscroll_updater_running = false; }; NETDATA.onscroll = function() { // console.log('onscroll'); NETDATA.options.last_page_scroll = Date.now(); NETDATA.options.auto_refresher_stop_until = 0; if(NETDATA.options.targets === null) return; if(NETDATA.options.current.async_on_scroll === true) { // async if(NETDATA.onscroll_updater_running === false) { NETDATA.onscroll_updater_running = true; setTimeout(NETDATA.onscroll_updater, 0); } else { if(NETDATA.onscroll_updater_watchdog !== null) clearTimeout(NETDATA.onscroll_updater_watchdog); NETDATA.onscroll_updater_watchdog = setTimeout(function() { if(NETDATA.onscroll_updater_running === false && NETDATA.options.last_page_scroll > NETDATA.onscroll_updater_last_run) { // console.log('watchdog'); NETDATA.onscroll_updater(); } NETDATA.onscroll_updater_watchdog = null; }, 200); } } else { // sync NETDATA.onscroll_updater(); } }; window.onresize = NETDATA.onresize; window.onscroll = NETDATA.onscroll; // ---------------------------------------------------------------------------------------------------------------- // Error Handling NETDATA.errorCodes = { 100: { message: "Cannot load chart library", alert: true }, 101: { message: "Cannot load jQuery", alert: true }, 402: { message: "Chart library not found", alert: false }, 403: { message: "Chart library not enabled/is failed", alert: false }, 404: { message: "Chart not found", alert: false }, 405: { message: "Cannot download charts index from server", alert: true }, 406: { message: "Invalid charts index downloaded from server", alert: true }, 407: { message: "Cannot HELLO netdata server", alert: false }, 408: { message: "Netdata servers sent invalid response to HELLO", alert: false }, 409: { message: "Cannot ACCESS netdata registry", alert: false }, 410: { message: "Netdata registry ACCESS failed", alert: false }, 411: { message: "Netdata registry server send invalid response to DELETE ", alert: false }, 412: { message: "Netdata registry DELETE failed", alert: false }, 413: { message: "Netdata registry server send invalid response to SWITCH ", alert: false }, 414: { message: "Netdata registry SWITCH failed", alert: false }, 415: { message: "Netdata alarms download failed", alert: false }, 416: { message: "Netdata alarms log download failed", alert: false }, 417: { message: "Netdata registry server send invalid response to SEARCH ", alert: false }, 418: { message: "Netdata registry SEARCH failed", alert: false } }; NETDATA.errorLast = { code: 0, message: "", datetime: 0 }; NETDATA.error = function(code, msg) { NETDATA.errorLast.code = code; NETDATA.errorLast.message = msg; NETDATA.errorLast.datetime = Date.now(); console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg); var ret = true; if(typeof netdataErrorCallback === 'function') { ret = netdataErrorCallback('system', code, msg); } if(ret && NETDATA.errorCodes[code].alert) alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg); }; NETDATA.errorReset = function() { NETDATA.errorLast.code = 0; NETDATA.errorLast.message = "You are doing fine!"; NETDATA.errorLast.datetime = 0; }; // ---------------------------------------------------------------------------------------------------------------- // fast numbers formatting NETDATA.fastNumberFormat = { formatters_fixed: [], formatters_zero_based: [], // this is the fastest and the preferred getIntlNumberFormat: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); return this.formatters_zero_based[key]; } else { // this is never used // it is added just for completeness return new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }, // this respects locale getLocaleString: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; return this.formatters_zero_based[key]; } else { return { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; } }, getFixed: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; return this.formatters_zero_based[key]; } else { return { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; } }, testIntlNumberFormat: function() { var n = 1.12345; var e1 = "1.12", e2 = "1,12"; var s = ""; try { var x = new Intl.NumberFormat(undefined, { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2 }); s = x.format(n); } catch(e) { s = ""; } // console.log('NumberFormat: ', s); return (s === e1 || s === e2); }, testLocaleString: function() { var n = 1.12345; var e1 = "1.12", e2 = "1,12"; var s = ""; try { s = value.toLocaleString(undefined, { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2 }); } catch(e) { s = ""; } // console.log('localeString: ', s); return (s === e1 || s === e2); }, // on first run we decide which formatter to use get: function(min, max) { if(this.testIntlNumberFormat()) { // console.log('numberformat'); this.get = this.getIntlNumberFormat; } else if(this.testLocaleString()) { // console.log('localestring'); this.get = this.getLocaleString; } else { // console.log('fixed'); this.get = this.getFixed; } return this.get(min, max); } }; // ---------------------------------------------------------------------------------------------------------------- // commonMin & commonMax NETDATA.commonMin = { keys: {}, latest: {}, get: function(state) { if(typeof state.__commonMin === 'undefined') { // get the commonMin setting var self = $(state.element); state.__commonMin = self.data('common-min') || null; } var min = state.data.min; var name = state.__commonMin; if(name === null) { // we don't need commonMin //state.log('no need for commonMin'); return min; } var t = this.keys[name]; if(typeof t === 'undefined') { // add our commonMin this.keys[name] = {}; t = this.keys[name]; } var uuid = state.uuid; if(typeof t[uuid] !== 'undefined') { if(t[uuid] === min) { //state.log('commonMin ' + state.__commonMin + ' not changed: ' + this.latest[name]); return this.latest[name]; } else if(min < this.latest[name]) { //state.log('commonMin ' + state.__commonMin + ' increased: ' + min); t[uuid] = min; this.latest[name] = min; return min; } } // add our min t[uuid] = min; // find the common min var m = min; for(var i in t) if(t.hasOwnProperty(i) && t[i] < m) m = t[i]; //state.log('commonMin ' + state.__commonMin + ' updated: ' + m); this.latest[name] = m; return m; } }; NETDATA.commonMax = { keys: {}, latest: {}, get: function(state) { if(typeof state.__commonMax === 'undefined') { // get the commonMax setting var self = $(state.element); state.__commonMax = self.data('common-max') || null; } var max = state.data.max; var name = state.__commonMax; if(name === null) { // we don't need commonMax //state.log('no need for commonMax'); return max; } var t = this.keys[name]; if(typeof t === 'undefined') { // add our commonMax this.keys[name] = {}; t = this.keys[name]; } var uuid = state.uuid; if(typeof t[uuid] !== 'undefined') { if(t[uuid] === max) { //state.log('commonMax ' + state.__commonMax + ' not changed: ' + this.latest[name]); return this.latest[name]; } else if(max > this.latest[name]) { //state.log('commonMax ' + state.__commonMax + ' increased: ' + max); t[uuid] = max; this.latest[name] = max; return max; } } // add our max t[uuid] = max; // find the common max var m = max; for(var i in t) if(t.hasOwnProperty(i) && t[i] > m) m = t[i]; //state.log('commonMax ' + state.__commonMax + ' updated: ' + m); this.latest[name] = m; return m; } }; // ---------------------------------------------------------------------------------------------------------------- // Chart Registry // When multiple charts need the same chart, we avoid downloading it // multiple times (and having it in browser memory multiple time) // by using this registry. // Every time we download a chart definition, we save it here with .add() // Then we try to get it back with .get(). If that fails, we download it. NETDATA.fixHost = function(host) { while(host.slice(-1) === '/') host = host.substring(0, host.length - 1); console.info('old host:', host); // http://localhost:8529/_db/api/v1/api/v1/chart?chart=netdata.server_cpu&_=1500781574657 host = 'http://172.16.17.32:8529/_db/api/v1/'; // by rico return host; }; NETDATA.chartRegistry = { charts: {}, fixid: function(id) { return id.replace(/:/g, "_").replace(/\//g, "_"); }, add: function(host, id, data) { host = this.fixid(host); id = this.fixid(id); if(typeof this.charts[host] === 'undefined') this.charts[host] = {}; console.log('added ' + host + '/' + id + ' with data:' + data); this.charts[host][id] = data; }, get: function(host, id) { host = this.fixid(host); id = this.fixid(id); if(typeof this.charts[host] === 'undefined') return null; if(typeof this.charts[host][id] === 'undefined') return null; //console.log('cached ' + host + '/' + id); return this.charts[host][id]; }, downloadAll: function(host, callback) { host = this.host; //NETDATA.fixHost(host); var self = this; console.log('Rico trace in downloadAll:', host + '/api/v1/charts'); $.ajax({ url: host + '/api/v1/charts', async: true, cache: false, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(data !== null) { var h = NETDATA.chartRegistry.fixid(host); self.charts[h] = data.charts; } else NETDATA.error(406, host + '/api/v1/charts'); if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(405, host + '/api/v1/charts'); if(typeof callback === 'function') return callback(null); }); } }; // ---------------------------------------------------------------------------------------------------------------- // Global Pan and Zoom on charts // Using this structure are synchronize all the charts, so that // when you pan or zoom one, all others are automatically refreshed // to the same timespan. NETDATA.globalPanAndZoom = { seq: 0, // timestamp ms // every time a chart is panned or zoomed // we set the timestamp here // then we use it as a sequence number // to find if other charts are synchronized // to this time-range master: null, // the master chart (state), to which all others // are synchronized force_before_ms: null, // the timespan to sync all other charts force_after_ms: null, callback: null, // set a new master setMaster: function(state, after, before) { if(NETDATA.options.current.sync_pan_and_zoom === false) return; if(this.master !== null && this.master !== state) this.master.resetChart(true, true); var now = Date.now(); this.master = state; this.seq = now; this.force_after_ms = after; this.force_before_ms = before; NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time; if(typeof this.callback === 'function') this.callback(true, after, before); }, // clear the master clearMaster: function() { if(this.master !== null) { var st = this.master; this.master = null; st.resetChart(); } this.master = null; this.seq = 0; this.force_after_ms = null; this.force_before_ms = null; NETDATA.options.auto_refresher_stop_until = 0; if(typeof this.callback === 'function') this.callback(false, 0, 0); }, // is the given state the master of the global // pan and zoom sync? isMaster: function(state) { return (this.master === state); }, // are we currently have a global pan and zoom sync? isActive: function() { return (this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0); }, // check if a chart, other than the master // needs to be refreshed, due to the global pan and zoom shouldBeAutoRefreshed: function(state) { if(this.master === null || this.seq === 0) return false; //if(state.needsRecreation()) // return true; return (state.tm.pan_and_zoom_seq !== this.seq); } }; // ---------------------------------------------------------------------------------------------------------------- // dimensions selection // FIXME // move color assignment to dimensions, here var dimensionStatus = function(parent, label, name_div, value_div, color) { this.enabled = false; this.parent = parent; this.label = label; this.name_div = null; this.value_div = null; this.color = NETDATA.themes.current.foreground; this.selected = (parent.unselected_count === 0); this.setOptions(name_div, value_div, color); }; dimensionStatus.prototype.invalidate = function() { this.name_div = null; this.value_div = null; this.enabled = false; }; dimensionStatus.prototype.setOptions = function(name_div, value_div, color) { this.color = color; if(this.name_div !== name_div) { this.name_div = name_div; this.name_div.title = this.label; this.name_div.style.color = this.color; if(this.selected === false) this.name_div.className = 'netdata-legend-name not-selected'; else this.name_div.className = 'netdata-legend-name selected'; } if(this.value_div !== value_div) { this.value_div = value_div; this.value_div.title = this.label; this.value_div.style.color = this.color; if(this.selected === false) this.value_div.className = 'netdata-legend-value not-selected'; else this.value_div.className = 'netdata-legend-value selected'; } this.enabled = true; this.setHandler(); }; dimensionStatus.prototype.setHandler = function() { if(this.enabled === false) return; var ds = this; // this.name_div.onmousedown = this.value_div.onmousedown = function(e) { this.name_div.onclick = this.value_div.onclick = function(e) { e.preventDefault(); if(ds.isSelected()) { // this is selected if(e.shiftKey === true || e.ctrlKey === true) { // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all) ds.unselect(); if(ds.parent.countSelected() === 0) ds.parent.selectAll(); } else { // no key is pressed -> select only this (except if it is the only selected already, in which case select all) if(ds.parent.countSelected() === 1) { ds.parent.selectAll(); } else { ds.parent.selectNone(); ds.select(); } } } else { // this is not selected if(e.shiftKey === true || e.ctrlKey === true) { // control or shift key is pressed -> select this too ds.select(); } else { // no key is pressed -> select only this ds.parent.selectNone(); ds.select(); } } ds.parent.state.redrawChart(); } }; dimensionStatus.prototype.select = function() { if(this.enabled === false) return; this.name_div.className = 'netdata-legend-name selected'; this.value_div.className = 'netdata-legend-value selected'; this.selected = true; }; dimensionStatus.prototype.unselect = function() { if(this.enabled === false) return; this.name_div.className = 'netdata-legend-name not-selected'; this.value_div.className = 'netdata-legend-value hidden'; this.selected = false; }; dimensionStatus.prototype.isSelected = function() { return(this.enabled === true && this.selected === true); }; // ---------------------------------------------------------------------------------------------------------------- var dimensionsVisibility = function(state) { this.state = state; this.len = 0; this.dimensions = {}; this.selected_count = 0; this.unselected_count = 0; }; dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) { if(typeof this.dimensions[label] === 'undefined') { this.len++; this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color); } else this.dimensions[label].setOptions(name_div, value_div, color); return this.dimensions[label]; }; dimensionsVisibility.prototype.dimensionGet = function(label) { return this.dimensions[label]; }; dimensionsVisibility.prototype.invalidateAll = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].invalidate(); }; dimensionsVisibility.prototype.selectAll = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].select(); }; dimensionsVisibility.prototype.countSelected = function() { var selected = 0; var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) if(this.dimensions[keys[len]].isSelected()) selected++; return selected; }; dimensionsVisibility.prototype.selectNone = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].unselect(); }; dimensionsVisibility.prototype.selected2BooleanArray = function(array) { var ret = []; this.selected_count = 0; this.unselected_count = 0; var len = array.length; while(len--) { var ds = this.dimensions[array[len]]; if(typeof ds === 'undefined') { // console.log(array[i] + ' is not found'); ret.unshift(false); } else if(ds.isSelected()) { ret.unshift(true); this.selected_count++; } else { ret.unshift(false); this.unselected_count++; } } if(this.selected_count === 0 && this.unselected_count !== 0) { this.selectAll(); return this.selected2BooleanArray(array); } return ret; }; // ---------------------------------------------------------------------------------------------------------------- // global selection sync NETDATA.globalSelectionSync = { state: null, dont_sync_before: 0, last_t: 0, slaves: [], stop: function() { if(this.state !== null) this.state.globalSelectionSyncStop(); }, delay: function() { if(this.state !== null) { this.state.globalSelectionSyncDelay(); } } }; // ---------------------------------------------------------------------------------------------------------------- // Our state object, where all per-chart values are stored var chartState = function(element) { var self = $(element); this.element = element; // IMPORTANT: // all private functions should use 'that', instead of 'this' var that = this; /* error() - private * show an error instead of the chart */ var error = function(msg) { var ret = true; if(typeof netdataErrorCallback === 'function') { ret = netdataErrorCallback('chart', that.id, msg); } if(ret) { that.element.innerHTML = that.id + ': ' + msg; that.enabled = false; that.current = that.pan; } }; // GUID - a unique identifier for the chart this.uuid = NETDATA.guid(); // string - the name of chart this.id = self.data('netdata'); // string - the key for localStorage settings this.settings_id = self.data('id') || null; // the user given dimensions of the element this.width = self.data('width') || NETDATA.chartDefaults.width; this.height = self.data('height') || NETDATA.chartDefaults.height; this.height_original = this.height; if(this.settings_id !== null) { this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) { // this is the callback that will be called // if and when the user resets all localStorage variables // to their defaults resizeChartToHeight(height); }); } // string - the netdata server URL, without any path console.log('Rico trace in chartState:',self.data('host')) console.log('Rico trace in chartState:',NETDATA.chartDefaults.host) this.host = self.data('host') || NETDATA.chartDefaults.host; // make sure the host does not end with / // all netdata API requests use absolute paths while(this.host.slice(-1) === '/') this.host = this.host.substring(0, this.host.length - 1); console.log('Rico trace in chartState: this.host=', this.host) // string - the grouping method requested by the user this.method = self.data('method') || NETDATA.chartDefaults.method; // the time-range requested by the user this.after = self.data('after') || NETDATA.chartDefaults.after; this.before = self.data('before') || NETDATA.chartDefaults.before; // the pixels per point requested by the user this.pixels_per_point = self.data('pixels-per-point') || 1; this.points = self.data('points') || null; // the dimensions requested by the user this.dimensions = self.data('dimensions') || null; // the chart library requested by the user this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library; // how many retries we have made to load chart data from the server this.retries_on_data_failures = 0; // object - the chart library used this.library = null; // color management this.colors = null; this.colors_assigned = {}; this.colors_available = null; this.colors_custom = null; // the element already created by the user this.element_message = null; // the element with the chart this.element_chart = null; // the element with the legend of the chart (if created by us) this.element_legend = null; this.element_legend_childs = { hidden: null, title_date: null, title_time: null, title_units: null, perfect_scroller: null, // the container to apply perfect scroller to series: null }; this.chart_url = null; // string - the url to download chart info this.chart = null; // object - the chart as downloaded from the server this.title = self.data('title') || null; // the title of the chart this.units = self.data('units') || null; // the units of the chart dimensions this.append_options = self.data('append-options') || null; // additional options to pass to netdata this.override_options = self.data('override-options') || null; // override options to pass to netdata this.running = false; // boolean - true when the chart is being refreshed now this.enabled = true; // boolean - is the chart enabled for refresh? this.paused = false; // boolean - is the chart paused for any reason? this.selected = false; // boolean - is the chart shown a selection? this.debug = self.data('debug') === true; // boolean - console.log() debug info about this chart this.netdata_first = 0; // milliseconds - the first timestamp in netdata this.netdata_last = 0; // milliseconds - the last timestamp in netdata this.requested_after = null; // milliseconds - the timestamp of the request after param this.requested_before = null; // milliseconds - the timestamp of the request before param this.requested_padding = null; this.view_after = 0; this.view_before = 0; this.value_decimal_detail = -1; var d = self.data('decimal-digits'); if(typeof d === 'number') { this.value_decimal_detail = d; } this.auto = { name: 'auto', autorefresh: true, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; this.pan = { name: 'pan', autorefresh: false, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; this.zoom = { name: 'zoom', autorefresh: false, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; // this is a pointer to one of the sub-classes below // auto, pan, zoom this.current = this.auto; // check the requested library is available // we don't initialize it here - it will be initialized when // this chart will be first used if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') { NETDATA.error(402, that.library_name); error('chart library "' + that.library_name + '" is not found'); return; } else if(NETDATA.chartLibraries[that.library_name].enabled === false) { NETDATA.error(403, that.library_name); error('chart library "' + that.library_name + '" is not enabled'); return; } else{ that.library = NETDATA.chartLibraries[that.library_name]; console.log('^^^^^^^^^^^^NETDATA.chartLibraries[] with ', that.library_name) } // milliseconds - the time the last refresh took this.refresh_dt_ms = 0; // if we need to report the rendering speed // find the element that needs to be updated var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms if(refresh_dt_element_name !== null) { this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null; } else this.refresh_dt_element = null; this.dimensions_visibility = new dimensionsVisibility(this); this._updating = false; // ============================================================================================================ // PRIVATE FUNCTIONS var createDOM = function() { if(that.enabled === false) return; if(that.element_message !== null) that.element_message.innerHTML = ''; if(that.element_legend !== null) that.element_legend.innerHTML = ''; if(that.element_chart !== null) that.element_chart.innerHTML = ''; that.element.innerHTML = ''; that.element_message = document.createElement('div'); that.element_message.className = 'netdata-message icon hidden'; that.element.appendChild(that.element_message); that.element_chart = document.createElement('div'); that.element_chart.id = that.library_name + '-' + that.uuid + '-chart'; that.element.appendChild(that.element_chart); if(that.hasLegend() === true) { that.element.className = "netdata-container-with-legend"; that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right'; that.element_legend = document.createElement('div'); that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend'; that.element.appendChild(that.element_legend); } else { that.element.className = "netdata-container"; that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart'; that.element_legend = null; } that.element_legend_childs.series = null; if(typeof(that.width) === 'string') $(that.element).css('width', that.width); else if(typeof(that.width) === 'number') $(that.element).css('width', that.width + 'px'); if(typeof(that.library.aspect_ratio) === 'undefined') { if(typeof(that.height) === 'string') that.element.style.height = that.height; else if(typeof(that.height) === 'number') that.element.style.height = that.height.toString() + 'px'; } else { var w = that.element.offsetWidth; if(w === null || w === 0) { // the div is hidden // this will resize the chart when next viewed that.tm.last_resized = 0; } else that.element.style.height = (w * that.library.aspect_ratio / 100).toString() + 'px'; } if(NETDATA.chartDefaults.min_width !== null) $(that.element).css('min-width', NETDATA.chartDefaults.min_width); that.tm.last_dom_created = Date.now(); showLoading(); }; /* init() private * initialize state variables * destroy all (possibly) created state elements * create the basic DOM for a chart */ var init = function() { if(that.enabled === false) return; that.paused = false; that.selected = false; that.chart_created = false; // boolean - is the library.create() been called? that.updates_counter = 0; // numeric - the number of refreshes made so far that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created that.tm = { last_initialized: 0, // milliseconds - the timestamp it was last initialized last_dom_created: 0, // milliseconds - the timestamp its DOM was last created last_mode_switch: 0, // milliseconds - the timestamp it switched modes last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart last_updated: 0, // the timestamp the chart last updated with data pan_and_zoom_seq: 0, // the sequence number of the global synchronization // between chart. // Used with NETDATA.globalPanAndZoom.seq last_visible_check: 0, // the time we last checked if it is visible last_resized: 0, // the time the chart was resized last_hidden: 0, // the time the chart was hidden last_unhidden: 0, // the time the chart was unhidden last_autorefreshed: 0 // the time the chart was last refreshed }; that.data = null; // the last data as downloaded from the netdata server that.data_url = 'invalid://'; // string - the last url used to update the chart that.data_points = 0; // number - the number of points returned from netdata that.data_after = 0; // milliseconds - the first timestamp of the data that.data_before = 0; // milliseconds - the last timestamp of the data that.data_update_every = 0; // milliseconds - the frequency to update the data that.tm.last_initialized = Date.now(); createDOM(); that.setMode('auto'); }; var maxMessageFontSize = function() { var screenHeight = screen.height; var el = that.element; // normally we want a font size, as tall as the element var h = el.clientHeight; // but give it some air, 20% let's say, or 5 pixels min var lost = Math.max(h * 0.2, 5); h -= lost; // center the text, vertically var paddingTop = (lost - 5) / 2; // but check the width too // it should fit 10 characters in it var w = el.clientWidth / 10; if(h > w) { paddingTop += (h - w) / 2; h = w; } // and don't make it too huge // 5% of the screen size is good if(h > screenHeight / 20) { paddingTop += (h - (screenHeight / 20)) / 2; h = screenHeight / 20; } // set it that.element_message.style.fontSize = h.toString() + 'px'; that.element_message.style.paddingTop = paddingTop.toString() + 'px'; }; var showMessageIcon = function(icon) { that.element_message.innerHTML = icon; maxMessageFontSize(); $(that.element_message).removeClass('hidden'); that.___messageHidden___ = undefined; }; var hideMessage = function() { if(typeof that.___messageHidden___ === 'undefined') { that.___messageHidden___ = true; $(that.element_message).addClass('hidden'); } }; var showRendering = function() { var icon; if(that.chart !== null) { if(that.chart.chart_type === 'line') icon = '<i class="fa fa-line-chart"></i>'; else icon = '<i class="fa fa-area-chart"></i>'; } else icon = '<i class="fa fa-area-chart"></i>'; showMessageIcon(icon + ' netdata'); }; var showLoading = function() { if(that.chart_created === false) { showMessageIcon('<i class="fa fa-refresh"></i> netdata'); return true; } return false; }; var isHidden = function() { return (typeof that.___chartIsHidden___ !== 'undefined'); }; // hide the chart, when it is not visible - called from isVisible() var hideChart = function() { // hide it, if it is not already hidden if(isHidden() === true) return; if(that.chart_created === true) { if(NETDATA.options.current.destroy_on_hide === true) { // we should destroy it init(); } else { showRendering(); that.element_chart.style.display = 'none'; if(that.element_legend !== null) that.element_legend.style.display = 'none'; if(that.element_legend_childs.toolbox !== null) that.element_legend_childs.toolbox.style.display = 'none'; if(that.element_legend_childs.resize_handler !== null) that.element_legend_childs.resize_handler.style.display = 'none'; that.tm.last_hidden = Date.now(); // de-allocate data // This works, but I not sure there are no corner cases somewhere // so it is commented - if the user has memory issues he can // set Destroy on Hide for all charts // that.data = null; } } that.___chartIsHidden___ = true; }; // unhide the chart, when it is visible - called from isVisible() var unhideChart = function() { if(isHidden() === false) return; that.___chartIsHidden___ = undefined; that.updates_since_last_unhide = 0; if(that.chart_created === false) { // we need to re-initialize it, to show our background // logo in bootstrap tabs, until the chart loads init(); } else { that.tm.last_unhidden = Date.now(); that.element_chart.style.display = ''; if(that.element_legend !== null) that.element_legend.style.display = ''; if(that.element_legend_childs.toolbox !== null) that.element_legend_childs.toolbox.style.display = ''; if(that.element_legend_childs.resize_handler !== null) that.element_legend_childs.resize_handler.style.display = ''; resizeChart(); hideMessage(); } }; var canBeRendered = function() { return (isHidden() === false && that.isVisible(true) === true); }; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers var callChartLibraryUpdateSafely = function(data) { var status; if(canBeRendered() === false) return false; if(NETDATA.options.debug.chart_errors === true) status = that.library.update(that, data); else { try { status = that.library.update(that, data); } catch(err) { status = false; } } if(status === false) { error('chart failed to be updated as ' + that.library_name); return false; } return true; }; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers var callChartLibraryCreateSafely = function(data) { var status; if(canBeRendered() === false) return false; if(NETDATA.options.debug.chart_errors === true) status = that.library.create(that, data); else { try { status = that.library.create(that, data); } catch(err) { status = false; } } if(status === false) { error('chart failed to be created as ' + that.library_name); return false; } that.chart_created = true; that.updates_since_last_creation = 0; return true; }; // ---------------------------------------------------------------------------------------------------------------- // Chart Resize // resizeChart() - private // to be called just before the chart library to make sure that // a properly sized dom is available var resizeChart = function() { if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_page_resize) { if(that.chart_created === false) return; if(that.needsRecreation()) { init(); } else if(typeof that.library.resize === 'function') { that.library.resize(that); if(that.element_legend_childs.perfect_scroller !== null) Ps.update(that.element_legend_childs.perfect_scroller); maxMessageFontSize(); } that.tm.last_resized = Date.now(); } }; // this is the actual chart resize algorithm // it will: // - resize the entire container // - update the internal states // - resize the chart as the div changes height // - update the scrollbar of the legend var resizeChartToHeight = function(h) { // console.log(h); that.element.style.height = h; if(that.settings_id !== null) NETDATA.localStorageSet('chart_heights.' + that.settings_id, h); var now = Date.now(); NETDATA.options.last_page_scroll = now; NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing; // force a resize that.tm.last_resized = 0; resizeChart(); }; this.resizeHandler = function(e) { e.preventDefault(); if(typeof this.event_resize === 'undefined' || this.event_resize.chart_original_w === 'undefined' || this.event_resize.chart_original_h === 'undefined') this.event_resize = { chart_original_w: this.element.clientWidth, chart_original_h: this.element.clientHeight, last: 0 }; if(e.type === 'touchstart') { this.event_resize.mouse_start_x = e.touches.item(0).pageX; this.event_resize.mouse_start_y = e.touches.item(0).pageY; } else { this.event_resize.mouse_start_x = e.clientX; this.event_resize.mouse_start_y = e.clientY; } this.event_resize.chart_start_w = this.element.clientWidth; this.event_resize.chart_start_h = this.element.clientHeight; this.event_resize.chart_last_w = this.element.clientWidth; this.event_resize.chart_last_h = this.element.clientHeight; var now = Date.now(); if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed && this.element_legend_childs.perfect_scroller !== null) { // double click / double tap event // console.dir(this.element_legend_childs.content); // console.dir(this.element_legend_childs.perfect_scroller); // the optimal height of the chart // showing the entire legend var optimal = this.event_resize.chart_last_h + this.element_legend_childs.perfect_scroller.scrollHeight - this.element_legend_childs.perfect_scroller.clientHeight; // if we are not optimal, be optimal if(this.event_resize.chart_last_h !== optimal) { // this.log('resize to optimal, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(optimal.toString() + 'px'); } // else if the current height is not the original/saved height // reset to the original/saved height else if(this.event_resize.chart_last_h !== this.event_resize.chart_original_h) { // this.log('resize to original, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px'); } // else if the current height is not the internal default height // reset to the internal default height else if((this.event_resize.chart_last_h.toString() + 'px') !== this.height_original) { // this.log('resize to internal default, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(this.height_original.toString()); } // else if the current height is not the firstchild's clientheight // resize to it else if(typeof this.element_legend_childs.perfect_scroller.firstChild !== 'undefined') { var parent_rect = this.element.getBoundingClientRect(); var content_rect = this.element_legend_childs.perfect_scroller.firstElementChild.getBoundingClientRect(); var wanted = content_rect.top - parent_rect.top + this.element_legend_childs.perfect_scroller.firstChild.clientHeight + 18; // 15 = toolbox + 3 space // console.log(parent_rect); // console.log(content_rect); // console.log(wanted); // this.log('resize to firstChild, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString() + 'px, firstChild = ' + wanted.toString() + 'px' ); if(this.event_resize.chart_last_h !== wanted) resizeChartToHeight(wanted.toString() + 'px'); } } else { this.event_resize.last = now; // process movement event document.onmousemove = document.ontouchmove = this.element_legend_childs.resize_handler.onmousemove = this.element_legend_childs.resize_handler.ontouchmove = function(e) { var y = null; switch(e.type) { case 'mousemove': y = e.clientY; break; case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break; } if(y !== null) { var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y; if(newH >= 70 && newH !== that.event_resize.chart_last_h) { resizeChartToHeight(newH.toString() + 'px'); that.event_resize.chart_last_h = newH; } } }; // process end event document.onmouseup = document.ontouchend = this.element_legend_childs.resize_handler.onmouseup = this.element_legend_childs.resize_handler.ontouchend = function(e) { void(e); // remove all the hooks document.onmouseup = document.onmousemove = document.ontouchmove = document.ontouchend = that.element_legend_childs.resize_handler.onmousemove = that.element_legend_childs.resize_handler.ontouchmove = that.element_legend_childs.resize_handler.onmouseout = that.element_legend_childs.resize_handler.onmouseup = that.element_legend_childs.resize_handler.ontouchend = null; // allow auto-refreshes NETDATA.options.auto_refresher_stop_until = 0; }; } }; var noDataToShow = function() { showMessageIcon('<i class="fa fa-warning"></i> empty'); that.legendUpdateDOM(); that.tm.last_autorefreshed = Date.now(); // that.data_update_every = 30 * 1000; //that.element_chart.style.display = 'none'; //if(that.element_legend !== null) that.element_legend.style.display = 'none'; //that.___chartIsHidden___ = true; }; // ============================================================================================================ // PUBLIC FUNCTIONS this.error = function(msg) { error(msg); }; this.setMode = function(m) { if(this.current !== null && this.current.name === m) return; if(m === 'auto') this.current = this.auto; else if(m === 'pan') this.current = this.pan; else if(m === 'zoom') this.current = this.zoom; else this.current = this.auto; this.current.force_update_at = 0; this.current.force_before_ms = null; this.current.force_after_ms = null; this.tm.last_mode_switch = Date.now(); }; // ---------------------------------------------------------------------------------------------------------------- // global selection sync // prevent to global selection sync for some time this.globalSelectionSyncDelay = function(ms) { if(NETDATA.options.current.sync_selection === false) return; if(typeof ms === 'number') NETDATA.globalSelectionSync.dont_sync_before = Date.now() + ms; else NETDATA.globalSelectionSync.dont_sync_before = Date.now() + NETDATA.options.current.sync_selection_delay; }; // can we globally apply selection sync? this.globalSelectionSyncAbility = function() { if(NETDATA.options.current.sync_selection === false) return false; return (NETDATA.globalSelectionSync.dont_sync_before <= Date.now()); }; this.globalSelectionSyncIsMaster = function() { return (NETDATA.globalSelectionSync.state === this); }; // this chart is the master of the global selection sync this.globalSelectionSyncBeMaster = function() { // am I the master? if(this.globalSelectionSyncIsMaster()) { if(this.debug === true) this.log('sync: I am the master already.'); return; } if(NETDATA.globalSelectionSync.state) { if(this.debug === true) this.log('sync: I am not the sync master. Resetting global sync.'); this.globalSelectionSyncStop(); } // become the master if(this.debug === true) this.log('sync: becoming sync master.'); this.selected = true; NETDATA.globalSelectionSync.state = this; // find the all slaves var targets = NETDATA.options.targets; var len = targets.length; while(len--) { var st = targets[len]; if(st === this) { if(this.debug === true) st.log('sync: not adding me to sync'); } else if(st.globalSelectionSyncIsEligible()) { if(this.debug === true) st.log('sync: adding to sync as slave'); st.globalSelectionSyncBeSlave(); } } // this.globalSelectionSyncDelay(100); }; // can the chart participate to the global selection sync as a slave? this.globalSelectionSyncIsEligible = function() { return (this.enabled === true && this.library !== null && typeof this.library.setSelection === 'function' && this.isVisible() === true && this.chart_created === true); }; // this chart becomes a slave of the global selection sync this.globalSelectionSyncBeSlave = function() { if(NETDATA.globalSelectionSync.state !== this) NETDATA.globalSelectionSync.slaves.push(this); }; // sync all the visible charts to the given time // this is to be called from the chart libraries this.globalSelectionSync = function(t) { if(this.globalSelectionSyncAbility() === false) return; if(this.globalSelectionSyncIsMaster() === false) { if(this.debug === true) this.log('sync: trying to be sync master.'); this.globalSelectionSyncBeMaster(); if(this.globalSelectionSyncAbility() === false) return; } NETDATA.globalSelectionSync.last_t = t; $.each(NETDATA.globalSelectionSync.slaves, function(i, st) { st.setSelection(t); }); }; // stop syncing all charts to the given time this.globalSelectionSyncStop = function() { if(NETDATA.globalSelectionSync.slaves.length) { if(this.debug === true) this.log('sync: cleaning up...'); $.each(NETDATA.globalSelectionSync.slaves, function(i, st) { if(st === that) { if(that.debug === true) st.log('sync: not adding me to sync stop'); } else { if(that.debug === true) st.log('sync: removed slave from sync'); st.clearSelection(); } }); NETDATA.globalSelectionSync.last_t = 0; NETDATA.globalSelectionSync.slaves = []; NETDATA.globalSelectionSync.state = null; } this.clearSelection(); }; this.setSelection = function(t) { if(typeof this.library.setSelection === 'function') this.selected = (this.library.setSelection(this, t) === true); else this.selected = true; if(this.selected === true && this.debug === true) this.log('selection set to ' + t.toString()); return this.selected; }; this.clearSelection = function() { if(this.selected === true) { if(typeof this.library.clearSelection === 'function') this.selected = (this.library.clearSelection(this) !== true); else this.selected = false; if(this.selected === false && this.debug === true) this.log('selection cleared'); this.legendReset(); } return this.selected; }; // find if a timestamp (ms) is shown in the current chart this.timeIsVisible = function(t) { return (t >= this.data_after && t <= this.data_before); }; this.calculateRowForTime = function(t) { if(this.timeIsVisible(t) === false) return -1; return Math.floor((t - this.data_after) / this.data_update_every); }; // ---------------------------------------------------------------------------------------------------------------- // console logging this.log = function(msg) { console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg); }; this.pauseChart = function() { if(this.paused === false) { if(this.debug === true) this.log('pauseChart()'); this.paused = true; } }; this.unpauseChart = function() { if(this.paused === true) { if(this.debug === true) this.log('unpauseChart()'); this.paused = false; } }; this.resetChart = function(dont_clear_master, dont_update) { if(this.debug === true) this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called'); if(typeof dont_clear_master === 'undefined') dont_clear_master = false; if(typeof dont_update === 'undefined') dont_update = false; if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) { if(this.debug === true) this.log('resetChart() diverting to clearMaster().'); // this will call us back with master === true NETDATA.globalPanAndZoom.clearMaster(); return; } this.clearSelection(); this.tm.pan_and_zoom_seq = 0; this.setMode('auto'); this.current.force_update_at = 0; this.current.force_before_ms = null; this.current.force_after_ms = null; this.tm.last_autorefreshed = 0; this.paused = false; this.selected = false; this.enabled = true; // this.debug = false; // do not update the chart here // or the chart will flip-flop when it is the master // of a selection sync and another chart becomes // the new master if(dont_update !== true && this.isVisible() === true) { this.updateChart(); } }; this.updateChartPanOrZoom = function(after, before) { var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): '; var ret = true; if(this.debug === true) this.log(logme); if(before < after) { if(this.debug === true) this.log(logme + 'flipped parameters, rejecting it.'); return false; } if(typeof this.fixed_min_duration === 'undefined') this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000); var min_duration = this.fixed_min_duration; var current_duration = Math.round(this.view_before - this.view_after); // round the numbers after = Math.round(after); before = Math.round(before); // align them to update_every // stretching them further away after -= after % this.data_update_every; before += this.data_update_every - (before % this.data_update_every); // the final wanted duration var wanted_duration = before - after; // to allow panning, accept just a point below our minimum if((current_duration - this.data_update_every) < min_duration) min_duration = current_duration - this.data_update_every; // we do it, but we adjust to minimum size and return false // when the wanted size is below the current and the minimum // and we zoom if(wanted_duration < current_duration && wanted_duration < min_duration) { if(this.debug === true) this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString()); min_duration = this.fixed_min_duration; var dt = (min_duration - wanted_duration) / 2; before += dt; after -= dt; wanted_duration = before - after; ret = false; } var tolerance = this.data_update_every * 2; var movement = Math.abs(before - this.view_before); if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret === true) { if(this.debug === true) this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false); return false; } if(this.current.name === 'auto') { this.log(logme + 'caller called me with mode: ' + this.current.name); this.setMode('pan'); } if(this.debug === true) this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret); this.current.force_update_at = Date.now() + NETDATA.options.current.pan_and_zoom_delay; this.current.force_after_ms = after; this.current.force_before_ms = before; NETDATA.globalPanAndZoom.setMaster(this, after, before); return ret; }; var __legendFormatValueChartDecimalsLastMin = undefined; var __legendFormatValueChartDecimalsLastMax = undefined; var __legendFormatValueChartDecimals = -1; var __intlNumberFormat = null; this.legendFormatValueDecimalsFromMinMax = function(min, max) { if(min === __legendFormatValueChartDecimalsLastMin && max === __legendFormatValueChartDecimalsLastMax) return; __legendFormatValueChartDecimalsLastMin = min; __legendFormatValueChartDecimalsLastMax = max; var old = __legendFormatValueChartDecimals; if(this.data !== null && this.data.min === this.data.max) // it is a fixed number, let the visualizer decide based on the value __legendFormatValueChartDecimals = -1; else if(this.value_decimal_detail !== -1) // there is an override __legendFormatValueChartDecimals = this.value_decimal_detail; else { // ok, let's calculate the proper number of decimal points var delta; if (min === max) delta = Math.abs(min); else delta = Math.abs(max - min); if (delta > 1000) __legendFormatValueChartDecimals = 0; else if (delta > 10) __legendFormatValueChartDecimals = 1; else if (delta > 1) __legendFormatValueChartDecimals = 2; else if (delta > 0.1) __legendFormatValueChartDecimals = 2; else __legendFormatValueChartDecimals = 4; } if(__legendFormatValueChartDecimals !== old) { if(__legendFormatValueChartDecimals < 0) __intlNumberFormat = null; else __intlNumberFormat = NETDATA.fastNumberFormat.get( __legendFormatValueChartDecimals, __legendFormatValueChartDecimals ); } }; this.legendFormatValue = function(value) { if(typeof value !== 'number') return '-'; if(__intlNumberFormat !== null) return __intlNumberFormat.format(value); var dmin, dmax; if(this.value_decimal_detail !== -1) { dmin = dmax = this.value_decimal_detail; } else { dmin = 0; var abs = (value < 0) ? -value : value; if (abs > 1000) dmax = 0; else if (abs > 10) dmax = 1; else if (abs > 1) dmax = 2; else if (abs > 0.1) dmax = 2; else dmax = 4; } return NETDATA.fastNumberFormat.get(dmin, dmax).format(value); }; this.legendSetLabelValue = function(label, value) { var series = this.element_legend_childs.series[label]; if(typeof series === 'undefined') return; if(series.value === null && series.user === null) return; /* // this slows down firefox and edge significantly // since it requires to use innerHTML(), instead of innerText() // if the value has not changed, skip DOM update //if(series.last === value) return; var s, r; if(typeof value === 'number') { var v = Math.abs(value); s = r = this.legendFormatValue(value); if(typeof series.last === 'number') { if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; } else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; series.last = v; } else { if(value === null) s = r = ''; else s = r = value; series.last = value; } */ var s = this.legendFormatValue(value); // caching: do not update the update to show the same value again if(s === series.last_shown_value) return; series.last_shown_value = s; if(series.value !== null) series.value.innerText = s; if(series.user !== null) series.user.innerText = s; }; this.__legendSetDateString = function(date) { if(date !== this.__last_shown_legend_date) { this.element_legend_childs.title_date.innerText = date; this.__last_shown_legend_date = date; } }; this.__legendSetTimeString = function(time) { if(time !== this.__last_shown_legend_time) { this.element_legend_childs.title_time.innerText = time; this.__last_shown_legend_time = time; } }; this.__legendSetUnitsString = function(units) { if(units !== this.__last_shown_legend_units) { this.element_legend_childs.title_units.innerText = units; this.__last_shown_legend_units = units; } }; this.legendSetDateLast = { ms: 0, date: undefined, time: undefined }; this.legendSetDate = function(ms) { if(typeof ms !== 'number') { this.legendShowUndefined(); return; } if(this.legendSetDateLast.ms !== ms) { var d = new Date(ms); this.legendSetDateLast.ms = ms; this.legendSetDateLast.date = d.toLocaleDateString(); this.legendSetDateLast.time = d.toLocaleTimeString(); } if(this.element_legend_childs.title_date !== null) this.__legendSetDateString(this.legendSetDateLast.date); if(this.element_legend_childs.title_time !== null) this.__legendSetTimeString(this.legendSetDateLast.time); if(this.element_legend_childs.title_units !== null) this.__legendSetUnitsString(this.units) }; this.legendShowUndefined = function() { if(this.element_legend_childs.title_date !== null) this.__legendSetDateString(' '); if(this.element_legend_childs.title_time !== null) this.__legendSetTimeString(this.chart.name); if(this.element_legend_childs.title_units !== null) this.__legendSetUnitsString(' '); if(this.data && this.element_legend_childs.series !== null) { var labels = this.data.dimension_names; var i = labels.length; while(i--) { var label = labels[i]; if(typeof label === 'undefined' || typeof this.element_legend_childs.series[label] === 'undefined') continue; this.legendSetLabelValue(label, null); } } }; this.legendShowLatestValues = function() { if(this.chart === null) return; if(this.selected) return; if(this.data === null || this.element_legend_childs.series === null) { this.legendShowUndefined(); return; } var show_undefined = true; if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) show_undefined = false; if(show_undefined) { this.legendShowUndefined(); return; } this.legendSetDate(this.view_before); var labels = this.data.dimension_names; var i = labels.length; while(i--) { var label = labels[i]; if(typeof label === 'undefined') continue; if(typeof this.element_legend_childs.series[label] === 'undefined') continue; if(show_undefined) this.legendSetLabelValue(label, null); else this.legendSetLabelValue(label, this.data.view_latest_values[i]); } }; this.legendReset = function() { this.legendShowLatestValues(); }; // this should be called just ONCE per dimension per chart this._chartDimensionColor = function(label) { this.chartPrepareColorPalette(); if(typeof this.colors_assigned[label] === 'undefined') { if(this.colors_available.length === 0) { var len; // copy the custom colors if(this.colors_custom !== null) { len = this.colors_custom.length; while (len--) this.colors_available.unshift(this.colors_custom[len]); } // copy the standard palette colors len = NETDATA.themes.current.colors.length; while(len--) this.colors_available.unshift(NETDATA.themes.current.colors[len]); } // assign a color to this dimension this.colors_assigned[label] = this.colors_available.shift(); if(this.debug === true) this.log('label "' + label + '" got color "' + this.colors_assigned[label]); } else { if(this.debug === true) this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"'); } this.colors.push(this.colors_assigned[label]); return this.colors_assigned[label]; }; this.chartPrepareColorPalette = function() { var len; if(this.colors_custom !== null) return; if(this.debug === true) this.log("Preparing chart color palette"); this.colors = []; this.colors_available = []; this.colors_custom = []; // add the standard colors len = NETDATA.themes.current.colors.length; while(len--) this.colors_available.unshift(NETDATA.themes.current.colors[len]); // add the user supplied colors var c = $(this.element).data('colors'); // this.log('read colors: ' + c); if(typeof c === 'string' && c.length > 0) { c = c.split(' '); len = c.length; while(len--) { if(this.debug === true) this.log("Adding custom color " + c[len].toString() + " to palette"); this.colors_custom.unshift(c[len]); this.colors_available.unshift(c[len]); } } if(this.debug === true) { this.log("colors_custom:"); this.log(this.colors_custom); this.log("colors_available:"); this.log(this.colors_available); } }; // get the ordered list of chart colors // this includes user defined colors this.chartCustomColors = function() { this.chartPrepareColorPalette(); var colors; if(this.colors_custom.length) colors = this.colors_custom; else colors = this.colors; if(this.debug === true) { this.log("chartCustomColors() returns:"); this.log(colors); } return colors; }; // get the ordered list of chart ASSIGNED colors // (this returns only the colors that have been // assigned to dimensions, prepended with any // custom colors defined) this.chartColors = function() { this.chartPrepareColorPalette(); if(this.debug === true) { this.log("chartColors() returns:"); this.log(this.colors); } return this.colors; }; this.legendUpdateDOM = function() { var needed = false, dim, keys, len, i; // check that the legend DOM is up to date for the downloaded dimensions if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) { // this.log('the legend does not have any series - requesting legend update'); needed = true; } else if(this.data === null) { // this.log('the chart does not have any data - requesting legend update'); needed = true; } else if(typeof this.element_legend_childs.series.labels_key === 'undefined') { needed = true; } else { var labels = this.data.dimension_names.toString(); if(labels !== this.element_legend_childs.series.labels_key) { needed = true; if(this.debug === true) this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"'); } } if(needed === false) { // make sure colors available this.chartPrepareColorPalette(); // do we have to update the current values? // we do this, only when the visible chart is current if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) { if(this.debug === true) this.log('chart is in latest position... updating values on legend...'); //var labels = this.data.dimension_names; //var i = labels.length; //while(i--) // this.legendSetLabelValue(labels[i], this.data.latest_values[i]); } return; } if(this.colors === null) { // this is the first time we update the chart // let's assign colors to all dimensions if(this.library.track_colors() === true) { keys = Object.keys(this.chart.dimensions); len = keys.length; for(i = 0; i < len ;i++) this._chartDimensionColor(this.chart.dimensions[keys[i]].name); } } // we will re-generate the colors for the chart // based on the dimensions this result has data for this.colors = []; if(this.debug === true) this.log('updating Legend DOM'); // mark all dimensions as invalid this.dimensions_visibility.invalidateAll(); var genLabel = function(state, parent, dim, name, count) { var color = state._chartDimensionColor(name); var user_element = null; var user_id = self.data('show-value-of-' + name.toLowerCase() + '-at') || null; if(user_id === null) user_id = self.data('show-value-of-' + dim.toLowerCase() + '-at') || null; if(user_id !== null) { user_element = document.getElementById(user_id) || null; if (user_element === null) state.log('Cannot find element with id: ' + user_id); } state.element_legend_childs.series[name] = { name: document.createElement('span'), value: document.createElement('span'), user: user_element, last: null, last_shown_value: null }; var label = state.element_legend_childs.series[name]; // create the dimension visibility tracking for this label state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color); var rgb = NETDATA.colorHex2Rgb(color); label.name.innerHTML = '<table class="netdata-legend-name-table-' + state.chart.chart_type + '" style="background-color: ' + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')' + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'; var text = document.createTextNode(' ' + name); label.name.appendChild(text); if(count > 0) parent.appendChild(document.createElement('br')); parent.appendChild(label.name); parent.appendChild(label.value); }; var content = document.createElement('div'); if(this.hasLegend()) { this.element_legend_childs = { content: content, resize_handler: document.createElement('div'), toolbox: document.createElement('div'), toolbox_left: document.createElement('div'), toolbox_right: document.createElement('div'), toolbox_reset: document.createElement('div'), toolbox_zoomin: document.createElement('div'), toolbox_zoomout: document.createElement('div'), toolbox_volume: document.createElement('div'), title_date: document.createElement('span'), title_time: document.createElement('span'), title_units: document.createElement('span'), perfect_scroller: document.createElement('div'), series: {} }; this.element_legend.innerHTML = ''; if(this.library.toolboxPanAndZoom !== null) { var get_pan_and_zoom_step = function(event) { if (event.ctrlKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_control; else if (event.shiftKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_shift; else if (event.altKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_alt; else return NETDATA.options.current.pan_and_zoom_factor; }; this.element_legend_childs.toolbox.className += ' netdata-legend-toolbox'; this.element.appendChild(this.element_legend_childs.toolbox); this.element_legend_childs.toolbox_left.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_left.innerHTML = '<i class="fa fa-backward"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_left); this.element_legend_childs.toolbox_left.onclick = function(e) { e.preventDefault(); var step = (that.view_before - that.view_after) * get_pan_and_zoom_step(e); var before = that.view_before - step; var after = that.view_after - step; if(after >= that.netdata_first) that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_left).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Pan Left', content: 'Pan the chart to the left. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_reset.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_reset.innerHTML = '<i class="fa fa-play"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_reset); this.element_legend_childs.toolbox_reset.onclick = function(e) { e.preventDefault(); NETDATA.resetAllCharts(that); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_reset).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Reset', content: 'Reset all the charts to their default auto-refreshing state. You can also <b>double click</b> the chart contents with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_right.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_right.innerHTML = '<i class="fa fa-forward"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_right); this.element_legend_childs.toolbox_right.onclick = function(e) { e.preventDefault(); var step = (that.view_before - that.view_after) * get_pan_and_zoom_step(e); var before = that.view_before + step; var after = that.view_after + step; if(before <= that.netdata_last) that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_right).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Pan Right', content: 'Pan the chart to the right. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_zoomin.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_zoomin.innerHTML = '<i class="fa fa-plus"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomin); this.element_legend_childs.toolbox_zoomin.onclick = function(e) { e.preventDefault(); var dt = ((that.view_before - that.view_after) * (get_pan_and_zoom_step(e) * 0.8) / 2); var before = that.view_before - dt; var after = that.view_after + dt; that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_zoomin).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Zoom In', content: 'Zoom in the chart. You can also press SHIFT and select an area of the chart to zoom in. On Chrome and Opera, you can press the SHIFT or the ALT keys and then use the mouse wheel to zoom in or out.<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_zoomout.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_zoomout.innerHTML = '<i class="fa fa-minus"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomout); this.element_legend_childs.toolbox_zoomout.onclick = function(e) { e.preventDefault(); var dt = (((that.view_before - that.view_after) / (1.0 - (get_pan_and_zoom_step(e) * 0.8)) - (that.view_before - that.view_after)) / 2); var before = that.view_before + dt; var after = that.view_after - dt; that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_zoomout).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Zoom Out', content: 'Zoom out the chart. On Chrome and Opera, you can also press the SHIFT or the ALT keys and then use the mouse wheel to zoom in or out.<br/><small>Help, can be disabled from the settings.</small>' }); //this.element_legend_childs.toolbox_volume.className += ' netdata-legend-toolbox-button'; //this.element_legend_childs.toolbox_volume.innerHTML = '<i class="fa fa-sort-amount-desc"></i>'; //this.element_legend_childs.toolbox_volume.title = 'Visible Volume'; //this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_volume); //this.element_legend_childs.toolbox_volume.onclick = function(e) { //e.preventDefault(); //alert('clicked toolbox_volume on ' + that.id); //} } else { this.element_legend_childs.toolbox = null; this.element_legend_childs.toolbox_left = null; this.element_legend_childs.toolbox_reset = null; this.element_legend_childs.toolbox_right = null; this.element_legend_childs.toolbox_zoomin = null; this.element_legend_childs.toolbox_zoomout = null; this.element_legend_childs.toolbox_volume = null; } this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler"; this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>'; this.element.appendChild(this.element_legend_childs.resize_handler); if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.resize_handler).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Resize', content: 'Drag this point with your mouse or your finger (on touch devices), to resize the chart vertically. You can also <b>double click it</b> or <b>double tap it</b> to reset between 2 states: the default and the one that fits all the values.<br/><small>Help, can be disabled from the settings.</small>' }); // mousedown event this.element_legend_childs.resize_handler.onmousedown = function(e) { that.resizeHandler(e); }; // touchstart event this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) { that.resizeHandler(e); }, false); this.element_legend_childs.title_date.className += " netdata-legend-title-date"; this.element_legend.appendChild(this.element_legend_childs.title_date); this.__last_shown_legend_date = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.title_time.className += " netdata-legend-title-time"; this.element_legend.appendChild(this.element_legend_childs.title_time); this.__last_shown_legend_time = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.title_units.className += " netdata-legend-title-units"; this.element_legend.appendChild(this.element_legend_childs.title_units); this.__last_shown_legend_units = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.perfect_scroller.className = 'netdata-legend-series'; this.element_legend.appendChild(this.element_legend_childs.perfect_scroller); content.className = 'netdata-legend-series-content'; this.element_legend_childs.perfect_scroller.appendChild(content); if(NETDATA.options.current.show_help === true) $(content).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', title: 'Chart Legend', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, content: 'You can click or tap on the values or the labels to select dimensions. By pressing SHIFT or CONTROL, you can enable or disable multiple dimensions.<br/><small>Help, can be disabled from the settings.</small>' }); } else { this.element_legend_childs = { content: content, resize_handler: null, toolbox: null, toolbox_left: null, toolbox_right: null, toolbox_reset: null, toolbox_zoomin: null, toolbox_zoomout: null, toolbox_volume: null, title_date: null, title_time: null, title_units: null, perfect_scroller: null, series: {} }; } if(this.data) { this.element_legend_childs.series.labels_key = this.data.dimension_names.toString(); if(this.debug === true) this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"'); for(i = 0, len = this.data.dimension_names.length; i < len ;i++) { genLabel(this, content, this.data.dimension_ids[i], this.data.dimension_names[i], i); } } else { var tmp = []; keys = Object.keys(this.chart.dimensions); for(i = 0, len = keys.length; i < len ;i++) { dim = keys[i]; tmp.push(this.chart.dimensions[dim].name); genLabel(this, content, dim, this.chart.dimensions[dim].name, i); } this.element_legend_childs.series.labels_key = tmp.toString(); if(this.debug === true) this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"'); } // create a hidden div to be used for hidding // the original legend of the chart library var el = document.createElement('div'); if(this.element_legend !== null) this.element_legend.appendChild(el); el.style.display = 'none'; this.element_legend_childs.hidden = document.createElement('div'); el.appendChild(this.element_legend_childs.hidden); if(this.element_legend_childs.perfect_scroller !== null) { Ps.initialize(this.element_legend_childs.perfect_scroller, { wheelSpeed: 0.2, wheelPropagation: true, swipePropagation: true, minScrollbarLength: null, maxScrollbarLength: null, useBothWheelAxes: false, suppressScrollX: true, suppressScrollY: false, scrollXMarginOffset: 0, scrollYMarginOffset: 0, theme: 'default' }); Ps.update(this.element_legend_childs.perfect_scroller); } this.legendShowLatestValues(); }; this.hasLegend = function() { if(typeof this.___hasLegendCache___ !== 'undefined') return this.___hasLegendCache___; var leg = false; if(this.library && this.library.legend(this) === 'right-side') { var legend = $(this.element).data('legend') || 'yes'; if(legend === 'yes') leg = true; } this.___hasLegendCache___ = leg; return leg; }; this.legendWidth = function() { return (this.hasLegend())?140:0; }; this.legendHeight = function() { return $(this.element).height(); }; this.chartWidth = function() { return $(this.element).width() - this.legendWidth(); }; this.chartHeight = function() { return $(this.element).height(); }; this.chartPixelsPerPoint = function() { // force an options provided detail var px = this.pixels_per_point; if(this.library && px < this.library.pixels_per_point(this)) px = this.library.pixels_per_point(this); if(px < NETDATA.options.current.pixels_per_point) px = NETDATA.options.current.pixels_per_point; return px; }; this.needsRecreation = function() { return ( this.chart_created === true && this.library && this.library.autoresize() === false && this.tm.last_resized < NETDATA.options.last_page_resize ); }; this.chartURL = function() { var after, before, points_multiplier = 1; if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) { this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq; after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000); before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000); this.view_after = after * 1000; this.view_before = before * 1000; this.requested_padding = null; points_multiplier = 1; } else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) { this.tm.pan_and_zoom_seq = 0; before = Math.round(this.current.force_before_ms / 1000); after = Math.round(this.current.force_after_ms / 1000); this.view_after = after * 1000; this.view_before = before * 1000; if(NETDATA.options.current.pan_and_zoom_data_padding === true) { this.requested_padding = Math.round((before - after) / 2); after -= this.requested_padding; before += this.requested_padding; this.requested_padding *= 1000; points_multiplier = 2; } this.current.force_before_ms = null; this.current.force_after_ms = null; } else { this.tm.pan_and_zoom_seq = 0; before = this.before; after = this.after; this.view_after = after * 1000; this.view_before = before * 1000; this.requested_padding = null; points_multiplier = 1; } this.requested_after = after * 1000; this.requested_before = before * 1000; this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint()); // build the data URL console.log('this.chart.data_url = ', this.chart.data_url) console.dir(this.chart) this.data_url = NETDATA.IAMServer + this.chart.data_url; this.data_url += "&format=" + this.library.format(); this.data_url += "&points=" + (this.data_points * points_multiplier).toString(); this.data_url += "&group=" + this.method; if(this.override_options !== null) this.data_url += "&options=" + this.override_options.toString(); else this.data_url += "&options=" + this.library.options(this); this.data_url += '|jsonwrap'; if(NETDATA.options.current.eliminate_zero_dimensions === true) this.data_url += '|nonzero'; if(this.append_options !== null) this.data_url += '|' + this.append_options.toString(); if(after) this.data_url += "&after=" + after.toString(); if(before) this.data_url += "&before=" + before.toString(); if(this.dimensions) this.data_url += "&dimensions=" + this.dimensions; if(NETDATA.options.debug.chart_data_url === true || this.debug === true) this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name); }; this.redrawChart = function() { if(this.data !== null) this.updateChartWithData(this.data); }; this.updateChartWithData = function(data) { if(this.debug === true) this.log('updateChartWithData() called.'); // this may force the chart to be re-created resizeChart(); this.data = data; this.updates_counter++; this.updates_since_last_unhide++; this.updates_since_last_creation++; var started = Date.now(); // if the result is JSON, find the latest update-every this.data_update_every = data.view_update_every * 1000; this.data_after = data.after * 1000; this.data_before = data.before * 1000; this.netdata_first = data.first_entry * 1000; this.netdata_last = data.last_entry * 1000; this.data_points = data.points; data.state = this; if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) { if(this.view_after < this.data_after) { // console.log('adjusting view_after from ' + this.view_after + ' to ' + this.data_after); this.view_after = this.data_after; } if(this.view_before > this.data_before) { // console.log('adjusting view_before from ' + this.view_before + ' to ' + this.data_before); this.view_before = this.data_before; } } else { this.view_after = this.data_after; this.view_before = this.data_before; } if(this.debug === true) { this.log('UPDATE No ' + this.updates_counter + ' COMPLETED'); if(this.current.force_after_ms) this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString()); else this.log('STATUS: forced : unset'); this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString()); this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString()); this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString()); this.log('STATUS: points : ' + (this.data_points).toString()); } if(this.data_points === 0) { noDataToShow(); return; } if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) { if(this.debug === true) this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.'); init(); return; } // check and update the legend this.legendUpdateDOM(); if(this.chart_created === true && typeof this.library.update === 'function') { if(this.debug === true) this.log('updating chart...'); if(callChartLibraryUpdateSafely(data) === false) return; } else { if(this.debug === true) this.log('creating chart...'); if(callChartLibraryCreateSafely(data) === false) return; } hideMessage(); this.legendShowLatestValues(); if(this.selected === true) NETDATA.globalSelectionSync.stop(); // update the performance counters var now = Date.now(); this.tm.last_updated = now; // don't update last_autorefreshed if this chart is // forced to be updated with global PanAndZoom if(NETDATA.globalPanAndZoom.isActive()) this.tm.last_autorefreshed = 0; else { if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes === true) this.tm.last_autorefreshed = now - (now % this.data_update_every); else this.tm.last_autorefreshed = now; } this.refresh_dt_ms = now - started; NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms; if(this.refresh_dt_element !== null) this.refresh_dt_element.innerText = this.refresh_dt_ms.toString(); }; this.updateChart = function(callback) { if(this.debug === true) this.log('updateChart() called.'); if(this._updating === true) { if(this.debug === true) this.log('I am already updating...'); if(typeof callback === 'function') return callback(); return; } // due to late initialization of charts and libraries // we need to check this too if(this.enabled === false) { if(this.debug === true) this.log('I am not enabled'); if(typeof callback === 'function') return callback(); return; } if(canBeRendered() === false) { if(typeof callback === 'function') return callback(); return; } if(this.chart === null) return this.getChart(function() { return that.updateChart(callback); }); if(this.library.initialized === false) { if(this.library.enabled === true) { return this.library.initialize(function () { return that.updateChart(callback); }); } else { error('chart library "' + this.library_name + '" is not available.'); if(typeof callback === 'function') return callback(); return; } } this.clearSelection(); this.chartURL(); //if(this.debug === true) this.log('updating from ' + this.data_url); NETDATA.statistics.refreshes_total++; NETDATA.statistics.refreshes_active++; if(NETDATA.statistics.refreshes_active > NETDATA.statistics.refreshes_active_max) NETDATA.statistics.refreshes_active_max = NETDATA.statistics.refreshes_active; this._updating = true; console.log('>>>>>>>>>>> Rico trace in updateChart with url=', this.data_url) NETDATA.IAM.get(this.data_url) //'/api/v1/data?chart=netdata.server_cpu&format=json&points=60&group=average&options=absolute|jsonwrap|nonzero&after=-60&dimensions=user&_=1500779913718') .then(function (response) { let chart = response.data $("#iam").text(JSON.stringify(chart)); console.log(chart); that.xhr = undefined; that.retries_on_data_failures = 0; that.updateChartWithData(chart); NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); }) .catch(function (msg) { //console.log(msg); that.xhr = undefined; if(msg.statusText !== 'abort') { that.retries_on_data_failures++; if(that.retries_on_data_failures > NETDATA.options.current.retries_on_data_failures) { // that.log('failed ' + that.retries_on_data_failures.toString() + ' times - giving up'); that.retries_on_data_failures = 0; error('data download failed for url: ' + that.data_url); } else { that.tm.last_autorefreshed = Date.now(); // that.log('failed ' + that.retries_on_data_failures.toString() + ' times, but I will retry'); } } NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); }); /*this.xhr = $.ajax( { url: this.data_url, cache: false, async: true, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' } //,xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { that.xhr = undefined; that.retries_on_data_failures = 0; if(that.debug === true) that.log('data received. updating chart.'); that.updateChartWithData(data); }) .fail(function(msg) { that.xhr = undefined; if(msg.statusText !== 'abort') { that.retries_on_data_failures++; if(that.retries_on_data_failures > NETDATA.options.current.retries_on_data_failures) { // that.log('failed ' + that.retries_on_data_failures.toString() + ' times - giving up'); that.retries_on_data_failures = 0; error('data download failed for url: ' + that.data_url); } else { that.tm.last_autorefreshed = Date.now(); // that.log('failed ' + that.retries_on_data_failures.toString() + ' times, but I will retry'); } } }) .always(function() { that.xhr = undefined; NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); });*/ }; this.isVisible = function(nocache) { if(typeof nocache === 'undefined') nocache = false; // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll); // caching - we do not evaluate the charts visibility // if the page has not been scrolled since the last check if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll) return this.___isVisible___; // tolerance is the number of pixels a chart can be off-screen // to consider it as visible and refresh it as if was visible var tolerance = 0; this.tm.last_visible_check = Date.now(); var rect = this.element.getBoundingClientRect(); var screenTop = window.scrollY; var screenBottom = screenTop + window.innerHeight; var chartTop = rect.top + screenTop; var chartBottom = chartTop + rect.height; if(rect.width === 0 || rect.height === 0) { hideChart(); this.___isVisible___ = false; return this.___isVisible___; } if(chartBottom + tolerance < screenTop || chartTop - tolerance > screenBottom) { // the chart is too far // this.log('nocache: ' + nocache.toString() + ', screen top: ' + screenTop.toString() + ', bottom: ' + screenBottom.toString() + ', chart top: ' + chartTop.toString() + ', bottom: ' + chartBottom.toString() + ', OFF SCREEN'); hideChart(); this.___isVisible___ = false; return this.___isVisible___; } else { // the chart is inside or very close // this.log('nocache: ' + nocache.toString() + ', screen top: ' + screenTop.toString() + ', bottom: ' + screenBottom.toString() + ', chart top: ' + chartTop.toString() + ', bottom: ' + chartBottom.toString() + ', VISIBLE'); unhideChart(); this.___isVisible___ = true; return this.___isVisible___; } }; this.isAutoRefreshable = function() { return (this.current.autorefresh); }; this.canBeAutoRefreshed = function() { var now = Date.now(); if(this.running === true) { if(this.debug === true) this.log('I am already running'); return false; } if(this.enabled === false) { if(this.debug === true) this.log('I am not enabled'); return false; } if(this.library === null || this.library.enabled === false) { error('charting library "' + this.library_name + '" is not available'); if(this.debug === true) this.log('My chart library ' + this.library_name + ' is not available'); return false; } if(this.isVisible() === false) { if(NETDATA.options.debug.visibility === true || this.debug === true) this.log('I am not visible'); return false; } if(this.current.force_update_at !== 0 && this.current.force_update_at < now) { if(this.debug === true) this.log('timed force update detected - allowing this update'); this.current.force_update_at = 0; return true; } if(this.isAutoRefreshable() === true) { // allow the first update, even if the page is not visible if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) { // if(NETDATA.options.debug.focus === true || this.debug === true) // this.log('canBeAutoRefreshed(): page does not have focus'); return false; } if(this.needsRecreation() === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): needs re-creation.'); return true; } // options valid only for autoRefresh() if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) { if(NETDATA.globalPanAndZoom.isActive()) { if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) { if(this.debug === true) this.log('canBeAutoRefreshed(): global panning: I need an update.'); return true; } else { if(this.debug === true) this.log('canBeAutoRefreshed(): global panning: I am already up to date.'); return false; } } if(this.selected === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): I have a selection in place.'); return false; } if(this.paused === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): I am paused.'); return false; } if(now - this.tm.last_autorefreshed >= this.data_update_every) { if(this.debug === true) this.log('canBeAutoRefreshed(): It is time to update me.'); return true; } } } return false; }; this.autoRefresh = function(callback) { if(this.canBeAutoRefreshed() === true && this.running === false) { var state = this; state.running = true; state.updateChart(function() { console.log('autoRefresh with updateChart') state.running = false; if(typeof callback !== 'undefined') return callback(); }); } else { console.log('autoRefresh with undefined') if(typeof callback !== 'undefined') return callback(); } }; this._defaultsFromDownloadedChart = function(chart) { this.chart = chart; this.chart_url = chart.url; this.data_update_every = chart.update_every * 1000; this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint()); this.tm.last_info_downloaded = Date.now(); if(this.title === null) this.title = chart.title; if(this.units === null) this.units = chart.units; }; // fetch the chart description from the netdata server this.getChart = function(callback) { console.log('Rico trace in getChart:', this.host) this.chart = NETDATA.chartRegistry.get(this.host, this.id); if(this.chart) { this._defaultsFromDownloadedChart(this.chart); if(typeof callback === 'function') return callback(); } else { this.chart_url = "/api/v1/chart?chart=" + this.id; if(this.debug === true) this.log('downloading ' + this.chart_url); console.log(' <<<<<<<<<<< Rico trace in getChart:', this.host + this.chart_url) // NETDATA.instance.get('/hostgroups?detail=true', { // params: { // ID: 12345 // } // }) // .then(function (response) { // console.log(response); // $("#api1").text(JSON.stringify(response)); // }) // .catch(function (error) { // console.log(error); // }); NETDATA.IAM.get(this.chart_url) .then(function (res) { var chart = res.data $("#iam").text(JSON.stringify(chart)); console.log(chart); chart.url = that.chart_url; that._defaultsFromDownloadedChart(chart); NETDATA.chartRegistry.add(that.host, that.id, chart); console.log('========== come into always to callback with ok===========') if(typeof callback === 'function') return callback(); }) .catch(function (error) { console.log(error); NETDATA.error(404, that.chart_url); error('chart not found on url "' + that.chart_url + '"'); console.log('========== come into always to callback with error===========') if(typeof callback === 'function') return callback(); }) // $.ajax( { // url: this.host + this.chart_url, // cache: false, // async: true, // //xhrFields: { withCredentials: true } // required for the cookie // }) // .done(function(chart) { // chart.url = that.chart_url; // that._defaultsFromDownloadedChart(chart); // NETDATA.chartRegistry.add(that.host, that.id, chart); // }) // .fail(function() { // NETDATA.error(404, that.chart_url); // error('chart not found on url "' + that.chart_url + '"'); // }) // .always(function() { // console.log('========== come into always to callback ===========') // if(typeof callback === 'function') // return callback(); // }); } }; // ============================================================================================================ // INITIALIZATION init(); }; NETDATA.resetAllCharts = function(state) { console.log('Rico trace in resetAllCharts') // first clear the global selection sync // to make sure no chart is in selected state state.globalSelectionSyncStop(); // there are 2 possibilities here // a. state is the global Pan and Zoom master // b. state is not the global Pan and Zoom master var master = true; if(NETDATA.globalPanAndZoom.isMaster(state) === false) master = false; // clear the global Pan and Zoom // this will also refresh the master // and unblock any charts currently mirroring the master NETDATA.globalPanAndZoom.clearMaster(); // if we were not the master, reset our status too // this is required because most probably the mouse // is over this chart, blocking it from auto-refreshing if(master === false && (state.paused === true || state.selected === true)) state.resetChart(); }; // get or create a chart state, given a DOM element NETDATA.chartState = function(element) { console.log('Rico trace in resetAllCharts') var state = $(element).data('netdata-state-object') || null; if(state === null) { state = new chartState(element); $(element).data('netdata-state-object', state); } return state; }; // ---------------------------------------------------------------------------------------------------------------- // Library functions // Load a script without jquery // This is used to load jquery - after it is loaded, we use jquery NETDATA._loadjQuery = function(callback) { if(typeof jQuery === 'undefined') { if(NETDATA.options.debug.main_loop === true) console.log('loading ' + NETDATA.jQuery); var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = NETDATA.jQuery; // script.onabort = onError; script.onerror = function() { NETDATA.error(101, NETDATA.jQuery); }; if(typeof callback === "function") script.onload = callback; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); } else if(typeof callback === "function") return callback(); }; NETDATA._loadCSS = function(filename) { // don't use jQuery here // styles are loaded before jQuery // to eliminate showing an unstyled page to the user var fileref = document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); if (typeof fileref !== 'undefined') document.getElementsByTagName("head")[0].appendChild(fileref); }; NETDATA.colorHex2Rgb = function(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; NETDATA.colorLuminance = function(hex, lum) { // validate hex string hex = String(hex).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; lum = lum || 0; // convert to decimal and change luminosity var rgb = "#", c, i; for (i = 0; i < 3; i++) { c = parseInt(hex.substr(i*2,2), 16); c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); rgb += ("00"+c).substr(c.length); } return rgb; }; NETDATA.guid = function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; NETDATA.zeropad = function(x) { if(x > -10 && x < 10) return '0' + x.toString(); else return x.toString(); }; // user function to signal us the DOM has been // updated. NETDATA.updatedDom = function() { NETDATA.options.updated_dom = true; }; NETDATA.ready = function(callback) { NETDATA.options.pauseCallback = callback; }; NETDATA.pause = function(callback) { if(typeof callback === 'function') { if (NETDATA.options.pause === true) return callback(); else NETDATA.options.pauseCallback = callback; } }; NETDATA.unpause = function() { NETDATA.options.pauseCallback = null; NETDATA.options.updated_dom = true; NETDATA.options.pause = false; }; // ---------------------------------------------------------------------------------------------------------------- // this is purely sequential charts refresher // it is meant to be autonomous NETDATA.chartRefresherNoParallel = function(index) { if(NETDATA.options.debug.main_loop === true) console.log('NETDATA.chartRefresherNoParallel(' + index + ')'); if(NETDATA.options.updated_dom === true) { // the dom has been updated // get the dom parts again NETDATA.parseDom(NETDATA.chartRefresher); return; } if(index >= NETDATA.options.targets.length) { if(NETDATA.options.debug.main_loop === true) console.log('waiting to restart main loop...'); NETDATA.options.auto_refresher_fast_weight = 0; setTimeout(function() { NETDATA.chartRefresher(); }, NETDATA.options.current.idle_between_loops); } else { var state = NETDATA.options.targets[index]; if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) { if(NETDATA.options.debug.main_loop === true) console.log('fast rendering...'); setTimeout(function() { state.autoRefresh(function () { NETDATA.chartRefresherNoParallel(++index); }); }, 0); } else { if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...'); NETDATA.options.auto_refresher_fast_weight = 0; setTimeout(function() { state.autoRefresh(function() { NETDATA.chartRefresherNoParallel(++index); }); }, NETDATA.options.current.idle_between_charts); } } }; NETDATA.chartRefresherWaitTime = function() { return NETDATA.options.current.idle_parallel_loops; }; // the default refresher NETDATA.chartRefresher = function() { console.log('auto-refresher...'); if(NETDATA.options.pause === true) { // console.log('auto-refresher is paused'); setTimeout(NETDATA.chartRefresher, NETDATA.chartRefresherWaitTime()); return; } if(typeof NETDATA.options.pauseCallback === 'function') { // console.log('auto-refresher is calling pauseCallback'); NETDATA.options.pause = true; NETDATA.options.pauseCallback(); NETDATA.chartRefresher(); return; } if(NETDATA.options.current.parallel_refresher === false) { // console.log('auto-refresher is calling chartRefresherNoParallel(0)'); NETDATA.chartRefresherNoParallel(0); return; } if(NETDATA.options.updated_dom === true) { // the dom has been updated // get the dom parts again // console.log('auto-refresher is calling parseDom()'); NETDATA.parseDom(NETDATA.chartRefresher); return; } var parallel = []; var targets = NETDATA.options.targets; var len = targets.length; console.log('Rico trace in chartRefresher with len=', len) var state; while(len--) { state = targets[len]; if(state.isVisible() === false || state.running === true) continue; if(state.library.initialized === false) { if(state.library.enabled === true) { state.library.initialize(NETDATA.chartRefresher); return; } else { console.log('chart library "' + state.library_name + '" is not enabled.') state.error('chart library "' + state.library_name + '" is not enabled.'); } } parallel.unshift(state); } if(parallel.length > 0) { // console.log('auto-refresher executing in parallel for ' + parallel.length.toString() + ' charts'); // this will execute the jobs in parallel $(parallel).each(function() { console.log('parallel to autoRefresh') this.autoRefresh(); }) } else { console.log('auto-refresher nothing to do'); } // run the next refresh iteration setTimeout(NETDATA.chartRefresher, NETDATA.chartRefresherWaitTime()); }; NETDATA.parseDom = function(callback) { NETDATA.options.last_page_scroll = Date.now(); NETDATA.options.updated_dom = false; var targets = $('div[data-netdata]'); //.filter(':visible'); if(NETDATA.options.debug.main_loop === true) console.log('DOM updated - there are ' + targets.length + ' charts on page.'); NETDATA.options.targets = []; var len = targets.length; while(len--) { // the initialization will take care of sizing // and the "loading..." message NETDATA.options.targets.push(NETDATA.chartState(targets[len])); console.log('targets looks like: ',targets[len]) console.log('NETDATA.options.targets looks like: ', NETDATA.chartState(targets[len])) } if(typeof callback === 'function') return callback(); }; // this is the main function - where everything starts NETDATA.start = function() { // this should be called only once NETDATA.options.page_is_visible = true; $(window).blur(function() { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = false; if(NETDATA.options.debug.focus === true) console.log('Lost Focus!'); } }); $(window).focus(function() { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = true; if(NETDATA.options.debug.focus === true) console.log('Focus restored!'); } }); if(typeof document.hasFocus === 'function' && !document.hasFocus()) { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = false; if(NETDATA.options.debug.focus === true) console.log('Document has no focus!'); } } // bootstrap tab switching $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll); // bootstrap modal switching var $modal = $('.modal'); $modal.on('hidden.bs.modal', NETDATA.onscroll); $modal.on('shown.bs.modal', NETDATA.onscroll); // bootstrap collapse switching var $collapse = $('.collapse'); $collapse.on('hidden.bs.collapse', NETDATA.onscroll); $collapse.on('shown.bs.collapse', NETDATA.onscroll); NETDATA.parseDom(NETDATA.chartRefresher); // Alarms initialization setTimeout(NETDATA.alarms.init, 1000); // Registry initialization setTimeout(NETDATA.registry.init, netdataRegistryAfterMs); if(typeof netdataCallback === 'function') netdataCallback(); }; // ---------------------------------------------------------------------------------------------------------------- // peity NETDATA.peityInitialize = function(callback) { if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) { $.ajax({ url: NETDATA.peity_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('peity', NETDATA.peity_js); }) .fail(function() { NETDATA.chartLibraries.peity.enabled = false; NETDATA.error(100, NETDATA.peity_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.peity.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.peityChartUpdate = function(state, data) { state.peity_instance.innerHTML = data.result; if(state.peity_options.stroke !== state.chartCustomColors()[0]) { state.peity_options.stroke = state.chartCustomColors()[0]; if(state.chart.chart_type === 'line') state.peity_options.fill = NETDATA.themes.current.background; else state.peity_options.fill = NETDATA.colorLuminance(state.chartCustomColors()[0], NETDATA.chartDefaults.fill_luminance); } $(state.peity_instance).peity('line', state.peity_options); return true; }; NETDATA.peityChartCreate = function(state, data) { state.peity_instance = document.createElement('div'); state.element_chart.appendChild(state.peity_instance); var self = $(state.element); state.peity_options = { stroke: NETDATA.themes.current.foreground, strokeWidth: self.data('peity-strokewidth') || 1, width: state.chartWidth(), height: state.chartHeight(), fill: NETDATA.themes.current.foreground }; NETDATA.peityChartUpdate(state, data); return true; }; // ---------------------------------------------------------------------------------------------------------------- // sparkline NETDATA.sparklineInitialize = function(callback) { if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) { $.ajax({ url: NETDATA.sparkline_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js); }) .fail(function() { NETDATA.chartLibraries.sparkline.enabled = false; NETDATA.error(100, NETDATA.sparkline_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.sparkline.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.sparklineChartUpdate = function(state, data) { state.sparkline_options.width = state.chartWidth(); state.sparkline_options.height = state.chartHeight(); $(state.element_chart).sparkline(data.result, state.sparkline_options); return true; }; NETDATA.sparklineChartCreate = function(state, data) { var self = $(state.element); var type = self.data('sparkline-type') || 'line'; var lineColor = self.data('sparkline-linecolor') || state.chartCustomColors()[0]; var fillColor = self.data('sparkline-fillcolor') || ((state.chart.chart_type === 'line')?NETDATA.themes.current.background:NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance)); var chartRangeMin = self.data('sparkline-chartrangemin') || undefined; var chartRangeMax = self.data('sparkline-chartrangemax') || undefined; var composite = self.data('sparkline-composite') || undefined; var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined; var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined; var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined; var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined; var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined; var spotColor = self.data('sparkline-spotcolor') || undefined; var minSpotColor = self.data('sparkline-minspotcolor') || undefined; var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined; var spotRadius = self.data('sparkline-spotradius') || undefined; var valueSpots = self.data('sparkline-valuespots') || undefined; var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined; var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined; var lineWidth = self.data('sparkline-linewidth') || undefined; var normalRangeMin = self.data('sparkline-normalrangemin') || undefined; var normalRangeMax = self.data('sparkline-normalrangemax') || undefined; var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined; var xvalues = self.data('sparkline-xvalues') || undefined; var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined; var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined; var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined; var disableInteraction = self.data('sparkline-disableinteraction') || false; var disableTooltips = self.data('sparkline-disabletooltips') || false; var disableHighlight = self.data('sparkline-disablehighlight') || false; var highlightLighten = self.data('sparkline-highlightlighten') || 1.4; var highlightColor = self.data('sparkline-highlightcolor') || undefined; var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined; var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined; var tooltipFormat = self.data('sparkline-tooltipformat') || undefined; var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined; var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units; var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true; var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined; var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined; var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined; var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); }; var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined; var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined; var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined; var animatedZooms = self.data('sparkline-animatedzooms') || false; if(spotColor === 'disable') spotColor=''; if(minSpotColor === 'disable') minSpotColor=''; if(maxSpotColor === 'disable') maxSpotColor=''; // state.log('sparkline type ' + type + ', lineColor: ' + lineColor + ', fillColor: ' + fillColor); state.sparkline_options = { type: type, lineColor: lineColor, fillColor: fillColor, chartRangeMin: chartRangeMin, chartRangeMax: chartRangeMax, composite: composite, enableTagOptions: enableTagOptions, tagOptionPrefix: tagOptionPrefix, tagValuesAttribute: tagValuesAttribute, disableHiddenCheck: disableHiddenCheck, defaultPixelsPerValue: defaultPixelsPerValue, spotColor: spotColor, minSpotColor: minSpotColor, maxSpotColor: maxSpotColor, spotRadius: spotRadius, valueSpots: valueSpots, highlightSpotColor: highlightSpotColor, highlightLineColor: highlightLineColor, lineWidth: lineWidth, normalRangeMin: normalRangeMin, normalRangeMax: normalRangeMax, drawNormalOnTop: drawNormalOnTop, xvalues: xvalues, chartRangeClip: chartRangeClip, chartRangeMinX: chartRangeMinX, chartRangeMaxX: chartRangeMaxX, disableInteraction: disableInteraction, disableTooltips: disableTooltips, disableHighlight: disableHighlight, highlightLighten: highlightLighten, highlightColor: highlightColor, tooltipContainer: tooltipContainer, tooltipClassname: tooltipClassname, tooltipChartTitle: state.title, tooltipFormat: tooltipFormat, tooltipPrefix: tooltipPrefix, tooltipSuffix: tooltipSuffix, tooltipSkipNull: tooltipSkipNull, tooltipValueLookups: tooltipValueLookups, tooltipFormatFieldlist: tooltipFormatFieldlist, tooltipFormatFieldlistKey: tooltipFormatFieldlistKey, numberFormatter: numberFormatter, numberDigitGroupSep: numberDigitGroupSep, numberDecimalMark: numberDecimalMark, numberDigitGroupCount: numberDigitGroupCount, animatedZooms: animatedZooms, width: state.chartWidth(), height: state.chartHeight() }; $(state.element_chart).sparkline(data.result, state.sparkline_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- // dygraph NETDATA.dygraph = { smooth: false }; NETDATA.dygraphToolboxPanAndZoom = function(state, after, before) { if(after < state.netdata_first) after = state.netdata_first; if(before > state.netdata_last) before = state.netdata_last; state.setMode('zoom'); state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.dygraph_user_action = true; state.dygraph_force_zoom = true; state.updateChartPanOrZoom(after, before); NETDATA.globalPanAndZoom.setMaster(state, after, before); }; NETDATA.dygraphSetSelection = function(state, t) { if(typeof state.dygraph_instance !== 'undefined') { var r = state.calculateRowForTime(t); if(r !== -1) state.dygraph_instance.setSelection(r); else { state.dygraph_instance.clearSelection(); state.legendShowUndefined(); } } return true; }; NETDATA.dygraphClearSelection = function(state) { if(typeof state.dygraph_instance !== 'undefined') { state.dygraph_instance.clearSelection(); } return true; }; NETDATA.dygraphSmoothInitialize = function(callback) { $.ajax({ url: NETDATA.dygraph_smooth_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.dygraph.smooth = true; smoothPlotter.smoothing = 0.3; }) .fail(function() { NETDATA.dygraph.smooth = false; }) .always(function() { if(typeof callback === "function") return callback(); }); }; NETDATA.dygraphInitialize = function(callback) { if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) { $.ajax({ url: NETDATA.dygraph_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js); }) .fail(function() { NETDATA.chartLibraries.dygraph.enabled = false; NETDATA.error(100, NETDATA.dygraph_js); }) .always(function() { if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true) NETDATA.dygraphSmoothInitialize(callback); else if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.dygraph.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.dygraphChartUpdate = function(state, data) { var dygraph = state.dygraph_instance; if(typeof dygraph === 'undefined') return NETDATA.dygraphChartCreate(state, data); // when the chart is not visible, and hidden // if there is a window resize, dygraph detects // its element size as 0x0. // this will make it re-appear properly if(state.tm.last_unhidden > state.dygraph_last_rendered) dygraph.resize(); var options = { file: data.result.data, colors: state.chartColors(), labels: data.result.labels, labelsDivWidth: state.chartWidth() - 70, visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names) }; if(state.dygraph_force_zoom === true) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() forced zoom update'); options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null; options.isZoomedIgnoreProgrammaticZoom = true; state.dygraph_force_zoom = false; } else if(state.current.name !== 'auto') { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() loose update'); } else { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() strict update'); options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null; options.isZoomedIgnoreProgrammaticZoom = true; } options.valueRange = state.dygraph_options.valueRange; var oldMax = null, oldMin = null; if (state.__commonMin !== null) { state.data.min = state.dygraph_instance.axes_[0].extremeRange[0]; oldMin = options.valueRange[0] = NETDATA.commonMin.get(state); } if (state.__commonMax !== null) { state.data.max = state.dygraph_instance.axes_[0].extremeRange[1]; oldMax = options.valueRange[1] = NETDATA.commonMax.get(state); } if(state.dygraph_smooth_eligible === true) { if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter) || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) { NETDATA.dygraphChartCreate(state, data); return; } } dygraph.updateOptions(options); var redraw = false; if(oldMin !== null && oldMin > state.dygraph_instance.axes_[0].extremeRange[0]) { state.data.min = state.dygraph_instance.axes_[0].extremeRange[0]; options.valueRange[0] = NETDATA.commonMin.get(state); redraw = true; } if(oldMax !== null && oldMax < state.dygraph_instance.axes_[0].extremeRange[1]) { state.data.max = state.dygraph_instance.axes_[0].extremeRange[1]; options.valueRange[1] = NETDATA.commonMax.get(state); redraw = true; } if(redraw === true) { // state.log('forcing redraw to adapt to common- min/max'); dygraph.updateOptions(options); } state.dygraph_last_rendered = Date.now(); return true; }; NETDATA.dygraphChartCreate = function(state, data) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartCreate()'); var self = $(state.element); var chart_type = self.data('dygraph-type') || state.chart.chart_type; if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area'; var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state) === true)?3:4; var smooth = (NETDATA.dygraph.smooth === true) ?(self.data('dygraph-smooth') || (chart_type === 'line' && NETDATA.chartLibraries.dygraph.isSparkline(state) === false)) :false; state.dygraph_options = { colors: self.data('dygraph-colors') || state.chartColors(), // leave a few pixels empty on the right of the chart rightGap: self.data('dygraph-rightgap') || 5, showRangeSelector: self.data('dygraph-showrangeselector') || false, showRoller: self.data('dygraph-showroller') || false, title: self.data('dygraph-title') || state.title, titleHeight: self.data('dygraph-titleheight') || 19, legend: self.data('dygraph-legend') || 'always', // we need this to get selection events labels: data.result.labels, labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden, labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' }, labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70, labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true, labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true, labelsKMB: false, labelsKMG2: false, showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true, hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true, includeZero: self.data('dygraph-includezero') || (chart_type === 'stacked'), xRangePad: self.data('dygraph-xrangepad') || 0, yRangePad: self.data('dygraph-yrangepad') || 1, valueRange: self.data('dygraph-valuerange') || [ null, null ], ylabel: state.units, yLabelWidth: self.data('dygraph-ylabelwidth') || 12, // the function to plot the chart plotter: null, // The width of the lines connecting data points. // This can be used to increase the contrast or some graphs. strokeWidth: self.data('dygraph-strokewidth') || ((chart_type === 'stacked')?0.1:((smooth === true)?1.5:0.7)), strokePattern: self.data('dygraph-strokepattern') || undefined, // The size of the dot to draw on each point in pixels (see drawPoints). // A dot is always drawn when a point is "isolated", // i.e. there is a missing point on either side of it. // This also controls the size of those dots. drawPoints: self.data('dygraph-drawpoints') || false, // Draw points at the edges of gaps in the data. // This improves visibility of small data segments or other data irregularities. drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true, connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false, pointSize: self.data('dygraph-pointsize') || 1, // enabling this makes the chart with little square lines stepPlot: self.data('dygraph-stepplot') || false, // Draw a border around graph lines to make crossing lines more easily // distinguishable. Useful for graphs with many lines. strokeBorderColor: self.data('dygraph-strokebordercolor') || NETDATA.themes.current.background, strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0, fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked'), fillAlpha: self.data('dygraph-fillalpha') || ((chart_type === 'stacked') ?NETDATA.options.current.color_fill_opacity_stacked :NETDATA.options.current.color_fill_opacity_area), stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked'), stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none', drawAxis: self.data('dygraph-drawaxis') || true, axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10, axisLineColor: self.data('dygraph-axislinecolor') || NETDATA.themes.current.axis, axisLineWidth: self.data('dygraph-axislinewidth') || 1.0, drawGrid: self.data('dygraph-drawgrid') || true, gridLinePattern: self.data('dygraph-gridlinepattern') || null, gridLineWidth: self.data('dygraph-gridlinewidth') || 1.0, gridLineColor: self.data('dygraph-gridlinecolor') || NETDATA.themes.current.grid, maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8, sigFigs: self.data('dygraph-sigfigs') || null, digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2, valueFormatter: self.data('dygraph-valueformatter') || undefined, highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize, highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 }, highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5, pointClickCallback: self.data('dygraph-pointclickcallback') || undefined, visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names), axes: { x: { pixelsPerLabel: 50, ticker: Dygraph.dateTicker, axisLabelFormatter: function (d, gran) { void(gran); return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds()); } }, y: { pixelsPerLabel: 15, axisLabelFormatter: function (y) { // unfortunately, we have to call this every single time state.legendFormatValueDecimalsFromMinMax( this.axes_[0].extremeRange[0], this.axes_[0].extremeRange[1] ); return state.legendFormatValue(y); } } }, legendFormatter: function(data) { var elements = state.element_legend_childs; // if the hidden div is not there // we are not managing the legend if(elements.hidden === null) return; if (typeof data.x !== 'undefined') { state.legendSetDate(data.x); var i = data.series.length; while(i--) { var series = data.series[i]; if(series.isVisible === true) state.legendSetLabelValue(series.label, series.y); else state.legendSetLabelValue(series.label, null); } } return ''; }, drawCallback: function(dygraph, is_initial) { if(state.current.name !== 'auto' && state.dygraph_user_action === true) { state.dygraph_user_action = false; var x_range = dygraph.xAxisRange(); var after = Math.round(x_range[0]); var before = Math.round(x_range[1]); if(NETDATA.options.debug.dygraph === true) state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): ' + (after / 1000).toString() + ' - ' + (before / 1000).toString()); if(before <= state.netdata_last && after >= state.netdata_first) state.updateChartPanOrZoom(after, before); } }, zoomCallback: function(minDate, maxDate, yRanges) { void(yRanges); if(NETDATA.options.debug.dygraph === true) state.log('dygraphZoomCallback()'); state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('zoom'); // refresh it to the greatest possible zoom level state.dygraph_user_action = true; state.dygraph_force_zoom = true; state.updateChartPanOrZoom(minDate, maxDate); }, highlightCallback: function(event, x, points, row, seriesName) { void(seriesName); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphHighlightCallback()'); state.pauseChart(); // there is a bug in dygraph when the chart is zoomed enough // the time it thinks is selected is wrong // here we calculate the time t based on the row number selected // which is ok // var t = state.data_after + row * state.data_update_every; // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every); state.globalSelectionSync(x); // fix legend zIndex using the internal structures of dygraph legend module // this works, but it is a hack! // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000; }, unhighlightCallback: function(event) { void(event); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphUnhighlightCallback()'); state.unpauseChart(); state.globalSelectionSyncStop(); }, interactionModel : { mousedown: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mousedown()'); state.dygraph_user_action = true; state.globalSelectionSyncStop(); if(NETDATA.options.debug.dygraph === true) state.log('dygraphMouseDown()'); // Right-click should not initiate a zoom. if(event.button && event.button === 2) return; context.initializeMouseDown(event, dygraph, context); if(event.button && event.button === 1) { if (event.altKey || event.shiftKey) { state.setMode('pan'); state.globalSelectionSyncDelay(); Dygraph.startPan(event, dygraph, context); } else { state.setMode('zoom'); state.globalSelectionSyncDelay(); Dygraph.startZoom(event, dygraph, context); } } else { if (event.altKey || event.shiftKey) { state.setMode('zoom'); state.globalSelectionSyncDelay(); Dygraph.startZoom(event, dygraph, context); } else { state.setMode('pan'); state.globalSelectionSyncDelay(); Dygraph.startPan(event, dygraph, context); } } }, mousemove: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mousemove()'); if(context.isPanning) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('pan'); context.is2DPan = false; Dygraph.movePan(event, dygraph, context); } else if(context.isZooming) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('zoom'); Dygraph.moveZoom(event, dygraph, context); } }, mouseup: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mouseup()'); if (context.isPanning) { state.dygraph_user_action = true; state.globalSelectionSyncDelay(); Dygraph.endPan(event, dygraph, context); } else if (context.isZooming) { state.dygraph_user_action = true; state.globalSelectionSyncDelay(); Dygraph.endZoom(event, dygraph, context); } }, click: function(event, dygraph, context) { void(dygraph); void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.click()'); event.preventDefault(); }, dblclick: function(event, dygraph, context) { void(event); void(dygraph); void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.dblclick()'); NETDATA.resetAllCharts(state); }, wheel: function(event, dygraph, context) { void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.wheel()'); // Take the offset of a mouse event on the dygraph canvas and // convert it to a pair of percentages from the bottom left. // (Not top left, bottom is where the lower value is.) function offsetToPercentage(g, offsetX, offsetY) { // This is calculating the pixel offset of the leftmost date. var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0]; var yar0 = g.yAxisRange(0); // This is calculating the pixel of the highest value. (Top pixel) var yOffset = g.toDomCoords(null, yar0[1])[1]; // x y w and h are relative to the corner of the drawing area, // so that the upper corner of the drawing area is (0, 0). var x = offsetX - xOffset; var y = offsetY - yOffset; // This is computing the rightmost pixel, effectively defining the // width. var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset; // This is computing the lowest pixel, effectively defining the height. var h = g.toDomCoords(null, yar0[0])[1] - yOffset; // Percentage from the left. var xPct = w === 0 ? 0 : (x / w); // Percentage from the top. var yPct = h === 0 ? 0 : (y / h); // The (1-) part below changes it from "% distance down from the top" // to "% distance up from the bottom". return [xPct, (1-yPct)]; } // Adjusts [x, y] toward each other by zoomInPercentage% // Split it so the left/bottom axis gets xBias/yBias of that change and // tight/top gets (1-xBias)/(1-yBias) of that change. // // If a bias is missing it splits it down the middle. function zoomRange(g, zoomInPercentage, xBias, yBias) { xBias = xBias || 0.5; yBias = yBias || 0.5; function adjustAxis(axis, zoomInPercentage, bias) { var delta = axis[1] - axis[0]; var increment = delta * zoomInPercentage; var foo = [increment * bias, increment * (1-bias)]; return [ axis[0] + foo[0], axis[1] - foo[1] ]; } var yAxes = g.yAxisRanges(); var newYAxes = []; for (var i = 0; i < yAxes.length; i++) { newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias); } return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias); } if(event.altKey || event.shiftKey) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); // http://dygraphs.com/gallery/interaction-api.js var normal_def; if(typeof event.wheelDelta === 'number' && !isNaN(event.wheelDelta)) // chrome normal_def = event.wheelDelta / 40; else // firefox normal_def = event.deltaY * -1.2; var normal = (event.detail) ? event.detail * -1 : normal_def; var percentage = normal / 50; if (!(event.offsetX && event.offsetY)){ event.offsetX = event.layerX - event.target.offsetLeft; event.offsetY = event.layerY - event.target.offsetTop; } var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY); var xPct = percentages[0]; var yPct = percentages[1]; var new_x_range = zoomRange(dygraph, percentage, xPct, yPct); var after = new_x_range[0]; var before = new_x_range[1]; var first = state.netdata_first + state.data_update_every; var last = state.netdata_last + state.data_update_every; if(before > last) { after -= (before - last); before = last; } if(after < first) { after = first; } state.setMode('zoom'); if(state.updateChartPanOrZoom(after, before) === true) dygraph.updateOptions({ dateWindow: [ after, before ] }); event.preventDefault(); } }, touchstart: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchstart()'); state.dygraph_user_action = true; state.setMode('zoom'); state.pauseChart(); Dygraph.defaultInteractionModel.touchstart(event, dygraph, context); // we overwrite the touch directions at the end, to overwrite // the internal default of dygraph context.touchDirections = { x: true, y: false }; state.dygraph_last_touch_start = Date.now(); state.dygraph_last_touch_move = 0; if(typeof event.touches[0].pageX === 'number') state.dygraph_last_touch_page_x = event.touches[0].pageX; else state.dygraph_last_touch_page_x = 0; }, touchmove: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchmove()'); state.dygraph_user_action = true; Dygraph.defaultInteractionModel.touchmove(event, dygraph, context); state.dygraph_last_touch_move = Date.now(); }, touchend: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchend()'); state.dygraph_user_action = true; Dygraph.defaultInteractionModel.touchend(event, dygraph, context); // if it didn't move, it is a selection if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) { // internal api of dygraph var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w; var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct); if(NETDATA.dygraphSetSelection(state, t) === true) state.globalSelectionSync(t); } // if it was double tap within double click time, reset the charts var now = Date.now(); if(typeof state.dygraph_last_touch_end !== 'undefined') { if(state.dygraph_last_touch_move === 0) { var dt = now - state.dygraph_last_touch_end; if(dt <= NETDATA.options.current.double_click_speed) NETDATA.resetAllCharts(state); } } // remember the timestamp of the last touch end state.dygraph_last_touch_end = now; } } }; if(NETDATA.chartLibraries.dygraph.isSparkline(state)) { state.dygraph_options.drawGrid = false; state.dygraph_options.drawAxis = false; state.dygraph_options.title = undefined; state.dygraph_options.ylabel = undefined; state.dygraph_options.yLabelWidth = 0; state.dygraph_options.labelsDivWidth = 120; state.dygraph_options.labelsDivStyles.width = '120px'; state.dygraph_options.labelsSeparateLines = true; state.dygraph_options.rightGap = 0; state.dygraph_options.yRangePad = 1; } if(smooth === true) { state.dygraph_smooth_eligible = true; if(NETDATA.options.current.smooth_plot === true) state.dygraph_options.plotter = smoothPlotter; } else state.dygraph_smooth_eligible = false; state.dygraph_instance = new Dygraph(state.element_chart, data.result.data, state.dygraph_options); state.dygraph_force_zoom = false; state.dygraph_user_action = false; state.dygraph_last_rendered = Date.now(); if(state.dygraph_options.valueRange[0] === null && state.dygraph_options.valueRange[1] === null) { if (typeof state.dygraph_instance.axes_[0].extremeRange !== 'undefined') { state.__commonMin = self.data('common-min') || null; state.__commonMax = self.data('common-max') || null; } else { state.log('incompatible version of Dygraph detected'); state.__commonMin = null; state.__commonMax = null; } } else { // if the user gave a valueRange, respect it state.__commonMin = null; state.__commonMax = null; } return true; }; // ---------------------------------------------------------------------------------------------------------------- // morris NETDATA.morrisInitialize = function(callback) { if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) { // morris requires raphael if(!NETDATA.chartLibraries.raphael.initialized) { if(NETDATA.chartLibraries.raphael.enabled) { NETDATA.raphaelInitialize(function() { NETDATA.morrisInitialize(callback); }); } else { NETDATA.chartLibraries.morris.enabled = false; if(typeof callback === "function") return callback(); } } else { NETDATA._loadCSS(NETDATA.morris_css); $.ajax({ url: NETDATA.morris_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('morris', NETDATA.morris_js); }) .fail(function() { NETDATA.chartLibraries.morris.enabled = false; NETDATA.error(100, NETDATA.morris_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } } else { NETDATA.chartLibraries.morris.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.morrisChartUpdate = function(state, data) { state.morris_instance.setData(data.result.data); return true; }; NETDATA.morrisChartCreate = function(state, data) { state.morris_options = { element: state.element_chart.id, data: data.result.data, xkey: 'time', ykeys: data.dimension_names, labels: data.dimension_names, lineWidth: 2, pointSize: 3, smooth: true, hideHover: 'auto', parseTime: true, continuousLine: false, behaveLikeLine: false }; if(state.chart.chart_type === 'line') state.morris_instance = new Morris.Line(state.morris_options); else if(state.chart.chart_type === 'area') { state.morris_options.behaveLikeLine = true; state.morris_instance = new Morris.Area(state.morris_options); } else // stacked state.morris_instance = new Morris.Area(state.morris_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- // raphael NETDATA.raphaelInitialize = function(callback) { if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) { $.ajax({ url: NETDATA.raphael_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js); }) .fail(function() { NETDATA.chartLibraries.raphael.enabled = false; NETDATA.error(100, NETDATA.raphael_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.raphael.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.raphaelChartUpdate = function(state, data) { $(state.element_chart).raphael(data.result, { width: state.chartWidth(), height: state.chartHeight() }); return false; }; NETDATA.raphaelChartCreate = function(state, data) { $(state.element_chart).raphael(data.result, { width: state.chartWidth(), height: state.chartHeight() }); return false; }; // ---------------------------------------------------------------------------------------------------------------- // C3 NETDATA.c3Initialize = function(callback) { if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) { // C3 requires D3 if(!NETDATA.chartLibraries.d3.initialized) { if(NETDATA.chartLibraries.d3.enabled) { NETDATA.d3Initialize(function() { NETDATA.c3Initialize(callback); }); } else { NETDATA.chartLibraries.c3.enabled = false; if(typeof callback === "function") return callback(); } } else { NETDATA._loadCSS(NETDATA.c3_css); $.ajax({ url: NETDATA.c3_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('c3', NETDATA.c3_js); }) .fail(function() { NETDATA.chartLibraries.c3.enabled = false; NETDATA.error(100, NETDATA.c3_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } } else { NETDATA.chartLibraries.c3.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.c3ChartUpdate = function(state, data) { state.c3_instance.destroy(); return NETDATA.c3ChartCreate(state, data); //state.c3_instance.load({ // rows: data.result, // unload: true //}); //return true; }; NETDATA.c3ChartCreate = function(state, data) { state.element_chart.id = 'c3-' + state.uuid; // console.log('id = ' + state.element_chart.id); state.c3_instance = c3.generate({ bindto: '#' + state.element_chart.id, size: { width: state.chartWidth(), height: state.chartHeight() }, color: { pattern: state.chartColors() }, data: { x: 'time', rows: data.result, type: (state.chart.chart_type === 'line')?'spline':'area-spline' }, axis: { x: { type: 'timeseries', tick: { format: function(x) { return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds()); } } } }, grid: { x: { show: true }, y: { show: true } }, point: { show: false }, line: { connectNull: false }, transition: { duration: 0 }, interaction: { enabled: true } }); // console.log(state.c3_instance); return true; }; // ---------------------------------------------------------------------------------------------------------------- // D3 NETDATA.d3Initialize = function(callback) { if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) { $.ajax({ url: NETDATA.d3_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('d3', NETDATA.d3_js); }) .fail(function() { NETDATA.chartLibraries.d3.enabled = false; NETDATA.error(100, NETDATA.d3_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.d3.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.d3ChartUpdate = function(state, data) { void(state); void(data); return false; }; NETDATA.d3ChartCreate = function(state, data) { void(state); void(data); return false; }; // ---------------------------------------------------------------------------------------------------------------- // google charts NETDATA.googleInitialize = function(callback) { if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) { $.ajax({ url: NETDATA.google_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('google', NETDATA.google_js); google.load('visualization', '1.1', { 'packages': ['corechart', 'controls'], 'callback': callback }); }) .fail(function() { NETDATA.chartLibraries.google.enabled = false; NETDATA.error(100, NETDATA.google_js); if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.google.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.googleChartUpdate = function(state, data) { var datatable = new google.visualization.DataTable(data.result); state.google_instance.draw(datatable, state.google_options); return true; }; NETDATA.googleChartCreate = function(state, data) { var datatable = new google.visualization.DataTable(data.result); state.google_options = { colors: state.chartColors(), // do not set width, height - the chart resizes itself //width: state.chartWidth(), //height: state.chartHeight(), lineWidth: 1, title: state.title, fontSize: 11, hAxis: { // title: "Time of Day", // format:'HH:mm:ss', viewWindowMode: 'maximized', slantedText: false, format:'HH:mm:ss', textStyle: { fontSize: 9 }, gridlines: { color: '#EEE' } }, vAxis: { title: state.units, viewWindowMode: 'pretty', minValue: -0.1, maxValue: 0.1, direction: 1, textStyle: { fontSize: 9 }, gridlines: { color: '#EEE' } }, chartArea: { width: '65%', height: '80%' }, focusTarget: 'category', annotation: { '1': { style: 'line' } }, pointsVisible: 0, titlePosition: 'out', titleTextStyle: { fontSize: 11 }, tooltip: { isHtml: false, ignoreBounds: true, textStyle: { fontSize: 9 } }, curveType: 'function', areaOpacity: 0.3, isStacked: false }; switch(state.chart.chart_type) { case "area": state.google_options.vAxis.viewWindowMode = 'maximized'; state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area; state.google_instance = new google.visualization.AreaChart(state.element_chart); break; case "stacked": state.google_options.isStacked = true; state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked; state.google_options.vAxis.viewWindowMode = 'maximized'; state.google_options.vAxis.minValue = null; state.google_options.vAxis.maxValue = null; state.google_instance = new google.visualization.AreaChart(state.element_chart); break; default: case "line": state.google_options.lineWidth = 2; state.google_instance = new google.visualization.LineChart(state.element_chart); break; } state.google_instance.draw(datatable, state.google_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- NETDATA.easypiechartPercentFromValueMinMax = function(value, min, max) { if(typeof value !== 'number') value = 0; if(typeof min !== 'number') min = 0; if(typeof max !== 'number') max = 0; if(min > value) min = value; if(max < value) max = value; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; var pcent = 0; if(value >= 0) { if(max !== 0) pcent = Math.round(value * 100 / max); if(pcent === 0) pcent = 0.1; } else { if(min !== 0) pcent = Math.round(-value * 100 / min); if(pcent === 0) pcent = -0.1; } return pcent; }; // ---------------------------------------------------------------------------------------------------------------- // easy-pie-chart NETDATA.easypiechartInitialize = function(callback) { if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) { $.ajax({ url: NETDATA.easypiechart_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js); }) .fail(function() { NETDATA.chartLibraries.easypiechart.enabled = false; NETDATA.error(100, NETDATA.easypiechart_js); }) .always(function() { if(typeof callback === "function") return callback(); }) } else { NETDATA.chartLibraries.easypiechart.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.easypiechartClearSelection = function(state) { if(typeof state.easyPieChartEvent !== 'undefined') { if(state.easyPieChartEvent.timer !== undefined) { clearTimeout(state.easyPieChartEvent.timer); } state.easyPieChartEvent.timer = undefined; } if(state.isAutoRefreshable() === true && state.data !== null) { NETDATA.easypiechartChartUpdate(state, state.data); } else { state.easyPieChartLabel.innerText = state.legendFormatValue(null); state.easyPieChart_instance.update(0); } state.easyPieChart_instance.enableAnimation(); return true; }; NETDATA.easypiechartSetSelection = function(state, t) { if(state.timeIsVisible(t) !== true) return NETDATA.easypiechartClearSelection(state); var slot = state.calculateRowForTime(t); if(slot < 0 || slot >= state.data.result.length) return NETDATA.easypiechartClearSelection(state); if(typeof state.easyPieChartEvent === 'undefined') { state.easyPieChartEvent = { timer: undefined, value: 0, pcent: 0 }; } var value = state.data.result[state.data.result.length - 1 - slot]; var min = (state.easyPieChartMin === null)?NETDATA.commonMin.get(state):state.easyPieChartMin; var max = (state.easyPieChartMax === null)?NETDATA.commonMax.get(state):state.easyPieChartMax; var pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); state.easyPieChartEvent.value = value; state.easyPieChartEvent.pcent = pcent; state.easyPieChartLabel.innerText = state.legendFormatValue(value); if(state.easyPieChartEvent.timer === undefined) { state.easyPieChart_instance.disableAnimation(); state.easyPieChartEvent.timer = setTimeout(function() { state.easyPieChartEvent.timer = undefined; state.easyPieChart_instance.update(state.easyPieChartEvent.pcent); }, NETDATA.options.current.charts_selection_animation_delay); } return true; }; NETDATA.easypiechartChartUpdate = function(state, data) { var value, min, max, pcent; if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshable() === false) { value = null; pcent = 0; } else { value = data.result[0]; min = (state.easyPieChartMin === null)?NETDATA.commonMin.get(state):state.easyPieChartMin; max = (state.easyPieChartMax === null)?NETDATA.commonMax.get(state):state.easyPieChartMax; pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); } state.easyPieChartLabel.innerText = state.legendFormatValue(value); state.easyPieChart_instance.update(pcent); return true; }; NETDATA.easypiechartChartCreate = function(state, data) { var self = $(state.element); var chart = $(state.element_chart); var value = data.result[0]; var min = self.data('easypiechart-min-value') || null; var max = self.data('easypiechart-max-value') || null; var adjust = self.data('easypiechart-adjust') || null; if(min === null) { min = NETDATA.commonMin.get(state); state.easyPieChartMin = null; } else state.easyPieChartMin = min; if(max === null) { max = NETDATA.commonMax.get(state); state.easyPieChartMax = null; } else state.easyPieChartMax = max; var pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); chart.data('data-percent', pcent); var size; switch(adjust) { case 'width': size = state.chartHeight(); break; case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break; case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break; case 'height': default: size = state.chartWidth(); break; } state.element.style.width = size + 'px'; state.element.style.height = size + 'px'; var stroke = Math.floor(size / 22); if(stroke < 3) stroke = 2; var valuefontsize = Math.floor((size * 2 / 3) / 5); var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2); state.easyPieChartLabel = document.createElement('span'); state.easyPieChartLabel.className = 'easyPieChartLabel'; state.easyPieChartLabel.innerText = state.legendFormatValue(value); state.easyPieChartLabel.style.fontSize = valuefontsize + 'px'; state.easyPieChartLabel.style.top = valuetop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartLabel); var titlefontsize = Math.round(valuefontsize * 1.6 / 3); var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40)); state.easyPieChartTitle = document.createElement('span'); state.easyPieChartTitle.className = 'easyPieChartTitle'; state.easyPieChartTitle.innerText = state.title; state.easyPieChartTitle.style.fontSize = titlefontsize + 'px'; state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px'; state.easyPieChartTitle.style.top = titletop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartTitle); var unitfontsize = Math.round(titlefontsize * 0.9); var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40)); state.easyPieChartUnits = document.createElement('span'); state.easyPieChartUnits.className = 'easyPieChartUnits'; state.easyPieChartUnits.innerText = state.units; state.easyPieChartUnits.style.fontSize = unitfontsize + 'px'; state.easyPieChartUnits.style.top = unittop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartUnits); var barColor = self.data('easypiechart-barcolor'); if(typeof barColor === 'undefined' || barColor === null) barColor = state.chartCustomColors()[0]; else { // <div ... data-easypiechart-barcolor="(function(percent){return(percent < 50 ? '#5cb85c' : percent < 85 ? '#f0ad4e' : '#cb3935');})" ...></div> var tmp = eval(barColor); if(typeof tmp === 'function') barColor = tmp; } chart.easyPieChart({ barColor: barColor, trackColor: self.data('easypiechart-trackcolor') || NETDATA.themes.current.easypiechart_track, scaleColor: self.data('easypiechart-scalecolor') || NETDATA.themes.current.easypiechart_scale, scaleLength: self.data('easypiechart-scalelength') || 5, lineCap: self.data('easypiechart-linecap') || 'round', lineWidth: self.data('easypiechart-linewidth') || stroke, trackWidth: self.data('easypiechart-trackwidth') || undefined, size: self.data('easypiechart-size') || size, rotate: self.data('easypiechart-rotate') || 0, animate: self.data('easypiechart-animate') || {duration: 500, enabled: true}, easing: self.data('easypiechart-easing') || undefined }); // when we just re-create the chart // do not animate the first update var animate = true; if(typeof state.easyPieChart_instance !== 'undefined') animate = false; state.easyPieChart_instance = chart.data('easyPieChart'); if(animate === false) state.easyPieChart_instance.disableAnimation(); state.easyPieChart_instance.update(pcent); if(animate === false) state.easyPieChart_instance.enableAnimation(); return true; }; // ---------------------------------------------------------------------------------------------------------------- // gauge.js NETDATA.gaugeInitialize = function(callback) { console.log('------ come into gaugeInitialize -------') if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) { $.ajax({ url: NETDATA.gauge_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js); }) .fail(function() { NETDATA.chartLibraries.gauge.enabled = false; NETDATA.error(100, NETDATA.gauge_js); }) .always(function() { if(typeof callback === "function") return callback(); }) } else { NETDATA.chartLibraries.gauge.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.gaugeAnimation = function(state, status) { var speed = 32; if(typeof status === 'boolean' && status === false) speed = 1000000000; else if(typeof status === 'number') speed = status; // console.log('gauge speed ' + speed); state.gauge_instance.animationSpeed = speed; state.___gaugeOld__.speed = speed; }; NETDATA.gaugeSet = function(state, value, min, max) { if(typeof value !== 'number') value = 0; if(typeof min !== 'number') min = 0; if(typeof max !== 'number') max = 0; if(value > max) max = value; if(value < min) min = value; if(min > max) { var t = min; min = max; max = t; } else if(min === max) max = min + 1; // gauge.js has an issue if the needle // is smaller than min or larger than max // when we set the new values // the needle will go crazy // to prevent it, we always feed it // with a percentage, so that the needle // is always between min and max var pcent = (value - min) * 100 / (max - min); // bug fix for gauge.js 1.3.1 // if the value is the absolute min or max, the chart is broken if(pcent < 0.001) pcent = 0.001; if(pcent > 99.999) pcent = 99.999; state.gauge_instance.set(pcent); // console.log('gauge set ' + pcent + ', value ' + value + ', min ' + min + ', max ' + max); state.___gaugeOld__.value = value; state.___gaugeOld__.min = min; state.___gaugeOld__.max = max; }; NETDATA.gaugeSetLabels = function(state, value, min, max) { if(state.___gaugeOld__.valueLabel !== value) { state.___gaugeOld__.valueLabel = value; state.gaugeChartLabel.innerText = state.legendFormatValue(value); } if(state.___gaugeOld__.minLabel !== min) { state.___gaugeOld__.minLabel = min; state.gaugeChartMin.innerText = state.legendFormatValue(min); } if(state.___gaugeOld__.maxLabel !== max) { state.___gaugeOld__.maxLabel = max; state.gaugeChartMax.innerText = state.legendFormatValue(max); } }; NETDATA.gaugeClearSelection = function(state) { if(typeof state.gaugeEvent !== 'undefined') { if(state.gaugeEvent.timer !== undefined) { clearTimeout(state.gaugeEvent.timer); } state.gaugeEvent.timer = undefined; } if(state.isAutoRefreshable() === true && state.data !== null) { NETDATA.gaugeChartUpdate(state, state.data); } else { NETDATA.gaugeAnimation(state, false); NETDATA.gaugeSet(state, null, null, null); NETDATA.gaugeSetLabels(state, null, null, null); } NETDATA.gaugeAnimation(state, true); return true; }; NETDATA.gaugeSetSelection = function(state, t) { if(state.timeIsVisible(t) !== true) return NETDATA.gaugeClearSelection(state); var slot = state.calculateRowForTime(t); if(slot < 0 || slot >= state.data.result.length) return NETDATA.gaugeClearSelection(state); if(typeof state.gaugeEvent === 'undefined') { state.gaugeEvent = { timer: undefined, value: 0, min: 0, max: 0 }; } var value = state.data.result[state.data.result.length - 1 - slot]; var min = (state.gaugeMin === null)?NETDATA.commonMin.get(state):state.gaugeMin; var max = (state.gaugeMax === null)?NETDATA.commonMax.get(state):state.gaugeMax; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; state.gaugeEvent.value = value; state.gaugeEvent.min = min; state.gaugeEvent.max = max; NETDATA.gaugeSetLabels(state, value, min, max); if(state.gaugeEvent.timer === undefined) { NETDATA.gaugeAnimation(state, false); state.gaugeEvent.timer = setTimeout(function() { state.gaugeEvent.timer = undefined; NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max); }, NETDATA.options.current.charts_selection_animation_delay); } return true; }; NETDATA.gaugeChartUpdate = function(state, data) { var value, min, max; if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshable() === false) { value = 0; min = 0; max = 1; NETDATA.gaugeSetLabels(state, null, null, null); } else { value = data.result[0]; min = (state.gaugeMin === null)?NETDATA.commonMin.get(state):state.gaugeMin; max = (state.gaugeMax === null)?NETDATA.commonMax.get(state):state.gaugeMax; if(value < min) min = value; if(value > max) max = value; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; NETDATA.gaugeSetLabels(state, value, min, max); } NETDATA.gaugeSet(state, value, min, max); return true; }; NETDATA.gaugeChartCreate = function(state, data) { var self = $(state.element); // var chart = $(state.element_chart); var value = data.result[0]; var min = self.data('gauge-min-value') || null; var max = self.data('gauge-max-value') || null; var adjust = self.data('gauge-adjust') || null; var pointerColor = self.data('gauge-pointer-color') || NETDATA.themes.current.gauge_pointer; var strokeColor = self.data('gauge-stroke-color') || NETDATA.themes.current.gauge_stroke; var startColor = self.data('gauge-start-color') || state.chartCustomColors()[0]; var stopColor = self.data('gauge-stop-color') || void 0; var generateGradient = self.data('gauge-generate-gradient') || false; if(min === null) { min = NETDATA.commonMin.get(state); state.gaugeMin = null; } else state.gaugeMin = min; if(max === null) { max = NETDATA.commonMax.get(state); state.gaugeMax = null; } else state.gaugeMax = max; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5; //switch(adjust) { // case 'width': width = height * ratio; break; // case 'height': // default: height = width / ratio; break; //} //state.element.style.width = width.toString() + 'px'; //state.element.style.height = height.toString() + 'px'; var lum_d = 0.05; var options = { lines: 12, // The number of lines to draw angle: 0.15, // The span of the gauge arc lineWidth: 0.50, // The line thickness radiusScale: 0.85, // Relative radius pointer: { length: 0.8, // 0.9 The radius of the inner circle strokeWidth: 0.035, // The rotation offset color: pointerColor // Fill color }, limitMax: true, // If false, the max value of the gauge will be updated if value surpass max limitMin: true, // If true, the min value of the gauge will be fixed unless you set it manually colorStart: startColor, // Colors colorStop: stopColor, // just experiment with them strokeColor: strokeColor, // to see which ones work best for you generateGradient: (generateGradient === true), gradientType: 0, highDpiSupport: true // High resolution support }; if (generateGradient.constructor === Array) { // example options: // data-gauge-generate-gradient="[0, 50, 100]" // data-gauge-gradient-percent-color-0="#FFFFFF" // data-gauge-gradient-percent-color-50="#999900" // data-gauge-gradient-percent-color-100="#000000" options.percentColors = []; var len = generateGradient.length; while(len--) { var pcent = generateGradient[len]; var color = self.attr('data-gauge-gradient-percent-color-' + pcent.toString()) || false; if(color !== false) { var a = []; a[0] = pcent / 100; a[1] = color; options.percentColors.unshift(a); } } if(options.percentColors.length === 0) delete options.percentColors; } else if(generateGradient === false && NETDATA.themes.current.gauge_gradient === true) { //noinspection PointlessArithmeticExpressionJS options.percentColors = [ [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))], [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))], [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))], [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))], [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))], [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))], [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))], [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))], [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))], [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))], [1.0, NETDATA.colorLuminance(startColor, 0.0)]]; } state.gauge_canvas = document.createElement('canvas'); state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas'; state.gauge_canvas.className = 'gaugeChart'; state.gauge_canvas.width = width; state.gauge_canvas.height = height; state.element_chart.appendChild(state.gauge_canvas); var valuefontsize = Math.floor(height / 6); var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2); state.gaugeChartLabel = document.createElement('span'); state.gaugeChartLabel.className = 'gaugeChartLabel'; state.gaugeChartLabel.style.fontSize = valuefontsize + 'px'; state.gaugeChartLabel.style.top = valuetop.toString() + 'px'; state.element_chart.appendChild(state.gaugeChartLabel); var titlefontsize = Math.round(valuefontsize / 2); var titletop = 0; state.gaugeChartTitle = document.createElement('span'); state.gaugeChartTitle.className = 'gaugeChartTitle'; state.gaugeChartTitle.innerText = state.title; state.gaugeChartTitle.style.fontSize = titlefontsize + 'px'; state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px'; state.gaugeChartTitle.style.top = titletop.toString() + 'px'; state.element_chart.appendChild(state.gaugeChartTitle); var unitfontsize = Math.round(titlefontsize * 0.9); state.gaugeChartUnits = document.createElement('span'); state.gaugeChartUnits.className = 'gaugeChartUnits'; state.gaugeChartUnits.innerText = state.units; state.gaugeChartUnits.style.fontSize = unitfontsize + 'px'; state.element_chart.appendChild(state.gaugeChartUnits); state.gaugeChartMin = document.createElement('span'); state.gaugeChartMin.className = 'gaugeChartMin'; state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px'; state.element_chart.appendChild(state.gaugeChartMin); state.gaugeChartMax = document.createElement('span'); state.gaugeChartMax.className = 'gaugeChartMax'; state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px'; state.element_chart.appendChild(state.gaugeChartMax); // when we just re-create the chart // do not animate the first update var animate = true; if(typeof state.gauge_instance !== 'undefined') animate = false; state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge! state.___gaugeOld__ = { value: value, min: min, max: max, valueLabel: null, minLabel: null, maxLabel: null }; // we will always feed a percentage state.gauge_instance.minValue = 0; state.gauge_instance.maxValue = 100; NETDATA.gaugeAnimation(state, animate); NETDATA.gaugeSet(state, value, min, max); NETDATA.gaugeSetLabels(state, value, min, max); NETDATA.gaugeAnimation(state, true); return true; }; // ---------------------------------------------------------------------------------------------------------------- // Charts Libraries Registration NETDATA.chartLibraries = { "dygraph": { initialize: NETDATA.dygraphInitialize, create: NETDATA.dygraphChartCreate, update: NETDATA.dygraphChartUpdate, resize: function(state) { if(typeof state.dygraph_instance.resize === 'function') state.dygraph_instance.resize(); }, setSelection: NETDATA.dygraphSetSelection, clearSelection: NETDATA.dygraphClearSelection, toolboxPanAndZoom: NETDATA.dygraphToolboxPanAndZoom, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return 'ms|flip'; }, legend: function(state) { return (this.isSparkline(state) === false)?'right-side':null; }, autoresize: function(state) { void(state); return true; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { return (this.isSparkline(state) === false)?3:2; }, isSparkline: function(state) { if(typeof state.dygraph_sparkline === 'undefined') { var t = $(state.element).data('dygraph-theme'); state.dygraph_sparkline = (t === 'sparkline'); } return state.dygraph_sparkline; } }, "sparkline": { initialize: NETDATA.sparklineInitialize, create: NETDATA.sparklineChartCreate, update: NETDATA.sparklineChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'flip|abs'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "peity": { initialize: NETDATA.peityInitialize, create: NETDATA.peityChartCreate, update: NETDATA.peityChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'ssvcomma'; }, options: function(state) { void(state); return 'null2zero|flip|abs'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "morris": { initialize: NETDATA.morrisInitialize, create: NETDATA.morrisChartCreate, update: NETDATA.morrisChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return 'objectrows|ms'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 50; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 15; } }, "google": { initialize: NETDATA.googleInitialize, create: NETDATA.googleChartCreate, update: NETDATA.googleChartUpdate, resize: null, setSelection: undefined, //function(state, t) { void(state); return true; }, clearSelection: undefined, //function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'datatable'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 300; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 4; } }, "raphael": { initialize: NETDATA.raphaelInitialize, create: NETDATA.raphaelChartCreate, update: NETDATA.raphaelChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "c3": { initialize: NETDATA.c3Initialize, create: NETDATA.c3ChartCreate, update: NETDATA.c3ChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'csvjsonarray'; }, options: function(state) { void(state); return 'milliseconds'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 15; } }, "d3": { initialize: NETDATA.d3Initialize, create: NETDATA.d3ChartCreate, update: NETDATA.d3ChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "easypiechart": { initialize: NETDATA.easypiechartInitialize, create: NETDATA.easypiechartChartCreate, update: NETDATA.easypiechartChartUpdate, resize: null, setSelection: NETDATA.easypiechartSetSelection, clearSelection: NETDATA.easypiechartClearSelection, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'absolute'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { void(state); return 3; }, aspect_ratio: 100 }, "gauge": { initialize: NETDATA.gaugeInitialize, create: NETDATA.gaugeChartCreate, update: NETDATA.gaugeChartUpdate, resize: null, setSelection: NETDATA.gaugeSetSelection, clearSelection: NETDATA.gaugeClearSelection, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'absolute'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { void(state); return 3; }, aspect_ratio: 70 } }; NETDATA.registerChartLibrary = function(library, url) { if(NETDATA.options.debug.libraries === true) console.log("registering chart library: " + library); NETDATA.chartLibraries[library].url = url; NETDATA.chartLibraries[library].initialized = true; NETDATA.chartLibraries[library].enabled = true; }; // ---------------------------------------------------------------------------------------------------------------- // Load required JS libraries and CSS NETDATA.requiredJs = [ { url: NETDATA.serverDefault + 'lib/bootstrap-3.3.7.min.js', async: false, isAlreadyLoaded: function() { // check if bootstrap is loaded if(typeof $().emulateTransitionEnd === 'function') return true; else { return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true); } } }, { url: NETDATA.serverDefault + 'lib/perfect-scrollbar-0.6.15.min.js', isAlreadyLoaded: function() { return false; } } ]; NETDATA.requiredCSS = [ { url: NETDATA.themes.current.bootstrap_css, isAlreadyLoaded: function() { return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true); } }, { url: NETDATA.serverDefault + 'css/font-awesome.min.css?v4.7.0', isAlreadyLoaded: function() { return false; } }, { url: NETDATA.themes.current.dashboard_css, isAlreadyLoaded: function() { return false; } } ]; NETDATA.loadedRequiredJs = 0; NETDATA.loadRequiredJs = function(index, callback) { console.log('============NETDATA.requiredJs[%d] with length=%d', index, NETDATA.requiredJs.length) console.dir( NETDATA.requiredJs[index] ) if(index >= NETDATA.requiredJs.length) { if(typeof callback === 'function') return callback(); return; } if(NETDATA.requiredJs[index].isAlreadyLoaded()) { console.log(' come into isAlreadyLoaded()') NETDATA.loadedRequiredJs++; NETDATA.loadRequiredJs(++index, callback); return; } let currentURL = NETDATA.requiredJs[index].url if(NETDATA.options.debug.main_loop === true) console.log('xxxxxx loading ' + currentURL); var async = true; if(typeof NETDATA.requiredJs[index].async !== 'undefined' && NETDATA.requiredJs[index].async === false) async = false; $.ajax({ url: currentURL, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { console.log('============NETDATA.requiredJs[%d] url= %s', index, currentURL) if(NETDATA.options.debug.main_loop === true) console.log('loaded ' + currentURL); }) .fail(function() { alert('Cannot load required JS library: ' + currentURL); }) .always(function() { NETDATA.loadedRequiredJs++; if(async === false) NETDATA.loadRequiredJs(++index, callback); }); if(async === true) NETDATA.loadRequiredJs(++index, callback); }; NETDATA.loadRequiredCSS = function(index) { if(index >= NETDATA.requiredCSS.length) return; if(NETDATA.requiredCSS[index].isAlreadyLoaded()) { NETDATA.loadRequiredCSS(++index); return; } if(NETDATA.options.debug.main_loop === true) console.log('loading ' + NETDATA.requiredCSS[index].url); NETDATA._loadCSS(NETDATA.requiredCSS[index].url); NETDATA.loadRequiredCSS(++index); }; // ---------------------------------------------------------------------------------------------------------------- // Registry of netdata hosts NETDATA.alarms = { onclick: null, // the callback to handle the click - it will be called with the alarm log entry chart_div_offset: -50, // give that space above the chart when scrolling to it chart_div_id_prefix: 'chart_', // the chart DIV IDs have this prefix (they should be NETDATA.name2id(chart.id)) chart_div_animation_duration: 0,// the duration of the animation while scrolling to a chart ms_penalty: 0, // the time penalty of the next alarm ms_between_notifications: 500, // firefox moves the alarms off-screen (above, outside the top of the screen) // if alarms are shown faster than: one per 500ms notifications: false, // when true, the browser supports notifications (may not be granted though) last_notification_id: 0, // the id of the last alarm_log we have raised an alarm for first_notification_id: 0, // the id of the first alarm_log entry for this session // this is used to prevent CLEAR notifications for past events // notifications_shown: [], server: null, // the server to connect to for fetching alarms current: null, // the list of raised alarms - updated in the background callback: null, // a callback function to call every time the list of raised alarms is refreshed notify: function(entry) { // console.log('alarm ' + entry.unique_id); if(entry.updated === true) { // console.log('alarm ' + entry.unique_id + ' has been updated by another alarm'); return; } var value_string = entry.value_string; if(NETDATA.alarms.current !== null) { // get the current value_string var t = NETDATA.alarms.current.alarms[entry.chart + '.' + entry.name]; if(typeof t !== 'undefined' && entry.status === t.status && typeof t.value_string !== 'undefined') value_string = t.value_string; } var name = entry.name.replace(/_/g, ' '); var status = entry.status.toLowerCase(); var title = name + ' = ' + value_string.toString(); var tag = entry.alarm_id; var icon = 'images/seo-performance-128.png'; var interaction = false; var data = entry; var show = true; // console.log('alarm ' + entry.unique_id + ' ' + entry.chart + '.' + entry.name + ' is ' + entry.status); switch(entry.status) { case 'REMOVED': show = false; break; case 'UNDEFINED': return; case 'UNINITIALIZED': return; case 'CLEAR': if(entry.unique_id < NETDATA.alarms.first_notification_id) { // console.log('alarm ' + entry.unique_id + ' is not current'); return; } if(entry.old_status === 'UNINITIALIZED' || entry.old_status === 'UNDEFINED') { // console.log('alarm' + entry.unique_id + ' switch to CLEAR from ' + entry.old_status); return; } if(entry.no_clear_notification === true) { // console.log('alarm' + entry.unique_id + ' is CLEAR but has no_clear_notification flag'); return; } title = name + ' back to normal (' + value_string.toString() + ')'; icon = 'images/check-mark-2-128-green.png'; interaction = false; break; case 'WARNING': if(entry.old_status === 'CRITICAL') status = 'demoted to ' + entry.status.toLowerCase(); icon = 'images/alert-128-orange.png'; interaction = false; break; case 'CRITICAL': if(entry.old_status === 'WARNING') status = 'escalated to ' + entry.status.toLowerCase(); icon = 'images/alert-128-red.png'; interaction = true; break; default: console.log('invalid alarm status ' + entry.status); return; } /* // cleanup old notifications with the same alarm_id as this one // FIXME: it does not seem to work on any web browser! var len = NETDATA.alarms.notifications_shown.length; while(len--) { var n = NETDATA.alarms.notifications_shown[len]; if(n.data.alarm_id === entry.alarm_id) { console.log('removing old alarm ' + n.data.unique_id); // close the notification n.close.bind(n); // remove it from the array NETDATA.alarms.notifications_shown.splice(len, 1); len = NETDATA.alarms.notifications_shown.length; } } */ if(show === true) { setTimeout(function() { // show this notification // console.log('new notification: ' + title); var n = new Notification(title, { body: entry.hostname + ' - ' + entry.chart + ' (' + entry.family + ') - ' + status + ': ' + entry.info, tag: tag, requireInteraction: interaction, icon: NETDATA.serverDefault + icon, data: data }); n.onclick = function(event) { event.preventDefault(); NETDATA.alarms.onclick(event.target.data); }; // console.log(n); // NETDATA.alarms.notifications_shown.push(n); // console.log(entry); }, NETDATA.alarms.ms_penalty); NETDATA.alarms.ms_penalty += NETDATA.alarms.ms_between_notifications; } }, scrollToChart: function(chart_id) { if(typeof chart_id === 'string') { var offset = $('#' + NETDATA.alarms.chart_div_id_prefix + NETDATA.name2id(chart_id)).offset(); if(typeof offset !== 'undefined') { $('html, body').animate({ scrollTop: offset.top + NETDATA.alarms.chart_div_offset }, NETDATA.alarms.chart_div_animation_duration); return true; } } return false; }, scrollToAlarm: function(alarm) { if(typeof alarm === 'object') { var ret = NETDATA.alarms.scrollToChart(alarm.chart); if(ret === true && NETDATA.options.page_is_visible === false) window.focus(); // alert('netdata dashboard will now scroll to chart: ' + alarm.chart + '\n\nThis alarm opened to bring the browser window in front of the screen. Click on the dashboard to prevent it from appearing again.'); } }, notifyAll: function() { // console.log('FETCHING ALARM LOG'); NETDATA.alarms.get_log(NETDATA.alarms.last_notification_id, function(data) { // console.log('ALARM LOG FETCHED'); if(data === null || typeof data !== 'object') { console.log('invalid alarms log response'); return; } if(data.length === 0) { console.log('received empty alarm log'); return; } // console.log('received alarm log of ' + data.length + ' entries, from ' + data[data.length - 1].unique_id.toString() + ' to ' + data[0].unique_id.toString()); data.sort(function(a, b) { if(a.unique_id > b.unique_id) return -1; if(a.unique_id < b.unique_id) return 1; return 0; }); NETDATA.alarms.ms_penalty = 0; var len = data.length; while(len--) { if(data[len].unique_id > NETDATA.alarms.last_notification_id) { NETDATA.alarms.notify(data[len]); } //else // console.log('ignoring alarm (older) with id ' + data[len].unique_id.toString()); } NETDATA.alarms.last_notification_id = data[0].unique_id; NETDATA.localStorageSet('last_notification_id', NETDATA.alarms.last_notification_id, null); // console.log('last notification id = ' + NETDATA.alarms.last_notification_id); }) }, check_notifications: function() { // returns true if we should fire 1+ notifications if(NETDATA.alarms.notifications !== true) { // console.log('notifications not available'); return false; } if(Notification.permission !== 'granted') { // console.log('notifications not granted'); return false; } if(typeof NETDATA.alarms.current !== 'undefined' && typeof NETDATA.alarms.current.alarms === 'object') { // console.log('can do alarms: old id = ' + NETDATA.alarms.last_notification_id + ' new id = ' + NETDATA.alarms.current.latest_alarm_log_unique_id); if(NETDATA.alarms.current.latest_alarm_log_unique_id > NETDATA.alarms.last_notification_id) { // console.log('new alarms detected'); return true; } //else console.log('no new alarms'); } // else console.log('cannot process alarms'); return false; }, get: function(what, callback) { $.ajax({ url: NETDATA.alarms.server + '/api/v1/alarms?' + what.toString(), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(NETDATA.alarms.first_notification_id === 0 && typeof data.latest_alarm_log_unique_id === 'number') NETDATA.alarms.first_notification_id = data.latest_alarm_log_unique_id; if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(415, NETDATA.alarms.server); if(typeof callback === 'function') return callback(null); }); }, update_forever: function() { NETDATA.alarms.get('active', function(data) { if(data !== null) { NETDATA.alarms.current = data; if(NETDATA.alarms.check_notifications() === true) { NETDATA.alarms.notifyAll(); } if (typeof NETDATA.alarms.callback === 'function') { NETDATA.alarms.callback(data); } // Health monitoring is disabled on this netdata if(data.status === false) return; } setTimeout(NETDATA.alarms.update_forever, 10000); }); }, get_log: function(last_id, callback) { // console.log('fetching all log after ' + last_id.toString()); $.ajax({ url: NETDATA.alarms.server + '/api/v1/alarm_log?after=' + last_id.toString(), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(416, NETDATA.alarms.server); if(typeof callback === 'function') return callback(null); }); }, init: function() { NETDATA.alarms.server = NETDATA.fixHost(NETDATA.serverDefault); console.log('Rico trace in alarms.init:', NETDATA.alarms.server) NETDATA.alarms.last_notification_id = NETDATA.localStorageGet('last_notification_id', NETDATA.alarms.last_notification_id, null); if(NETDATA.alarms.onclick === null) NETDATA.alarms.onclick = NETDATA.alarms.scrollToAlarm; if(netdataShowAlarms === true) { NETDATA.alarms.update_forever(); if('Notification' in window) { // console.log('notifications available'); NETDATA.alarms.notifications = true; if(Notification.permission === 'default') Notification.requestPermission(); } } } }; // ---------------------------------------------------------------------------------------------------------------- // Registry of netdata hosts NETDATA.registry = { server: null, // the netdata registry server person_guid: null, // the unique ID of this browser / user machine_guid: null, // the unique ID the netdata server that served dashboard.js hostname: 'unknown', // the hostname of the netdata server that served dashboard.js machines: null, // the user's other URLs machines_array: null, // the user's other URLs in an array person_urls: null, parsePersonUrls: function(person_urls) { // console.log(person_urls); NETDATA.registry.person_urls = person_urls; if(person_urls) { NETDATA.registry.machines = {}; NETDATA.registry.machines_array = []; var apu = person_urls; var i = apu.length; while(i--) { if(typeof NETDATA.registry.machines[apu[i][0]] === 'undefined') { // console.log('adding: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString()); var obj = { guid: apu[i][0], url: apu[i][1], last_t: apu[i][2], accesses: apu[i][3], name: apu[i][4], alternate_urls: [] }; obj.alternate_urls.push(apu[i][1]); NETDATA.registry.machines[apu[i][0]] = obj; NETDATA.registry.machines_array.push(obj); } else { // console.log('appending: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString()); var pu = NETDATA.registry.machines[apu[i][0]]; if(pu.last_t < apu[i][2]) { pu.url = apu[i][1]; pu.last_t = apu[i][2]; pu.name = apu[i][4]; } pu.accesses += apu[i][3]; pu.alternate_urls.push(apu[i][1]); } } } if(typeof netdataRegistryCallback === 'function') netdataRegistryCallback(NETDATA.registry.machines_array); }, init: function() { if(netdataRegistry !== true) return; NETDATA.registry.hello(NETDATA.serverDefault, function(data) { if(data) { NETDATA.registry.server = data.registry; NETDATA.registry.machine_guid = data.machine_guid; NETDATA.registry.hostname = data.hostname; NETDATA.registry.access(2, function (person_urls) { NETDATA.registry.parsePersonUrls(person_urls); }); } }); }, hello: function(host, callback) { host = this.host; //NETDATA.fixHost(host); // send HELLO to a netdata server: // 1. verifies the server is reachable // 2. responds with the registry URL, the machine GUID of this netdata server and its hostname $.ajax({ url: host + '/api/v1/registry?action=hello', async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(408, host + ' response: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(407, host); if(typeof callback === 'function') return callback(null); }); }, access: function(max_redirects, callback) { // send ACCESS to a netdata registry: // 1. it lets it know we are accessing a netdata server (its machine GUID and its URL) // 2. it responds with a list of netdata servers we know // the registry identifies us using a cookie it sets the first time we access it // the registry may respond with a redirect URL to send us to another registry $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=access&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault), // + '&visible_url=' + encodeURIComponent(document.location), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { var redirect = null; if(typeof data.registry === 'string') redirect = data.registry; if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(409, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(data === null) { if(redirect !== null && max_redirects > 0) { NETDATA.registry.server = redirect; NETDATA.registry.access(max_redirects - 1, callback); } else { if(typeof callback === 'function') return callback(null); } } else { if(typeof data.person_guid === 'string') NETDATA.registry.person_guid = data.person_guid; if(typeof callback === 'function') return callback(data.urls); } }) .fail(function() { NETDATA.error(410, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, delete: function(delete_url, callback) { // send DELETE to a netdata registry: $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=delete&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&delete_url=' + encodeURIComponent(delete_url), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(411, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(412, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, search: function(machine_guid, callback) { // SEARCH for the URLs of a machine: $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=search&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&for=' + machine_guid, async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(417, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(418, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, switch: function(new_person_guid, callback) { // impersonate $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=switch&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&to=' + new_person_guid, async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(413, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(414, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); } }; // ---------------------------------------------------------------------------------------------------------------- // Boot it! if(typeof netdataPrepCallback === 'function') netdataPrepCallback(); NETDATA.errorReset(); NETDATA.loadRequiredCSS(0); NETDATA._loadjQuery(function() { NETDATA.loadRequiredJs(0, function() { if(typeof $().emulateTransitionEnd !== 'function') { // bootstrap is not available NETDATA.options.current.show_help = false; } if(typeof netdataDontStart === 'undefined' || !netdataDontStart) { if(NETDATA.options.debug.main_loop === true) console.log('starting chart refresh thread'); NETDATA.start(); } }); }); })(window, document);
1.117188
1
webpack-server.config.js
stevenkaspar/react-redux-webpack-keystone-boilerplate
5
4879
var webpack = require('webpack'); const path = require('path') const UglifyJSPlugin = require('uglifyjs-webpack-plugin') const output = { development: { path: path.resolve(__dirname, './routes/redux-render'), filename: '[name].js', libraryTarget: "commonjs2" }, production: { path: path.resolve(__dirname, './routes/redux-render'), filename: '[name].js', libraryTarget: "commonjs2" } } const devtool = { development: '', production: '' } const entry = { development: { 'render': './routes/redux-render/src/render.jsx', }, production: { 'render': './routes/redux-render/src/render.jsx', } } const plugins = { development: [], production: [] } const env_key = process.env.NODE_ENV === 'development' ? 'development' : 'production' module.exports = { context: __dirname, target: 'node', entry: entry[env_key], output: output[env_key], devtool: devtool[env_key], plugins: plugins[env_key], module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: "babel-loader", options: { presets: [ 'es2015', 'react', 'stage-2' ] }, }, { test: /\.scss$/, loaders: ['css-loader', 'sass-loader'] } ] } }; // const path = require('path'); // const webpack = require('webpack'); // // require('dotenv').config(); // // module.exports = { // entry: [ // 'react-hot-loader/patch', // // 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', // './public/js/src/app.js' // ], // output: { // filename: 'bundle.js', // path: path.resolve(__dirname, '/public/js/dist'), // publicPath: '/' // }, // devServer: { // hot: true, // contentBase: './public', // inline: true, // publicPath: 'http://localhost:8080/', // port: 8080 // }, // devtool: process.env.NODE_ENV === 'development' ? 'source-map' : 'false', // plugins: [ // new webpack.ProvidePlugin({ // $: 'jquery', // jQuery: 'jquery', // 'window.jQuery': 'jquery', // Popper: ['popper.js', 'default'], // // In case you imported plugins individually, you must also require them here: // Util: "exports-loader?Util!bootstrap/js/dist/util", // Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown", // }), // // new CleanWebpackPlugin(['dist']), // // new HtmlWebpackPlugin({ // // title: 'Hot Module Replacement' // // }), // new webpack.NamedModulesPlugin(), // new webpack.HotModuleReplacementPlugin() // ], // module: { // rules: [ // { // test: /\.(html|css|txt)$/, // use: 'raw-loader' // }, // { // test: /\.scss$/, // use: [{ // loader: "style-loader" // creates style nodes from JS strings // }, { // loader: "css-loader" // translates CSS into CommonJS // }, { // loader: "sass-loader" // compiles Sass to CSS // }] // }, // { // test: /\.js$/, // exclude: /(node_modules|bower_components)/, // loader: "babel-loader", // options: { // presets: [ // 'es2015', // 'react', // 'stage-2' // ] // }, // } // ] // } // };
1.0625
1
src/core/ui5ApiFormatter.js
wozjac/brackets-ui5
4
4887
define((require, exports) => { "use strict"; const codeEditor = require("src/editor/codeEditor"), constants = require("src/core/constants"), ui5ApiService = require("src/core/ui5ApiService"); function getFormattedObjectApi(ui5ObjectApi, cleanHtml = false, inheritedAsArray = false, flatStatic = false) { const api = { name: ui5ObjectApi.name, extends: ui5ObjectApi.extends, apiDocUrl: ui5ObjectApi.apiDocUrl, isDeprecated: false, hasMethods: false, hasEvents: false, hasConstructor: false, hasConstructorParams: false, hasProperties: false, hasInheritedMethods: false, hasBaseObject: false, hasAggregations: false }; api.description = codeEditor.formatJsDoc(ui5ObjectApi.description, cleanHtml); if (ui5ObjectApi.extends) { api.hasBaseObject = true; } if (ui5ObjectApi.methods) { api.hasMethods = true; api.methods = ui5ObjectApi.methods.filter((element) => { return element.visibility === "public"; }); api.methods = JSON.parse(JSON.stringify(api.methods)); api.methods.forEach((method) => { method.objectName = ui5ObjectApi.name; method.description = codeEditor.formatJsDoc(method.description, cleanHtml); if (method.deprecated) { method.description = `[DEPRECATED! ${codeEditor.formatJsDoc(method.deprecated.text, true)}] ${method.description}`; } if (method.static) { if (flatStatic === true) { method.name = method.name; } else { method.name = `${ui5ObjectApi.name}.${method.name}`; } } if (method.parameters) { prepareParameters(method, cleanHtml); } let path = method.name; if (path.indexOf("module:") !== -1) { path = path.replace("module:", ""); path = encodeURIComponent(path); } if (method.returnValue && method.returnValue.type) { const returnType = method.returnValue.type.replace("[]", ""); const returnObject = ui5ApiService.getUi5Objects()[returnType]; if (returnObject) { method.hasUi5ObjectReturnType = true; method.ui5ObjectReturnType = returnType; } else { method.hasUi5ObjectReturnType = false; } } method.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/methods/${path}`; }); } if (ui5ObjectApi.events) { api.hasEvents = true; api.events = ui5ObjectApi.events.filter((element) => { return element.visibility === "public"; }); api.events = JSON.parse(JSON.stringify(api.events)); api.events.forEach((event) => { event.objectName = ui5ObjectApi.name; event.description = codeEditor.formatJsDoc(event.description, cleanHtml); if (event.deprecated) { event.description = `[DEPRECATED! ${codeEditor.formatJsDoc(event.deprecated.text, true)}] ${event.description}`; } if (event.parameters) { prepareParameters(event, cleanHtml); } event.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/events/${event.name}`; }); } let properties; switch (ui5ObjectApi.kind) { case "class": try { properties = ui5ObjectApi["ui5-metadata"].properties; } catch (error) { properties = []; } if (ui5ObjectApi.hasOwnProperty("constructor")) { api.hasConstructor = true; api.constructor = JSON.parse(JSON.stringify(ui5ObjectApi.constructor)); api.constructor.description = codeEditor.formatJsDoc(api.constructor.description, cleanHtml); if (ui5ObjectApi.constructor.parameters) { api.hasConstructorParams = true; api.constructorParams = JSON.parse(JSON.stringify(ui5ObjectApi.constructor.parameters)); api.constructorParams.forEach((param) => { param.description = codeEditor.formatJsDoc(param.description, cleanHtml); param.objectName = ui5ObjectApi.name; if (param.parameterProperties) { param.hasProperties = true; param.parameterProperties = JSON.parse(JSON.stringify(param.parameterProperties)); const properties = []; for (const prop in param.parameterProperties) { const parameterProperty = param.parameterProperties[prop]; parameterProperty.description = codeEditor.formatJsDoc(parameterProperty.description, cleanHtml); parameterProperty.objectName = ui5ObjectApi.name; properties.push(parameterProperty); } param.parameterProperties = properties; } }); } } break; case "enum": case "namespace": properties = ui5ObjectApi.properties; break; } if (properties && properties.length > 0) { properties = properties.filter((property) => { return property.visibility === "public"; }); api.hasProperties = true; api.properties = JSON.parse(JSON.stringify(properties)); api.properties.forEach((property) => { if (!property.type || property.type === "undefined") { property.type = ""; } else { const theType = property.type.replace("[]", ""); const typeObject = ui5ApiService.getUi5Objects()[theType]; if (typeObject) { property.hasUi5ObjectType = true; property.ui5ObjectType = theType; } else { property.hasUi5ObjectType = false; } } property.objectName = ui5ObjectApi.name; property.description = codeEditor.formatJsDoc(property.description, cleanHtml); if (property.deprecated) { property.description = `[DEPRECATED! ${codeEditor.formatJsDoc(property.deprecated.text, true)}] ${property.description}`; } property.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/controlProperties`; }); } if (ui5ObjectApi.deprecated) { api.isDeprecated = true; } if (ui5ObjectApi["ui5-metadata"] && ui5ObjectApi["ui5-metadata"].aggregations) { api.hasAggregations = true; api.aggregations = ui5ObjectApi["ui5-metadata"].aggregations.filter((element) => { return element.visibility === "public"; }); api.aggregations = JSON.parse(JSON.stringify(api.aggregations)); api.aggregations.forEach((aggregation) => { aggregation.objectName = ui5ObjectApi.name; const theType = aggregation.type.replace("[]", ""); const typeObject = ui5ApiService.getUi5Objects()[theType]; if (typeObject) { aggregation.hasUi5ObjectType = true; aggregation.ui5ObjectType = theType; } else { aggregation.hasUi5ObjectType = false; } aggregation.description = codeEditor.formatJsDoc(aggregation.description, cleanHtml); aggregation.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/aggregations`; }); } if (ui5ObjectApi.inheritedApi) { api.inheritedApi = {}; for (const objectKey in ui5ObjectApi.inheritedApi) { api.inheritedApi[objectKey] = getFormattedObjectApi(ui5ObjectApi.inheritedApi[objectKey], cleanHtml); if (ui5ObjectApi.inheritedApi[objectKey].methods) { api.hasInheritedMethods = true; } } } if (inheritedAsArray === true) { const inheritedApiAsArray = []; let inheritedObject; for (const objectName in api.inheritedApi) { inheritedObject = api.inheritedApi[objectName]; inheritedApiAsArray.push(inheritedObject); } api.inheritedApi = inheritedApiAsArray; } return api; } function prepareParameters(object, cleanHtml) { object.parameters.forEach((parameter) => { parameter.description = codeEditor.formatJsDoc(parameter.description, cleanHtml); if (parameter.parameterProperties) { const paramProperties = []; for (const p in parameter.parameterProperties) { const param = parameter.parameterProperties[p]; param.name = p; param.description = codeEditor.formatJsDoc(param.description, cleanHtml); paramProperties.push(param); } parameter.parameterProperties = paramProperties; } }); } function filterApiMembers(ui5ObjectApi, memberSearchString, memberGroupFilter) { const objectApi = JSON.parse(JSON.stringify(ui5ObjectApi)); function filterMembers(key1, key2) { let filterable; if (key2) { filterable = objectApi[key1][key2]; } else { filterable = objectApi[key1]; } if (filterable) { return filterable.filter((member) => { if (member.visibility !== "public") { return false; } return new RegExp(memberSearchString, "i").test(member.name); }); } } const filterableKeys = ["methods", "events", "properties", "aggregations"]; if (memberSearchString) { for (const key of filterableKeys) { if (objectApi.kind === "class" && (key === "properties" || key === "aggregations")) { objectApi["ui5-metadata"][key] = filterMembers("ui5-metadata", key); if (!objectApi["ui5-metadata"][key] || (objectApi["ui5-metadata"][key] && objectApi["ui5-metadata"][key].length === 0)) { delete objectApi["ui5-metadata"][key]; } } else { objectApi[key] = filterMembers(key); if (!objectApi[key] || (objectApi[key] && objectApi[key].length === 0)) { delete objectApi[key]; } } } delete objectApi.constructor; } if (memberGroupFilter) { const deleteMarkers = { properties: true, methods: true, events: true, aggregations: true, construct: true }; switch (memberGroupFilter) { case constants.memberGroupFilter.aggregations: deleteMarkers.aggregations = false; break; case constants.memberGroupFilter.methods: deleteMarkers.methods = false; break; case constants.memberGroupFilter.properties: deleteMarkers.properties = false; break; case constants.memberGroupFilter.events: deleteMarkers.events = false; break; case constants.memberGroupFilter.construct: deleteMarkers.construct = false; break; } _deleteMembers(objectApi, deleteMarkers); } if (objectApi.inheritedApi) { for (const name in objectApi.inheritedApi) { objectApi.inheritedApi[name] = filterApiMembers(objectApi.inheritedApi[name], memberSearchString, memberGroupFilter); } } return objectApi; } function _deleteMembers(objectApi, deleteMarkers) { if (deleteMarkers.properties === true) { if (objectApi.kind === "class") { delete objectApi["ui5-metadata"].properties; } else { delete objectApi.properties; } } if (deleteMarkers.aggregations === true) { if (objectApi.kind === "class") { delete objectApi["ui5-metadata"].aggregations; } else { delete objectApi.aggregations; } } if (deleteMarkers.events === true) { delete objectApi.events; } if (deleteMarkers.methods === true) { delete objectApi.methods; } if (deleteMarkers.construct === true) { delete objectApi.constructor; } } function convertModuleNameToPath(moduleName) { return moduleName.replace("module:", "").replace(/\//g, "."); } exports.getFormattedObjectApi = getFormattedObjectApi; exports.filterApiMembers = filterApiMembers; exports.convertModuleNameToPath = convertModuleNameToPath; });
1.453125
1
docs/html/dir_17b4a9b5ba749112246522facd776253.js
wrathematics/fml
15
4895
var dir_17b4a9b5ba749112246522facd776253 = [ [ "gpublas.hh", "hip_2gpublas_8hh_source.html", null ], [ "gpulapack.hh", "hip_2gpulapack_8hh_source.html", null ], [ "gpuprims.hh", "hip_2gpuprims_8hh_source.html", null ], [ "gpurand.hh", "hip_2gpurand_8hh_source.html", null ], [ "rocm_smi.hh", "rocm__smi_8hh_source.html", null ], [ "types.hh", "gpu_2arch_2hip_2types_8hh_source.html", null ] ];
-0.06543
0
routes/relatorio.js
ArthurFritz/Mock-Curso-F-rias
0
4903
var express = require('express'); var router = express.Router(); var user = [ {id: 1, nome: '<NAME>', login: "jose", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 2, nome: '<NAME>', login: "mariano", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 3, nome: '<NAME>', login: "magyver", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 4, nome: '<NAME>', login: "irineu", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 5, nome: '<NAME>', login: "carlos", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 6, nome: '<NAME>', login: "carlos", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 7, nome: '<NAME>', login: "carlos", email: '<EMAIL>', perfil:"ALUNO", urlFoto: null, senha:123456} ]; var mockInfo = [ { usuario : user[0], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26"], frequencia: 50 }, { usuario : user[1], presenca : ["2018-01-22","2018-01-23","2018-01-24"], frequencia: 30 }, { usuario : user[2], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25"], frequencia: 40 }, { usuario : user[3], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26","2018-01-29"], frequencia: 60 }, { usuario : user[4], presenca : ["2018-01-22"], frequencia: 10 }, { usuario : user[5], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26","2018-01-29","2018-01-30","2018-01-31"], frequencia: 80 } ]; router.get('/:disciplina', function(req, res) { var result = JSON.parse(JSON.stringify(mockInfo)); if(req.params.disciplina > 2){ var remover = req.params.disciplina - 1; for(var a=0; a< remover && result.length > 0; a++){ if(result.length > 0 ){ result.splice(-1,1) } } } res.send(result); }); module.exports = router;
1.054688
1
style-guide/src/components/design-system-partials/otkit-icons.js
neha-ot/design-tokens
73
4911
import React, { useState } from 'react'; import _ from 'lodash'; import icons from 'otkit-icons/token.common'; import SectionHeader from '../section-header'; import styles from '../../styles/otkit-icons.module.scss'; const Icons = () => { const [filter, setFilter] = useState(''); const keys = _.keys(icons).sort(); const actualIcons = _.without(keys, 'iconSize'); const getFilter = event => { const key = event.target.value || ''; setFilter(key.toLowerCase()); }; const renderHeaderContent = () => ( <input className={styles.form} type="text" onChange={getFilter} placeholder="Search icon" /> ); const tokens = actualIcons .filter(name => { if (filter === '') { return true; } const iconName = _.kebabCase(name); const regex = RegExp(`.*${filter}.*`, 'g'); return iconName.match(regex); }) .map(name => { const value = icons[name]; return ( <div className={styles.card} key={name}> <div className={styles.iconBlock}> <div className={styles.icon} dangerouslySetInnerHTML={{ __html: value }} /> </div> <div className={styles.iconName}>{_.kebabCase(name)}</div> </div> ); }); return ( <div className={styles.mainContainer}> <SectionHeader text="Icons" type="SectionHeader__small" content={renderHeaderContent()} /> <div className={styles.sectionIcon}>{tokens}</div> </div> ); }; export default Icons;
1.5625
2
public/dist/application.js
kejack/workbench
0
4919
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'workbench'; var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ngTable', 'ui.router','mwl.calendar', 'ui.bootstrap', 'ui.utils', 'formly', 'formlyBootstrap']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })(); 'use strict'; //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); } ]); //Then define the init function for starting up the application angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); }); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('categories', ['core']); 'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('core'); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('events', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('files', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('projects', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('tasks', ['core', 'ui.bootstrap']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('users'); 'use strict'; // Configuring the new module angular.module('categories').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Categories', 'categories', 'dropdown', '/categories(/create)?'); Menus.addSubMenuItem('topbar', 'categories', 'List Categories', 'categories'); Menus.addSubMenuItem('topbar', 'categories', 'New Category', 'categories/create'); } ]); 'use strict'; //Setting up route angular.module('categories').config(['$stateProvider', function($stateProvider) { // Categories state routing $stateProvider. state('listCategories', { url: '/categories', templateUrl: 'modules/categories/views/list-categories.client.view.html' }). state('createCategory', { url: '/categories/create', templateUrl: 'modules/categories/views/create-category.client.view.html' }). state('viewCategory', { url: '/categories/:categoryId', templateUrl: 'modules/categories/views/view-category.client.view.html' }). state('editCategory', { url: '/categories/:categoryId/edit', templateUrl: 'modules/categories/views/edit-category.client.view.html' }); } ]); 'use strict'; // Categories controller angular.module('categories').controller('CategoriesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Categories', 'TableSettings', 'CategoriesForm', function($scope, $stateParams, $location, Authentication, Categories, TableSettings, CategoriesForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Categories); $scope.category = {}; $scope.setFormFields = function(disabled) { $scope.formFields = CategoriesForm.getFormFields(disabled); }; // Create new Category $scope.create = function() { var category = new Categories($scope.category); // Redirect after save category.$save(function(response) { $location.path('categories/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Category $scope.remove = function(category) { if ( category ) { category = Categories.get({categoryId:category._id}, function() { category.$remove(); $scope.tableParams.reload(); }); } else { $scope.category.$remove(function() { $location.path('categories'); }); } }; // Update existing Category $scope.update = function() { var category = $scope.category; category.$update(function() { $location.path('categories/' + category._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewCategory = function() { $scope.category = Categories.get( {categoryId: $stateParams.categoryId} ); $scope.setFormFields(true); }; $scope.toEditCategory = function() { $scope.category = Categories.get( {categoryId: $stateParams.categoryId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Categories service used to communicate Categories REST endpoints angular.module('categories').factory('Categories', ['$resource', function($resource) { return $resource('categories/:categoryId', { categoryId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('categories') .factory('CategoriesForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }); } ]); 'use strict'; angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus', function($scope, Authentication, Menus) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); } ]); 'use strict'; angular.module('core').controller('HomeController', ['$scope', 'Authentication', function($scope, Authentication) { // This provides Authentication context. $scope.authentication = Authentication; } ]); 'use strict'; angular.module('core') .directive('ngReallyClick', ['$modal', function($modal) { var ModalInstanceCtrl = ["$scope", "$modalInstance", function($scope, $modalInstance) { $scope.ok = function() { $modalInstance.close(); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }]; return { restrict: 'A', scope: { ngReallyClick: '&' }, link: function(scope, element, attrs) { element.bind('click', function() { var message = attrs.ngReallyMessage || 'Are you sure ?'; var modalHtml = '<div class="modal-body">' + message + '</div>'; modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>'; var modalInstance = $modal.open({ template: modalHtml, controller: ModalInstanceCtrl }); modalInstance.result.then(function() { scope.ngReallyClick(); }, function() { //Modal dismissed }); }); } }; } ]); 'use strict'; //Menu service used for managing menus angular.module('core').service('Menus', [ function() { // Define a set of default roles this.defaultRoles = ['*']; // Define the menus object this.menus = {}; // A private function for rendering decision var shouldRender = function(user) { if (user) { if (!!~this.roles.indexOf('*')) { return true; } else { for (var userRoleIndex in user.roles) { for (var roleIndex in this.roles) { if (this.roles[roleIndex] === user.roles[userRoleIndex]) { return true; } } } } } else { return this.isPublic; } return false; }; // Validate menu existance this.validateMenuExistance = function(menuId) { if (menuId && menuId.length) { if (this.menus[menuId]) { return true; } else { throw new Error('Menu does not exists'); } } else { throw new Error('MenuId was not provided'); } return false; }; // Get the menu object by menu id this.getMenu = function(menuId) { // Validate that the menu exists this.validateMenuExistance(menuId); // Return the menu object return this.menus[menuId]; }; // Add new menu object by menu id this.addMenu = function(menuId, isPublic, roles) { // Create the new menu this.menus[menuId] = { isPublic: isPublic || false, roles: roles || this.defaultRoles, items: [], shouldRender: shouldRender }; // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeMenu = function(menuId) { // Validate that the menu exists this.validateMenuExistance(menuId); // Return the menu object delete this.menus[menuId]; }; // Add menu item object this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuItemType, menuItemUIRoute, isPublic, roles, position) { // Validate that the menu exists this.validateMenuExistance(menuId); // Push new menu item this.menus[menuId].items.push({ title: menuItemTitle, link: menuItemURL, menuItemType: menuItemType || 'item', menuItemClass: menuItemType, uiRoute: menuItemUIRoute || ('/' + menuItemURL), isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].isPublic : isPublic), roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].roles : roles), position: position || 0, items: [], shouldRender: shouldRender }); // Return the menu object return this.menus[menuId]; }; // Add submenu item object this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles, position) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item for (var itemIndex in this.menus[menuId].items) { if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) { // Push new submenu item this.menus[menuId].items[itemIndex].items.push({ title: menuItemTitle, link: menuItemURL, uiRoute: menuItemUIRoute || ('/' + menuItemURL), isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].items[itemIndex].isPublic : isPublic), roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].items[itemIndex].roles : roles), position: position || 0, shouldRender: shouldRender }); } } // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeMenuItem = function(menuId, menuItemURL) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item to remove for (var itemIndex in this.menus[menuId].items) { if (this.menus[menuId].items[itemIndex].link === menuItemURL) { this.menus[menuId].items.splice(itemIndex, 1); } } // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeSubMenuItem = function(menuId, submenuItemURL) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item to remove for (var itemIndex in this.menus[menuId].items) { for (var subitemIndex in this.menus[menuId].items[itemIndex].items) { if (this.menus[menuId].items[itemIndex].items[subitemIndex].link === submenuItemURL) { this.menus[menuId].items[itemIndex].items.splice(subitemIndex, 1); } } } // Return the menu object return this.menus[menuId]; }; //Adding the topbar menu this.addMenu('topbar'); } ]); (function() { 'use strict'; angular .module('core') .factory('TableSettings', ['NgTableParams', function(NgTableParams) { var getData = function(Entity) { return function($defer, params) { Entity.get(params.url(), function(response) { params.total(response.total); $defer.resolve(response.results); }); }; }; var params = { page: 1, count: 5 }; var settings = { total: 0, counts: [5, 10, 15], filterDelay: 0, }; var getParams = function(Entity) { var tableParams = new NgTableParams(params, settings); tableParams.settings({getData: getData(Entity)}); return tableParams; }; var service = { getParams: getParams }; return service; }]); })(); 'use strict'; // Configuring the new module angular.module('events').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Events', 'events', 'dropdown', '/events(/create)?'); Menus.addSubMenuItem('topbar', 'events', 'List Events', 'events'); Menus.addSubMenuItem('topbar', 'events', 'New Event', 'events/create'); } ]); 'use strict'; //Setting up route angular.module('events').config(['$stateProvider', function($stateProvider) { // Events state routing $stateProvider. state('listEvents', { url: '/events', templateUrl: 'modules/events/views/list-events.client.view.html' }). state('createEvent', { url: '/events/create', templateUrl: 'modules/events/views/create-event.client.view.html' }). state('viewEvent', { url: '/events/:eventId', templateUrl: 'modules/events/views/view-event.client.view.html' }). state('editEvent', { url: '/events/:eventId/edit', templateUrl: 'modules/events/views/edit-event.client.view.html' }); } ]); 'use strict'; // Events controller angular.module('events').controller('EventsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Events', 'TableSettings', 'EventsForm', function($scope, $stateParams, $location, Authentication, Events, TableSettings, EventsForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Events); $scope.event = {}; $scope.setFormFields = function(disabled) { $scope.formFields = EventsForm.getFormFields(disabled); }; // Create new Event $scope.create = function() { var event = new Events($scope.event); // Redirect after save event.$save(function(response) { $location.path('events/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Event $scope.remove = function(event) { if ( event ) { event = Events.get({eventId:event._id}, function() { event.$remove(); $scope.tableParams.reload(); }); } else { $scope.event.$remove(function() { $location.path('events'); }); } }; // Update existing Event $scope.update = function() { var event = $scope.event; event.$update(function() { $location.path('events/' + event._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewEvent = function() { $scope.event = Events.get( {eventId: $stateParams.eventId} ); $scope.setFormFields(true); }; $scope.toEditEvent = function() { $scope.event = Events.get( {eventId: $stateParams.eventId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Events service used to communicate Events REST endpoints angular.module('events').factory('Events', ['$resource', function($resource) { return $resource('events/:eventId', { eventId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('events') .factory('EventsForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('files').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Files', 'files', 'dropdown', '/files(/create)?'); Menus.addSubMenuItem('topbar', 'files', 'List Files', 'files'); Menus.addSubMenuItem('topbar', 'files', 'New File', 'files/create'); } ]); 'use strict'; //Setting up route angular.module('files').config(['$stateProvider', function($stateProvider) { // Files state routing $stateProvider. state('listFiles', { url: '/files', templateUrl: 'modules/files/views/list-files.client.view.html' }). state('createFile', { url: '/files/create', templateUrl: 'modules/files/views/create-file.client.view.html' }). state('viewFile', { url: '/files/:fileId', templateUrl: 'modules/files/views/view-file.client.view.html' }). state('editFile', { url: '/files/:fileId/edit', templateUrl: 'modules/files/views/edit-file.client.view.html' }); } ]); 'use strict'; // Files controller angular.module('files').controller('FilesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Files', 'TableSettings', 'FilesForm', function($scope, $stateParams, $location, Authentication, Files, TableSettings, FilesForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Files); $scope.file = {}; $scope.setFormFields = function(disabled) { $scope.formFields = FilesForm.getFormFields(disabled); }; // Create new File $scope.create = function() { var file = new Files($scope.file); // Redirect after save file.$save(function(response) { $location.path('files/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing File $scope.remove = function(file) { if ( file ) { file = Files.get({fileId:file._id}, function() { file.$remove(); $scope.tableParams.reload(); }); } else { $scope.file.$remove(function() { $location.path('files'); }); } }; // Update existing File $scope.update = function() { var file = $scope.file; file.$update(function() { $location.path('files/' + file._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewFile = function() { $scope.file = Files.get( {fileId: $stateParams.fileId} ); $scope.setFormFields(true); }; $scope.toEditFile = function() { $scope.file = Files.get( {fileId: $stateParams.fileId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Files service used to communicate Files REST endpoints angular.module('files').factory('Files', ['$resource', function($resource) { return $resource('files/:fileId', { fileId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('files') .factory('FilesForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('projects').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Projects', 'projects', 'dropdown', '/projects(/create)?'); Menus.addSubMenuItem('topbar', 'projects', 'List Projects', 'projects'); Menus.addSubMenuItem('topbar', 'projects', 'New Project', 'projects/create'); } ]); 'use strict'; //Setting up route angular.module('projects').config(['$stateProvider', function($stateProvider) { // Projects state routing $stateProvider. state('listProjects', { url: '/projects', templateUrl: 'modules/projects/views/list-projects.client.view.html' }). state('createProject', { url: '/projects/create', templateUrl: 'modules/projects/views/create-project.client.view.html' }). state('viewProject', { url: '/projects/:projectId', templateUrl: 'modules/projects/views/view-project.client.view.html' }). state('editProject', { url: '/projects/:projectId/edit', templateUrl: 'modules/projects/views/edit-project.client.view.html' }); } ]); 'use strict'; // Projects controller angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Projects', 'TableSettings', 'ProjectsForm', function($scope, $stateParams, $location, Authentication, Projects, TableSettings, ProjectsForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Projects); $scope.project = {}; $scope.setFormFields = function(disabled) { $scope.formFields = ProjectsForm.getFormFields(disabled); }; // Create new Project $scope.create = function() { var project = new Projects($scope.project); // Redirect after save project.$save(function(response) { $location.path('projects/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Project $scope.remove = function(project) { if ( project ) { project = Projects.get({projectId:project._id}, function() { project.$remove(); $scope.tableParams.reload(); }); } else { $scope.project.$remove(function() { $location.path('projects'); }); } }; // Update existing Project $scope.update = function() { var project = $scope.project; project.$update(function() { $location.path('projects/' + project._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewProject = function() { $scope.project = Projects.get( {projectId: $stateParams.projectId} ); $scope.setFormFields(true); }; $scope.toEditProject = function() { $scope.project = Projects.get( {projectId: $stateParams.projectId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Projects service used to communicate Projects REST endpoints angular.module('projects').factory('Projects', ['$resource', function($resource) { return $resource('projects/:projectId', { projectId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('projects') .factory('ProjectsForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('tasks').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Tasks', 'tasks', 'dropdown', '/tasks(/create)?'); Menus.addSubMenuItem('topbar', 'tasks', 'List Tasks', 'tasks'); Menus.addSubMenuItem('topbar', 'tasks', 'New Task', 'tasks/create'); } ]); 'use strict'; //Setting up route angular.module('tasks').config(['$stateProvider', function($stateProvider) { // Tasks state routing $stateProvider. state('listTasks', { url: '/tasks', templateUrl: 'modules/tasks/views/list-tasks.client.view.html' }). state('createTask', { url: '/tasks/create', templateUrl: 'modules/tasks/views/create-task.client.view.html' }). state('viewTask', { url: '/tasks/:taskId', templateUrl: 'modules/tasks/views/view-task.client.view.html' }). state('editTask', { url: '/tasks/:taskId/edit', templateUrl: 'modules/tasks/views/edit-task.client.view.html' }); } ]); 'use strict'; // Tasks controller angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks', 'TableSettings', 'TasksForm', 'Users', 'Projects', 'Categories', function($scope, $stateParams, $location, Authentication, Tasks, TableSettings, TasksForm, Users, Projects, Categories ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Tasks); $scope.task = {}; $scope.userOptions = Users.query(); $scope.projectOptions = Projects.query(); $scope.categoryOptions = Categories.query(); $scope.setFormFields = function(disabled ) { $scope.formFields = TasksForm.getFormFields(disabled, $scope.userOptions, $scope.projectOptions, $scope.categoryOptions); }; // Create new Task $scope.create = function() { var task = new Tasks($scope.task); // Redirect after save task.$save(function(response) { $location.path('tasks/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Task $scope.remove = function(task) { if ( task ) { task = Tasks.get({taskId:task._id}, function() { task.$remove(); $scope.tableParams.reload(); }); } else { $scope.task.$remove(function() { $location.path('tasks'); }); } }; // Update existing Task $scope.update = function() { var task = $scope.task; task.$update(function() { $location.path('tasks/' + task._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewTask = function() { $scope.task = Tasks.get( {taskId: $stateParams.taskId} ); $scope.setFormFields(true); }; $scope.toEditTask = function() { $scope.task = Tasks.get( {taskId: $stateParams.taskId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Tasks service used to communicate Tasks REST endpoints angular.module('tasks').factory('Tasks', ['$resource', function($resource) { return $resource('tasks/:taskId', { taskId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('tasks') .factory('TasksForm', factory); function factory() { var getFormFields = function(disabled, userOptions, projectOptions, categoryOptions) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } }, { key: 'description', type: 'textarea', templateOptions: { label: 'Description:', disabled: disabled } }, { key: 'assignee', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Aassignee', //multiple: true, labelProp: 'displayName', valueProp: '_id', options: userOptions, disabled: disabled } }, { key: 'watcher', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Watcher', //multiple: true, labelProp: 'displayName', valueProp: '_id', options: userOptions, disabled: disabled } }, { key: 'project', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Project', //multiple: true, labelProp: 'name', valueProp: '_id', options: projectOptions, disabled: disabled } }, { key: 'category', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Category', //multiple: true, labelProp: 'name', valueProp: '_id', options: categoryOptions, disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Config HTTP Error Handling angular.module('users').config(['$httpProvider', function($httpProvider) { // Set the httpProvider "not authorized" interceptor $httpProvider.interceptors.push(['$q', '$location', 'Authentication', function($q, $location, Authentication) { return { responseError: function(rejection) { switch (rejection.status) { case 401: // Deauthenticate the global user Authentication.user = null; // Redirect to signin page $location.path('signin'); break; case 403: // Add unauthorized behaviour break; } return $q.reject(rejection); } }; } ]); } ]); 'use strict'; // Setting up route angular.module('users').config(['$stateProvider', function($stateProvider) { // Users state routing $stateProvider. state('profile', { url: '/settings/profile', templateUrl: 'modules/users/views/settings/edit-profile.client.view.html' }). state('password', { url: '/settings/password', templateUrl: 'modules/users/views/settings/change-password.client.view.html' }). state('accounts', { url: '/settings/accounts', templateUrl: 'modules/users/views/settings/social-accounts.client.view.html' }). state('signup', { url: '/signup', templateUrl: 'modules/users/views/authentication/signup.client.view.html' }). state('signin', { url: '/signin', templateUrl: 'modules/users/views/authentication/signin.client.view.html' }). state('forgot', { url: '/password/forgot', templateUrl: 'modules/users/views/password/forgot-password.client.view.html' }). state('reset-invalid', { url: '/password/reset/invalid', templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html' }). state('reset-success', { url: '/password/reset/success', templateUrl: 'modules/users/views/password/reset-password-success.client.view.html' }). state('reset', { url: '/password/reset/:token', templateUrl: 'modules/users/views/password/reset-password.client.view.html' }); } ]); 'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$http', '$location', 'Authentication', function($scope, $stateParams, $http, $location, Authentication) { $scope.authentication = Authentication; //If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); // Submit forgotten password account id $scope.askForPasswordReset = function() { $scope.success = $scope.error = null; $http.post('/auth/forgot', $scope.credentials).success(function(response) { // Show user success message and clear form $scope.credentials = null; $scope.success = response.message; }).error(function(response) { // Show user error message and clear form $scope.credentials = null; $scope.error = response.message; }); }; // Change user password $scope.resetUserPassword = function() { $scope.success = $scope.error = null; $http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) { // If successful show success message and clear form $scope.passwordDetails = null; // Attach user profile Authentication.user = response; // And redirect to the index page $location.path('/password/reset/success'); }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; angular.module('users').controller('SettingsController', ['$scope', '$http', '$location', 'Users', 'Authentication', function($scope, $http, $location, Users, Authentication) { $scope.user = Authentication.user; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); // Check if there are additional accounts $scope.hasConnectedAdditionalSocialAccounts = function(provider) { for (var i in $scope.user.additionalProvidersData) { return true; } return false; }; // Check if provider is already in use with current user $scope.isConnectedSocialAccount = function(provider) { return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]); }; // Remove a user social account $scope.removeUserSocialAccount = function(provider) { $scope.success = $scope.error = null; $http.delete('/users/accounts', { params: { provider: provider } }).success(function(response) { // If successful show success message and clear form $scope.success = true; $scope.user = Authentication.user = response; }).error(function(response) { $scope.error = response.message; }); }; // Update a user profile $scope.updateUserProfile = function(isValid) { if (isValid) { $scope.success = $scope.error = null; var user = new Users($scope.user); user.$update(function(response) { $scope.success = true; Authentication.user = response; }, function(response) { $scope.error = response.data.message; }); } else { $scope.submitted = true; } }; // Change user password $scope.changeUserPassword = function() { $scope.success = $scope.error = null; $http.post('/users/password', $scope.passwordDetails).success(function(response) { // If successful show success message and clear form $scope.success = true; $scope.passwordDetails = null; }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; // Authentication service for user variables angular.module('users').factory('Authentication', [ function() { var _this = this; _this._data = { user: window.user }; return _this._data; } ]); 'use strict'; // Users service used for communicating with the users REST endpoint angular.module('users').factory('Users', ['$resource', function($resource) { return $resource('users', {}, { update: { method: 'PUT' } }); } ]);
1.210938
1
testServer/index.js
kgroat/BuildingBlox
2
4927
/*jshint -W024*/ /*jslint node: true*/ 'use strict'; var express = require('express'); var http = require('http'); var port = 3000; var app = express(); app.use(require('express-markdown')({ directory: __dirname + '/..' })); app.use('/', express.static(__dirname + '/pages')); app.use('/dist', express.static(__dirname + '/../dist')); app.use('/node_modules', express.static(__dirname + '/../node_modules')); http.createServer(app).listen(port, function () { console.log('Express server listening on port ' + port); });
1.234375
1
ShadowEditor.Web/src/loader/lol/HiddenBones.js
qingqibing/ShadowEditor
5
4935
/** * @author lolking / http://www.lolking.net/models * @author tengge / https://github.com/tengge1 */ var HiddenBones = { 12: { 9: { recall: {}, all: { recall_chair: true } }, 10: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 11: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 12: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 13: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 14: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 15: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 16: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 17: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 18: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} } }, 21: { 9: { all: { orange: true }, recall: { l_weapon: true, r_weapon: true } }, 10: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 11: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 12: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 13: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 14: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } } }, 22: { 8: { all: { c_drone_base: true }, joke: {}, dance: {} } }, 36: { 9: { all: { recall_chair: true }, recall: {} } }, 41: { 0: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 1: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 2: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 3: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 4: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 5: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 6: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 7: { all: { orange1: true, orange2: true, orange3: true }, joke: {} } }, 44: { 4: { all: { jacket: true }, dance: { jacket: true, weapon: true }, recall: { weapon: true } } }, 55: { 7: { recall: {}, all: { xmas_pole_skin07: true } } }, 61: { 7: { recall: {}, all: { planet1: true, planet2: true, planet3: true, planet4: true, planet5: true, planet6: true } } }, 69: { 4: { all: { l_fan: true, r_fan: true }, recall: {} } }, 80: { 8: { all: { oven: true }, recall: {} } }, 83: { 0: { all: {}, idle2: { weapon: true } }, 1: { all: {}, idle2: { weapon: true } }, 2: { all: {}, idle2: { weapon: true } } }, 103: { 7: { recall: {}, all: { arcade: true } } }, 114: { 5: { all: { weapon_krab: true, root_krab: true }, recall: {} } }, 115: { 4: { all: { sled: true }, satcheljump: { bomb: true, bomb_b: true } } }, 119: { 4: { all: { chair_root: true, sun_reflector_root: true }, recall: {} } }, 136: { 0: { all: { shades_sunglass: true }, joke: {} }, 1: { all: { shades_sunglass: true }, joke: {} } }, 143: { 4: { attack1: { r_wing: true, l_wing: true }, attack2: { r_wing: true, l_wing: true }, dance: { r_wing: true, l_wing: true }, idle1: { r_wing: true, l_wing: true }, idle3: { r_wing: true, l_wing: true }, idle4: { r_wing: true, l_wing: true }, laugh: { r_wing: true, l_wing: true }, run: { r_wing: true, l_wing: true }, spell2: { r_wing: true, l_wing: true }, all: {} } }, 157: { 4: { all: { flute: true }, dance: {} }, 5: { all: { flute: true }, dance: {} }, 6: { all: { flute: true }, dance: {} }, 7: { all: { flute: true }, dance: {} }, 8: { all: { flute: true }, dance: {} } }, 201: { 3: { all: { poro: true } } }, 222: { 4: { all: { rocket_launcher: true }, r_attack1: {}, r_attack2: {}, r_idle1: {}, r_idle_in: {}, r_run: {}, r_run_fast: {}, r_run_haste: {}, r_spell2: {}, r_spell3: {}, r_spell3_run: {}, r_spell4: {}, respawn_trans_rlauncher: {}, rlauncher_spell3: {}, spell1a: {} } }, 238: { 10: { all: { chair_skin10: true, step1_skin10: true, step2_skin10: true }, recall: {} } }, 245: { 0: { deathrespawn: {}, all: { book_pen: true } }, 1: { deathrespawn: {}, all: { book_pen: true } }, 2: { deathrespawn: {}, all: { book_pen: true } }, 3: { deathrespawn: {}, all: { book_pen: true } }, 4: { deathrespawn: {}, all: { book_pen: true } }, 5: { deathrespawn: {}, all: { book_pen: true } }, 6: { deathrespawn: {}, all: { book_pen: true } }, 7: { deathrespawn: {}, all: { book_pen: true } }, 8: { deathrespawn: {}, all: { book_pen: true } }, 9: { deathrespawn: {}, all: { book_pen: true } }, 10: { deathrespawn: {}, all: { book_pen: true } } }, 254: { 0: { all: { teacup: true }, taunt2: {} }, 1: { all: { teacup: true }, taunt2: {} }, 3: { all: { teacup: true }, taunt2: {} }, 4: { all: { teacup: true }, taunt2: {} } }, 412: { 1: { all: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true, tire: true }, recall: { tire: true }, undersea_recall_loop: { tire: true }, undersea_recall_loop2: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true }, undersea_recall_windup: { tire: true }, undersea_recall_windup2: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true } }, 5: { all: { mini_root: true }, joke: {} } }, 420: { 0: { all: { c_tentacle1: true } }, 1: { all: { c_tentacle1: true } } }, 429: { 3: { death: { altar_spear: true, buffbone_cstm_back_spear1: true, buffbone_cstm_back_spear2: true, buffbone_cstm_back_spear3: true } } }, 432: { 0: { all: { follower_root: true }, dance: {} }, 2: { all: { follower_root: true }, dance: {} }, 3: { all: { follower_root: true }, dance: {} }, 4: { all: { follower_root: true }, dance: {} } }, gnarbig: { 0: { all: { rock: true }, spell1: {}, laugh: {} }, 1: { all: { rock: true }, spell1: {}, laugh: {} }, 2: { all: { rock: true, cane_bot: true, cane_top: true }, spell1: { cane_bot: true, cane_top: true }, laugh: { cane_bot: true, cane_top: true }, recall: { rock: true } }, 3: { all: { rock: true }, spell1: {}, laugh: {} }, 4: { all: { rock: true }, spell1: {}, laugh: {} }, 5: { all: { rock: true }, spell1: {}, laugh: {} }, 6: { all: { rock: true }, spell1: {}, laugh: {} }, 7: { all: { rock: true }, spell1: {}, laugh: {} }, 8: { all: { rock: true }, spell1: {}, laugh: {} }, 9: { all: { rock: true }, spell1: {}, laugh: {} }, 10: { all: { rock: true }, spell1: {}, laugh: {} }, 11: { all: { rock: true }, spell1: {}, laugh: {} }, 12: { all: { rock: true }, spell1: {}, laugh: {} } } }; export default HiddenBones;
0.601563
1
src/core_modules/capture-core/components/ColumnSelectorDialog/DragDropSort/DragDropListItem.component.js
hispindia/dhis2-capture-app
0
4943
// @flow import React, { Component } from 'react'; import { DragSource, DropTarget } from 'react-dnd'; import TableCell from '@material-ui/core/TableCell'; import Checkbox from '@material-ui/core/Checkbox'; import ReorderIcon from '@material-ui/icons/Reorder'; type Props = { id: string, visible: boolean, text: string, handleToggle: (id: string) => void, isDragging: () => void, connectDragSource: (any) => void, connectDropTarget: (any) => void, }; const style = { cursor: 'move', outline: 'none', }; const ItemTypes = { LISTITEM: 'listItem', }; const cardSource = { beginDrag(props) { return { id: props.id, index: props.index, }; }, }; const cardTarget = { hover(props, monitor) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; // Don't replace items with themselves. if (dragIndex === hoverIndex) { return; } // Time to actually perform the action. props.moveListItem(dragIndex, hoverIndex); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; }, }; class DragDropListItem extends Component<Props> { render() { const { text, isDragging, connectDragSource, connectDropTarget } = this.props; const opacity = isDragging ? 0 : 1; // $FlowFixMe[incompatible-extend] automated comment return connectDropTarget(connectDragSource( <tr key={this.props.id} tabIndex={-1} style={{ ...style, opacity }}> <TableCell component="th" scope="row"> <Checkbox color={'primary'} checked={this.props.visible} tabIndex={-1} disableRipple onClick={this.props.handleToggle(this.props.id)} /> {text} </TableCell> <TableCell> <ReorderIcon style={{ float: 'right' }} /> </TableCell> </tr>, )); } } export default DragSource(ItemTypes.LISTITEM, cardSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }))(DropTarget(ItemTypes.LISTITEM, cardTarget, connect => ({ connectDropTarget: connect.dropTarget() }))(DragDropListItem));
1.804688
2
src/components/BucketList.js
KeithMurph/bucketList
0
4951
import React, { useState } from 'react'; import BucketForm from './BucketForm'; import Bucket from './Bucket'; function BucketList() { const [bucket, setBucket] = useState([]); // Function to add a bucket list item const addBucketItem = (item) => { console.log( '🚀 ~ file: BucketList.js ~ line 10 ~ addBucketItem ~ item', item ); // Check to see if the item text is empty if (!item.text) { return; } // Add the new bucket list item to the existing array of objects const newBucket = [item, ...bucket]; console.log(`old bucket: `, bucket); console.log(`newBucket: `, newBucket); // Call setBucket to update state with our new set of bucket list items setBucket(newBucket); }; // Function to mark bucket list item as complete const completeBucketItem = (id) => { // If the ID passed to this function matches the ID of the item that was clicked, mark it as complete let updatedBucket = bucket.map((item) => { if (item.id === id) { item.isComplete = !item.isComplete; } return item; }); console.log(updatedBucket); setBucket(updatedBucket); }; // Function to remove bucket list item and update state const removeBucketItem = (id) => { const updatedBucket = [...bucket].filter((item) => item.id !== id); setBucket(updatedBucket); }; // Function to edit the bucket list item const editBucketItem = (itemId, newValue) => { // Make sure that the value isn't empty if (!newValue.text) { return; } // We use the "prev" argument provided with the useState hook to map through our list of items // We then check to see if the item ID matches the if of the item that was clicked and if so we set it to a new value setBucket((prev) => prev.map((item) => (item.id === itemId ? newValue : item)) ); }; return ( <div> <h1>What is on your bucket list?</h1> <BucketForm onSubmit={addBucketItem} /> <Bucket bucket={bucket} completeBucketItem={completeBucketItem} removeBucketItem={removeBucketItem} editBucketItem={editBucketItem} ></Bucket> </div> ); } export default BucketList;
2.390625
2
src/components/user-form/user-form.component.js
thiagodesouza/github-users
1
4959
import { app } from '../../app.module'; import template from './user-form.component.html'; import './user-form.component.scss'; class UserFormController { static get $inject() { return ['$scope', '$element', '$http', '$ngRedux']; } constructor($scope, $element, $http, $ngRedux) { Object.assign(this, { $: $element[0], $scope, $http, $ngRedux, }); this.__store = $ngRedux.connect(store => Object({ users: store.users.data, }), )(this); this.open = false; this.user = null; this.userIsValid = false; } $onInit() { Object.assign(this.$, { toggle: this.toggle.bind(this), }); } $onDestroy() { this.__store(); } toggle() { this.open = !this.open; if (this.open) { this.$.setAttribute('open', ''); } else { this.$.removeAttribute('open'); } } clear() { this.user = null; this.userIsValid = false; } cancel() { if (this.open) { this.toggle(); } this.clear(); } save() { this.callback({ data: this.user }); this.cancel(); } _isValidUser() { return !!this.user && !this.users.some(item => item.login === this.user.login); } handleSearchButton() { const searchInput = this.$.querySelector('#user-form-content-search-input'); const searchButton = this.$.querySelector('#user-form-content-search-button'); if (searchInput.value) { searchButton.setAttribute('loading', ''); this.$http({ method: 'GET', url: `https://api.github.com/users/${searchInput.value}`, }).then( response => { this.user = response.data; this.userIsValid = !!this.user && !this.users.some(item => item.login === this.user.login); this.$.querySelector('#user-form-content-search-input').value = null; searchButton.removeAttribute('loading', ''); }, err => { // eslint-disable-next-line no-console console.log(err); searchButton.removeAttribute('loading', ''); }, ); } } } class UserForm { constructor() { this.template = template; this.bindings = { callback: '&', }; this.controller = UserFormController; } } app.component('userForm', new UserForm());
1.492188
1
src/api/view/PackResultView.js
SunilDhaker/freight-packer
25
4967
import Utils from '../utils/cik/Utils'; import CargoListView from './CargoListView'; import CargoView from './CargoView'; import Pool from '../utils/cik/Pool'; import PackedCargoBoxView from './PackedCargoBoxView'; import PackingSpaceView from './PackingSpaceView'; import Tween from '../utils/cik/Tween'; import Packer from '../packer/Packer'; import BoxEntry from '../components/box/BoxEntry'; import Signaler from '../utils/cik/Signaler'; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * @typedef {Object} PackResultViewParams * @property {import('../UX').default} ux * @property {Number} animationDuration */ /** @type {PackResultViewParams} */ const defaultParams = { animationDuration: 1 }; /** * @param {CargoView} cargoView * @returns {PackedCargoBoxView} */ function poolNewFN(cargoView){ //console.log('pool new', cargoView); let packedCargoView = new PackedCargoBoxView(cargoView.entry); packedCargoView.Extend(cargoView); return packedCargoView; } /** * @param {PackedCargoBoxView} object * @param {CargoView} cargoView * @returns {PackedCargoBoxView} */ function poolResetFN(object, cargoView){ //console.log('pool reset', cargoView); object.Extend(cargoView); return object; } function getOrientationAngles(orientation){ switch(orientation){ case 'xyz': return [0, 0, 0]; case 'xzy': return [90, 0, 0]; case 'yxz': return [0, 0, 90]; case 'yzx': return [90, 0, 90]; case 'zxy': return [90, -90, 0]; case 'zyx': return [0, -90, 0]; } } /** * @param {string} orientation */ function getOrientationEuler(orientation){ const rad = Math.PI / 180.0; let a = getOrientationAngles(orientation); return new THREE.Euler(a[0] * rad, a[1] * rad, a[2] * rad); } var tempBox = new THREE.Box3(); var tempVec = new THREE.Vector3(); const signals = { packVizStart: 'packVizStart', packVizEnd: 'packVizEnd', cargoVizCreate: 'cargoVizCreate', cargoVizPack: 'cargoVizPack', cargoVizUnpack: 'cargoVizUnpack' }; class PackResultView extends Signaler{ /** * @param {CargoListView} cargoListView * @param {PackingSpaceView} packingSpaceView * @param {PackResultViewParams} params */ constructor(cargoListView, packingSpaceView, params){ super(); this.cargoListView = cargoListView; this.packingSpaceView = packingSpaceView; this.params = Utils.AssignUndefined(params, defaultParams); /** @type {Array<CargoView} */ this.cargoViews = []; this.view = new THREE.Object3D(); this.pool = new Pool(poolNewFN, poolResetFN); /** @type {Array<Tween>} */ this.animatingViews = []; if(typeof window.Pizzicato !== 'undefined'){ let musipack = new (require('./components/Musipack').default)(this); } } /** * @param {Packer.PackingResult} packingResult */ async DisplayPackingResult(packingResult){ this.Dispatch(signals.packVizStart, packingResult); if(packingResult.packed.length < 1) return; let scope = this; let units = this.params.ux.params.units; let containingVolume = packingResult.packed[0].containingVolume; let matrix = this.packingSpaceView.GetMatrix(containingVolume); let offset = new THREE.Vector3(); let orientation = new THREE.Quaternion(); let scale = new THREE.Vector3(); matrix.decompose(offset, orientation, scale); /** @type {Map<CargoView, Number>} */ let packedQuantities = new Map(); let animatingViews = this.animatingViews; let view = this.view; //let onTweenComplete = this.OnCargoFirstTweenComplete.bind(this); let zEntry = containingVolume.dimensions.length; let numPackedItems = packingResult.packed.length; let delayPerItem = this.params.animationDuration * 1000 / numPackedItems; for(let i = 0; i < numPackedItems; i++){ let item = packingResult.packed[i]; let cargoViewTemplate = this.cargoListView.GetTemplate(item.entry); let packedQuantity = packedQuantities.get(cargoViewTemplate); let totalQuantity = cargoViewTemplate.entry.quantity; if(packedQuantity === undefined) packedQuantities.set(cargoViewTemplate, packedQuantity = 0); packedQuantities.set(cargoViewTemplate, ++packedQuantity); let textColor = packedQuantity === totalQuantity ? 'rgb(255, 255, 255)' : 'rgb(255, 0, 0)'; this.cargoListView.UpdateLabel(cargoViewTemplate, packedQuantity + '/' + totalQuantity, textColor); let packedCargoView = this.pool.Request(cargoViewTemplate); this.cargoViews.push(packedCargoView); let rotation = getOrientationEuler(item.orientation); packedCargoView.SetRotationAngles(rotation.x, rotation.y, rotation.z); let x = item.position.x + offset.x, y = item.position.y + offset.y, z = item.position.z + offset.z; let posTweenCombo = Tween.Combo.RequestN(Tween.functions.ease.easeOutQuad, .5, x, 0, y, 0, zEntry, z - zEntry ); function onTweenComplete(tween){ scope.Dispatch(signals.cargoVizPack, item); scope.OnCargoFirstTweenComplete(tween); } posTweenCombo.extraData = packedCargoView; posTweenCombo.Hook(packedCargoView.position, 'x', 'y', 'z'); posTweenCombo.onComplete = onTweenComplete; posTweenCombo.Update(0); animatingViews.push(posTweenCombo); view.add(packedCargoView.view); await sleep(delayPerItem); } await sleep(500); let unpackedOffset = 6 * units; for(let i = 0, numUnpackedItems = packingResult.unpacked.length; i < numUnpackedItems; i++){ let item = packingResult.unpacked[i]; let cargoViewTemplate = this.cargoListView.GetTemplate(item.entry); let totalQuantity = cargoViewTemplate.entry.quantity; if(packedQuantities.has(cargoViewTemplate) === false){ let textColor = false ? 'rgb(255, 255, 255)' : 'rgb(255, 0, 0)'; this.cargoListView.UpdateLabel(cargoViewTemplate, '0/' + totalQuantity, textColor); } if(i === 0) unpackedOffset += item.entry.dimensions.width / 2; for(let j = 0; j < item.unpackedQuantity; j++){ let packedCargoView = this.pool.Request(cargoViewTemplate); this.cargoViews.push(packedCargoView); let x = containingVolume.dimensions.width * 1.5 + unpackedOffset + offset.x, y = item.entry.dimensions.height / 2 + offset.y, z = item.entry.dimensions.length * j + offset.z; let posTweenCombo = Tween.Combo.RequestN(Tween.functions.ease.easeOutQuad, .5, x, 0, y, 0, zEntry, z - zEntry ); function onTweenComplete(tween){ scope.Dispatch(signals.cargoVizUnpack, item); scope.OnCargoFirstTweenComplete(tween); } posTweenCombo.extraData = packedCargoView; posTweenCombo.Hook(packedCargoView.position, 'x', 'y', 'z'); posTweenCombo.onComplete = onTweenComplete; posTweenCombo.Update(0); animatingViews.push(posTweenCombo); view.add(packedCargoView.view); await sleep(delayPerItem * .5); } unpackedOffset += item.entry.dimensions.width + 6 * units; } } /** @param {Tween|Tween.Combo} tween */ OnCargoFirstTweenComplete(tween){ let packedCargoView = tween.extraData; this.OnTweenComplete(tween); let scaleTweenCombo = Tween.Combo.RequestN(Tween.functions.special.pingPong, .1, 1, .1, 1, .1, 1, .1 ); scaleTweenCombo.extraData = packedCargoView; scaleTweenCombo.Hook(packedCargoView.view.scale, 'x', 'y', 'z'); scaleTweenCombo.onComplete = this.OnTweenComplete.bind(this);; scaleTweenCombo.Update(0); this.animatingViews.push(scaleTweenCombo); } /** @param {Tween|Tween.Combo} tween */ OnTweenComplete(tween){ let packedCargoView = tween.extraData; packedCargoView.view.scale.set(1, 1, 1); let index = this.animatingViews.indexOf(tween); if(index != -1){ this.animatingViews.splice(index, 1); } tween.Unhook(); tween.Return(); } /** @param {string} entryUID */ SelectEntry(entryUID){ if(!entryUID){ this.DisableHighlights(); } else{ this.Highlight(entryUID); } } DisableHighlights(){ for(let i = 0, numCargoViews = this.cargoViews.length; i < numCargoViews; i++){ this.cargoViews[i].focus = 1; } } /** @param {string} entryUID */ Highlight(entryUID){ for(let i = 0, numCargoViews = this.cargoViews.length; i < numCargoViews; i++){ let cargoView = this.cargoViews[i]; let cvEntry = cargoView.entry; if(cvEntry.uid === entryUID){ cargoView.focus = 1.75; } else{ cargoView.focus = .25; } } } /** @param {Number} value */ Slice(value){ if(value >= 1){ this.view.children.forEach(child => { child.visible = true; }); return; } let minY = Number.MAX_SAFE_INTEGER, maxY = Number.MIN_SAFE_INTEGER; this.view.children.forEach(child => { tempBox.setFromObject(child); tempBox.getSize(tempVec); let halfHeight = tempVec.y / 2; tempBox.getCenter(tempVec); let low = tempVec.y - halfHeight; let high = tempVec.y + halfHeight; if(low < minY) minY = low; if(high > maxY) maxY = high; }); let y = minY + value * (maxY - minY); //console.log('slice ' + y.toFixed(2) + ' between ' + minY.toFixed(2) + ' and ' + maxY.toFixed(2)); this.view.children.forEach(child => { tempBox.setFromObject(child); tempBox.getSize(tempVec); let halfHeight = tempVec.y / 2; tempBox.getCenter(tempVec); let low = tempVec.y - halfHeight; if(low < y) child.visible = true; else child.visible = false; }); } Clear(){ this.animatingViews.length = 0; this.cargoViews.length = 0; while(this.view.children.length > 0) this.view.remove(this.view.children[this.view.children.length - 1]); } Update(){ this.animatingViews.forEach(animatingView => { animatingView.Update(); }); } static get signals(){ return signals; } } export default PackResultView;
1.5625
2
dist/es2015/ExePlatformModule.js
yefusheng/ng-platfroms
0
4975
import { NgModule } from '@angular/core'; import { ExePlatformService } from "./ExePlatform.service"; import { AuthService } from "./Auth.service"; //import {ExePlatformConponentModule} from "./dynamic-component/ExePlatformConponentModule"; import { WindowsPlatformModule } from "./windows/WindowsPlatformModule"; //导入对应的平台模块 // let platformModule=new PlatformStragety().getStragety(); var ExePlatformModule = (function () { function ExePlatformModule() { } return ExePlatformModule; }()); export { ExePlatformModule }; ExePlatformModule.decorators = [ { type: NgModule, args: [{ imports: [ WindowsPlatformModule, ], // exports: [ExePlatformConponentModule], providers: [ AuthService, ExePlatformService, ] },] }, ]; /** @nocollapse */ ExePlatformModule.ctorParameters = function () { return []; };
0.773438
1
agtms-vue/src/store/store.js
Saisimon/AGTMS
2
4983
import Vue from 'vue' import Vuex from 'vuex' import base from './modules/base' import list from './modules/list' import edit from './modules/edit' import template from './modules/template' import selection from './modules/selection' Vue.use(Vuex) export default new Vuex.Store({ modules: { base, list, edit, template, selection } })
0.753906
1
lib/websocket-relay.js
piznel/ffmpeg-jsmpeg
0
4991
// Use the websocket-relay to serve a raw MPEG-TS over WebSockets. You can use // ffmpeg to feed the relay. ffmpeg -> websocket-relay -> browser // Example: // node websocket-relay 8081 8082 // ffmpeg -i <some input> -f mpegts https://localhost:8081/ const fs = require('fs'); const https = require('https'); const pem = require('https-pem') const WebSocket = require('ws'); const ffmpeg = require('./ffmpeg.js'); const shared = require('./shared'); const config = require('./config.js'); var isWebSocketHandshake = require('is-websocket-handshake') module.exports = function (inputPort, outputPort) { const STREAM_PORT = inputPort || 8081; const WEBSOCKET_PORT = outputPort || 8082; const RECORD_STREAM = false; var httpsserver = https.createServer(pem); httpsserver.on('upgrade', function (req, socket, head) { if (isWebSocketHandshake(req)) { console.log('FFmpeg-jsRTSP : received proper WebSocket handshake') } }) // Websocket Server var socketServer = new WebSocket.Server({ server: httpsserver, perMessageDeflate: false }); socketServer.connectionCount = 0; socketServer.on('connection', function (socket, upgradeReq) { if (socketServer.connectionCount === 0) ffmpeg(); socketServer.connectionCount++; console.log( 'FFmpeg-jsRTSP : New WebSocket Connection: ', (upgradeReq || socket.upgradeReq).socket.remoteAddress, (upgradeReq || socket.upgradeReq).headers['user-agent'], '(' + socketServer.connectionCount + ' total)' ); socket.on('close', function (code, message) { socketServer.connectionCount--; if (socketServer.connectionCount === 0) shared.ffmpeg.kill() console.log( 'FFmpeg-jsRTSP : Disconnected WebSocket (' + socketServer.connectionCount + ' total)' ); }); socket.on('message', function (message) { let msg = JSON.parse(message) let change = false; if (msg.hasOwnProperty('width')) { if (config.resolution !== msg.width + 'x?') { config.resolution = msg.width + 'x?' change = true } } if (msg.hasOwnProperty('url')) { if (config.uri !== msg.url) { config.uri = msg.url change = true } } if (msg.hasOwnProperty('quality')) { if (config.quality !== msg.quality) { config.quality = msg.quality change = true } } if (change) { if (shared.ffmpeg) shared.ffmpeg.kill() ffmpeg() } }) }); socketServer.broadcast = function (data) { socketServer.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { try { client.send(data); } catch (err) { console.log(err) } } }); }; httpsserver.listen(WEBSOCKET_PORT); // HTTPS Server to accept incomming MPEG-TS Stream from ffmpeg var streamServer = https.createServer(pem, function (request, response) { response.connection.setTimeout(0); console.log( 'FFmpeg-jsRTSP : Stream Connected: ' + request.socket.remoteAddress + ':' + request.socket.remotePort ); request.on('data', function (data) { socketServer.broadcast(data); if (request.socket.recording) { request.socket.recording.write(data); } }); request.on('end', function () { console.log('close'); if (request.socket.recording) { request.socket.recording.close(); } }); // Record the stream to a local file? if (RECORD_STREAM) { var path = 'recordings/' + Date.now() + '.ts'; request.socket.recording = fs.createWriteStream(path); } }).listen(STREAM_PORT); console.log('FFmpeg-jsRTSP : Listening for incomming MPEG-TS Stream on https://127.0.0.1:' + STREAM_PORT); console.log('FFmpeg-jsRTSP : Awaiting WebSocket connections on ' + WEBSOCKET_PORT + ' port.'); }
1.484375
1
src/generation/index.js
luqaska/static-url-shortener
7
4999
const fs = require('fs'); const path = require('path'); const deleteDir = require('../utilities/deleteDir'); const redirect = require('./redirect'); const notFound = require('./not-found'); /** * Perform redirect generation for a given {@link RedirectTree} * @param {string} out The base full output directory path for the redirect tree * @param {RedirectTree} tree The redirect tree structure to generate redirects for * @param {TemplateFunction} template The redirect HTML generation template function */ const handleTree = (out, tree, template) => { // If no data and no subpaths, stop if (!Object.prototype.hasOwnProperty.call(tree, 'data') && !Object.prototype.hasOwnProperty.call(tree, 'subpaths')) return; // We have either data or subpaths, so we need to create the directory if (!fs.existsSync(out)) fs.mkdirSync(out); // If we have data, output a redirect file if (Object.prototype.hasOwnProperty.call(tree, 'data')) redirect.output(template, tree.data, out); // If we have subpaths, recurse over each subpath if (Object.prototype.hasOwnProperty.call(tree, 'subpaths')) for (const subpath in tree.subpaths) { if (!Object.prototype.hasOwnProperty.call(tree.subpaths, subpath)) continue; handleTree(path.join(out, subpath), tree.subpaths[subpath], template); } }; /** * Perform redirect generation for a given {@link RedirectTree} * @param {string} out The full output directory path for the redirect tree (will be cleaned) * @param {RedirectTree} tree The redirect tree to generate redirects for * @return {Promise<void>} */ module.exports = async (out, tree) => { // Clean the output directory deleteDir(out); // Get the doT template const template = redirect.load(); // Start generating recursively handleTree(out, tree, template); // Generate the final 404.html file await notFound(out, tree); };
1.5625
2
assets/js/script.js
ahnjaeyung/Day_Planner
0
5007
var savedPlans = Object.keys(localStorage); var saveBtn = $(".saveBtn"); var timer = true var currentHour = moment().hours(); var time = setInterval(function () { if (timer === true) { $("#currentDay").text(moment().format("LLL")); } }, 1000) //end of setInterval function rowColor() { $(".time-block").each(function () { var hourId = $(this).attr("id"); // console.log(hourAttr); var hourRow = hourId.substring(5, hourId.length); //takes just the number // console.log(hourRow); intHourRow = parseInt(hourRow) // console.log(intHourRow); intCurrentHour = parseInt(currentHour) if (parseInt(intHourRow) < currentHour) { $(this).addClass("past"); } else if (parseInt(intHourRow) === currentHour) { $(this).addClass("present"); } else if (parseInt(intHourRow) > currentHour) { $(this).addClass("future"); } } ) }; //end of rowColor function definition rowColor(); saveBtn.on("click", function () { var taskInput = $(this).siblings(".description").val(); var timeSlot = $(this).parent().attr("id"); localStorage.setItem(timeSlot, taskInput); }); // end of saveBtn click event for (i = 0; i < savedPlans.length; i++) { var taskInput = localStorage.getItem(savedPlans[i]); var savedText = $("#" + savedPlans[i]).find("textarea") savedText.val(taskInput); } // end of for loop
1.9375
2
Samples/MasterPortal/js/timeago/locales/jquery.timeago.sr-Latn.js
hhnguyen/xRM-Portals-Community-Edition
117
5015
// English (Template) jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "pre", suffixFromNow: "od sada", seconds: "manje od minuta", minute: "oko minut", minutes: "%d minuta", hour: "oko sat vremena", hours: "oko %d sata/i", day: "dan", days: "%d dana", month: "oko mesec dana", months: "%d meseca/i", year: "oko godinu dana", years: "%d godine/a", wordSeparator: " ", numbers: [] };
0.490234
0
taotao-manager/taotao-manager-web/src/main/webapp/WEB-INF/js/jquery-easyui-1.4.1/plugins/jquery.combo.js
littlehorse1019/taotao-shop
1
5023
/** * jQuery EasyUI 1.4.1 * * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved. * * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt * To use it on other terms please contact us at <EMAIL> * */ (function ($) { $(function () { $(document).unbind(".combo").bind("mousedown.combo mousewheel.combo", function (e) { var p = $(e.target).closest("span.combo,div.combo-p"); if (p.length) { _1(p); return; } $("body>div.combo-p>div.combo-panel:visible").panel("close"); }); }); function _2(_3) { var _4 = $.data(_3, "combo"); var _5 = _4.options; if (!_4.panel) { _4.panel = $("<div class=\"combo-panel\"></div>").appendTo("body"); _4.panel.panel({ minWidth: _5.panelMinWidth, maxWidth: _5.panelMaxWidth, minHeight: _5.panelMinHeight, maxHeight: _5.panelMaxHeight, doSize: false, closed: true, cls: "combo-p", style: {position: "absolute", zIndex: 10}, onOpen: function () { var _6 = $(this).panel("options").comboTarget; var _7 = $.data(_6, "combo"); if (_7) { _7.options.onShowPanel.call(_6); } }, onBeforeClose: function () { _1(this); }, onClose: function () { var _8 = $(this).panel("options").comboTarget; var _9 = $.data(_8, "combo"); if (_9) { _9.options.onHidePanel.call(_8); } } }); } var _a = $.extend(true, [], _5.icons); if (_5.hasDownArrow) { _a.push({ iconCls: "combo-arrow", handler: function (e) { _f(e.data.target); } }); } $(_3).addClass("combo-f").textbox($.extend({}, _5, { icons: _a, onChange: function () { } })); $(_3).attr("comboName", $(_3).attr("textboxName")); _4.combo = $(_3).next(); _4.combo.addClass("combo"); }; function _b(_c) { var _d = $.data(_c, "combo"); var _e = _d.options; var p = _d.panel; if (p.is(":visible")) { p.panel("close"); } if (!_e.cloned) { p.panel("destroy"); } $(_c).textbox("destroy"); }; function _f(_10) { var _11 = $.data(_10, "combo").panel; if (_11.is(":visible")) { _12(_10); } else { var p = $(_10).closest("div.combo-panel"); $("div.combo-panel:visible").not(_11).not(p).panel("close"); $(_10).combo("showPanel"); } $(_10).combo("textbox").focus(); }; function _1(_13) { $(_13).find(".combo-f").each(function () { var p = $(this).combo("panel"); if (p.is(":visible")) { p.panel("close"); } }); }; function _14(e) { var _15 = e.data.target; var _16 = $.data(_15, "combo"); var _17 = _16.options; var _18 = _16.panel; if (!_17.editable) { _f(_15); } else { var p = $(_15).closest("div.combo-panel"); $("div.combo-panel:visible").not(_18).not(p).panel("close"); } }; function _19(e) { var _1a = e.data.target; var t = $(_1a); var _1b = t.data("combo"); var _1c = t.combo("options"); switch (e.keyCode) { case 38: _1c.keyHandler.up.call(_1a, e); break; case 40: _1c.keyHandler.down.call(_1a, e); break; case 37: _1c.keyHandler.left.call(_1a, e); break; case 39: _1c.keyHandler.right.call(_1a, e); break; case 13: e.preventDefault(); _1c.keyHandler.enter.call(_1a, e); return false; case 9: case 27: _12(_1a); break; default: if (_1c.editable) { if (_1b.timer) { clearTimeout(_1b.timer); } _1b.timer = setTimeout(function () { var q = t.combo("getText"); if (_1b.previousText != q) { _1b.previousText = q; t.combo("showPanel"); _1c.keyHandler.query.call(_1a, q, e); t.combo("validate"); } }, _1c.delay); } } }; function _1d(_1e) { var _1f = $.data(_1e, "combo"); var _20 = _1f.combo; var _21 = _1f.panel; var _22 = $(_1e).combo("options"); var _23 = _21.panel("options"); _23.comboTarget = _1e; if (_23.closed) { _21.panel("panel").show().css({ zIndex: ($.fn.menu ? $.fn.menu.defaults.zIndex++ : $.fn.window.defaults.zIndex++), left: -999999 }); _21.panel("resize", { width: (_22.panelWidth ? _22.panelWidth : _20._outerWidth()), height: _22.panelHeight }); _21.panel("panel").hide(); _21.panel("open"); } (function () { if (_21.is(":visible")) { _21.panel("move", {left: _24(), top: _25()}); setTimeout(arguments.callee, 200); } })(); function _24() { var _26 = _20.offset().left; if (_22.panelAlign == "right") { _26 += _20._outerWidth() - _21._outerWidth(); } if (_26 + _21._outerWidth() > $(window)._outerWidth() + $(document).scrollLeft()) { _26 = $(window)._outerWidth() + $(document).scrollLeft() - _21._outerWidth(); } if (_26 < 0) { _26 = 0; } return _26; }; function _25() { var top = _20.offset().top + _20._outerHeight(); if (top + _21._outerHeight() > $(window)._outerHeight() + $(document).scrollTop()) { top = _20.offset().top - _21._outerHeight(); } if (top < $(document).scrollTop()) { top = _20.offset().top + _20._outerHeight(); } return top; }; }; function _12(_27) { var _28 = $.data(_27, "combo").panel; _28.panel("close"); }; function _29(_2a) { var _2b = $.data(_2a, "combo"); var _2c = _2b.options; var _2d = _2b.combo; $(_2a).textbox("clear"); if (_2c.multiple) { _2d.find(".textbox-value").remove(); } else { _2d.find(".textbox-value").val(""); } }; function _2e(_2f, _30) { var _31 = $.data(_2f, "combo"); var _32 = $(_2f).textbox("getText"); if (_32 != _30) { $(_2f).textbox("setText", _30); _31.previousText = _30; } }; function _33(_34) { var _35 = []; var _36 = $.data(_34, "combo").combo; _36.find(".textbox-value").each(function () { _35.push($(this).val()); }); return _35; }; function _37(_38, _39) { var _3a = $.data(_38, "combo"); var _3b = _3a.options; var _3c = _3a.combo; if (!$.isArray(_39)) { _39 = _39.split(_3b.separator); } var _3d = _33(_38); _3c.find(".textbox-value").remove(); var _3e = $(_38).attr("textboxName") || ""; for (var i = 0; i < _39.length; i++) { var _3f = $("<input type=\"hidden\" class=\"textbox-value\">").appendTo(_3c); _3f.attr("name", _3e); if (_3b.disabled) { _3f.attr("disabled", "disabled"); } _3f.val(_39[i]); } var _40 = (function () { if (_3d.length != _39.length) { return true; } var a1 = $.extend(true, [], _3d); var a2 = $.extend(true, [], _39); a1.sort(); a2.sort(); for (var i = 0; i < a1.length; i++) { if (a1[i] != a2[i]) { return true; } } return false; })(); if (_40) { if (_3b.multiple) { _3b.onChange.call(_38, _39, _3d); } else { _3b.onChange.call(_38, _39[0], _3d[0]); } } }; function _41(_42) { var _43 = _33(_42); return _43[0]; }; function _44(_45, _46) { _37(_45, [_46]); }; function _47(_48) { var _49 = $.data(_48, "combo").options; var _4a = _49.onChange; _49.onChange = function () { }; if (_49.multiple) { _37(_48, _49.value ? _49.value : []); } else { _44(_48, _49.value); } _49.onChange = _4a; }; $.fn.combo = function (_4b, _4c) { if (typeof _4b == "string") { var _4d = $.fn.combo.methods[_4b]; if (_4d) { return _4d(this, _4c); } else { return this.textbox(_4b, _4c); } } _4b = _4b || {}; return this.each(function () { var _4e = $.data(this, "combo"); if (_4e) { $.extend(_4e.options, _4b); if (_4b.value != undefined) { _4e.options.originalValue = _4b.value; } } else { _4e = $.data(this, "combo", { options: $.extend({}, $.fn.combo.defaults, $.fn.combo.parseOptions(this), _4b), previousText: "" }); _4e.options.originalValue = _4e.options.value; } _2(this); _47(this); }); }; $.fn.combo.methods = { options: function (jq) { var _4f = jq.textbox("options"); return $.extend($.data(jq[0], "combo").options, { width: _4f.width, height: _4f.height, disabled: _4f.disabled, readonly: _4f.readonly }); }, cloneFrom: function (jq, _50) { return jq.each(function () { $(this).textbox("cloneFrom", _50); $.data(this, "combo", { options: $.extend(true, {cloned: true}, $(_50).combo("options")), combo: $(this).next(), panel: $(_50).combo("panel") }); $(this).addClass("combo-f").attr("comboName", $(this).attr("textboxName")); }); }, panel: function (jq) { return $.data(jq[0], "combo").panel; }, destroy: function (jq) { return jq.each(function () { _b(this); }); }, showPanel: function (jq) { return jq.each(function () { _1d(this); }); }, hidePanel: function (jq) { return jq.each(function () { _12(this); }); }, clear: function (jq) { return jq.each(function () { _29(this); }); }, reset: function (jq) { return jq.each(function () { var _51 = $.data(this, "combo").options; if (_51.multiple) { $(this).combo("setValues", _51.originalValue); } else { $(this).combo("setValue", _51.originalValue); } }); }, setText: function (jq, _52) { return jq.each(function () { _2e(this, _52); }); }, getValues: function (jq) { return _33(jq[0]); }, setValues: function (jq, _53) { return jq.each(function () { _37(this, _53); }); }, getValue: function (jq) { return _41(jq[0]); }, setValue: function (jq, _54) { return jq.each(function () { _44(this, _54); }); } }; $.fn.combo.parseOptions = function (_55) { var t = $(_55); return $.extend({}, $.fn.textbox.parseOptions(_55), $.parser.parseOptions(_55, ["separator", "panelAlign", { panelWidth: "number", hasDownArrow: "boolean", delay: "number", selectOnNavigation: "boolean" }, { panelMinWidth: "number", panelMaxWidth: "number", panelMinHeight: "number", panelMaxHeight: "number" }]), { panelHeight: (t.attr("panelHeight") == "auto" ? "auto" : parseInt(t.attr("panelHeight")) || undefined), multiple: (t.attr("multiple") ? true : undefined) }); }; $.fn.combo.defaults = $.extend({}, $.fn.textbox.defaults, { inputEvents: {click: _14, keydown: _19, paste: _19, drop: _19}, panelWidth: null, panelHeight: 200, panelMinWidth: null, panelMaxWidth: null, panelMinHeight: null, panelMaxHeight: null, panelAlign: "left", multiple: false, selectOnNavigation: true, separator: ",", hasDownArrow: true, delay: 200, keyHandler: { up: function (e) { }, down: function (e) { }, left: function (e) { }, right: function (e) { }, enter: function (e) { }, query: function (q, e) { } }, onShowPanel: function () { }, onHidePanel: function () { }, onChange: function (_56, _57) { } }); })(jQuery);
1.484375
1
src/io/ApplicationUpdater.js
Andrea-MariaDB-2/arc-electron
1,123
5031
import { autoUpdater } from 'electron-updater'; import { EventEmitter } from 'events'; import { dialog, nativeImage, ipcMain, BrowserWindow } from 'electron'; import path from 'path'; import { logger } from './Logger.js'; autoUpdater.logger = logger; /** @typedef {import('electron-updater').UpdateInfo} UpdateInfo */ /** @typedef {import('@advanced-rest-client/arc-types').Config.ARCConfig} ARCConfig */ export const checkingHandler = Symbol('checkingHandler'); export const updateAvailableHandler = Symbol('updateAvailableHandler'); export const updateNotAvailableHandler = Symbol('updateNotAvailableHandle'); export const updateErrorHandler = Symbol('updateErrorHandler'); export const downloadProgressHandler = Symbol('downloadProgressHandler'); export const downloadReadyHandler = Symbol('downloadReadyHandler'); export const checkUpdateHandler = Symbol('checkUpdateHandler'); /** * A module to check for updates. * * UpdateInfo model: * - version {String} - The version. * - files {Array<module:builder-util-runtime.UpdateFileInfo>} * - releaseName {String} - The release name. * - releaseNotes {String} - The release notes. * - releaseDate {String} - The release date. * - stagingPercentage {Number} - The staged rollout percentage, 0-100. */ export class ApplicationUpdater extends EventEmitter { constructor() { super(); this.state = 0; this.lastInfoObject = undefined; this[checkingHandler] = this[checkingHandler].bind(this); this[updateAvailableHandler] = this[updateAvailableHandler].bind(this); this[updateNotAvailableHandler] = this[updateNotAvailableHandler].bind(this); this[updateErrorHandler] = this[updateErrorHandler].bind(this); this[downloadProgressHandler] = this[downloadProgressHandler].bind(this); this[downloadReadyHandler] = this[downloadReadyHandler].bind(this); this.installUpdate = this.installUpdate.bind(this); this.check = this.check.bind(this); } /** * Adds auto-update library event listeners. */ listen() { autoUpdater.on('checking-for-update', this[checkingHandler]); autoUpdater.on('update-available', this[updateAvailableHandler]); autoUpdater.on('update-not-available', this[updateNotAvailableHandler]); autoUpdater.on('error', this[updateErrorHandler]); autoUpdater.on('download-progress', this[downloadProgressHandler]); autoUpdater.on('update-downloaded', this[downloadReadyHandler]); ipcMain.handle('check-for-update', this[checkUpdateHandler].bind(this)); ipcMain.on('install-update', this.installUpdate); } /** * Adds auto-update library event listeners. */ unlisten() { autoUpdater.off('checking-for-update', this[checkingHandler]); autoUpdater.off('update-available', this[updateAvailableHandler]); autoUpdater.off('update-not-available', this[updateNotAvailableHandler]); autoUpdater.off('error', this[updateErrorHandler]); autoUpdater.off('download-progress', this[downloadProgressHandler]); autoUpdater.off('update-downloaded', this[downloadReadyHandler]); ipcMain.removeHandler('check-for-update'); ipcMain.off('install-update', this.installUpdate); } /** * Checks if `channel` is a valid channel signature. * @param {String} channel * @return {Boolean} */ isValidChannel(channel) { return ['beta', 'alpha', 'latest'].indexOf(channel) !== -1; } /** * Checks for update. * * @param {object=} opts Options for checking for an update. */ check(opts={}) { this.lastOptions = opts; logger.info('Checking for application updates...'); autoUpdater.checkForUpdates(); } /** * Sets the channel value on auto updater * @param {string} channel Channel name */ setReleaseChannel(channel) { if (this.isValidChannel(channel)) { logger.debug(`Setting the release channel to${ channel}`); autoUpdater.channel = channel; } else { logger.warn(`Channel ${channel} is not a valid application release channel.`); } } /** * Checks for app update. * This function **must** be called after the app ready event. * * @param {ARCConfig=} settings Current application configuration. * @param {boolean=} skipAppUpdate When set it skips application update check */ start(settings={}, skipAppUpdate=false) { logger.info('ApplicationUpdater::Initializing auto updater.'); const { updater={} } = settings; const { auto, channel } = updater; if (channel) { if (this.isValidChannel(channel)) { logger.info(`ApplicationUpdater::Setting auto updater channel to ${channel}`); autoUpdater.channel = channel; } } if (skipAppUpdate || auto === false) { logger.debug('Auto Updater is disabled. Manual requests will still download the update.'); autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; return; } if (!skipAppUpdate) { setTimeout(() => this.check()); } } /** * Quits the application and installs the update. */ installUpdate() { logger.info('Initializing update process (quit & install)'); autoUpdater.quitAndInstall(); } /** * Handler for the `check-for-update` event dispatched by the renderer process. * Calls `check()` with option to not notify the user about the update * @returns {Promise<UpdateInfo>} */ async [checkUpdateHandler]() { const result = await autoUpdater.checkForUpdates(); if (!result || !result.updateInfo) { return undefined; } return result.updateInfo; } /** * Emitted when checking if an update has started. */ [checkingHandler]() { this.state = 1; this.lastInfoObject = undefined; this.emit('notify-windows', 'checking-for-update'); this.emit('status-changed', 'checking-for-update'); } /** * Emitted when there is an available update. The update is downloaded * automatically. * * @param {UpdateInfo} info Update info object. See class docs for details. */ [updateAvailableHandler](info) { logger.debug('Update available.'); this.state = 2; this.lastInfoObject = info; this.emit('notify-windows', 'update-available', info); this.emit('status-changed', 'download-progress'); if (!this.lastOptions || !this.lastOptions.notify) { return; } this.updateAvailableDialog(); } /** * Emitted when there is no available update. * * @param {UpdateInfo} info Update info object. See class docs for details. */ [updateNotAvailableHandler](info) { logger.debug('Update not available.'); this.state = 3; this.lastInfoObject = info; this.emit('notify-windows', 'update-not-available', info); this.emit('status-changed', 'not-available'); this.notifyUser('No update available.', `${info.version} is the latest version.`); } /** * Emitted when there is an error while updating. * * @param {any} error Error from the library. */ [updateErrorHandler](error) { const { message, code } = error; logger.error('Update error'); this.state = 4; this.lastInfoObject = error; this.emit('notify-windows', 'autoupdate-error', { message, code, }); this.emit('status-changed', 'not-available'); if (code === 8) { let msg = 'Unable to update the application when it runs in'; msg += ' read-only mode. Move the application to the Applications'; msg += ' folder first and try again.'; this.notifyUser('Update error', msg, true); } else { this.notifyUser('Update error', message, true); } } /** * Emitted on download progress. * * @param {object} progressObj Progress info data. Contains `progress` property which has the following properties: * - bytesPerSecond * - percent * - total * - transferred */ [downloadProgressHandler](progressObj) { logger.debug('Update download progress'); this.state = 5; this.lastInfoObject = progressObj; this.emit('notify-windows', 'download-progress', progressObj); } /** * Emitted when a new version is downloaded. * * @param {UpdateInfo} info Update info object. See class docs for details. */ [downloadReadyHandler](info) { logger.debug('Update download ready', info); this.state = 6; this.lastInfoObject = info; this.emit('notify-windows', 'update-downloaded', info); this.emit('status-changed', 'update-downloaded'); if (this.lastOptions && this.lastOptions.notify) { setImmediate(() => autoUpdater.quitAndInstall()); } } /** * Notifies the user about update event. * * @param {string} message Message to display. * @param {string} detail MacOS only. Additional detail message. * @param {boolean=} isError Should be true when notifying about error. */ notifyUser(message, detail, isError) { this.lastOptions = this.lastOptions || {}; if (!this.lastOptions || !this.lastOptions.notify) { return; } const dialogOpts = { type: isError ? 'error' : 'info', title: 'ARC updater', message, detail, }; if (!isError) { const imgPath = path.join(__dirname, '..', '..', 'assets', 'icon.iconset', 'icon_512x512.png'); dialogOpts.icon = nativeImage.createFromPath(imgPath); } dialog.showMessageBox(dialogOpts); } async updateAvailableDialog() { let msg = 'Application update is available. '; msg += 'Do you want to install it now?'; const window = BrowserWindow.getFocusedWindow(); const result = await dialog.showMessageBox(window, { type: 'info', title: 'Application update', message: msg, buttons: ['Yes', 'No'] }); if (result.response === 0) { autoUpdater.downloadUpdate(); } } /** * A function reserved for the application menu to call. * Checks for the update status when requested. * @param {string} action The action requested by the user. */ menuActionHandler(action) { if (action.indexOf('application') === -1) { return; } switch (action) { case 'application:install-update': this.installUpdate(); break; case 'application:check-for-update': this.check({ notify: true, }); break; default: } } }
1.234375
1
js/webGISMaps.js
mtnekros/WebGIS-Assignment-Project
1
5039
// base osm layer var osmLayer =new ol.layer.Tile({ title: 'Base Map', source: new ol.source.OSM(), type: 'base' }) // initializing map object var map = new ol.Map({ target: 'mainMap', layers: [ osmLayer ], view: new ol.View({ center: ol.proj.fromLonLat([84.1240, 28.3949]), zoom: 7 }) }); // bing base map initializing var bingBase = new ol.layer.Tile({ title: 'BingMaps', // same name as variable type: 'base', visible: false, source: new ol.source.BingMaps({ key: '<KEY>', imagerySet: 'AerialWithLabels', maxZoom: 19 }) }); map.addLayer(bingBase); // bingBase map toggling functionalities var bingBaseCheckBox = document.getElementById("bingBaseLayer"); bingBaseCheckBox.addEventListener("change",toggleBaseMap); function toggleBaseMap() { if (bingBaseCheckBox.checked) { bingBase.setVisible(true); osmLayer.setVisible(false); return 1; } else { osmLayer.setVisible(true); bingBase.setVisible(false); return 0; } } // initializing total population layer var populationLayer = new ol.layer.Image({ visible: true, source: new ol.source.ImageWMS({ url: 'http://localhost:8080/geoserver/Nepal/wms', params: {'Layers': 'Nepal:nepal_district'}, serverType: 'geoserver' }) }); // initializing male population layer var malePopulationLayer = new ol.layer.Image({ visible: false, source: new ol.source.ImageWMS({ url: 'http://localhost:8080/geoserver/Nepal/wms', params: {'Layers' : 'Nepal:MalePopulation'}, serverType: 'geoserver' }) }); // initializing female population layer var femalePopulationLayer = new ol.layer.Image({ visible: false, source: new ol.source.ImageWMS({ url: 'http://localhost:8080/geoserver/Nepal/wms', params: {'Layers' : 'Nepal:femalePopulation'}, serverType: 'geoserver' }) }); // initializing administrative layer var administrativeLayer = new ol.layer.Image({ visible: false, source: new ol.source.ImageWMS({ url: 'http://localhost:8080/geoserver/Nepal/wms', params: {'LAYERS': 'Nepal:municipalities-polygon'}, serverType: 'geoserver' }) }); // initializing land cover layer var landCoverLayer = new ol.layer.Image({ visible: false, source: new ol.source.ImageWMS({ url: 'http://localhost:8080/geoserver/Nepal/wms', params: {'LAYERS': 'Nepal:geotiff_coverage'}, serverType: 'geoserver' }) }); // making the list of above layers layers = { 'totalPopLayerLegend':populationLayer, 'malePopulationLayerLegend':malePopulationLayer, 'femalePopulationLayerLegend':femalePopulationLayer, 'administrativeLayerLegend':administrativeLayer, 'landCoverLayerLegend':landCoverLayer }; // adding the layers to map using for loop for (var key in layers) { map.addLayer(layers[key]); } // initializing checkboxes from the document $(function (){ $('.layerCheckBox').change( function() { var legend = $(this).attr('data-legend')// which is also the key for layers dictionary if ($(this).is(':checked')) { layers[legend].setVisible(true); hideAllLegendExcept(legend); } else { layers[legend].setVisible(false); } } ) }); // function to hide all layers function hideAllLegendExcept(legendToShow) { for (var key in layers) { $('#'+key).hide(); } $('#'+legendToShow).slideDown(100); } hideAllLegendExcept("totalPopLayerLegend")
1.09375
1
views/comparisons.js
garrlker/regl-site
4
5047
var choo = require('choo') var back = require('./components/back') var css = require('dom-css') var request = require('browser-request') var hl = require('highlight.js') module.exports = function (params, state, send) { function main (code) { var container = document.createElement('div') container.id ='text' container.className = 'code-body' css(container, { width: '50%', height: window.innerHeight, position: 'fixed', padding: '30px', top: '0px', right: '0px', fontSize: '80%', opacity: 0.9, display: 'inline-block', overflow: 'scroll', background: 'rgb(30,30,30)', fontFamily: '12px Consolas, Courier, monospace' }) var pre = document.createElement('pre') var block = document.createElement('code') container.appendChild(pre) pre.appendChild(block) if (code) { block.innerHTML = hl.highlight('js', code).value } return container } var examples = ['threejs', 'twgl', 'regl', 'webgl'] var toggles = [] examples.forEach(function (label, i) { var toggle = document.createElement('div') toggle.innerHTML = label toggle.className = 'switch' css(toggle, { width: '20%', height: '40px', top: i * 80 + 400, right: '50%', marginRight: '60px', background: 'rgb(30,30,30)', position: 'fixed', padding: '10px', paddingLeft: '20px', fontSize: '175%', fontFamily: 'klartext_monolight', cursor: 'pointer' }) if (label === state.comparisons.selected) { css(toggle, {opacity: 0.9}) } else { css(toggle, {opacity: 0.7}) } toggles.push(toggle) toggle.onclick = function () { send('comparisons:select', {payload: label}) } }) var comparisons = state.comparisons.contents ? state.comparisons.contents[state.comparisons.selected] : null return choo.view` <main> <div class='row' id='title'> <div class='hero-medium'> <h1 align='right'>comparisons</h1> </div> <div class='color-block-medium pink'></div> </div> <div> ${main(comparisons)} ${toggles} </div> ${back()} </main>` }
1.898438
2
src/adapters/bugsnag.js
dial-once/node-logtify-bugsnag
2
5055
const assert = require('assert'); const BugsnagStreamLink = require('../bugsnag-link'); /** @class Bugsnag Adapter for the bugsnag subscriber. Exposes the notify function as if a standard bugsnag module was used @constructor consumes the instance of a LoggerStream @class * */ class Bugsnag { /** @constructor Construct an instance of a bugsnag adapter @param stream {Object} - an instance of a @class LoggerStream @param settings {Object} - stream settings * */ constructor(stream, settings) { assert(stream); this.settings = settings; this.Message = stream.Message; // if notify @function is called, a user probably just wants it to be notified without progressing further along the stream // that is why we use a seprate instance of a subscriber instead of a loggerStream.bugsnagSubscriber this.bugsnag = new BugsnagStreamLink(settings); this.requestHandler = this.bugsnag.notifier ? this.bugsnag.notifier.requestHandler : undefined; this.errorHandler = this.bugsnag.notifier ? this.bugsnag.notifier.errorHandler : undefined; } /** @function notify A function to fire a notify request to bugsnag api @param message {String|Object|Error} - an object to include into a notification @param metadatas {Object} - metadata to include into the notification * */ notify(message, ...metadatas) { this.bugsnag.handle(new this.Message('error', message, ...metadatas)); } } module.exports = Bugsnag;
1.9375
2
src/updateTexture.js
bbbbx/toy.gl
1
5063
import defaultValue from "./defaultValue"; /** * Update texture data. * @param {WebGLRenderingContext} gl * @param {WebGLTexture} texture * @param {Object | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} source * @param {Number} source.width * @param {Number} source.height * @param {TypedArray} source.arrayBufferView * @param {Number} [source.level=0] * @param {Number} [source.internalFormat=gl.RGBA] * @param {Number} [source.format=gl.RGBA] * @param {Number} [source.type=gl.UNSIGNED_BYTE] * @returns {WebGLTexture} */ function updateTexture(gl, texture, source) { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); if (source instanceof HTMLImageElement || source instanceof HTMLCanvasElement || source instanceof HTMLVideoElement) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, videoElem); } else { const { width, height, arrayBufferView } = source; const level = defaultValue(source.level, 0); const internalFormat = defaultValue(source.internalFormat, gl.RGBA); const format = defaultValue(source.format, gl.RGBA); const type = defaultValue(source.internalFormat, gl.UNSIGNED_BYTE); const border = 0; gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border, format, type, arrayBufferView); } gl.bindTexture(gl.TEXTURE_2D, null); return texture; } export default updateTexture;
1.375
1
apps/figma-broker/functions/file.js
vnys/design-system
0
5071
import fs from 'fs' import del from 'del' import fetch from 'node-fetch' import R from 'ramda' import { createFolder } from './folder' import prettier from 'prettier' const prettierConfig = fs.readFileSync('./../../.prettierrc.yaml', 'utf8') const getFilePath = (path, name, ext) => `${path}/${name}.${ext}` const write = (file, path, name, ext) => { const filePath = getFilePath(path, name, ext) fs.writeFile(filePath, file, 'utf-8', (error) => { if (error) { throw new Error('Error in write(): ', { error, filePath }) } }) } const stream = (url, path, name, ext) => fetch(url).then((res) => { const filePath = getFilePath(path, name, ext) var file = fs.createWriteStream(filePath) res.body.pipe(file) }) export const writeFileStream = (url, path, name, ext) => { if (url && path && name) { createFolder(path) stream(url, path, name, ext) } else { throw new Error( 'Missing required parameters to correctly run writeFileStream()!', ) } } export const writeFile = (path, name, ext, file) => { if (file && path && name && ext) { createFolder(path) let value = file if (ext === 'js' || ext === 'ts') { const options = prettier.resolveConfig.sync(prettierConfig) value = prettier.format(file, options) } write(value, path, name, ext) } else { throw new Error('Missing required parameters to correctly run writeFile()!') } } export const curriedWriteFile = R.curry(writeFile) export async function readFile(path, name, ext) { const data = await fs.promises.readFile(getFilePath(path, name, ext), { encoding: 'utf8', }) return Promise.resolve(JSON.parse(data)) } export const readTokens = (path) => fs.readdirSync(path).map((fileName) => ({ name: fileName.replace(/.json/, ''), extension: 'json', tokens: JSON.parse(fs.readFileSync(`${path}/${fileName}`)), })) export const writeResults = (results, savePath, extension = 'json') => results.forEach(({ value, name, path = '' }) => { const writeFileToDisk = curriedWriteFile( `${savePath}/${path}`, name, extension, ) switch (extension) { case 'ts': case 'js': writeFileToDisk( `export const ${name} = ${JSON.stringify(value, null, 2)}\n`, ) break case 'json': writeFileToDisk(`${JSON.stringify(value, null, 2)}\n`) break default: writeFileToDisk(value) } }) export const writeResultsIndividually = ( results, savePath, extension = 'json', ) => { results.forEach(({ value, name }) => { writeResults(value, `${savePath}/${name}`, extension) }) } export async function fetchFile(url) { return fetch(url).then((res) => res.text()) } export const writeUrlToFile = (results, savePath, extension = 'json') => results.forEach(({ url, name, path = '' }) => { if (url) { writeFileStream(url, `${savePath}/${path}`, name, extension) } }) export const deletePaths = del
1.273438
1
sources/views/settings.js
ilya-xbsoftware/jet-start
0
5079
import {JetView} from "webix-jet"; import activityTypes from "../models/activityTypes"; import icons from "../models/icons"; import statuses from "../models/statuses"; import settingsChangeLang from "./settings/settingsChangeLang"; import SettingsTable from "./settings/settingsTable"; export default class Settings extends JetView { constructor(app, name) { super(app, name); this.activityTable = new SettingsTable(this.app, "", activityTypes, icons.activity); this.contactTable = new SettingsTable(this.app, "", statuses, icons.contact); } config() { const _ = this.app.getService("locale")._; return { padding: 30, rows: [ { padding: 30, rows: [ settingsChangeLang ] }, { view: "tabview", localId: "tabView", cells: [ { header: _("activityTypes"), id: "settingsActivityTypes", body: this.activityTable }, { header: _("contactStatuses"), id: "settingsContactStatuses", body: this.contactTable } ] } ] }; } }
1.210938
1
src/parameters/AnyParameter.js
kelseykm/vcard4
11
5087
import { BaseParameter } from './BaseParameter.js'; import { MissingArgument, InvalidArgument } from '../errors/index.js'; export class AnyParameter extends BaseParameter { static identifier = 'AnyParameter'; #value; #param; get param() { return `${this.#param}`; } get value() { return this.#cleanUp(this.#value.repr()); } get valueXML() { return this.#value.reprXML(); } get valueJSON() { return this.#value.reprJSON(); } #paramRegExp = /^(?:A-GNSS|A-GPS|AOA|best-guess|Cell|DBH|DBH_HELO|Derived|Device-Assisted_A-GPS|Device-Assisted_EOTD|Device-Based_A-GPS|Device-Based_EOTD|DHCP|E-CID|ELS-BLE|ELS-WiFi|GNSS|GPS|Handset_AFLT|Handset_EFLT|Hybrid_A-GPS|hybridAGPS_AFLT|hybridCellSector_AGPS|hybridTDOA_AOA|hybridTDOA_AGPS|hybridTDOA_AGPS_AOA|IPDL|LLDP-MED|Manual|MBS|MPL|NEAD-BLE|NEAD-WiFi|networkRFFingerprinting|networkTDOA|networkTOA|NMR|OTDOA|RFID|RSSI|RSSI-RTT|RTT|TA|TA-NMR|Triangulation|UTDOA|Wiremap|802\.11|x-[A-Za-z0-9]+)$/i; #valueRegExp = /^(?:Boolean|DateTime(?:List)?|Float(?:List)?|Integer(?:List)?|LanguageTag|Sex|SpecialValue|Text(?:List)?|URI)Type$/; #cleanUp(value) { return value.replaceAll('^', '^^').replaceAll('\n', '^n').replaceAll('"', '^’'); } #validate(param, value) { if (typeof param === 'undefined' || typeof value === 'undefined') throw new MissingArgument('Parameter name and value for AnyParameter must be supplied'); else if (!this.#paramRegExp.test(param)) throw new InvalidArgument('Invalid parameter name for AnyParameter'); else if (!this.#valueRegExp.test(value?.constructor?.identifier)) throw new InvalidArgument('Invalid value for AnyParameter'); } constructor(param, value) { super(); this.#validate(param, value); this.#param = param; this.#value = value; this.checkAbstractPropertiesAndMethods(); Object.freeze(this); } } Object.freeze(AnyParameter);
1.273438
1
assets/js/dist/event/searchEvent.js
vitaliy-shahanyants/fitness-application
0
5095
import React from 'react'; import axios from 'axios'; import FormData from 'form-data'; import DisplayEvent from './displayEvent.js' const initialState = { events:[], search_for:'', clickOnevent:false, clickedEvent_id:0, } export default class SearchEvent extends React.Component{ constructor(props){ super(props); this.state = initialState; this.searchForEvent = this.searchForEvent.bind(this); } searchForEvent(search_for){ let data = new FormData(); data.append('search_for',search_for); axios.post(window.pageURL+"searchForEvent",data).then((res)=>{ this.setState({events:res.data, search_for:search_for}); }) } render(){ return( <div className="container"> <h1>Search For Events</h1> <div className="form-group row"> <label className="col-2 col-form-label">Search For Event Name Or Description</label> <div className="col-10"> <input className="form-control" type="text" value={this.state.search_for} onChange={(e)=>{ this.searchForEvent(e.target.value); }}/> </div> </div> <div className="row"> <button className="btn btn-primary" onClick={this.searchForEvent}>Search</button> </div> <ListOfEvents events={this.state} /> </div> ); } } class ListOfEvents extends React.Component{ constructor(props){ super(props); this.state = props.events; this.joinEvent = this.joinEvent.bind(this); this.clickedEvent - this.clickedEvent.bind(this); } clickedEvent(id){ this.setState({clickOnevent:true,clickedEvent_id:id}); } joinEvent(id){ let data = new FormData(); data.append('event_id',id); axios.post(window.pageURL+"joinEvent",data).then((res)=>{ }) } componentWillReceiveProps(nextProps){ this.state = nextProps.events; } render(){ return( <div> {this.state.clickOnevent ? <div> <div> <button className="btn btn-primary" onClick={(e)=>{ this.joinEvent(this.state.clickedEvent_id); }}>Join</button> </div> <DisplayEvent event_id={this.state.clickedEvent_id} /> </div> : <div> <div className="row"> <div className="col-3"> <strong>Event Name</strong> </div> <div className="col-3"> <strong>Start and End Date</strong> </div> <div className="col-4"> <strong>Description</strong> </div> <div className="col-2"> </div> </div> {this.state.events.map((val,i)=>{ return( <div className="row" key={i}> <div className="col-3"> <span role="button" style={{'color':'blue'}} onClick={()=>{ this.clickedEvent(val.event_id); }}> {val.event_name} </span> </div> <div className="col-3"> {val.event_start_date} - {val.event_end_date} </div> <div className="col-4"> {val.event_description} </div> <div className="col-2"> <button className="btn btn-primary" onClick={(e)=>{ this.joinEvent(val.event_id); }}> Join </button> </div> </div> ); })} </div> } </div> ); } }
1.625
2
src/swapLegacy/redux/index.js
bdcorps/airswap.js
24
5103
import middleware from './middleware' import reducers, { selectors as reducerSelectors } from './reducers' import * as eventTrackingSelectors from './eventTrackingSelectors' import * as derivedSelectors from './selectors' const selectors = { ...derivedSelectors, ...eventTrackingSelectors, ...reducerSelectors, } export { middleware, reducers, selectors }
0.451172
0
resources/js/views/User/Plots/PlotMainPage.js
ArtemPobedennyi/portal.umbrellaproject.cc
0
5111
import React, { useState, useEffect, } from "react"; import { useHistory } from "react-router-dom"; import { useDispatch, useSelector } from 'react-redux'; // core components import GridContainer from "@/components/Grid/GridContainer.js"; import GridItem from "@/components/Grid/GridItem.js"; // styles import { makeStyles } from "@material-ui/core/styles"; import styles from "@/assets/jss/material-dashboard-pro-react/views/commonPageStyle.js"; const useStyles = makeStyles(styles); // actions import { LogoutAction, } from '@/redux/actions/AuthActions'; export default function PlotMainPage() { const history = useHistory(); const dispatch = useDispatch(); const { isAuthenticated, isAdmin, } = useSelector((state) => state.userAuth); useEffect(() => { if(isAdmin && isAuthenticated) { history.push('/admin'); return; } else if(!isAuthenticated) { dispatch(LogoutAction(history)); return; } }, [isAdmin, isAuthenticated]); useEffect(() => { let backgroundImg = 'url(/images/cityplots/box1_blur.png)'; document.getElementById('plot_main_block').style.backgroundImage = backgroundImg; }, []) const handleMouseEnter = (id) => { let backgroundImg = ''; if(id === 1) { backgroundImg = 'url(/images/cityplots/box1_blur.png)'; } else if(id === 2) { backgroundImg = 'url(/images/cityplots/box2_blur.png)'; } else if(id === 3) { backgroundImg = 'url(/images/cityplots/box3_blur.png)'; } else if(id === 4) { backgroundImg = 'url(/images/cityplots/box4_blur.png)'; } document.getElementById('plot_main_block').style.backgroundImage = backgroundImg; }; const goTocityplotPage = (id) => { history.push('/plots/' + id); } return( <div className="plot-main-container"> <GridContainer className="plot-grid-container" id="plot_main_block"> <GridItem xs={12} sm={12} md={3} className="plot-block plot-1" onMouseEnter={() => handleMouseEnter(1)} onClick={() => goTocityplotPage(10123)}> <div className="block-body"> {/* <div className="title-container"> <h5 className="card-title">SURVIVORS</h5> <p className="card-text"><span>BASIC</span> <span>cityplot</span></p> </div> <div className="rarity-container"> <label className="card-text common">COMMON</label> <label className="card-text uncommon">UNCOMMON</label> </div> */} </div> </GridItem> <GridItem xs={12} sm={12} md={3} className="plot-block plot-2" onMouseEnter={() => handleMouseEnter(2)} onClick={() => goTocityplotPage(10124)}> <div className="block-body"> {/* <div className="title-container"> <h5 className="card-title">SURVIVORS</h5> <p className="card-text"><span>TACTICAL</span> cityplot</p> </div> <div className="rarity-container"> <label className="card-text unique">UNIQUE</label> </div> */} </div> </GridItem> <GridItem xs={12} sm={12} md={3} className="plot-block plot-3" onMouseEnter={() => handleMouseEnter(3)} onClick={() => goTocityplotPage(10125)}> <div className="block-body"> {/* <div className="title-container"> <h5 className="card-title">SCIENTIST</h5> <p className="card-text"><span>ALPHA</span> TYPE</p> </div> <div className="rarity-container"> <label className="card-text common">COMMON</label> <label className="card-text uncommon">UNCOMMON</label> </div> */} </div> </GridItem> <GridItem xs={12} sm={12} md={3} className="plot-block plot-4" onMouseEnter={() => handleMouseEnter(4)} onClick={() => goTocityplotPage(10126)}> <div className="block-body"> {/* <div className="title-container"> <h5 className="card-title">SCIENTIST</h5> <p className="card-text"><span>OMEGA</span> TYPE</p> </div> <div className="rarity-container"> <label className="card-text unique">UNIQUE</label> </div> */} </div> </GridItem> </GridContainer> </div> ); };
1.570313
2
src/operations/v1/list-training-data-containing-document.js
ptxyz/wd-utils
0
5119
const yargs = require('yargs') const util = require('util') const core = require('../../lib') async function main (argv) { // get connection const conn = await core.connection.initConnection(argv.connection) // retrieve training data const td = (await core.wds.getTrainingData(conn)).data[0] // identify queries that are affected const qs = core.helpers.getMatchingQueriesAndExamples(td, argv.document_id, argv.include_segments) // inspect the matches console.log(util.inspect(qs, { depth: 8, maxArrayLength: Infinity, colors: true })) // calculate unique queries and examples affected const uniqueQueries = qs.map(v => v.query.query_id).filter(core.helpers.onlyUnique) console.log('') console.log(`training queries containing document: ${uniqueQueries.length}`) console.log(`matched examples in training data: ${qs.length}`) // TODO: merge multiple matches on same query into 1 single entry if (argv.report && !process.env.DRY_RUN) { await core.helpers.writeObjectToFile({ matchingExamples: qs }, argv.report) console.log(`affected queries written to ${argv.report}`) } return new core.classes.Result(1, 0, 0, [qs]) } function getArgs () { return yargs .option('document_id', { alias: 'd', describe: 'document id to find in training examples' }) .option('connection', { alias: 'c', describe: 'WDS connection info JSON' }) .option('report', { alias: 'r', describe: 'write affected training data to this file' }) .option('include_segments', { alias: 's', describe: 'include document and any associated segments', type: 'boolean', default: true }) .option('dry_run', { alias: 'z', describe: 'dry run of operation', type: 'boolean', default: false }) .demandOption(['document_id', 'connection'], 'Requires a document id and WDS connection') .argv } module.exports = () => { core.execution.execute(main, getArgs()) }
1.796875
2
node_modules/@patternfly/react-core/dist/esm/components/Dropdown/DropdownToggle.js
nikunjdoshi67/Npatternfly
0
5127
import { __rest } from "tslib"; import * as React from 'react'; import CaretDownIcon from '@patternfly/react-icons/dist/js/icons/caret-down-icon'; import { Toggle } from './Toggle'; import styles from '@patternfly/react-styles/css/components/Dropdown/dropdown'; import { DropdownContext } from './dropdownConstants'; import { css } from '@patternfly/react-styles'; export const DropdownToggle = (_a) => { var { id = '', children = null, className = '', isOpen = false, parentRef = null, isFocused = false, isHovered = false, isActive = false, isDisabled = false, isPlain = false, isPrimary = false, // eslint-disable-next-line @typescript-eslint/no-unused-vars onToggle = (_isOpen) => undefined, iconComponent: IconComponent = CaretDownIcon, splitButtonItems, splitButtonVariant = 'checkbox', 'aria-haspopup': ariaHasPopup, // eslint-disable-next-line @typescript-eslint/no-unused-vars ref } = _a, // Types of Ref are different for React.FC vs React.Component props = __rest(_a, ["id", "children", "className", "isOpen", "parentRef", "isFocused", "isHovered", "isActive", "isDisabled", "isPlain", "isPrimary", "onToggle", "iconComponent", "splitButtonItems", "splitButtonVariant", 'aria-haspopup', "ref"]); const toggle = (React.createElement(DropdownContext.Consumer, null, ({ toggleTextClass, toggleIconClass }) => (React.createElement(Toggle, Object.assign({}, props, { id: id, className: className, isOpen: isOpen, parentRef: parentRef, isFocused: isFocused, isHovered: isHovered, isActive: isActive, isDisabled: isDisabled, isPlain: isPlain, isPrimary: isPrimary, onToggle: onToggle, "aria-haspopup": ariaHasPopup }, (splitButtonItems && { isSplitButton: true, 'aria-label': props['aria-label'] || 'Select' })), children && React.createElement("span", { className: IconComponent && css(toggleTextClass) }, children), IconComponent && React.createElement(IconComponent, { className: css(children && toggleIconClass) }))))); if (splitButtonItems) { return (React.createElement("div", { className: css(styles.dropdownToggle, styles.modifiers.splitButton, splitButtonVariant === 'action' && styles.modifiers.action, isDisabled && styles.modifiers.disabled) }, splitButtonItems, toggle)); } return toggle; }; //# sourceMappingURL=DropdownToggle.js.map
1.460938
1
js/ph.js
kongyujian/Fishackathon2016_Geospatial
0
5135
var weekAverage = 0; $(function(){ var flowArr = []; $.ajax({ url: "http://allow-any-origin.appspot.com/http://waterdata.usgs.gov/nwis/uv?format=rdb&period=&begin_date=2016-04-15&end_date=2016-04-24&cb_00055=on&site_no=04119400" }) .done(function(data){ data = data.split(/\r?\n/); var lines = []; for(var i = 0; i < data.length; i++){ if (data[i].charAt(0) != "#"){ var token = data[i].split('\t'); lines.push(token); } } lines.shift(); lines.shift(); for (var i = 0; i < lines.length; i++){ var day = moment(lines[i][2]); var flowData = lines[i][4]; flowArr.push([day.unix() * 1000, flowData]); } var total = 0; for (var i = 0; i < flowArr.length; i++){ if (flowArr[i][1] != undefined) total += parseInt(flowArr[i][1]); } weekAverage = total / flowArr.length; $("#avg-motion").html(weekAverage.toFixed(2) + "m/s"); window.phgauge.set(weekAverage); initializePHGraph(flowArr, flowArr); }) }) function initializePHGraph(data1, data2){ var phplot = $("#canvas_ph").length && $.plot($("#canvas_ph"), [ {label: "Probe 1", data: data1}//, {label:"Probe 2", data: data2} ], { series: { lines: { show: false, fill: true }, splines: { show: true, tension: 0.4, lineWidth: 1, fill: 0.4 }, points: { radius: 1, show: true }, shadowSize: 2 }, grid: { verticalLines: true, hoverable: true, clickable: true, tickColor: "#d5d5d5", borderWidth: 1, color: '#fff' }, colors: ["rgba(38, 185, 154, 0.38)", "rgba(3, 88, 106, 0.38)"], xaxis: { tickColor: "rgba(51, 51, 51, 0.06)", mode: "time", tickSize: [1, "day"], //tickLength: 10, axisLabel: "Date", axisLabelUseCanvas: true, axisLabelFontSizePixels: 12, axisLabelFontFamily: 'Verdana, Arial', axisLabelPadding: 10, mode: "time", timeformat: "%Y/%m/%d" }, yaxis: { ticks: 8, tickColor: "rgba(51, 51, 51, 0.06)", }, legend: { show: true, labelBoxBorderColor: "rgba(38, 185, 154, 0.38)", position: "se", labelFormatter: function(label, series) { // series is the series object for the label return '<a href="#' + label + '" style="color:#1ABB9C">' + label + '</a>'; } //margin: number of pixels or [x margin, y margin] //backgroundColor: null or color //backgroundOpacity: number between 0 and 1 //container: null or jQuery object/DOM element/jQuery expression //sorted: null/false, true, "ascending", "descending", "reverse", or a comparator }, tooltip: { show: true, content: "%s" } }); window.phplot = phplot; }
1.414063
1
src/helpers.js
deciob/d3-bar
0
5143
import {entries} from '../node_modules/d3-collection/index'; import {max} from '../node_modules/d3-array/index'; function inspect(x) { return (typeof x === 'function') ? inspectFn(x) : inspectArgs(x); } function inspectFn(f) { return (f.name) ? f.name : f.toString(); } function inspectArgs(args) { return args.reduce(function(acc, x){ return acc += inspect(x); }, '(') + ')'; } export function curry(fx) { var arity = fx.length; return function f1() { var args = Array.prototype.slice.call(arguments, 0); if (args.length >= arity) { return fx.apply(null, args); } else { var f2 = function f2() { var args2 = Array.prototype.slice.call(arguments, 0); return f1.apply(null, args.concat(args2)); } f2.toString = function() { return inspectFn(fx) + inspectArgs(args); } return f2; } }; } // isObject :: a -> Bool export function isObject(o) { return Object.prototype.toString.call(o) === '[object Object]'; } // clone :: Object -> Object export function clone(obj) { if (obj === null || typeof obj !== 'object') return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = clone(obj[attr]); } } return copy; } // extend target with source, clone by default // extend :: Object -> Object -> Object -> Object export function extend(target, source, options) { if (!isObject(target) || !isObject(source)) { throw new Error('extend only accepts objects'); } var useClone = (!options || options.useClone === undefined) ? true : options.useClone; // notOverride (target) defaults to false. var notOverride = (options && options.notOverride === undefined || !options) ? false : options.notOverride; var targetClone = useClone ? clone(target) : target; for (var prop in source) { if (notOverride) { targetClone[prop] = targetClone[prop] ? targetClone[prop] : source[prop]; } else { targetClone[prop] = source[prop]; } } return targetClone; } // For each attribute in `state` it sets a getter-setter function on `obj`. // Accepts one level nested `state` objects. // getset :: a -> a export function getSet(obj, state) { entries(state).forEach(function(o) { obj[o.key] = function getSetCallback(x) { if (!arguments.length) return state[o.key]; if (isObject(o.value)) { state[o.key] = extend(o.value, x); } else { state[o.key] = x; } return obj; }; }); return obj; } // getRange :: String -> Object -> Array export function getRange(axes, config) { var width = config.width - config.margin.left - config.margin.right; var height = config.height - config.margin.top - config.margin.bottom; if (axes === 'x') { return config.invertOrientation ? [0, height] : [0, width]; } else if (axes = 'y') { return config.invertOrientation ? [0, width] : [0, height]; } } function getContinousDomain(accessor, data) { return [0, max(data, accessor)]; } function getOrdinalDomain(accessor, data) { return data.map(function(d) { return accessor(d); }); } export function getDomain(scaleType, accessor, data) { if (scaleType === 'continuous') { return getContinousDomain(accessor, data); } else if (scaleType === 'ordinal') { return getOrdinalDomain(accessor, data); } } var getRangeCurried = curry(getRange); export var getXRange = getRangeCurried('x'); export var getYRange = getRangeCurried('y');
1.875
2
crates/swc/tests/tsc-references/objectLiteralShorthandPropertiesAssignment_es2015.2.minified.js
mengxy/swc
21,008
5151
function bar(name, id) { return { name, id }; } bar("Hello", 5), bar("Hello", 5), bar("Hello", 5);
0.871094
1
lib/breadcrumb.js
arlesondak/File-Explorer
0
5159
// include node modules const path = require('path'); const buildBreadCrumb = pathname => { const pathArray = pathname.split('/').filter(element => element !== ''); let htmlSnippet = `<li class="breadcrumb-item"><a href="/">Home</a></li>`;; let link = `/`; pathArray.forEach((pathItem, i) => { link = path.join(link, pathItem); if(i !== pathArray.length - 1){ htmlSnippet += `<li class="breadcrumb-item"><a href="${link}">${pathItem}</a></li>`; } else { htmlSnippet += `<li class="breadcrumb-item active" aria-current="page">${pathItem}</li>`; } }); return htmlSnippet; }; module.exports = buildBreadCrumb;
1.75
2
src/main/webapp/app/src/module/utils/componentes/validationFactory.js
dfslima/portalCliente
0
5167
app.factory('validationFactory', function(){ var validationFactory = {}; validationFactory.lengthInputs = function(inputValue, minLength, maxLength, nameInput, isRequired, $scope) { return lengthInputs(inputValue, minLength, maxLength, nameInput, isRequired, $scope); }; validationFactory.validarCNPJ = function(cnpj) { return validarCNPJ(cnpj); }; validationFactory.showNameCustomer = function (customer) { if(customer != undefined) { if(customer.type == 2) return customer.corporateName; else return customer.name; } }; return validationFactory; });
1.273438
1
src/components/bottom-cta/become-partner-bottom-cta.js
abeuscher/contentstackjobapp
0
5175
import { useStaticQuery, graphql } from "gatsby" import React from "react" import BottomCTA from "./bottom-cta" export default function BizBottomCTA() { const data = useStaticQuery(graphql` query BecomePartnerBottomCtaQuery { csBecomeAPartner { bottom_cta { header copy } } } `) return ( <BottomCTA data={data.csBecomeAPartner.bottom_cta} /> ) }
0.957031
1
commands/botinfo.js
Purgador/walterio
0
5183
const moment = require("moment"); require('moment-duration-format'); module.exports = async (client, message, args, ops) => { const actividad = moment.duration(client.uptime).format(" D [d], H [hrs], m [m], s [s]"), servers = client.guilds.cache.size, lang = ops.lang.commands.botinfo, users = client.users.cache.size, canales = client.channels.cache.size, voz = client.voice.connections.size, emojis = client.emojis.cache.size, version = require('../package.json').version, discordjs = require('discord.js').version, cpu = `${Math.round(process.cpuUsage().user / 1024 / 1024)}%`, memory = `${Math.round((process.memoryUsage().heapUsed / 1024 / 1024).toString().slice(0,6))} MB`, invite = await client.generateInvite(["ADMINISTRATOR"]), main = new ops.Discord.MessageEmbed() .setAuthor(client.user.username, client.user.displayAvatarURL({dynamic:true})) .addField('⁉️ ' + lang.statistics, `>>> **EL RISAS, OswaldoYT** ${lang.owner}\n**${servers.toLocaleString()}** ${lang.guilds}\n**${users.toLocaleString()}** ${lang.users}\n**${canales.toLocaleString()}** ${lang.channels}\n**${emojis.toLocaleString()}** Emojis\n**${client.comandos.size.toLocaleString()}** ${lang.commands}\n**${client.eventos.size.toLocaleString()}** ${lang.events}\n**${actividad}** ${lang.uptime}\n**${Math.round(message.client.ws.ping)}ms** Ping\n**${voz}** ${lang.connections.toLocaleString()}\n**${version}** ${lang.version}\n**${discordjs}** Discord.JS\n**${ops.prefix}** Prefix\n**${memory}** ${lang.usage}\n**${cpu}** CPU`, true) .addField('🔧 LINKS', `>>> [Invite](${invite})\n[Discord](https://invite.gg/bahiano)`, true) .setColor(0x00ffff) .setFooter(ops.lang.events.message.isMentioned.footer + require("../package.json").version, client.user.displayAvatarURL({dynamic:true})) .setTimestamp() message.channel.send(main) }
1.554688
2
webpack.config.js
searchsam/conducir
0
5191
import path from "path"; import webpack from "webpack"; import HtmlWebpackPlugin from "html-webpack-plugin"; import MiniCssExtractPlugin from "mini-css-extract-plugin"; export default { mode: "production", devtool: "source-map", entry: [path.resolve(__dirname, "./client/src/app/index.js")], target: "web", output: { path: path.resolve(__dirname, "./client/dist"), publicPath: "/", filename: "bundle.js" }, plugins: [ new MiniCssExtractPlugin(), new HtmlWebpackPlugin({ template: "./client/src/app/index.html", inject: true }) ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ["babel-loader"] }, { test: /\.css$/, use: ["style-loader", "css-loader"] }, { test: /\.[s]css$/, use: [ MiniCssExtractPlugin.loader, "style-loader", "css-loader", "sass-loader" ] } ] } };
0.917969
1
src/server/controllers/SessionController.js
LIGL06/RunaTest
0
5199
import jwt from 'jsonwebtoken'; import Router from 'koa-router'; import moment from 'moment-timezone'; import bcrypt from 'bcrypt'; import { logger } from '../modules'; import User from '../models/User'; require('dotenv') .config(); const SessionController = Router({ prefix: '/session' }); SessionController.post('/register', async (ctx) => { const payload = { ...ctx.request.body }; const [user] = await User.get({ email: payload.email }); if (!user) { await new Promise((resolve, reject) => { bcrypt.hash(payload.password, 10, async (err, hash) => { if (err) reject(err); const userFields = { legalName: payload.legalName, legalRfc: payload.legalRfc, password: <PASSWORD>, email: payload.email, created_at: moment.tz('America/Monterrey') .format('YYYY-MM-DD HH:mm:ss'), admin: false }; try { await User.create(userFields); logger.info('New user registration', { ...userFields }); ctx.body = { ...userFields }; resolve(); } catch { reject(new Error('Create User Error')); } }); }); } else { ctx.status = 401; ctx.body = { error: 'Usuario registrado' }; } }); SessionController.post('/login', async (ctx) => { const payload = { ...ctx.request.body }; if (!ctx.request.body.password) { ctx.status = 401; ctx.body = { error: 'No password sent' }; return; } let status = false; const [user] = await User.get({ email: payload.email }); if (!user) { ctx.status = 401; ctx.body = { error: 'Invalid credentials' }; return; } const session = { user: { id: user.id, legalName: user.legalName, legalRfc: user.legalRfc, email: user.email, admin: user.admin } }; await new Promise((resolve, reject) => { bcrypt.compare(payload.password, user.password).then((res) => { if (res) { status = true; jwt.sign(session, process.env.JWT_SIGN, { expiresIn: '2h' }, (err, token) => { if (err) reject(err); logger.info(`Session created: ${ session.user.legalName }, ${ session.user.legalRfc }`); ctx.body = { session, token }; resolve(); }); } else { ctx.status = 401; ctx.body = { error: 'Invalid credentials' }; resolve(); } }); }); }); export default SessionController;
1.523438
2
public/js/colorPicker.js
Hugocsundberg/CGWU
0
5207
const colorButtons = document.querySelectorAll('.color-buttons label .button'); colorButtons.forEach((button) => { button.addEventListener('click', (e) => { if (e.target.parentElement.parentElement.classList.contains('gray')) { document.querySelector('section.section-4 .bg-image img').src = 'public/images/bg/color/Studio-gray.webp'; } else if (e.target.parentElement.parentElement.classList.contains('green')) { document.querySelector('section.section-4 .bg-image img').src = 'public/images/bg/color/Studio-green.webp'; } else if (e.target.parentElement.parentElement.classList.contains('red')) { document.querySelector('section.section-4 .bg-image img').src = 'public/images/bg/color/Studio-red.webp'; } else if (e.target.parentElement.parentElement.classList.contains('blue')) { document.querySelector('section.section-4 .bg-image img').src = 'public/images/bg/color/Studio-blue.webp'; } }); });
1.335938
1
resources/js/app.js
ezitek-solutions/laravel-starter-kit-bootstrap-vue
0
5215
require('./bootstrap'); import { createApp } from 'vue'; createApp({ data() { return { greeting: 'Hello World!' }; } }).mount('#app');
0.765625
1
src/components/Dir.js
kuhnuri/kuhnuri-cms-frontend
1
5223
import React, { Component } from 'react'; class Dir extends Component { toggle() { if (!!this.props.children || this.props.node.expanded) { this.props.toggle(this.props.project, this.props.node) } else { this.props.loadAndToggle(this.props.project, this.props.node) } } render() { if (this.props.node.type === 'DIRECTORY') { return ( <li> <span onClick={() => this.toggle()} className={[ 'controller', this.props.node.expanded ? 'expanded' : 'collapsed' ].join(' ')}> [{this.props.node.expanded ? '-' : '+'}]</span> <span>{this.props.node.name}</span> {(this.props.node.expanded && this.props.node.children) && <ul>{this.props.node.children.map(file => <Dir key={file.path} {...this.props} node={file} />)}</ul> } </li> ) } else { return ( <li className={[ this.props.node.active ? 'active' : null ].join(' ')}> <span className={'controller'}>&nbsp;&nbsp;&nbsp;</span> <span onClick={() => this.props.open(this.props.project.path, this.props.node.path)}>{this.props.node.name}</span> </li> ) } } } export default Dir
1.515625
2
lib/reports/ReportCountSummaryTurningMovement.js
CityofToronto/bdit_flashcrow
6
5231
/* eslint-disable class-methods-use-this */ import ArrayUtils from '@/lib/ArrayUtils'; import { ReportBlock, ReportType } from '@/lib/Constants'; import ReportBaseFlow from '@/lib/reports/ReportBaseFlow'; import ReportBaseFlowDirectional from '@/lib/reports/ReportBaseFlowDirectional'; import { indexRangeHourOfDay, indexRangePeakTime, } from '@/lib/reports/time/ReportTimeUtils'; import TimeFormatters from '@/lib/time/TimeFormatters'; const REGEX_PX = /PX (\d+)/; /** * Subclass of {@link ReportBaseFlow} for the Turning Movement Count Summary Report. * * @see https://www.notion.so/bditto/Turning-Movement-Count-Summary-Report-d9bc143ed7e14acc894a4c0c0135c8a4 */ class ReportCountSummaryTurningMovement extends ReportBaseFlow { type() { return ReportType.COUNT_SUMMARY_TURNING_MOVEMENT; } static sumIndexRange(countData, indexRange) { const { lo, hi } = indexRange; if (lo === hi) { const data = ReportBaseFlowDirectional.emptyTmcRecord(); return ReportBaseFlowDirectional.computeMovementAndVehicleTotals(data); } const countDataPoints = countData .slice(lo, hi) .map(({ data }) => data); return ArrayUtils.sumObjects(countDataPoints); } static avgPerHourIndexRange(countData, indexRange) { const { lo, hi } = indexRange; if (lo === hi) { const data = ReportBaseFlowDirectional.emptyTmcRecord(); return ReportBaseFlowDirectional.computeMovementAndVehicleTotals(data); } const sum = ReportCountSummaryTurningMovement.sumIndexRange(countData, indexRange); const avg = {}; const n = hi - lo; Object.entries(sum).forEach(([key, value]) => { avg[key] = Math.round(ReportBaseFlow.ROWS_PER_HOUR * value / n); }); return ReportBaseFlowDirectional.computeMovementAndVehicleTotals(avg); } static sumSection(totaledData, indexRange) { const sum = ReportCountSummaryTurningMovement.sumIndexRange( totaledData, indexRange, ); const timeRange = ReportCountSummaryTurningMovement.timeRange( totaledData, indexRange, ); return { sum, timeRange, }; } static avgSection(countData, indexRange) { const avg = ReportCountSummaryTurningMovement.avgPerHourIndexRange( countData, indexRange, ); const timeRange = ReportCountSummaryTurningMovement.timeRange( countData, indexRange, ); return { avg, timeRange, }; } static transformCountData(countData) { const totaledData = ReportBaseFlowDirectional.computeAllMovementAndVehicleTotals( countData, ); const indicesAm = indexRangeHourOfDay(totaledData, 0, 12); const indicesAmPeak = indexRangePeakTime( totaledData, indicesAm, { hours: 1 }, ({ VEHICLE_TOTAL }) => VEHICLE_TOTAL, ); const amPeak = ReportCountSummaryTurningMovement.sumSection( totaledData, indicesAmPeak, ); const indicesAm2Hour = indexRangePeakTime( totaledData, indicesAm, { hours: 2 }, ({ VEHICLE_TOTAL }) => VEHICLE_TOTAL, ); const am = ReportCountSummaryTurningMovement.sumSection( totaledData, indicesAm2Hour, ); const indicesPm = indexRangeHourOfDay(totaledData, 12, 24); const indicesPmPeak = indexRangePeakTime( totaledData, indicesPm, { hours: 1 }, ({ VEHICLE_TOTAL }) => VEHICLE_TOTAL, ); const pmPeak = ReportCountSummaryTurningMovement.sumSection( totaledData, indicesPmPeak, ); const indicesPm2Hour = indexRangePeakTime( totaledData, indicesPm, { hours: 2 }, ({ VEHICLE_TOTAL }) => VEHICLE_TOTAL, ); const pm = ReportCountSummaryTurningMovement.sumSection( totaledData, indicesPm2Hour, ); /* * If we total, average, round in that order, totaled values will appear off, even though it's * more correct from a statistical / analytical perspective to do it that way. As such, we * average, round, and then total at the end, to ensure sums look right. * * The assumption is that the error introduced by this process is acceptable. (In any case, * we're not adding *that* many numbers together, so it is at the very least small in an * absolute sense.) */ const indicesOffHours = { lo: indicesAm2Hour.hi, hi: indicesPm2Hour.lo }; const offHours = ReportCountSummaryTurningMovement.avgSection( countData, indicesOffHours, ); const indicesAll = { lo: 0, hi: totaledData.length }; const all = ReportCountSummaryTurningMovement.sumSection( totaledData, indicesAll, ); return { amPeak, pmPeak, offHours, am, pm, all, }; } static getTrafficSignalId(countLocation) { if (countLocation === null) { return null; } const { description } = countLocation; const match = REGEX_PX.exec(description); if (match === null) { return null; } const px = parseInt(match[1], 10); if (Number.isNaN(px)) { return null; } return px; } transformData(study, { countLocation, counts, studyData }) { if (counts.length === 0) { return []; } const [count] = counts; const { date, hours, id } = count; const px = ReportCountSummaryTurningMovement.getTrafficSignalId(countLocation); const countData = studyData.get(id); const stats = ReportCountSummaryTurningMovement.transformCountData(countData); return { date, hours, px, stats, }; } generateCsv(count, { stats }) { const { amPeak, pmPeak, offHours, am, pm, all, } = stats; const dataKeys = Object.keys(amPeak.sum); const dataColumns = dataKeys.map(key => ({ key, header: key })); const columns = [ { key: 'name', header: 'Name' }, { key: 'start', header: 'Start' }, { key: 'end', header: 'End' }, ...dataColumns, ]; const rows = [ { name: 'AM PEAK', ...amPeak.timeRange, ...amPeak.sum, }, { name: 'PM PEAK', ...pmPeak.timeRange, ...pmPeak.sum, }, { name: 'OFF HOUR AVG', ...offHours.timeRange, ...offHours.avg, }, { name: '2 HOUR AM', ...am.timeRange, ...am.sum, }, { name: '2 HOUR PM', ...pm.timeRange, ...pm.sum, }, { name: 'TOTAL SUM', ...all.timeRange, ...all.sum, }, ]; return { columns, rows }; } // PDF GENERATION static getTableHeader() { const dirs = [ { value: 'Exits', style: { bl: true } }, { value: 'Left' }, { value: 'Thru' }, { value: 'Right' }, { value: 'Total' }, ]; return [ [ { value: 'Time Period', rowspan: 2, style: { br: true }, }, { value: 'Vehicle Type', rowspan: 2, }, { value: 'NORTHBOUND', colspan: 5, style: { bl: true }, }, { value: 'EASTBOUND', colspan: 5, style: { bl: true }, }, { value: 'SOUTHBOUND', colspan: 5, style: { bl: true }, }, { value: 'WESTBOUND', colspan: 5, style: { bl: true }, }, { value: null, rowspan: 2, style: { bl: true }, }, { value: null, colspan: 5, }, ], [ ...dirs, ...dirs, ...dirs, ...dirs, { value: 'N' }, { value: 'E' }, { value: 'S' }, { value: 'W' }, { value: 'Total' }, ], ]; } static getTableSectionLayout(sectionData, timeRange, title, shade) { const timeRangeHuman = TimeFormatters.formatRangeTimeOfDay(timeRange); const dirs = ['N', 'E', 'S', 'W']; const turns = ['L', 'T', 'R', 'TOTAL']; return [ [ { value: timeRangeHuman, header: true, style: { br: true, shade }, }, { value: 'CAR', header: true, style: { shade } }, ...Array.prototype.concat.apply([], dirs.map(dir => [ { value: sectionData[`${dir}_CARS_EXITS`], style: { bl: true, shade }, }, ...turns.map(turn => ({ value: sectionData[`${dir}_CARS_${turn}`], style: { shade }, })), ])), { value: 'PED', header: true, style: { bl: true, br: true, shade } }, ...dirs.map(dir => ({ value: sectionData[`${dir}_PEDS`], style: { shade }, })), { value: sectionData.PEDS_TOTAL, style: { bl: true, shade } }, ], [ { value: title, header: true, rowspan: 2, style: { br: true, shade }, }, { value: 'TRUCK', header: true, style: { shade } }, ...Array.prototype.concat.apply([], dirs.map(dir => [ { value: sectionData[`${dir}_TRUCK_EXITS`], style: { bl: true, shade }, }, ...turns.map(turn => ({ value: sectionData[`${dir}_TRUCK_${turn}`], style: { shade }, })), ])), { value: 'BIKE', header: true, style: { bl: true, br: true, shade } }, ...dirs.map(dir => ({ value: sectionData[`${dir}_BIKE`], style: { shade }, })), { value: sectionData.BIKE_TOTAL, style: { bl: true, shade } }, ], [ { value: 'BUS', header: true, style: { shade } }, ...Array.prototype.concat.apply([], dirs.map(dir => [ { value: sectionData[`${dir}_BUS_EXITS`], style: { bl: true, shade }, }, ...turns.map(turn => ({ value: sectionData[`${dir}_BUS_${turn}`], style: { shade }, })), ])), { value: 'OTHER', header: true, style: { bl: true, br: true, shade } }, ...dirs.map(dir => ({ value: sectionData[`${dir}_OTHER`], style: { shade }, })), { value: sectionData.OTHER_TOTAL, style: { bl: true, shade } }, ], [ { value: sectionData.TOTAL, header: true, style: { br: true, shade }, }, { value: 'TOTAL', header: true, style: { bt: true, shade } }, ...Array.prototype.concat.apply([], dirs.map(dir => [ { value: sectionData[`${dir}_VEHICLE_EXITS`], style: { bt: true, bl: true, shade }, }, ...turns.map(turn => ({ value: sectionData[`${dir}_VEHICLE_${turn}`], style: { bt: true, shade }, })), ])), { value: sectionData.VEHICLE_TOTAL, style: { bl: true, bt: true, br: true, bb: true, shade, }, }, { value: null, colspan: 5, style: { shade }, }, ], [ { value: null, colspan: 28 }, ], ]; } static getTableOptions(reportData) { const header = ReportCountSummaryTurningMovement.getTableHeader(); const body = [ ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.all.sum, reportData.all.timeRange, 'TOTAL SUM', false, ), ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.amPeak.sum, reportData.amPeak.timeRange, 'AM PEAK', true, ), ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.pmPeak.sum, reportData.pmPeak.timeRange, 'PM PEAK', false, ), ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.offHours.avg, reportData.offHours.timeRange, 'OFF HOUR AVG', true, ), ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.am.sum, reportData.am.timeRange, '2 HOUR AM', false, ), ...ReportCountSummaryTurningMovement.getTableSectionLayout( reportData.pm.sum, reportData.pm.timeRange, '2 HOUR PM', true, ), ]; return { tableStyle: { fontSize: '2xs' }, columnStyles: [ { c: 0 }, { c: 1 }, { c: 22 }, ], header, body, }; } static getCountMetadataOptions({ date, hours, px, stats, }) { const dateStr = TimeFormatters.formatDefault(date); const dayOfWeekStr = TimeFormatters.formatDayOfWeek(date); const fullDateStr = `${dateStr} (${dayOfWeekStr})`; const hoursStr = hours === null ? null : hours.description; const pxStr = px === null ? null : px.toString(); const { BIKE_TOTAL, PEDS_TOTAL, TOTAL, VEHICLE_TOTAL, } = stats.all.sum; const entries = [ { cols: 3, name: 'Date', value: fullDateStr }, { cols: 3, name: 'Study Hours', value: hoursStr }, { cols: 6, name: 'Traffic Signal Number', value: pxStr }, { cols: 3, name: 'Total Volume', value: TOTAL }, { cols: 3, name: 'Total Vehicles', value: VEHICLE_TOTAL }, { cols: 3, name: 'Total Cyclists', value: BIKE_TOTAL }, { cols: 3, name: 'Total Pedestrians', value: PEDS_TOTAL }, ]; return { entries }; } generateLayoutContent(count, reportData) { const countMetadataOptions = ReportCountSummaryTurningMovement.getCountMetadataOptions( reportData, ); const { stats } = reportData; const tableOptions = ReportCountSummaryTurningMovement.getTableOptions(stats); return [ { type: ReportBlock.METADATA, options: countMetadataOptions }, { type: ReportBlock.TABLE, options: tableOptions }, ]; } } export default ReportCountSummaryTurningMovement;
1.648438
2
src/obj/workspace/Dataset.js
kankanol1/geshu
0
5239
export default class Dataset { x; y; id; name; }
0.086914
0
tests/unit/components/Form.spec.js
willmendesneto/star-wars-redux-app
0
5247
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import Form from '../../../app/components/Form'; describe('Form component: Form', () => { it('should save values grabbed with captureValues in state()', () => { const form = shallow(<Form />); const instance = form.instance(); instance.captureValues({ foo: 'bar' }); instance.captureValues({ foo2: 'bar2' }); expect(form.state('values')).to.be.deep.equal({ foo: 'bar', foo2: 'bar2' }); }); it('should remove blank or undefined values from state', () => { const form = shallow(<Form />); const instance = form.instance(); instance.captureValues({ foo: 'bar', foo2: 'bar2' }); instance.captureValues({ foo: undefined }); expect(form.state('values')).to.be.deep.equal({ foo2: 'bar2' }); instance.captureValues({ foo2: '' }); expect(form.state('values')).to.be.deep.equal({}); }); it('should pass event parameters into "onSubmit" method', () => { const callback = sinon.spy(); const form = shallow(<Form onSubmit={callback} />); const instance = form.instance(); instance.captureValues({ foo: 'bar' }); form.simulate('submit'); expect(callback.calledWith(sinon.match.any, { foo: 'bar' })).to.eql(true); }); });
1.5625
2
sjsc/src/test/resources/testinput/endtoend/printstub.js
msridhar/SJS
34
5255
print("Hello, via print()");
0.085938
0
test/R2Amount.js
CharlesEricADAM/node-td-rcm
2
5263
import test from 'ava'; import R2Amount from '../lib/R2Amount'; import IndicativeArea from '../lib/indicativeArea/IndicativeArea'; import AmountIndicativeArea from '../lib/indicativeArea/AmountIndicativeArea'; import {TaxCredit, FixedIncomeProducts, CrowdfundingProducts, Fees} from '../lib/amountItems'; const indicativeArea = new IndicativeArea({ year: '2016', siret: '80426417400017', type: 1 }); const amountIndicativeArea = indicativeArea.amountR2(); test('set data', t => { const taxCredit = new TaxCredit({AD: 10}); const fixedIncomeProducts = new FixedIncomeProducts({AR: 142, AS: 10}); const crowdfundingProducts = new CrowdfundingProducts({KR: 153, KS: 21}); const fees = new Fees(9); const r2 = new R2Amount({amountIndicativeArea, taxCredit, fixedIncomeProducts, crowdfundingProducts, fees}); t.true(r2.amountIndicativeArea instanceof AmountIndicativeArea); t.true(r2.taxCredit instanceof TaxCredit); t.true(r2.fixedIncomeProducts instanceof FixedIncomeProducts); t.true(r2.crowdfundingProducts instanceof CrowdfundingProducts); t.true(r2.fees instanceof Fees); }); test('validation', t => { const taxCredit = new TaxCredit({AD: 10}); const fixedIncomeProducts = new FixedIncomeProducts({AR: 142, AS: 10}); const crowdfundingProducts = new CrowdfundingProducts({KR: 153, KS: 21}); const fees = new Fees(9); const r2 = new R2Amount({amountIndicativeArea, taxCredit, fixedIncomeProducts, crowdfundingProducts, fees}); t.true(r2.validation()); }); test('export', t => { const taxCredit = new TaxCredit({AD: 10}); const fixedIncomeProducts = new FixedIncomeProducts({AR: 142, AS: 10}); const crowdfundingProducts = new CrowdfundingProducts({KR: 153, KS: 21}); const fees = new Fees(9); const r2 = new R2Amount({amountIndicativeArea, taxCredit, fixedIncomeProducts, crowdfundingProducts, fees}); require('fs').writeFileSync('toto.txt', JSON.stringify(r2.export())); t.deepEqual(r2.export(), [ '2016', '80426417400017', 1, ' ', ' ', ' ', ' ', 'R2', '0000000000', '0000000000', '0000000010', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', ' ', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000000', '0000000142', '0000000010', '0000000153', '0000000021', ' ', '0000000000', '0000000000', '0000000009', '0000000000', '0000000000', ' ' ]); });
1.421875
1
771_c.js
nszyc/leetcode-javascript-solution
0
5271
var numJewelsInStones = function(J, S) { var count = 0 for (var i = 0; i < S.length; i++) { var s = S[i] var isJewel = false for (var j = 0; j < J.length; j++) { if (s == J[j]) { isJewel = true } } if (isJewel) { count++ } } return count }
1.484375
1
app/extensions/storidge/views/profiles/create/createProfileController.js
lukaspj/portainer
4
5279
angular.module('extension.storidge') .controller('StoridgeCreateProfileController', ['$scope', '$state', '$transition$', 'Notifications', 'StoridgeProfileService', function ($scope, $state, $transition$, Notifications, StoridgeProfileService) { $scope.state = { NoLimit: true, LimitIOPS: false, LimitBandwidth: false, ManualInputDirectory: false, actionInProgress: false }; $scope.RedundancyOptions = [ { value: 2, label: '2-copy' }, { value: 3, label: '3-copy' } ]; $scope.create = function () { var profile = $scope.model; if (!$scope.state.LimitIOPS) { delete profile.MinIOPS; delete profile.MaxIOPS; } if (!$scope.state.LimitBandwidth) { delete profile.MinBandwidth; delete profile.MaxBandwidth; } $scope.state.actionInProgress = true; StoridgeProfileService.create(profile) .then(function success() { Notifications.success('Profile successfully created'); $state.go('storidge.profiles'); }) .catch(function error(err) { Notifications.error('Failure', err, 'Unable to create profile'); }) .finally(function final() { $scope.state.actionInProgress = false; }); }; $scope.updatedName = function() { if (!$scope.state.ManualInputDirectory) { var profile = $scope.model; profile.Directory = '/cio/' + profile.Name; } }; $scope.updatedDirectory = function() { if (!$scope.state.ManualInputDirectory) { $scope.state.ManualInputDirectory = true; } }; function initView() { var profile = new StoridgeProfileDefaultModel(); profile.Name = $transition$.params().profileName; profile.Directory = '/cio/' + profile.Name; $scope.model = profile; } initView(); }]);
1.320313
1
lib/attributes.js
aijle/react-native-svg
1
5287
function arrayDiffer(a, b) { if (!a || !b) { return true; } if (a.length !== b.length) { return true; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return true; } } return false; } function fontDiffer(a, b) { if (a === b) { return false; } return ( a.fontStyle !== b.fontStyle || a.fontVariant !== b.fontVariant || a.fontWeight !== b.fontWeight || a.fontStretch !== b.fontStretch || a.fontSize !== b.fontSize || a.fontFamily !== b.fontFamily || a.textAnchor !== b.textAnchor || a.textDecoration !== b.textDecoration || a.letterSpacing !== b.letterSpacing || a.wordSpacing !== b.wordSpacing || a.kerning !== b.kerning || a.fontVariantLigatures !== b.fontVariantLigatures || a.fontData !== b.fontData || a.fontFeatureSettings !== b.fontFeatureSettings ); } const ViewBoxAttributes = { minX: true, minY: true, vbWidth: true, vbHeight: true, align: true, meetOrSlice: true }; const NodeAttributes = { name: true, matrix: { diff: arrayDiffer }, scaleX: true, scaleY: true, opacity: true, clipRule: true, clipPath: true, propList: { diff: arrayDiffer }, responsible: true }; const FillAndStrokeAttributes = { fill: { diff: arrayDiffer }, fillOpacity: true, fillRule: true, stroke: { diff: arrayDiffer }, strokeOpacity: true, strokeWidth: true, strokeLinecap: true, strokeLinejoin: true, strokeDasharray: { diff: arrayDiffer }, strokeDashoffset: true, strokeMiterlimit: true }; const RenderableAttributes = { ...NodeAttributes, ...FillAndStrokeAttributes }; const GroupAttributes = { ...RenderableAttributes, font: { diff: fontDiffer } }; const UseAttributes = { ...RenderableAttributes, href: true, width: true, height: true }; const SymbolAttributes = { ...ViewBoxAttributes, name: true }; const PathAttributes = { ...RenderableAttributes, d: true }; const TextSpecificAttributes = { ...RenderableAttributes, alignmentBaseline: true, baselineShift: true, verticalAlign: true, lengthAdjust: true, textLength: true }; const TextAttributes = { ...TextSpecificAttributes, font: { diff: fontDiffer }, deltaX: arrayDiffer, deltaY: arrayDiffer, rotate: arrayDiffer, positionX: arrayDiffer, positionY: arrayDiffer }; const TextPathAttributes = { ...TextSpecificAttributes, href: true, startOffset: true, method: true, spacing: true, side: true, midLine: true }; const TSpanAttibutes = { ...TextAttributes, content: true }; const ClipPathAttributes = { name: true }; const GradientAttributes = { ...ClipPathAttributes, gradient: { diff: arrayDiffer }, gradientUnits: true, gradientTransform: { diff: arrayDiffer } }; const LinearGradientAttributes = { ...GradientAttributes, x1: true, y1: true, x2: true, y2: true }; const RadialGradientAttributes = { ...GradientAttributes, fx: true, fy: true, rx: true, ry: true, cx: true, cy: true, r: true }; const CircleAttributes = { ...RenderableAttributes, cx: true, cy: true, r: true }; const EllipseAttributes = { ...RenderableAttributes, cx: true, cy: true, rx: true, ry: true }; const ImageAttributes = { ...RenderableAttributes, x: true, y: true, width: true, height: true, src: true, align: true, meetOrSlice: true }; const LineAttributes = { ...RenderableAttributes, x1: true, y1: true, x2: true, y2: true }; const RectAttributes = { ...RenderableAttributes, x: true, y: true, width: true, height: true, rx: true, ry: true }; export { PathAttributes, TextAttributes, TSpanAttibutes, TextPathAttributes, GroupAttributes, ClipPathAttributes, CircleAttributes, EllipseAttributes, ImageAttributes, LineAttributes, RectAttributes, UseAttributes, SymbolAttributes, LinearGradientAttributes, RadialGradientAttributes, ViewBoxAttributes };
1.648438
2
server.js
ViniciusGuterres/dashboard-covid
0
5295
const express = require('express'); const app = express(); app.use(express.static("./public")); app.set("view engine", "ejs"); app.get("/", function (req, res) { res.render("pages/index"); }) app.get("/dashboard", function (req, res){ res.render("pages/dashboard"); }) app.get("/avisos", function (req, res) { res.render("pages/avisos"); }) app.get("/cadastrar", function (req, res) { res.render("pages/cadastro"); }) app.listen(8080); console.log("rodando");
1.070313
1
src/tasks/peer.js
ddnlink/capistrano
0
5303
/** * 本代码是节点部署脚本 * * 使用方法: * * ``` * $ deploy peer * ``` */ "use strict"; import path from "path"; import plan, { runtime } from "@ddn/flightplan"; import config from "../config"; import initPath from "../plans/initPath"; import useServer from "../plans/useServer"; import upload from "../plans/upload"; import uploadPeer from "../plans/upload-peer"; const userConfig = config.userConfig; function deployment(yargs) { const argv = yargs .reset() .option("e", { alias: "env", description: "init the env`s remote server", }) .help("h") .alias("h", "help").argv; const commands = argv._; makePlan(commands); run(commands); } function makePlan(commands) { const stage = commands[0]; const isPrepare = commands[1] && commands[1] === "prepare"; console.log("isPrepare", isPrepare); const { application, uploadFileName, deployTo, releasesDirectory, keepReleases, currentDirectory, sharedDirectory, } = userConfig; const options = userConfig[stage]; const targetPath = path.join(deployTo, application); const currentPath = path.join(targetPath, currentDirectory); const releasesPath = path.join(targetPath, releasesDirectory); const sharedPath = path.join(targetPath, sharedDirectory); // 请先在服务器端建立该目录 plan.target(stage, options.target); // 远程 前端处理 initPath(userConfig); // 上传 peer 安装包 uploadPeer(userConfig); if (isPrepare) { // 上传配置文件 upload(userConfig); // 上传Nginx配置到服务器 useServer(userConfig); } // 与 current 有少许差别 plan.remote((remote) => { // 拷贝新代码 remote.with(`cd ${targetPath}`, () => { // 断开当前文件夹与前一版本的连接,然后建立对当前版本的软连接(先要停止服务) if (!isPrepare) { remote.log("DDN stopping..."); remote.with(`cd ${currentDirectory}`, () => { remote.exec("./ddnd stop"); remote.log("DDN stoped!"); }); } remote.log("Tar and create system link to current..."); remote.with(`cd ${releasesPath}`, () => { const file = uploadFileName + userConfig.extendName; remote.exec(`tar zxf ${file}`); // 如果想显示解压文件,加上 v 参数 }); const currentRepoPath = path.join(releasesPath, uploadFileName); remote.exec( "rm -rf " + currentDirectory + " && ln -s " + currentRepoPath + " " + currentDirectory ); }); // current 安装并处理链接 remote.with(`cd ${currentPath}`, () => { remote.log("link shared folders and files..."); // 链接文件夹,有些文件夹不需要连接,比如:打包好的节点中 node_modules 是不能共享的,应该排除软连接保护 for (const dir of userConfig.linkedDirs) { remote.exec( `mkdir -p ${sharedPath}/${dir}` ); // 文件夹不存在,链接成功也没用 remote.exec(`rm -rf ${dir}`); // 最新链接的肯定不存在 remote.exec( `ln -s ${sharedPath}/${dir} ./` ); } // 上传生产环境的配置。第一次初始化的时候,或者需要修改的时候,就提供 prepare 命令,上传或更新最新配置文件 if (isPrepare) { remote.with(`cd ${sharedPath}`, () => { if (remote.runtime.config) { remote.exec(`rm -f .ddnrc.js`); // 解压文件 remote.exec( `tar zxvf configures.tar.gz .` ); remote.log(`copying ${remote.runtime.config}`); remote.exec(`mkdir -p ./config`); remote.exec(`cp ./configures/${remote.runtime.config} ./config/.ddnrc.js`); // 清理 remote.log("删除配置文件"); remote.exec(`rm -rf configures`); remote.exec( `rm configures.tar.gz` ); } }) } // 链接生产环境的配置,记得通过上面的命令,先进行上传 for (const file of userConfig.linkedFiles) { remote.exec(`rm -f ${file}`); remote.exec( // 这里使用连接程序会出错 `ln -s ${sharedPath}/config/${file} ./` `cp ${sharedPath}/config/${file} ./` ); } }); }); // 构建、启动、停止等操作 plan.remote((remote) => { // /current 安装并处理链接 remote.with(`cd ${currentPath}`, () => { // 初始化配置。注5:这里使用sudo命令,兼容localnet,本地需要使用命令行密码。 if (isPrepare) { // remote.sudo("chmod u+x init/*.sh && chmod 755 ddnd && ./ddnd configure", { // user: "root", // silent: true, // failsafe: true, // }); } // 启动命令 // remote.exec("./ddnd start"); }); }); } function run(commands) { plan.run("default", commands[0]); } export default deployment;
1.5625
2
projects/capstone-project/src/client/js/processData.js
ysvist/travel-app
0
5311
const checkDate = (arrivalDate) => { const now = new Date(); const arrivalDateEpoch = new Date(arrivalDate); if (!arrivalDate || arrivalDateEpoch < now) { return false; } else { return calculateTravelTime({ now, arrivalDateEpoch }); } }; function calculateTravelTime({ now, arrivalDateEpoch }) { const millisecondsToArrival = arrivalDateEpoch - now; // convert milliseconds to number of days, rounding up to the nearest full day const daysToArrival = Math.ceil(millisecondsToArrival / 1000 / 60 / 60 / 24); Client.updateCountdown({ daysToArrival }); return daysToArrival; } async function getLocationData(userQuery) { const response = await fetch("http://localhost:8081/userData", { method: "POST", credentials: "same-origin", mode: "cors", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ input: userQuery }), }); const responseJSON = await response.json(); return responseJSON; } async function getForecastData(locationData, daysToDeparture) { const response = await fetch("http://localhost:8081/travelForecast", { method: "POST", credentials: "same-origin", mode: "cors", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ location: locationData, days: daysToDeparture }), }); const responseJSON = await response.json(); return responseJSON; } async function getPhoto(locationData) { const response = await fetch("http://localhost:8081/destinationImage", { method: "POST", credentials: "same-origin", mode: "cors", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: locationData }), }); const responseJSON = await response.json(); return responseJSON; } export { checkDate, getForecastData, getLocationData, getPhoto };
1.789063
2
node_modules/bower/node_modules/insight/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/test/string/raw/shim.js
andela-jejezie/peopleProject
443
5319
// Partially taken from: // https://github.com/paulmillr/es6-shim/blob/master/test/string.js 'use strict'; module.exports = function (t, a) { var callSite = []; callSite.raw = ["The total is ", " ($", " with tax)"]; a(t(callSite, '{total}', '{total * 1.01}'), 'The total is {total} (${total * 1.01} with tax)'); callSite.raw = []; a(t(callSite, '{total}', '{total * 1.01}'), ''); };
1.148438
1
node_modules/imask/esm/controls/html-mask-element.js
qiwi3268/Expertise-2.0
0
5327
import { d as _inherits, e as _createSuper, a as _classCallCheck, _ as _createClass } from '../_rollupPluginBabelHelpers-6ccb1f64.js'; import MaskElement from './mask-element.js'; import IMask from '../core/holder.js'; /** Bridge between HTMLElement and {@link Masked} */ var HTMLMaskElement = /*#__PURE__*/function (_MaskElement) { _inherits(HTMLMaskElement, _MaskElement); var _super = _createSuper(HTMLMaskElement); /** Mapping between HTMLElement events and mask internal events */ /** HTMLElement to use mask on */ /** @param {HTMLInputElement|HTMLTextAreaElement} input */ function HTMLMaskElement(input) { var _this; _classCallCheck(this, HTMLMaskElement); _this = _super.call(this); _this.input = input; _this._handlers = {}; return _this; } /** */ // $FlowFixMe https://github.com/facebook/flow/issues/2839 _createClass(HTMLMaskElement, [{ key: "rootElement", get: function get() { return this.input.getRootNode ? this.input.getRootNode() : document; } /** Is element in focus @readonly */ }, { key: "isActive", get: function get() { //$FlowFixMe return this.input === this.rootElement.activeElement; } /** Returns HTMLElement selection start @override */ }, { key: "_unsafeSelectionStart", get: function get() { return this.input.selectionStart; } /** Returns HTMLElement selection end @override */ }, { key: "_unsafeSelectionEnd", get: function get() { return this.input.selectionEnd; } /** Sets HTMLElement selection @override */ }, { key: "_unsafeSelect", value: function _unsafeSelect(start, end) { this.input.setSelectionRange(start, end); } /** HTMLElement value @override */ }, { key: "value", get: function get() { return this.input.value; }, set: function set(value) { this.input.value = value; } /** Binds HTMLElement events to mask internal events @override */ }, { key: "bindEvents", value: function bindEvents(handlers) { var _this2 = this; Object.keys(handlers).forEach(function (event) { return _this2._toggleEventHandler(HTMLMaskElement.EVENTS_MAP[event], handlers[event]); }); } /** Unbinds HTMLElement events to mask internal events @override */ }, { key: "unbindEvents", value: function unbindEvents() { var _this3 = this; Object.keys(this._handlers).forEach(function (event) { return _this3._toggleEventHandler(event); }); } /** */ }, { key: "_toggleEventHandler", value: function _toggleEventHandler(event, handler) { if (this._handlers[event]) { this.input.removeEventListener(event, this._handlers[event]); delete this._handlers[event]; } if (handler) { this.input.addEventListener(event, handler); this._handlers[event] = handler; } } }]); return HTMLMaskElement; }(MaskElement); HTMLMaskElement.EVENTS_MAP = { selectionChange: 'keydown', input: 'input', drop: 'drop', click: 'click', focus: 'focus', commit: 'blur' }; IMask.HTMLMaskElement = HTMLMaskElement; export default HTMLMaskElement;
1.632813
2
test/index.test.js
rittme/lobato
2
5335
const fs = require("fs").promises; const aurelius = require("../src/index"); test("can correctly transform file to md", async () => { const origin = await fs.readFile("./test/testfile.js", { encoding: "utf-8" }); const expected = await fs.readFile("./test/expected.md", { encoding: "utf-8", }); expect(aurelius(origin, "javascript")).toEqual(expected); });
1.0625
1
src/index.js
georgiee/lab-pixicam
53
5343
var core = module.exports = { Camera: require('./camera'), World: require('./world'), Minimap: require('./minimap'), mixins: require('./mixins') }; global.pixicam = core;
0.279297
0
test/e2e/common/uid.js
1783cwf/electerm
6,095
5351
/** * output uid with os name prefix */ const { nanoid } = require('nanoid') const os = require('os').platform() module.exports = () => { return os + '_' + nanoid() }
0.789063
1
tools/generator-fluid/test/testApp.js
sycosquirl18/FluidFramework
2
5359
/*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const path = require("path"); const assert = require("yeoman-assert"); const helpers = require("yeoman-test"); const shell = require('shelljs'); describe("Yo fluid", function () { // increasing the timeout, since generation can sometimes exceed the default 2000ms. this.timeout(10000); describe("Unit", () => { describe("View - React - advanced", () => { let runContext; let oldCwd; before(() => { oldCwd = process.cwd(); runContext = helpers.run(path.join(__dirname, "../app/index.js")) .withPrompts({ dataObjectName: "foobar", viewFramework: "react", scaffolding: "advanced", }); return runContext; }); it("Produces the expected files", () => { const expectedFiles = [ "src/dataObject.tsx", "src/index.ts", "src/interface.ts", "src/view.tsx", ".gitignore", ".npmrc", "jest-puppeteer.config.js", "jest.config.js", "package.json", "README.md", "tsconfig.json", "webpack.config.js", ] assert.file(expectedFiles); const unexpectedFiles = [ "src/dataObject.ts", "src/view.ts", ] assert.noFile(unexpectedFiles); }); after(() => { process.chdir(oldCwd); runContext.cleanTestDirectory(); }); }); describe("View - React - beginner", () => { let runContext; let oldCwd; before(() => { oldCwd = process.cwd(); runContext = helpers.run(path.join(__dirname, "../app/index.js")) .withPrompts({ dataObjectName: "foobar", viewFramework: "react", scaffolding: "beginner", }); return runContext; }); it("Produces the expected files", () => { const expectedFiles = [ "src/dataObject.tsx", "src/index.ts", ".gitignore", ".npmrc", "jest-puppeteer.config.js", "jest.config.js", "package.json", "README.md", "tsconfig.json", "webpack.config.js", ] assert.file(expectedFiles); const unexpectedFiles = [ "src/dataObject.ts", "src/view.ts", ] assert.noFile(unexpectedFiles); }); after(() => { process.chdir(oldCwd); runContext.cleanTestDirectory(); }); }); describe("View - None - advanced", () => { let runContext; let oldCwd; before(() => { oldCwd = process.cwd(); runContext = helpers.run(path.join(__dirname, "../app/index.js")) .withPrompts({ dataObjectName: "foobar", viewFramework: "none", scaffolding: "advanced", }); return runContext; }); it("Produces the expected files", () => { const expectedFiles = [ "src/dataObject.ts", "src/index.ts", "src/interface.ts", "src/view.ts", ".gitignore", ".npmrc", "jest-puppeteer.config.js", "jest.config.js", "package.json", "README.md", "tsconfig.json", "webpack.config.js", ] assert.file(expectedFiles); const unexpectedFiles = [ "src/dataObject.tsx", "src/view.tsx", ] assert.noFile(unexpectedFiles); }); after(() => { process.chdir(oldCwd); runContext.cleanTestDirectory(); }); }); describe("View - None - beginner", () => { let runContext; let oldCwd; before(() => { oldCwd = process.cwd(); runContext = helpers.run(path.join(__dirname, "../app/index.js")) .withPrompts({ dataObjectName: "foobar", viewFramework: "none", scaffolding: "beginner", }); return runContext; }); it("Produces the expected files", () => { const expectedFiles = [ "src/dataObject.ts", "src/index.ts", ".gitignore", ".npmrc", "jest-puppeteer.config.js", "jest.config.js", "package.json", "README.md", "tsconfig.json", "webpack.config.js", ] assert.file(expectedFiles); const unexpectedFiles = [ "src/dataObject.tsx", "src/view.tsx", ] assert.noFile(unexpectedFiles); }); after(() => { process.chdir(oldCwd); runContext.cleanTestDirectory(); }); }); }); });
1.359375
1
client/tests/e2e/specs/subnav.js
CodeBag414/cloudradioo
0
5367
module.exports = { '@disabled': false, 'Subnav is hidden': function(client) { client .url(client.launch_url) .assert.hidden('.subnav') .end(); }, 'Show and close subnav': function(client) { client .url(client.launch_url) .resizeWindow(1500, 800) .click('.nav-cloudradioo') .pause(500) .assert.visible('.subnav') .click('.nav-cloudradioo') .pause(500) .assert.hidden('.subnav') .end(); }, 'Show correct subnav content': function(client) { client .url(client.launch_url) .resizeWindow(1500, 800) .click('.nav-cloudradioo') .pause(500) .assert.containsText('.option-elements.active', 'Discover New Music') .click('.nav-filter') .pause(500) .assert.containsText('.option-elements.active', 'Filter Your Taste') .click('.nav-history') .pause(500) .assert.containsText('.option-elements.active', 'History Of Your Tracks') .end(); } };
1.078125
1
server/services/offender/responses/index.js
uk-gov-mirror/ministryofjustice.prisoner-content-hub-frontend
0
5375
const { Offender } = require('./offender'); const { IncentivesSummary } = require('./incentives'); const { Balances } = require('./balances'); const { KeyWorker } = require('./keyWorker'); const { NextVisit } = require('./nextVisit'); const { ImportantDates } = require('./importantDates'); const { Timetable } = require('./timetable'); const { TimetableEvent } = require('./timetableEvent'); module.exports = { IncentivesSummary, Balances, Offender, KeyWorker, NextVisit, ImportantDates, Timetable, TimetableEvent, };
0.519531
1
.data-dist/mods/gen7/rulesets.js
Muhframos/pokemon-showdown
0
5383
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); const Rulesets = { standard: { inherit: true, ruleset: ['Obtainable', 'Team Preview', 'Sleep Clause Mod', 'Species Clause', 'Nickname Clause', 'OHKO Clause', 'Moody Clause', 'Evasion Moves Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod'], minSourceGen: 0, // auto }, standarddoubles: { inherit: true, ruleset: ['Obtainable', 'Team Preview', 'Species Clause', 'Nickname Clause', 'OHKO Clause', 'Moody Clause', 'Evasion Abilities Clause', 'Evasion Moves Clause', 'Gravity Sleep Clause', 'Endless Battle Clause', 'HP Percentage Mod', 'Cancel Mod'], minSourceGen: 0, // auto }, obtainablemoves: { inherit: true, banlist: [ // Leaf Blade: Gen 6+ Nuzleaf level-up // Sucker Punch: Gen 4 Shiftry tutor 'Shiftry + Leaf Blade + Sucker Punch', // Aura Break Zygarde can't be changed to 10% forme in gen 7 // making moves only obtainable from gen 6 illegal 'Zygarde-10% + Aura Break + Rock Smash', 'Zygarde-10% + Aura Break + Secret Power', 'Zygarde-10% + Aura Break + Strength', ], }, gravitysleepclause: { effectType: 'ValidatorRule', name: 'Gravity Sleep Clause', desc: "Bans Gravity + sleep moves below 100% accuracy", banlist: ['Gravity ++ Grass Whistle', 'Gravity ++ Hypnosis', 'Gravity ++ Lovely Kiss', 'Gravity ++ Sing', 'Gravity ++ Sleep Powder'], onBegin() { this.add('rule', 'Gravity Sleep Clause: The combination of Gravity and sleep-inducing moves with imperfect accuracy are banned'); }, }, teampreview: { inherit: true, onBegin() { this.add('clearpoke'); for (const pokemon of this.getAllPokemon()) { const details = pokemon.details.replace(', shiny', '') .replace(/(Arceus|Gourgeist|Genesect|Pumpkaboo|Silvally|Urshifu)(-[a-zA-Z?-]+)?/g, '$1-*'); this.add('poke', pokemon.side.id, details, pokemon.item ? 'item' : ''); } }, }, }; exports.Rulesets = Rulesets; //# sourceMappingURL=sourceMaps/rulesets.js.map
1.210938
1
src/components/MainSidebar.js
gauravsavanur07/spruik
5
5391
import React, { Component } from 'react' import './MainSidebar.css' import adchainLogo from './assets/ad_chain_logo_white_text.png' import metaxLogo from './assets/metax_logo_white_text.png' class MainSidebar extends Component { componentDidMount() { /* window.$('.ui.sidebar') .sidebar({ dimPage:false }) */ } render () { const Link = this._link return ( <div className='MainSidebar ui sidebar inverted vertical menu visible'> <div className='adChainLogo ui image'> <a href='/'> <img src={adchainLogo} alt='adChain' /> </a> </div> <div className='ListTitle ui header'> adChain Registry </div> <div className="SidebarList overflow-y"> <ul className='ui list'> <li className='item'> <li className='item'><a href='#/domains?approved=true'>Domains in registry</a></li> <Link to='/domains' activeClassName='active'>All domains</Link> <li className='item'><a href='#/domains?pending=true'>Domains in application</a></li> </li> <li className='item'><a href='#/domains?in_voting=true'>Domains in voting</a></li> <li className='item'> <li className='item'><a href='#/domains?rejected=true'>Rejected domains</a></li> <Link to='/domains?approved=true'>Domains in registry</Link> <li className='item ApplyLink'><a href='#/apply'>Apply now</a></li> </li> <li className='item'> <Link to='/domains?pending=true'>Domains in application</Link> </li> <li className='item'> <Link to='/domains?in_voting=true'>Domains in voting</Link> </li> <li className='item'> <Link to='/domains?rejected=true'>Rejected domains</Link> </li> <li className='item ApplyLink'> <Link to='/apply'>Apply now</Link> </li> </div> <div className="SidebarFooter"> <div className='metaxLogo ui image'> <a href='https://metax.io' target='_blank' rel='noopener noreferrer'> <img src={metaxLogo} alt='MetaX' /> </a> </div> <div className='Copyright'> <p>© Copyright 2017 MetaXchain, Inc.<br /> All rights reserved.</p> </div> </div> </div> ) } } export default MainSidebar
1.085938
1
src/pages/contact.js
TahsinProduction/EliteAnswers
0
5399
import React from 'react' import Layout from '../components/layout' import SEO from '../components/seo' const AboutPage = () => ( <Layout pageTitle="Contact Us"> <SEO title="ContactUS" keywords={[`gatsby`, `application`, `react`]} /> <div className="col-md-3"></div> <img src = "https://lh3.googleusercontent.com/9liGmQurv_ClCtUes9BVsfaFrpuODInWPKSvO_KbyBCBqq8Zub6JU8tJL5CK_zvJTqyUN9Uy6Hhd6GPcNAJ8JvXyMjjrlUE8V1EfzWj8usCdnyIJAyWDGke8LU0xwBKIu_mqUkeq" width="100%" height="auto" margin="0 auto" alt="embed" /> <center><h1>If you have any query or problem or want to say something to us then please fill the form below</h1><h1>You will receive reply shortly</h1></center> <iframe src="https://docs.google.com/forms/d/e/1FAIpQLSce1xHd5ZL2qiJzL6MBL9cguPg-4-wamSDp2wSHQPE2ZnTWEQ/viewform?embedded=true" title="TahsinProduction" width="100%" height="1450" frameborder="0" marginheight="100%" marginwidth="100%">Loading…</iframe> </Layout>) export default AboutPage
1.25
1
src/Persons.js
abalbi/vision
0
5407
function Persons () { this.items = []; } Persons.prototype.posibility = function () { var hour = Ownb.date().getHours(); var xx = hour > 12 ? -(24 - hour) : hour; xx -= 2; var posibility; var yy = (.10 * (xx*xx))-1; if(yy < 0) yy = yy*-1; rand = Math.floor(Math.random() * 100); posibility = rand < yy; return posibility; } Persons.prototype.add = function (item) { var is_new_person; if(this.posibility()) { var person = this.new(); if(person.animation_current.constructor.name == 'WalkRightAnimation') { person.position.x = -person.position.width + 10; } if(person.animation_current.constructor.name == 'WalkLeftAnimation') { person.position.x = Saga.canvas().width; } this.items.push(person); } } Persons.prototype.new = function () { return new Person().reset(); } Persons.prototype.clean = function (persons_delete) { for (i in persons_delete) { var elem = persons_delete[i]; persons_delete.splice(i,1); this.items.splice(elem,1); } } Persons.prototype.update = function () { this.add(); var persons_delete = [] for(var i in this.items) { var person = this.items[i]; person.update(); if(Saga.canvas().width < person.position.x) { persons_delete.push(i); } if(person.position.x < 0 - 50){ persons_delete.push(i); } } this.clean(persons_delete); }
1.625
2
examples/router.js
skynj/v-charts
0
5415
/* eslint-disable comma-dangle */ import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export const TEST_ROUTES = [ { path: '/columns-rows', name: 'data', component: () => import('./test/columns-rows.vue') }, { path: '/custom-props', name: 'options', component: () => import('./test/custom-props.vue') }, { path: '/events', name: 'events', component: () => import('./test/events.vue') }, { path: '/extend', name: 'extend', component: () => import('./test/extend.vue') }, { path: '/hook', name: 'hook', component: () => import('./test/hook.vue') }, { path: '/init', name: 'init', component: () => import('./test/init.vue') }, { path: '/judge-width', name: 'judge-width', component: () => import('./test/judge-width.vue') }, { path: '/loading-empty', name: 'loading-empty', component: () => import('./test/loading-empty.vue') }, { path: '/mark', name: 'mark', component: () => import('./test/mark.vue') }, { path: '/resize', name: 'resize', component: () => import('./test/resize.vue') }, { path: '/set-option', name: 'set-option', component: () => import('./test/set-option.vue') }, { path: '/number-format', name: 'number', component: () => import('./test/number-format.vue') }, ] export default new Router({ routes: [ { path: '/', name: '安装', component: () => import('./pages/install') }, { path: '/chart/:type', name: '图表', component: () => import('./pages/chart') }, { path: '/bmap', name: '百度地图', component: () => import('./pages/bmap') }, { path: '/amap', name: '高德地图', component: () => import('./pages/amap') }, ].concat(TEST_ROUTES) })
1.117188
1
example/auth.js
noffle/materialized-group-auth
0
5423
var mauth = require('../') var db = require('level')('/tmp/auth.db') var auth = mauth(db) var minimist = require('minimist') var argv = minimist(process.argv.slice(2)) if (argv._[0] === 'write') { var doc = { type: argv.type, key: argv.key, by: argv.by || null, role: argv.role, group: argv.group, id: argv.id } auth.batch([doc], function (err) { if (err) console.error(err) }) } else if (argv._[0] === 'groups') { auth.getGroups(function (err, groups) { if (err) return console.error(err) groups.forEach((group) => console.log(group)) }) } else if (argv._[0] === 'members') { auth.getMembers(argv._[1], function (err, members) { if (err) return console.error(err) members.forEach((member) => console.log(member)) }) } else if (argv._[0] === 'membership') { auth.getMembership(argv._[1], function (err, groups) { if (err) return console.error(err) groups.forEach((groups) => console.log(groups)) }) }
1.101563
1
src/reactReduxMiddleware/container/index.js
Gaara526/react-redux-train
1
5431
/** * @since 2018-12-14 15:10 * @author pengyumeng */ import React, { Component } from 'react'; import 'antd/dist/antd.css'; import { connect } from '../lib/react-redux'; import Number from '../components/Number'; import Alert from '../components/Alert'; import actions from '../actions'; import './index.pcss'; const mapStateToProps = (state) => ({ number: state.changeNumber.number, showAlert: state.toggleAlert.showAlert, }); class Demo extends Component { handleClickAdd = () => { this.props.dispatch({ type: actions.number.INCREMENT }); }; handleClickMinus = () => { this.props.dispatch({ type: actions.number.DECREMENT }); }; handleClickClear = () => { this.props.dispatch({ type: actions.number.CLEAR }); }; handleClickAlert = () => { this.props.dispatch({ type: actions.alert.TOGGLE_ALERT }); }; render() { const { number, showAlert, } = this.props; return ( <div className="wrap"> <h3>redux middleware</h3> <Number value={number} handleClickAdd={this.handleClickAdd} handleClickMinus={this.handleClickMinus} handleClickClear={this.handleClickClear} /> <Alert showAlert={showAlert} handleClickAlert={this.handleClickAlert} /> </div> ); } } export default connect( mapStateToProps, )(Demo);
1.570313
2
node_modules/string.prototype.trimstart/node_modules/es-abstract/2019/AddEntriesFromIterable.js
GenaAiv/portfolio-website
0
5439
'use strict'; var inspect = require('object-inspect'); var GetIntrinsic = require('../GetIntrinsic'); var $TypeError = GetIntrinsic('%TypeError%'); var Call = require('./Call'); var Get = require('./Get'); var GetIterator = require('./GetIterator'); var IsCallable = require('./IsCallable'); var IteratorClose = require('./IteratorClose'); var IteratorStep = require('./IteratorStep'); var IteratorValue = require('./IteratorValue'); var Type = require('./Type'); // https://tc39.es/ecma262/#sec-add-entries-from-iterable module.exports = function AddEntriesFromIterable(target, iterable, adder) { if (!IsCallable(adder)) { throw new $TypeError('Assertion failed: `adder` is not callable'); } if (iterable == null) { throw new $TypeError('Assertion failed: `iterable` is present, and not nullish'); } var iteratorRecord = GetIterator(iterable); while (true) { // eslint-disable-line no-constant-condition var next = IteratorStep(iteratorRecord); if (!next) { return target; } var nextItem = IteratorValue(next); if (Type(nextItem) !== 'Object') { var error = new $TypeError('iterator next must return an Object, got ' + inspect(nextItem)); return IteratorClose( iteratorRecord, function () { throw error; } // eslint-disable-line no-loop-func ); } try { var k = Get(nextItem, '0'); var v = Get(nextItem, '1'); Call(adder, target, [k, v]); } catch (e) { return IteratorClose( iteratorRecord, function () { throw e; } ); } } };
1.6875
2
vue-pc/src/store/modules/common.js
qq296629801/bzGhost
0
5447
import Vue from "vue"; import cache from "@/utils/cache.js" export const state = { // 加载动画 loadingShow: false, // 登录弹窗状态 loginPopupShow: false, // 聊天对象 chatObj:{ }, // 红包对象 packetData:{}, newsPush:{}, // 缓存 post:[], friend:[], group:[], conversation:[] }; //缓存浏览器的数据名称 const cacheNameList = ["user","token","config","roles","permissions","post","friend","group","conversation"]; let clearTime; export const mutations = { setPost(state, data){ if(data){ state.post = Object.assign({}, state.post, data); cache.set("post",state.post); } }, setFriend(state, data){ if(data){ state.friend = Object.assign({}, state.friend, data); cache.set("friend",state.friend); } }, setGroup(state, data){ if(data){ state.group = Object.assign({}, state.group, data); cache.set("group",state.group); } }, setConversation(state, data){ if(data){ state.conversation = Object.assign({}, state.conversation, data); cache.set("conversation",state.conversation); } }, setCacheData(state) { for (let name of cacheNameList) { let data = cache.get(name); if (data) { state[name] = data; } } }, setPacketData(state, data){ if(data){ state.packetData = data } }, // setNewsPush(state, data){ if(data){ state.newsPush = data } }, // setChatObj(state, data){ if(data){ state.chatObj = data } }, //数据加载状态 setLoadingShow(state, data) { if(state.loadingShow){ clearTime && clearTimeout(clearTime); clearTime = setTimeout(function(){ state.loadingShow = data; },50); } else { state.loadingShow = data; } }, //登录弹窗状态 setLoginPopupShow(state, data) { state.loginPopupShow = data; } }; export const actions = { };
1.570313
2
src/main/resources/js/other.js
gengzi/codecopy
7
5455
function getAesString(data, key, iv) {//加密 var key = CryptoJS.enc.Utf8.parse(key); var iv = CryptoJS.enc.Utf8.parse(iv); var encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); //返回的是base64格式的密文 } function getDAesString(encrypted, key, iv) {//解密 var key = CryptoJS.enc.Utf8.parse(key); var iv = CryptoJS.enc.Utf8.parse(iv); var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } function getAES(data) { //加密 var key = '<KEY>'; //密钥 var iv = '1234567812345678'; var encrypted = getAesString(data, key, iv); //密文 var encrypted1 = CryptoJS.enc.Utf8.parse(encrypted); return encrypted; } function getDAes(data) {//解密 var key = '<KEY>'; //密钥 var iv = '1234567812345678'; var decryptedStr = getDAesString(data, key, iv); return decryptedStr; } function getRSAString(data, key) {//加密 var key = CryptoJS.enc.Utf8.parse(key); var encrypted = CryptoJS.RSA.encrypt(data, key, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); //返回的是base64格式的密文 } function getRSAString(encrypted, key) {//解密 var key = CryptoJS.enc.Utf8.parse(key); var decrypted = CryptoJS.RSA.decrypt(encrypted, key, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } // 使用 jsencrypt 进行 rsa 前端的加密和解密 // https://github.com/travist/jsencrypt /** * RSA 加密,使用公钥加密 * @param key 公钥 * @param str 需要加密的内容 * @returns {CipherParams|PromiseLike<ArrayBuffer>|null|string|string|*} */ function encryptRSAByPublicKey(str, key) { Encrypt = new JSEncrypt(); Encrypt.setPublicKey(key); return Encrypt.encrypt(str); } /** * RSA 解密,使用密钥解密 * @param str 需要解密的内容 * @param key 密钥 * @returns {WordArray|PromiseLike<ArrayBuffer>|null|*|undefined} */ function decryptRSAByPrivateKey(str, key) { Encrypt = new JSEncrypt(); Encrypt.setPrivateKey(key); return Encrypt.decrypt(str); }
1.671875
2
test/support/mongooseuser.js
sielay/octopusidentity
0
5463
var userPlugin = require( 'mongoose-user' ); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var MongooseUserSchema = new Schema( { email : { type : String, default : '' }, hashed_password : { type : String, default : '' }, salt : { type : String, default : '' }, name : { type : String, default : '' } } ); MongooseUserSchema.plugin( userPlugin, {} ); var MongooseUserModel = mongoose.model( 'MongooseUser', MongooseUserSchema ); module.exports = MongooseUserModel;
1.148438
1
node_modules/rc-field-form/lib/index.js
dillonthompson/dillonthompson.github.io
10
5471
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Field", { enumerable: true, get: function get() { return _Field.default; } }); Object.defineProperty(exports, "List", { enumerable: true, get: function get() { return _List.default; } }); Object.defineProperty(exports, "useForm", { enumerable: true, get: function get() { return _useForm.default; } }); Object.defineProperty(exports, "FormProvider", { enumerable: true, get: function get() { return _FormContext.FormProvider; } }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _Field = _interopRequireDefault(require("./Field")); var _List = _interopRequireDefault(require("./List")); var _useForm = _interopRequireDefault(require("./useForm")); var _Form = _interopRequireDefault(require("./Form")); var _FormContext = require("./FormContext"); var InternalForm = /*#__PURE__*/React.forwardRef(_Form.default); var RefForm = InternalForm; RefForm.FormProvider = _FormContext.FormProvider; RefForm.Field = _Field.default; RefForm.List = _List.default; RefForm.useForm = _useForm.default; var _default = RefForm; exports.default = _default;
1.140625
1
doc/html/search/functions_b.js
SKA-ScienceDataProcessor/FastImaging
7
5479
var searchData= [ ['normalise_5fimage_5fbeam_5fresult_5f1d',['normalise_image_beam_result_1D',['../namespacestp.html#a674d910ef471f5f234894a92057a0a47',1,'stp']]], ['num_5flower',['num_lower',['../classtk_1_1band__matrix.html#a57b351eff7db8c9875a5204ea3132d42',1,'tk::band_matrix']]], ['num_5fupper',['num_upper',['../classtk_1_1band__matrix.html#a964e9950c0f778b13a963e4acfa8d6ae',1,'tk::band_matrix']]] ];
0.214844
0
modules/personals/server/models/personal.server.model.js
bhuvansalanke/BookingApplication-master
0
5487
//database var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ApptTypeSchema = require('./appt-type.server.model'); var PersonalSchema = new Schema({ created: { type: Date, default: Date.now }, fName: { type: String, default: '', required: 'Please fill your first name', trim: true }, lName: { type: String, default: '', required: 'Please fill your last name', trim: true }, emailId: { type: String, default: '', required: 'Please fill your email id', trim: true }, contact: { type: String, default: '', required: 'Please fill your contact number', trim: true }, isConsultant: { type: Boolean }, speciality: { type: String, default: '', trim: true }, qualification: { type: String, default: '', trim: true }, experience: { type: String, default: '', trim: true }, rating: { type: Number, default: 0, trim: true }, treatments: [ApptTypeSchema], slots: [{ day: { type: String, default: '', required: 'Please fill the day', trim: true } , starttime: { type: Date }, endtime: { type: Date }, location: { type: String } }], user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Personal', PersonalSchema);
1.125
1
src/demo/AppMinimumUsage.js
quickshiftin/react-html5-camera-photo
1
5495
import React, { Component } from 'react'; import Camera, { FACING_MODES } from '../lib'; import './reset.css'; class App extends Component { onTakePhoto (dataUri) { // Do stuff with the photo... console.log('takePhoto'); } render () { return ( <div className="App"> <Camera onTakePhoto = { (dataUri) => { this.onTakePhoto(dataUri); } } idealFacingMode = {FACING_MODES.ENVIRONMENT} /> </div> ); } } export default App;
1.15625
1
public/js/Admin/Main.js
Red-Beard7/suf
0
5503
const $duration = $("#global_alert").data('duration'); window.setTimeout(function() { $("#global_alert").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, ($duration * 1000)); $(() => { /** * ********************************************************* NAVIGATIONS */ //== Nav Elements const $headerContainer = $('.header_container'); const $sideBar = $('#sidebar'); const $navStateToggle = $('#nav_state_toggle'); const $navLogoName = $('.nav_logo_name'); const $navName = $('.nav_name'); const $navSubtitle = $('.nav_subtitle'); const $navDropdownIcon = $('.nav_dropdown_icon'); let lsKey = 'fixedNav'; let lsVal = ''; /*_____________________ NAV STATE _____________________*/ const $hiddenElements = [$sideBar, $navLogoName, $navName, $navSubtitle, $navDropdownIcon, $headerContainer, $('section')]; const fixedNavState = (state) => { if(state === 'toggle') { $($hiddenElements).each(function() { $(this).toggleClass('fixed'); }); } else if(state === 'remove') { $($hiddenElements).each(function() { $(this).removeClass('fixed'); }); } else if(state === 'add') { $($hiddenElements).each(function() { $(this).addClass('fixed'); }); } } if(localStorage.getItem(lsKey) === 'true') { fixedNavState('toggle'); $navStateToggle.prop('checked', true); } if($(window).width() < 768) { fixedNavState('remove'); } $(window).on('resize', () => { if($(this).width() < 768) { fixedNavState('remove'); } }) $navStateToggle.on('change', function() { if($(this).prop('checked')) { fixedNavState('toggle'); if($sideBar.hasClass('fixed')) { lsVal = 'true'; } localStorage.setItem(lsKey, lsVal); } else { fixedNavState('toggle'); localStorage.setItem(lsKey, 'false'); } }); /*_____________________ SHOW NAVBAR _____________________*/ const showMenu = (headerToggle, navbarId) => { const toggleBtn = document.getElementById(headerToggle), nav = document.getElementById(navbarId) // Validate that variables exist if(headerToggle && navbarId && $(window).width() < 768){ toggleBtn.addEventListener('click', ()=>{ // We add the show-menu class to the div tag with the nav__menu class nav.classList.toggle('show_menu') //Change Icon toggleBtn.classList.toggle('bx-x'); }); } } if($('#header_toggle').length && $sideBar.length) { showMenu('header_toggle','sidebar'); } /*_____________________ DROPDOWN _____________________*/ const navDropdown = document.querySelectorAll('.nav_dropdown'); function collapseDropdown() { navDropdown.forEach(l => l.classList.remove('active')) this.classList.add('active'); } navDropdown.forEach(l => l.addEventListener('click', collapseDropdown)); $sideBar.on('mouseleave', () => { collapseDropdown(); }) /*_____________________ ACTIVE LINK _____________________*/ const linkColor = document.querySelectorAll('.nav_link') function colorLink() { linkColor.forEach(l => l.classList.remove('active')) this.classList.add('active') } linkColor.forEach(l => l.addEventListener('click', colorLink)); /** * ********************************************************* ANIME INPUT */ let $animeInput = $('.anime_input'); if($animeInput.val()) { $animeInput.addClass('dirty_input'); } else { $animeInput.removeClass('dirty_input'); } $animeInput.each(function() { $(this).on('blur', function() { if($(this).val()) { $(this).addClass('dirty_input'); } else { $(this).removeClass('dirty_input'); } }); }); });
1.28125
1
src/components/DotStepper/DotStepper.test.js
abdusabri/hsds-react
59
5511
import React from 'react' import { mount } from 'enzyme' import { DotStepperUI, BulletUI, ProgressBulletUI } from './DotStepper.css' import DotStepper from './' import Tooltip from '../Tooltip' describe('className', () => { test('Has default className', () => { const wrapper = mount(<DotStepper />) expect(wrapper.find(DotStepperUI).hasClass('c-DotStepper')).toBeTruthy() }) test('Can render custom className', () => { const customClassName = 'clazz' const wrapper = mount(<DotStepper className={customClassName} />) expect(wrapper.find(DotStepperUI).hasClass(customClassName)).toBeTruthy() }) }) describe('Steps', () => { test('Renders a BulletUI component for each step', () => { const numSteps = 8 const wrapper = mount(<DotStepper numSteps={numSteps} />) expect(wrapper.find(BulletUI)).toHaveLength(numSteps) }) test('Renders a single ProgressBulletUI component', () => { const numSteps = 8 const wrapper = mount(<DotStepper numSteps={numSteps} />) expect(wrapper.find(ProgressBulletUI)).toHaveLength(1) }) }) describe('Tooltip', () => { test('Should render a Tooltip component', () => { const numSteps = 8 const step = 4 const wrapper = mount(<DotStepper numSteps={numSteps} step={step} />) expect(wrapper.find(Tooltip).prop('title')).toEqual( `Step ${step} of ${numSteps}` ) }) })
1.328125
1
CMS/CMSScripts/Vendor/jQuery/jquery-1.11.0-amd.js
mzhokh/FilterByCategoryWidget
26
5519
// This module returns no conflicted version of jQuery. // The purpose is to permit requiring newest version of jQuery, when // there are older versions used by legacy code at the same time. define(['jquery'], function (jq) { return jq.noConflict(true); });
0.554688
1
docs/src/pages/components/index.js
srinivasdamam/evergreen
3
5527
import React from 'react' import Helmet from 'react-helmet' import TopBar from '../../components/TopBar' import IA from '../../IA' import Overview from '../../components/Overview' import Layout from '../../components/Layout' import PageFooter from '../../components/PageFooter' export default () => { return ( <Layout> <Helmet> <title>Components · Evergreen</title> </Helmet> <div> <TopBar /> <main tabIndex={-1}> <Overview ia={IA} /> </main> </div> <PageFooter /> </Layout> ) }
0.78125
1
chrome/renderer/resources/extensions/app_custom_bindings.js
pozdnyakov/chromium-crosswalk
0
5535
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Custom binding for the app API. var GetAvailability = requireNative('v8_context').GetAvailability; if (!GetAvailability('app').is_available) { exports.chromeApp = {}; exports.onInstallStateResponse = function(){}; return; } var appNatives = requireNative('app'); var process = requireNative('process'); var extensionId = process.GetExtensionId(); var logActivity = requireNative('activityLogger'); function wrapForLogging(fun) { var id = extensionId; return (function() { // TODO(ataly): We need to make sure we use the right prototype for // fun.apply. Array slice can either be rewritten or similarly defined. logActivity.LogAPICall(id, "app." + fun.name, $Array.slice(arguments)); return $Function.apply(fun, this, arguments); }); } // This becomes chrome.app var app; if (!extensionId) { app = { getIsInstalled: appNatives.GetIsInstalled, getDetails: appNatives.GetDetails, getDetailsForFrame: appNatives.GetDetailsForFrame, runningState: appNatives.GetRunningState }; } else { app = { getIsInstalled: wrapForLogging(appNatives.GetIsInstalled), getDetails: wrapForLogging(appNatives.GetDetails), getDetailsForFrame: wrapForLogging(appNatives.GetDetailsForFrame), runningState: wrapForLogging(appNatives.GetRunningState) }; } // Tricky; "getIsInstalled" is actually exposed as the getter "isInstalled", // but we don't have a way to express this in the schema JSON (nor is it // worth it for this one special case). // // So, define it manually, and let the getIsInstalled function act as its // documentation. if (!extensionId) app.__defineGetter__('isInstalled', appNatives.GetIsInstalled); else app.__defineGetter__('isInstalled', wrapForLogging(appNatives.GetIsInstalled)); // Called by app_bindings.cc. function onInstallStateResponse(state, callbackId) { var callback = callbacks[callbackId]; delete callbacks[callbackId]; if (typeof(callback) == 'function') callback(state); } // TODO(kalman): move this stuff to its own custom bindings. var callbacks = {}; var nextCallbackId = 1; app.installState = function getInstallState(callback) { var callbackId = nextCallbackId++; callbacks[callbackId] = callback; appNatives.GetInstallState(callbackId); }; if (extensionId) app.installState = wrapForLogging(app.installState); // This must match InstallAppBindings() in // chrome/renderer/extensions/dispatcher.cc. exports.chromeApp = app; exports.onInstallStateResponse = onInstallStateResponse;
1.578125
2
webpack.config.js
sernano/mixi
1
5543
const isDev = process.env.NODE_ENV === 'development'; const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { mode: isDev ? 'development' : 'production', entry: { bundle: [ '@babel/polyfill', // enables async-await './client/index.js' ], style: ['./client/style.scss'] }, output: { path: path.join(__dirname, '/public'), filename: '[name].js' }, resolve: { extensions: ['.js', '.jsx'] }, devtool: 'source-map', watchOptions: { ignored: /node_modules/ }, module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, 'style-loader', 'css-loader'] }, { test: /\.scss$/, exclude: [/node_modules/], use: ['style-loader', 'css-loader', 'sass-loader'] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css' }) ] };
1.03125
1
src/styles/theme/spacing.js
Eazybee/Video-Album
0
5551
export const spacings = { auto: 'auto', zero: '0', xxsm: '.1em', xsm: '.2em', md: '.5em', nm: '1em', xnm: '2.4em', lg: '5em', x: '10em', xl: '16em', fw: '100%', video: '20em', share: '30em', inputMargin: '.7em 0', }; export default spacings;
0.488281
0
routes/db.js
iot-platform-for-smart-home/panorama
0
5559
var mysql = require('mysql'); var pool = mysql.createPool({ host:'localhost', user:'root', port:3306, password:'<PASSWORD>', database:'expressjs' }); function query(sql,callback){ pool.getConnection(function(err,connection){ connection.query(sql,function(err,rows){ callback(err,rows); connection.release(); }); }); } exports.query = query;
1.109375
1
src/pages/index.js
frankmalafronte/Twilight-assess
0
5567
import React from "react"; import List from "../components/List"; export default () => ( <div> <List /> </div> );
0.414063
0
util.js
JesusisFreedom/generator-ng-webpack
0
5575
'use strict'; var path = require('path'); var fs = require('fs'); module.exports = { rewrite: rewrite, rewriteFile: rewriteFile, appName: appName, copyTemplates: copyTemplates, relativeUrl: relativeUrl }; function rewriteFile (args) { args.path = args.path || process.cwd(); var fullPath = path.join(args.path, args.file); args.haystack = fs.readFileSync(fullPath, 'utf8'); var body = rewrite(args); fs.writeFileSync(fullPath, body); } function escapeRegExp (str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } function rewrite (args) { // check if splicable is already in the body text var re = new RegExp(args.splicable.map(function (line) { return '\s*' + escapeRegExp(line); }).join('\n')); if (re.test(args.haystack)) { return args.haystack; } var lines = args.haystack.split('\n'); var otherwiseLineIndex = 0; lines.forEach(function (line, i) { if (line.indexOf(args.needle) !== -1) { otherwiseLineIndex = i; } }); var spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } var spaceStr = ''; while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(function (line) { return spaceStr + line; }).join('\n')); return lines.join('\n'); } function appName (self) { var counter = 0, suffix = self.options['app-suffix']; // Have to check this because of generator bug #386 process.argv.forEach(function(val) { if (val.indexOf('--app-suffix') > -1) { counter++; } }); if (counter === 0 || (typeof suffix === 'boolean' && suffix)) { suffix = 'App'; } return suffix ? self.lodash.classify(suffix) : ''; } function createFileName (template, name) { // Find matches for parans var filterMatches = template.match(/\(([^)]+)\)/g); var filter = ''; if(filterMatches) { filter = filterMatches[0].replace('(', '').replace(')', ''); template = template.replace(filterMatches[0], ''); } return { name: template.replace('name', name), filter: filter }; } function templateIsUsable (processedName, self) { var filters = self.config.get('filters') || []; var include = true; if(processedName.filter && filters.indexOf(processedName.filter) === -1) { include = false; } var index = processedName.name.lastIndexOf('.'); var ext = processedName.name.slice(index + 1); var extensions = self.config.get('extensions') || []; if(extensions.indexOf(ext) >= 0 && include) { return true; } return false; } function copyTemplates (self, type, templateDir, configName) { templateDir = templateDir || path.join(self.sourceRoot(), type); configName = configName || type + 'Templates'; if(self.config.get(configName)) { templateDir = path.join(process.cwd(), self.config.get(configName)); } fs.readdirSync(templateDir) .forEach(function(template) { var processedName = createFileName(template, self.name); var fileName = processedName.name; var templateFile = path.join(templateDir, template); if(templateIsUsable(processedName, self)) { self.template(templateFile, path.join(self.dir, fileName)); } }); }; function relativeUrl(basePath, targetPath) { var relativePath = path.relative(basePath, targetPath); return relativePath.split(path.sep).join('/'); }
1.3125
1
src/index.js
Cap32/hoist-react-instance-methods
2
5583
export default function hoistReactInstance(getInstance, methods) { return (Target) => { if (typeof getInstance !== 'function' || typeof Target !== 'string' // don't hoist over string (html) components ) { methods && [].concat(methods).forEach((method) => { Target.prototype[method] = function (...args) { const element = getInstance(this); if (element && element[method]) { return element[method](...args); } }; }); } return Target; }; }
1.054688
1
flowtypes/broadcast.js
rhainer/interactive-broadcast-js
0
5591
// @flow /* eslint no-undef: "off" */ /* beautify preserve:start */ declare type ParticipantAVProperty = 'audio' | 'video' | 'volume'; declare type ParticipantAVProps = { video: boolean, audio: boolean, volume: number } declare type SessionName = 'stage' | 'backstage'; declare type InstancesToConnect = Array<SessionName>; declare type NetworkQuality = 'great' | 'good' | 'poor'; declare type ImgData = null | string; declare type onSnapshotReady = Unit; declare type ParticipantAVPropertyUpdate = { property: 'volume', value: number } | { property: 'video', value: boolean } | { property: 'audio', value: boolean } ; declare type ParticipantState = { connected: boolean, stream: null | Stream, networkQuality: null | NetworkQuality, video: boolean, audio: boolean, volume: number } // $FlowFixMe - Creating this type without using an intersection does not throw an error (?) declare type FanParticipantState = ParticipantState & { record?: ActiveFan }; declare type ParticipantWithConnection = ParticipantState & { connection: Connection }; declare type ProducerWithConnection = { connection: Connection } declare type UserWithConnection = ParticipantWithConnection | ActiveFanWithConnection | ProducerWithConnection; declare type BroadcastParticipants = { fan: FanParticipantState, celebrity: ParticipantState, host: ParticipantState, backstageFan: FanParticipantState }; declare type InteractiveFan = { uid: UserId }; declare type ActiveFan = { id: UserId, name: string, browser: string, mobile: boolean, networkQuality: null | NetworkQuality, streamId: string, snapshot: null | string, inPrivateCall: boolean, isBackstage: boolean, isOnStage: boolean }; declare type ActiveFanWithConnection = ActiveFan & { connection: Connection }; declare type ActiveFanMap = { [fanId: string]: ActiveFan } declare type ActiveFanUpdate = null | { id?: string, name?: string, browser?: string, networkQuality?: null | NetworkQuality, mobile?: boolean, snapshot?: string, streamId?: string }; declare type ActiveFans = { order: UserId[], map: ActiveFanMap } declare type ChatId = ParticipantType | UserId; declare type ProducerChats = {[chatId: ChatId]: ChatState }; declare type PrivateCallParticipant = ParticipantType | 'activeFan'; declare type PrivateCallState = null | { isWith: HostCeleb } | { isWith: FanType, fanId: UserId }; declare type ProducerActiveState = null | boolean; declare type BroadcastState = { event: null | BroadcastEvent, connected: boolean, publishOnlyEnabled: boolean, privateCall: PrivateCallState, publishers: { camera: null | { [publisherId: string]: Publisher} }, subscribers: { camera: null | { [subscriberId: string]: Subscriber} }, meta: null | CoreMeta, participants: BroadcastParticipants, activeFans: ActiveFans, chats: ProducerChats, stageCountdown: number, viewers: number, interactiveLimit: number, archiving: boolean, reconnecting: boolean, disconnected: boolean, elapsedTime: string, fanTransition: boolean }; declare type FanStatus = 'disconnected' | 'connecting' | 'inLine' | 'backstage' | 'stage' | 'privateCall' | 'temporarillyMuted'; declare type FanState = { ableToJoin: boolean, fanName: string, status: FanStatus, inPrivateCall: boolean, networkTest: { interval: number | null, timeout: number | null } }; declare type FanParticipantType = 'backstageFan' | 'fan'; declare type FanType = 'activeFan' | FanParticipantType; declare type ParticipantType = FanParticipantType | 'host' | 'celebrity'; declare type FanInitOptions = { adminId: UserId, userUrl: string }; declare type CelebHostInitOptions = FanInitOptions & { userType: 'celebrity' | 'host' }; declare type ActiveFanOrderUpdate = { newIndex: number, oldIndex: number }; /** * Chat Types */ declare type ChatUser = 'activeFan' | 'producer' | ParticipantType; declare type ChatMessage = { from: ConnectionId, to: ConnectionId, isMe: boolean, text: string, timestamp: number }; declare type ChatMessagePartial = { text: string, timestamp: number, fromType: ChatUser, fromId?: UserId }; declare type ChatState = { chatId: ParticipantType | UserId, session: SessionName, toType: ChatUser, fromType: ChatUser, fromId?: UserId, // This will be used to indentify active fans only to: UserWithConnection, displayed: boolean, minimized: boolean, messages: ChatMessage[], inPrivateCall?: boolean }; /** * Actions */ declare type BroadcastAction = { type: 'FAN_TRANSITION', fanTransition: boolean } | { type: 'SET_BROADCAST_EVENT', event: BroadcastEvent } | { type: 'RESET_BROADCAST_EVENT' } | { type: 'BACKSTAGE_CONNECTED', connected: boolean } | { type: 'BROADCAST_CONNECTED', connected: boolean } | { type: 'PRESENCE_CONNECTING', connecting: boolean } | { type: 'SET_PUBLISH_ONLY_ENABLED', publishOnlyEnabled: boolean } | { type: 'BROADCAST_PARTICIPANT_JOINED', participantType: ParticipantType, stream: Stream } | { type: 'BROADCAST_PARTICIPANT_LEFT', participantType: ParticipantType } | { type: 'PARTICIPANT_AV_PROPERTY_CHANGED', participantType: ParticipantType, update: ParticipantAVPropertyUpdate } | { type: 'SET_BROADCAST_EVENT_STATUS', status: EventStatus } | { type: 'SET_BROADCAST_EVENT_SHOW_STARTED', showStartedAt: string } | { type: 'SET_ELAPSED_TIME', elapsedTime: string } | { type: 'SET_BROADCAST_STATE', state: CoreState } | { type: 'SET_PRIVATE_CALL_STATE', privateCall: PrivateCallState } | { type: 'PRIVATE_ACTIVE_FAN_CALL', fanId: UserId, inPrivateCall: boolean } | { type: 'END_PRIVATE_ACTIVE_FAN_CALL', fan: ActiveFan } | { type: 'UPDATE_ACTIVE_FANS', update: ActiveFanMap } | { type: 'UPDATE_ACTIVE_FAN_RECORD', fanType: 'backstageFan' | 'fan', record: ActiveFan } | { type: 'REORDER_BROADCAST_ACTIVE_FANS', update: ActiveFanOrderUpdate } | { type: 'START_NEW_FAN_CHAT', fan: ActiveFanWithConnection, toType: FanType, privateCall?: boolean } | { type: 'START_NEW_PARTICIPANT_CHAT', participantType: ParticipantType, participant: ParticipantWithConnection } | { type: 'START_NEW_PRODUCER_CHAT', fromType: ChatUser, fromId?: UserId, producer: ProducerWithConnection } | { type: 'UPDATE_CHAT_PROPERTY', chatId: ChatId, property: $Keys<ChatState>, update: * } | { type: 'REMOVE_CHAT', chatId: ChatId } | { type: 'DISPLAY_CHAT', chatId: ChatId, display: boolean } | { type: 'MINIMIZE_CHAT', chatId: ChatId, minimize: boolean } | { type: 'NEW_CHAT_MESSAGE', chatId: ChatId, message: ChatMessage } | { type: 'UPDATE_STAGE_COUNTDOWN', stageCountdown: number } | { type: 'UPDATE_VIEWERS', viewers: number } | { type: 'SET_INTERACTIVE_LIMIT', interactiveLimit: number } | { type: 'SET_DISCONNECTED', disconnected: boolean } | { type: 'SET_RECONNECTING', reconnecting: boolean } | { type: 'SET_ARCHIVING', archiving: boolean }; declare type FanAction = { type: 'SET_NEW_FAN_ACKD', newFanSignalAckd: boolean } | { type: 'SET_FAN_NAME', fanName: string } | { type: 'SET_FAN_STATUS', status: FanStatus } | { type: 'SET_ABLE_TO_JOIN', ableToJoin: boolean } | { type: 'SET_FAN_PRIVATE_CALL', inPrivateCall: boolean } | { type: 'SET_NETWORK_TEST_INTERVAL', interval: null | number } | { type: 'SET_NETWORK_TEST_TIMEOUT', timeout: null | number } | { type: 'SET_FITMODE', fitMode: FitMode } | { type: 'SET_PUBLISHER_MINIMIZED', minimized: boolean };
1.59375
2
service/processModel.service.js
Lakshamana/spm-client
0
5599
import { maybe } from '~/util/utils' let source export function makeProcessModelServices(axios) { return { /** * Subscribes to a server's sent event (sse), * dispatched on kafka message comsumption * @param {Number} processModelId * @param {Function} callback */ subscribe(processModelId, token, callback) { const url = `http://${process.env.API_HOST}:${process.env.API_PORT}/api/spm-kafka/subscribe/${processModelId}` + '?token=' + token source = new EventSource(url) source.onmessage = evt => { callback(JSON.parse(evt.data).xmlCell) } }, get source() { return source }, unsubscribe() { axios.get('/api/spm-kafka/unsubscribe').then(response => { if (source) { source.removeEventListener('message') source.close() source = undefined } }) }, publish(username, processModelId, cell, operation) { return axios.post('/api/spm-kafka/publish', { username, processModelId, ...maybe('operation', operation), xmlCell: { nodeType: cell.getAttribute('type'), label: cell.getAttribute('label'), objectId: cell.id, style: cell.style, isEdge: !!cell.edge, ...maybe('x', !cell.edge && cell.geometry.x), ...maybe('y', !cell.edge && cell.geometry.y), ...maybe( 'sourceNode', cell.edge && { objectId: cell.source.id } ), ...maybe( 'targetNode', cell.edge && { objectId: cell.target.id } ) } }) } } }
0.980469
1
install/src/PQ Dashboard/Scripts/TSX/openSEE.js
StephenCWills/PQDashboard
0
5607
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var ReactDOM = require("react-dom"); var OpenSEE_1 = require("./../TS/Services/OpenSEE"); var createBrowserHistory_1 = require("history/createBrowserHistory"); var queryString = require("query-string"); var _ = require("lodash"); var WaveformViewerGraph_1 = require("./WaveformViewerGraph"); var PolarChart_1 = require("./PolarChart"); var AccumulatedPoints_1 = require("./AccumulatedPoints"); var Tooltip_1 = require("./Tooltip"); var OpenSEE = (function (_super) { __extends(OpenSEE, _super); function OpenSEE(props) { var _this = _super.call(this, props) || this; _this.openSEEService = new OpenSEE_1.default(); _this.history = createBrowserHistory_1.default(); var query = queryString.parse(_this.history['location'].search); _this.resizeId; _this.state = { eventid: (query['eventid'] != undefined ? query['eventid'] : 0), StartDate: query['StartDate'], EndDate: query['EndDate'], displayVolt: true, displayCur: true, faultcurves: query['faultcurves'] == '1' || query['faultcurves'] == 'true', breakerdigitals: query['breakerdigitals'] == '1' || query['breakerdigitals'] == 'true', Width: window.innerWidth, Hover: 0, PointsTable: [], TableData: {}, backButtons: [], forwardButtons: [], PostedData: {} }; _this.TableData = {}; _this.history['listen'](function (location, action) { var query = queryString.parse(_this.history['location'].search); _this.setState({ eventid: (query['eventid'] != undefined ? query['eventid'] : 0), StartDate: query['StartDate'], EndDate: query['EndDate'], faultcurves: query['faultcurves'] == '1' || query['faultcurves'] == 'true', breakerdigitals: query['breakerdigitals'] == '1' || query['breakerdigitals'] == 'true', }); }); return _this; } OpenSEE.prototype.componentDidMount = function () { var _this = this; window.addEventListener("resize", this.handleScreenSizeChange.bind(this)); this.openSEEService.getHeaderData(this.state).done(function (data) { _this.showData(data); var back = []; back.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForSystem.m_Item1, "system-back", "&navigation=system", "<")); back.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForMeterLocation.m_Item1, "station-back", "&navigation=station", "<")); back.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForMeter.m_Item1, "meter-back", "&navigation=meter", "<")); back.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForLine.m_Item1, "line-back", "&navigation=line", "<")); var forward = []; forward.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForSystem.m_Item2, "system-next", "&navigation=system", ">")); forward.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForMeterLocation.m_Item2, "station-next", "&navigation=station", ">")); forward.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForMeter.m_Item2, "meter-next", "&navigation=meter", ">")); forward.push(_this.nextBackButton(data.nextBackLookup.GetPreviousAndNextEventIdsForLine.m_Item2, "line-next", "&navigation=line", ">")); _this.setState({ PostedData: data, backButtons: back, forwardButtons: forward }, function () { _this.nextBackSelect($('#next-back-selection option:selected').val()); $('#next-back-selection').change(function () { _this.nextBackSelect($('#next-back-selection option:selected').val()); }); }); }); }; OpenSEE.prototype.componentWillUnmount = function () { $(window).off('resize'); }; OpenSEE.prototype.handleScreenSizeChange = function () { var _this = this; clearTimeout(this.resizeId); this.resizeId = setTimeout(function () { _this.setState({ Width: window.innerWidth, Height: _this.calculateHeights(_this.state) }); }, 500); }; OpenSEE.prototype.render = function () { var _this = this; var height = this.calculateHeights(this.state); return (React.createElement("div", null, React.createElement("div", { id: "pageHeader", style: { width: '100%' } }, React.createElement("table", { style: { width: '100%' } }, React.createElement("tbody", null, React.createElement("tr", null, React.createElement("td", { style: { textAlign: 'left', width: '10%' } }, React.createElement("img", { src: '../Images/GPA-Logo---30-pix(on-white).png' })), React.createElement("td", { style: { textAlign: 'center', width: '80%' } }, React.createElement("img", { src: '../Images/openSEET.png' })), React.createElement("td", { style: { textAlign: 'right', verticalAlign: 'top', whiteSpace: 'nowrap', width: '10%' } }, React.createElement("img", { alt: "", src: "../Images/GPA-Logo.png", style: { display: 'none' } }))), React.createElement("tr", null, React.createElement("td", { colSpan: 3, style: { textAlign: 'center' } }, React.createElement("div", null, React.createElement("span", { id: "TitleData" }), "\u00A0\u00A0\u00A0", React.createElement("a", { type: "button", target: "_blank", id: "editButton" }, "edit"))))))), React.createElement("div", { className: "DockWaveformHeader" }, React.createElement("table", { style: { width: '75%', margin: '0 auto' } }, React.createElement("tbody", null, React.createElement("tr", null, React.createElement("td", { style: { textAlign: 'center' } }, React.createElement("button", { className: "smallbutton", onClick: function () { return _this.resetZoom(); } }, "Reset Zoom")), React.createElement("td", { style: { textAlign: 'center' } }, React.createElement("input", { className: "smallbutton", type: "button", value: "Show Points", onClick: function () { return _this.showhidePoints(); }, id: "showpoints" })), React.createElement("td", { style: { textAlign: 'center' } }, this.state.backButtons, React.createElement("select", { id: "next-back-selection", defaultValue: "system" }, React.createElement("option", { value: "system" }, "System"), React.createElement("option", { value: "station" }, "Station"), React.createElement("option", { value: "meter" }, "Meter"), React.createElement("option", { value: "line" }, "Line")), this.state.forwardButtons), React.createElement("td", { style: { textAlign: 'center' } }, React.createElement("input", { className: "smallbutton", type: "button", value: "Show Tooltip", onClick: function () { return _this.showhideTooltip(); }, id: "showtooltip" })), React.createElement("td", { style: { textAlign: 'center' } }, React.createElement("input", { className: "smallbutton", type: "button", value: "Show Phasor", onClick: function () { return _this.showhidePhasor(); }, id: "showphasor" })), React.createElement("td", { style: { textAlign: 'center', display: 'none' } }, React.createElement("input", { className: "smallbutton", type: "button", value: "Export Data", onClick: function () { }, id: "exportdata" })))))), React.createElement("div", { className: "panel-body collapse in", style: { padding: '0' } }, React.createElement(PolarChart_1.default, { data: this.state.TableData, callback: this.stateSetter.bind(this) }), React.createElement(AccumulatedPoints_1.default, { pointsTable: this.state.PointsTable, callback: this.stateSetter.bind(this), postedData: this.state.PostedData }), React.createElement(Tooltip_1.default, { data: this.state.TableData, hover: this.state.Hover }), React.createElement(WaveformViewerGraph_1.default, { eventId: this.state.eventid, startDate: this.state.StartDate, endDate: this.state.EndDate, type: "Voltage", pixels: this.state.Width, stateSetter: this.stateSetter.bind(this), height: height, hover: this.state.Hover, tableData: this.TableData, pointsTable: this.state.PointsTable, tableSetter: this.tableUpdater.bind(this), display: this.state.displayVolt, postedData: this.state.PostedData }), React.createElement(WaveformViewerGraph_1.default, { eventId: this.state.eventid, startDate: this.state.StartDate, endDate: this.state.EndDate, type: "Current", pixels: this.state.Width, stateSetter: this.stateSetter.bind(this), height: height, hover: this.state.Hover, tableData: this.TableData, pointsTable: this.state.PointsTable, tableSetter: this.tableUpdater.bind(this), display: this.state.displayCur, postedData: this.state.PostedData }), React.createElement(WaveformViewerGraph_1.default, { eventId: this.state.eventid, startDate: this.state.StartDate, endDate: this.state.EndDate, type: "F", pixels: this.state.Width, stateSetter: this.stateSetter.bind(this), height: height, hover: this.state.Hover, tableData: this.TableData, pointsTable: this.state.PointsTable, tableSetter: this.tableUpdater.bind(this), display: this.state.faultcurves, postedData: this.state.PostedData }), React.createElement(WaveformViewerGraph_1.default, { eventId: this.state.eventid, startDate: this.state.StartDate, endDate: this.state.EndDate, type: "B", pixels: this.state.Width, stateSetter: this.stateSetter.bind(this), height: height, hover: this.state.Hover, tableData: this.TableData, pointsTable: this.state.PointsTable, tableSetter: this.tableUpdater.bind(this), display: this.state.breakerdigitals, postedData: this.state.PostedData })))); }; OpenSEE.prototype.stateSetter = function (obj) { var _this = this; this.setState(obj, function () { var prop = _.clone(_this.state); delete prop.Hover; delete prop.Width; delete prop.TableData; delete prop.PointsTable; delete prop.displayCur; delete prop.displayVolt; delete prop.backButtons; delete prop.forwardButtons; delete prop.PostedData; var qs = queryString.parse(queryString.stringify(prop, { encode: false })); var hqs = queryString.parse(_this.history['location'].search); if (!_.isEqual(qs, hqs)) _this.history['push'](_this.history['location'].pathname + '?' + queryString.stringify(prop, { encode: false })); }); }; OpenSEE.prototype.tableUpdater = function (obj) { this.TableData = _.merge(this.TableData, obj); this.setState({ TableData: this.TableData }); }; OpenSEE.prototype.resetZoom = function () { this.history['push'](this.history['location'].pathname + '?eventid=' + this.state.eventid + (this.state.faultcurves ? '&faultcurves=1' : '') + (this.state.breakerdigitals ? '&breakerdigitals=1' : '')); }; OpenSEE.prototype.calculateHeights = function (obj) { return (window.innerHeight - 100 - 30) / (Number(obj.displayVolt) + Number(obj.displayCur) + Number(obj.faultcurves) + Number(obj.breakerdigitals)); }; OpenSEE.prototype.nextBackSelect = function (nextBackType) { $('.nextbackbutton').hide(); $('#' + nextBackType + '-back').show(); $('#' + nextBackType + '-next').show(); }; OpenSEE.prototype.showhidePoints = function () { if ($('#showpoints').val() == "Show Points") { $('#showpoints').val("Hide Points"); $('#accumulatedpoints').show(); } else { $('#showpoints').val("Show Points"); $('#accumulatedpoints').hide(); } }; OpenSEE.prototype.showhideTooltip = function () { if ($('#showtooltip').val() == "Show Tooltip") { $('#showtooltip').val("Hide Tooltip"); $('#unifiedtooltip').show(); $('.legendCheckbox').show(); } else { $('#showtooltip').val("Show Tooltip"); $('#unifiedtooltip').hide(); $('.legendCheckbox').hide(); } }; OpenSEE.prototype.showhidePhasor = function () { if ($('#showphasor').val() == "Show Phasor") { $('#showphasor').val("Hide Phasor"); $('#phasor').show(); } else { $('#showphasor').val("Show Phasor"); $('#phasor').hide(); } }; OpenSEE.prototype.showData = function (data) { if (data.postedEventName != undefined) { var label = ""; var details = ""; var separator = "&nbsp;&nbsp;&nbsp;||&nbsp;&nbsp;&nbsp;"; var faultLink = '<a href="#" title="Click for fault details" onClick="showdetails(this);">Fault</a>'; label += "Station: " + data.postedStationName; label += separator + "Meter: " + data.postedMeterName; label += separator + "Line: " + data.postedLineName; label += "<br />"; if (data.postedEventName != "Fault") label += "Event Type: " + data.postedEventName; else label += "Event Type: " + faultLink; label += separator + "Event Time: " + data.postedEventDate; if (data.postedStartTime != undefined) details += "Start: " + data.postedStartTime; if (data.postedPhase != undefined) { if (details != "") details += separator; details += "Phase: " + data.postedPhase; } if (data.postedDurationPeriod != undefined) { if (details != "") details += separator; details += "Duration: " + data.postedDurationPeriod; } if (data.postedMagnitude != undefined) { if (details != "") details += separator; details += "Magnitude: " + data.postedMagnitude; } if (details != "") label += "<br />" + details; details = ""; if (data.postedBreakerNumber != undefined) details += "Breaker: " + data.postedBreakerNumber; if (data.postedBreakerPhase != undefined) { if (details != "") details += separator; details += "Phase: " + data.postedBreakerPhase; } if (data.postedBreakerTiming != undefined) { if (details != "") details += separator; details += "Timing: " + data.postedBreakerTiming; } if (data.postedBreakerSpeed != undefined) { if (details != "") details += separator; details += "Speed: " + data.postedBreakerSpeed; } if (data.postedBreakerOperation != undefined) { if (details != "") details += separator; details += "Operation: " + data.postedBreakerOperation; } if (details != "") label += "<br />" + details; document.getElementById('TitleData').innerHTML = label; if (data.xdaInstance != undefined) $('#editButton').prop('href', data.xdaInstance + "/Workbench/Event.cshtml?EventID=" + this.state.eventid); } }; OpenSEE.prototype.nextBackButton = function (evt, id, postedURLQueryString, text) { if (evt != null) { var title = evt.StartTime; var url = "?eventid=" + evt.ID + postedURLQueryString; return React.createElement("a", { href: url, id: id, key: id, className: 'nextbackbutton smallbutton', title: title, style: { padding: '4px 20px' } }, text); } else return React.createElement("a", { href: '#', id: id, key: id, className: 'nextbackbutton smallbutton-disabled', title: 'No event', style: { padding: '4px 20px' } }, text); }; return OpenSEE; }(React.Component)); exports.OpenSEE = OpenSEE; ReactDOM.render(React.createElement(OpenSEE, null), document.getElementById('DockCharts')); //# sourceMappingURL=openSEE.js.map
1.492188
1
tags/v20160318/admin/views/order/pickup.js
XiaoFeiFeng/shipping
0
5615
'use strict' define([], function () { angular.module('orderPickupModule', []) .controller("orderPickupCtrl", ['$scope', '$ui', '$data', '$request', '$timeout', function ($scope, $ui, $data, $request, $timeout) { $scope.currentPage = 1; $scope.pageSize = 10; $scope.pageChange = function () { $scope.initGridData(); } $scope.handler = function (data) { $ui.openWindow('views/order/handler.html', 'orderhandlerCtrl', data.addressStr, function (result) { if (result) { $timeout(function () { $scope.submit(data, result); }, 100); } }); } //提交分发数据 $scope.submit = function (pickup, merchant) { var data = {}; data.tracks = pickup.tracks; if (!data.tracks) { data.tracks = []; } var track = {}; track.address = merchant.address; track.mid = merchant._id.$id; track.tel = merchant.telephone; data.tracks.push(track); data.state = 1; data.owner = merchant._id.$id; $request.post('api/?model=package&action=edit&id=' + pickup._id.$id, data, function (response) { if (response.success) { $ui.notify("分发成功", "提示", function () { $scope. initGridData(); $scope.initGridData(); }); } else if (angular.isUndefined(response.success)) { $ui.error(response, "错误"); } else { $ui.error(response.error, "错误"); } }, function (err) { $ui.error('添加失败,' + err, '错误'); }); } $scope.formatterTimer = function (input) { var date = new Date(input * 1000); return date.format("yyyy-MM-dd HH:mm:ss"); } $scope.gridOptions = { data: [], cols: [ {FieldName: 'name', DisplayName: '寄件人',}, {FieldName: 'tel', DisplayName: '电话',}, {FieldName: 'created_time', DisplayName: '下单时间', Formatter: $scope.formatterTimer}, {FieldName: 'addressStr', DisplayName: '地址',}, ], colsOpr: { headName: '操作', headClass: '', init: { showView: false, viewFn: function (data) { $scope.viewDetail(data); }, showEdit: false, editFn: function (data) { $scope.edit(data); }, showDelete: false, }, colInfo: [ { title: '分配加盟商', iconClass: 'fa fa-edit', clickFn: function (data) { $scope.handler(data); }, }, ], }, rowOpr: { rowSelected: function (data) { //alert("row selected"); }, }, colsHidden: [], } $scope.initGridData = function (state) { $request.get('api/?model=package&action=get_packages&state=0' + '&pi=' + $scope.currentPage + '&ps=' + $scope.pageSize, function (response) { if (response.success) { $scope.handlerData(response.data); $scope.totalItems = response.count; } else if (angular.isUndefined(response.success)) { $ui.error(response); } else { $ui.error(response.error); } } ); } $scope.handlerData = function (data) { if (data && data.length > 0) { angular.forEach(data, function (d) { d.addressStr = d.district.cn.join(" ") + " " + d.address; }) } else { data = []; } $scope.gridOptions.data = data; } $scope.initGridData(); } ]) })
1.460938
1
src/main/resources/static/javascript/jserr.js
MagikLau/WeChatPlatformApplication
14
5623
var BJ_REPORT=function(e){ function n(){ if(t.id!=S.IDS.DEFAULT||t.key!=S.KEY)return{ id:t.id, key:t.key }; var e={ _href:location.href, href:location.href.replace("https://mp.weixin.qq.com/","") }; e.cgi=e.href.indexOf("?")>-1?e.href.match(/.*?\?/g)[0].slice(0,-1):e.href; var n=(e.href+"&").match(/action\=(.*?)&/); n&&n[1]&&(e.action=n[1]); var i=S.IDS.DEFAULT,r=S.KEY; return"cgi-bin/masssendpage"==e.cgi?(i=S.IDS.MASS,r=66):"advanced/autoreply"==e.cgi?(i=S.IDS.AUTO_REPLY, r=70):"advanced/selfmenu"==e.cgi?(i=S.IDS.SELF_MENU,r=68):"misc/appmsgcomment"==e.cgi?(i=S.IDS.COMMENT, r=71):"cgi-bin/newoperatevote"==e.cgi?(i=S.IDS.VOTE,r=72):"misc/kf"==e.cgi?(i=S.IDS.KF, r=73):"merchant/rewardstat"==e.cgi||"merchant/reward"==e.cgi?(i=S.IDS.REWARD,r=74):"cgi-bin/appmsgcopyright"==e.cgi||"cgi-bin/imgcopyright"==e.cgi||"cgi-bin/ori_video"==e.cgi?(i=S.IDS.COPYRIGHT, r=75):"cgi-bin/message"==e.cgi?(i=S.IDS.MSG,r=76):"cgi-bin/user_tag"==e.cgi?(i=S.IDS.USER, r=77):"cgi-bin/appmsg"==e.cgi&&("list_card"==e.action||"list"==e.action)||"cgi-bin/filepage"==e.cgi?(i=S.IDS.LIST, r=78):"cgi-bin/operate_voice"==e.cgi?(i=S.IDS.AUDIO,r=79):"cgi-bin/appmsg"==e.cgi&&"video_edit"==e.action?(i=S.IDS.VEDIO, r=80):"cgi-bin/appmsg"==e.cgi&&"edit"==e.action?(i=S.IDS.APPMSG,r=62):"cgi-bin/frame"==e.cgi&&/t=ad_system/.test(e.href)||/merchant\/ad_/.test(e.cgi)?(i=S.IDS.AD, r=81):"misc/useranalysis"==e.cgi||"misc/appmsganalysis"==e.cgi||"misc/menuanalysis"==e.cgi||"misc/messageanalysis"==e.cgi||"misc/interfaceanalysis"==e.cgi?(i=S.IDS.ANALYSIS, r=82):"cgi-bin/settingpage"==e.cgi||"acct/contractorinfo"==e.cgi?(i=S.IDS.SETTING, r=83):"merchant/store"==e.cgi||"merchant/order"==e.cgi||"acct/wxverify"==e.cgi?(i=S.IDS.VERIFY, r=84):"cgi-bin/safecenterstatus"==e.cgi?(i=S.IDS.SAFE,r=85):"cgi-bin/illegalrecord"==e.cgi?(i=S.IDS.ILLEGAL, r=86):"advanced/advanced"==e.cgi||"advanced/diagram"==e.cgi||"cgi-bin/frame"==e.cgi&&/t=advanced\/dev_tools_frame/.test(e.href)?(i=S.IDS.ADVANCED, r=87):"acct/contractorpage"==e.cgi?(i=S.IDS.REGISTER,r=88):"cgi-bin/readtemplate"==e.cgi?(i=S.IDS.TMPL, r=89):"advanced/tmplmsg"==e.cgi?(i=S.IDS.TMPLMSG,r=90):"merchant/entityshop"==e.cgi||"merchant/newentityshop"==e.cgi?(i=S.IDS.SHOP, r=92):"merchant/goods"==e.cgi||"merchant/goodsgroup"==e.cgi||"merchant/shelf"==e.cgi||"merchant/goodsimage"==e.cgi||"merchant/delivery"==e.cgi||"merchant/productorder"==e.cgi||"merchant/merchantstat"==e.cgi||"merchant/introduction"==e.cgi||"merchant/merchantpush"==e.cgi||"merchant/merchantentrance"==e.cgi?(i=S.IDS.MERCHANT, r=104):"cgi-bin/home"==e.cgi?(i=S.IDS.HOME,r=93):"merchant/cardapply"==e.cgi&&"listapply"==e.action?r=95:e.cgi.indexOf("beacon")>-1&&(i=S.IDS.IBEACON, r=96),wx&&"en_US"==wx.lang&&(i=125,r=125),t.id=i,t.key=r,{ id:i, key:r }; } function i(e,n){ return e.indexOf("TypeError: #<KeyboardEvent> is not a function")>-1||e.indexOf("TypeError: #<MouseEvent> is not a function")>-1?!1:e.indexOf("ReferenceError: LIST_INFO is not defined")>-1?!1:e.indexOf("TypeError: e is not a constructor")>-1?!1:location&&/token=\d+/.test(location.href)&&"0"==wx.uin?!1:/Mozilla\/5.0.*ipad.*BaiduHD/i.test(n)&&e.indexOf("ReferenceError: Can't find variable: bds")>-1?!1:/Linux; U; Android.*letv/i.test(n)&&e.indexOf("ReferenceError: diableNightMode is not defined")>-1?!1:!0; } if(e.BJ_REPORT)return e.BJ_REPORT; var r=[],t={ uin:0, url:"https://badjs.weixinbridge.com/badjs", combo:0, level:4, ignore:[], random:1, delay:0, submit:null },c=function(e,n){ return Object.prototype.toString.call(e)==="[object "+(n||"Object")+"]"; },o=function(e){ var n=typeof e; return"object"===n&&!!e; },a=function(e){ return null===e?!0:c(e,"Number")?!1:!e; },g=e.onerror; e.onerror=function(n,r,t,o,a){ var s=n; a&&a.stack&&(s=d(a)),c(s,"Event")&&(s+=s.type?"--"+s.type+"--"+(s.target?s.target.tagName+"::"+s.target.src:""):""), r&&r.length>0&&0==/^https\:\/\/(mp\.weixin\.qq\.com|res\.wx\.qq\.com)/.test(r),(1!=t||1!=o&&86!=o||-1!=n.indexOf("eval"))&&0!=i(s,window.navigator.userAgent)&&(S.push({ msg:s+"|onerror", target:r, rowNum:t, colNum:o }),I(),g&&g.apply(e,arguments)); }; var s=function(e){ try{ if(e.stack){ var n=e.stack.match("https?://[^\n]+"); n=n?n[0]:""; var r=n.match(":(\\d+):(\\d+)"); r||(r=[0,0,0]); var t=d(e).replace(/https?\:\/\/.*?\.js\:/g,""); return 0==i(t,window.navigator.userAgent)?null:{ msg:t, rowNum:r[1], colNum:r[2], target:n.replace(r[0],"") }; } return e; }catch(c){ return e; } },d=function(e){ var n=e.stack.replace(/\n/gi,"").split(/\bat\b/).slice(0,5).join("@").replace(/\?[^:]+/gi,""),i=e.toString(); return n.indexOf(i)<0&&(n=i+"@"+n),n; },m=function(e,n){ var i=[],r=[],c=[]; if(o(e)){ e.level=e.level||t.level; for(var g in e){ var s=e[g]; if(!a(s)){ if(o(s))try{ s=JSON.stringify(s); }catch(d){ s="[BJ_REPORT detect value stringify error] "+d.toString(); } c.push(g+":"+s),i.push(g+"="+encodeURIComponent(s)),r.push(g+"["+n+"]="+encodeURIComponent(s)); } } } return[r.join("&"),c.join(","),i.join("&")]; },u=[],l=[],f=function(e){ var n=e.replace(/\&_t=\d*/,""); for(var i in l)if(l[i]==n)return; if(l.push(n),t.submit)t.submit(e);else{ var r=new Image; u.push(r),r.src=e; } var c="error"; if(c=e.match(/msg=(.*?)&/),c&&c[1]&&(c=c[1]),wx&&wx.uin&&(c+=encodeURIComponent("|uin|"+wx.uin)), t.key){ var r=new Image; r.src="https://mp.weixin.qq.com/misc/jslog?id="+t.key+"&content="+c+"&level=error"; } var o=new Image; o.src="https://mp.weixin.qq.com/misc/jslog?id=65&content="+c+"&level=error"; },p=[],h=0,I=function(e){ if(t.report){ for(;r.length;){ var n=!1,i=r.shift(),o=m(i,p.length); if(c(t.ignore,"Array"))for(var a=0,g=t.ignore.length;g>a;a++){ var s=t.ignore[a]; if(c(s,"RegExp")&&s.test(o[1])||c(s,"Function")&&s(i,o[1])){ n=!0; break; } } n||(t.combo?p.push(o[0]):f(t.report+o[2]+"&_t="+ +new Date),t.onReport&&t.onReport(t.id,i)); } var d=p.length; if(d){ var u=function(){ clearTimeout(h),console.log("comboReport"+p.join("&")),f(t.report+p.join("&")+"&count="+d+"&_t="+ +new Date), h=0,p=[]; }; e?u():h||(h=setTimeout(u,t.delay,!0),console.log("_config.delay"+t.delay)); } } },S={ KEY:67, IDS:{ DEFAULT:"5", MASS:"6", SELF_MENU:"7", LINK:"11", AUTO_REPLY:"12", COMMENT:"13", VOTE:"14", KF:"15", REWARD:"16", COPYRIGHT:"17", MSG:"18", USER:"19", LIST:"20", AUDIO:"21", VEDIO:"22", APPMSG:"4", AD:"23", ANALYSIS:"24", SETTING:"25", VERIFY:"26", SAFE:"27", ILLEGAL:"28", ADVANCED:"29", REGISTER:"30", TMPL:"31", IE:"32", CARD:"33", SHOP:"34", TMPLMSG:"35", HOME:"36", Android:"37", IOS:"38", IBEACON:"72", MERCHANT:"82" }, destory:function(){ I=function(){}; }, push:function(e,n){ if(Math.random()>=t.random)return S; var i; if(o(e)){ if(i=s(e),n&&(i.msg+="["+n+"]"),i){ if(i.target&&0==/^https?\:\/\/(mp\.weixin\.qq\.com|res\.wx\.qq\.com)/.test(i.target))return S; r.push(i); } }else n&&(e+="["+n+"]"),r.push({ msg:e }); return I(),S; }, report:function(e,n){ return e&&S.push(e,n),S; }, info:function(e){ return e?(o(e)?e.level=2:e={ msg:e, level:2 },S.push(e),S):S; }, debug:function(e){ return e?(o(e)?e.level=1:e={ msg:e, level:1 },S.push(e),S):S; }, init:function(e){ for(var n in e)t[n]=e[n]; var i=parseInt(t.id,10),n=parseInt(t.key,10); return window.navigator.userAgent&&/;\s*MSIE\s*[8|7]\.0b?;/i.test(window.navigator.userAgent)?(i=S.IDS.IE, n=0):window.navigator.userAgent.indexOf("Android")>-1||window.navigator.userAgent.indexOf("Adr")>-1?(i=S.IDS.Android, n=0):window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)&&(i=S.IDS.IOS, n=0),i&&n&&(t.report=t.url+"?id="+i+"&key="+n+"&uin="+(wx&&wx.uin)+"&from="+encodeURIComponent(location.href)+"&"), S; }, monitor:function(e,n,i){ if(n=n||"badjs|monitor",e){ var r=new Image; r.src="https://mp.weixin.qq.com/misc/jslog?id="+e+"&content="+encodeURIComponent(n)+"&level=error"; } if(i){ var c=new Image; c.src=t.url+"?id="+i+"&msg="+encodeURIComponent(n)+"&uin="+(wx&&wx.uin)+"&from="+encodeURIComponent(location.href)+"&level=4"; } }, getConfig:function(){ return t; }, __onerror__:e.onerror }; return"undefined"!=typeof console&&console.error&&setTimeout(function(){ var e=((location.hash||"").match(/([#&])BJ_ERROR=([^&$]+)/)||[])[2]; e&&console.error("BJ_ERROR",decodeURIComponent(e).replace(/(:\d+:\d+)\s*/g,"$1\n")); },0,!0),t.id=S.IDS.DEFAULT,t.key=S.KEY,n(),S.init(),S; }(window);
1.039063
1