<commit_before>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var minifyCss    = require('gulp-minify-css');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');
var fs           = require('fs');
var isStream     = require('is-stream');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'ie 8',
        'ie 9',
        'android 2.3',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(minifyCss, {
      advanced: false,
      rebase: false
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.'));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify)
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.'));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{lib,templates}/**/*.php', '*.php'],
    proxy: config.devUrl,
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<commit_msg>fix the sass less resolution by switching pipes<commit_after>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var minifyCss    = require('gulp-minify-css');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');
var fs           = require('fs');
var isStream     = require('is-stream');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'ie 8',
        'ie 9',
        'android 2.3',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(minifyCss, {
      advanced: false,
      rebase: false
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.'));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify)
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.'));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{lib,templates}/**/*.php', '*.php'],
    proxy: config.devUrl,
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<|endoftext|>


<commit_before>/* Janus Event Tracer (C) 2022 QXIP BV */

var base_filter = require('@pastash/pastash').base_filter,
  util = require('util'),
  logger = require('@pastash/pastash').logger;

var recordCache = require("record-cache");
var fetch = require('cross-fetch');

function nano_now(date){ return (date * 1000) + '000' }
function just_now(){ return new Date().getTime() }
function uuid(){ return (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2) };

function FilterAppJanusTracer() {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppJanusTracer',
    optional_params: ['debug', 'cacheSize', 'cacheAge', 'endpoint', 'bypass'],
    default_values: {
      'cacheSize': 50000,
      'cacheAge':  60000,
      'endpoint': 'http://localhost:3100/tempo/api/push',
      'bypass': true,
      'debug': false
    },
    start_hook: this.start.bind(this)
  });
}

util.inherits(FilterAppJanusTracer, base_filter.BaseFilter);

FilterAppJanusTracer.prototype.start = async function(callback) {

  // Event cache
  var cache = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.cache = cache;

  // Session cache
  var sessions = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.sessions = sessions;

  logger.info('Initialized App Janus Event Tracer');
  callback();
};

FilterAppJanusTracer.prototype.process = function(data) {
   if (!data.message) return data;
   var line = JSON.parse(data.message);
   if (!line.session_id || !line.handle_id) return data

   if (line.type == 1){
	var event = { name: line.event.name, event: line.event.name, id: line.session_id }
	event.traceId = uuid()
	event.duration = 0
	if (line.event.name == "created"){
		// start root trace, do not update
		this.sessions.add(event.session_id, just_now());
		this.session.add('uuid_'+event.session_id, event.traceId)
	} else if (line.event.name == "destroyed"){
		// end root trace
		this.sessions.remove(event.session_id);
		this.sessions.remove('uuid_'+event.session_id);
	}

   } else if (line.type == 2) {
	if (!line.event.data) return;
	var event = { name: line.event.name, event: line.event.name, id: line.session_id, handle: line.handle_id }
	// session tracing + reset
	event.traceId = this.sessions.get('uuid_'+event.session_id, 1)[0] || uuid();
	var previous_ts = this.sessions.get(event.session_id, 1)[0] || 0;
	event.duration = just_now() - parseInt(previous_ts);
	this.sessions.add(event.session_id, just_now());

	if(event.name == "attached") {
		// session_id, handle_id, opaque_id
	} else if (event.name == "detached") {
		// session_id, handle_id, opaque_id
		this.sessions.remove(event.handle_id);
	}
	event.parentId = event.id

   } else if (line.type == 64){
	if (!line.event.data) return data;
	var event = { name: line.event.plugin, event: line.event.data.event, id: line.event.data.id, handle: line.handle_id }
	// session tracing + reset
	event.traceId = this.sessions.get('uuid_'+event.session_id, 1)[0] || uuid();
	var previous_ts = this.sessions.get(event.session_id, 1)[0] || 0;
	event.duration = just_now() - parseInt(previous_ts);
	this.sessions.add(event.session_id, just_now());

	if (event.event == "joined"){
		// session_id, handle_id, opaque_id, event.data.id
		// correlate: session_id --> event.data.id
		this.cache.add(event.id, event.session_id);
	} else if (event.event == "configured"){
		// session_id, handle_id, opaque_id, event.data.id
	} else if (event.event == "published"){
		// session_id, handle_id, opaque_id, event.data.id
		this.cache.add(event.id, event.session_id);
	} else if (event.event == "unpublished"){
		// correlate: event.data.id --> session_id
		event.session_id = this.cache.get(fingerprint_event, 1)[0] || false;
		line.session_id = event.session_id;
	} else if (event.event == "leaving"){
		// correlate: event.data.id --> session_id
		event.session_id = this.cache.get(fingerprint_event, 1)[0] || false;
		line.session_id = event.session_id;
		this.cache.delete(event.id)
	}
        event.parentId = event.session_id
   }

   if(event){
	event.timestamp = line.timestamp;
	event.body = line;
   }
   if(event) var trace = tracegen(event, this.endpoint)
   if (!this.bypass) this.emit('output', trace)
   else if (this.bypass) this.emit('output', data);

};

exports.create = function() {
  return new FilterAppJanusTracer();
};

async function tracegen(event, endpoint){

    var trace = [{
	 "id": event.id,
	 "traceId": event.traceId,
	 "timestamp": nano_now(event.timestamp),
	 "duration": event.duration,
	 "name": event.name,
	  "localEndpoint": {
	    "serviceName": event.event
	  }
    }]
    if (event.parentId){ trace[0].parentId = event.parentId }
    if (event.tags){ trace[0].tags = event.tags }
    logger.info("trace: ", trace);
    // send event to endpoint
    if(endpoint){
	const response = fetch(endpoint, {
	  method: 'POST',
	  body: JSON.stringify(trace),
	  headers: {'Content-Type': 'application/json'}
	})
  .then(res => {
    logger.info(res.json())
  })
  .catch(err => {
    logger.error(err)
  });

  }

}
<commit_msg>Update filter_app_janus_tracer.js<commit_after>/* Janus Event Tracer (C) 2022 QXIP BV */

var base_filter = require('@pastash/pastash').base_filter,
  util = require('util'),
  logger = require('@pastash/pastash').logger;

var recordCache = require("record-cache");
var fetch = require('cross-fetch');

function nano_now(date){ return parseInt(date.toString().padEnd(16, '0')) }
function just_now(date){ return nano_now( date || new Date().getTime() ) }
function uuid(){ return (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2) };

function FilterAppJanusTracer() {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppJanusTracer',
    optional_params: ['debug', 'cacheSize', 'cacheAge', 'endpoint', 'bypass'],
    default_values: {
      'cacheSize': 50000,
      'cacheAge':  60000,
      'endpoint': 'http://localhost:3100/tempo/api/push',
      'bypass': true,
      'debug': false
    },
    start_hook: this.start.bind(this)
  });
}

util.inherits(FilterAppJanusTracer, base_filter.BaseFilter);

FilterAppJanusTracer.prototype.start = async function(callback) {

  // Event cache
  var cache = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.cache = cache;

  // Session cache
  var sessions = recordCache({
    maxSize: this.cacheSize,
    maxAge: this.cacheAge,
    onStale: false
  });
  this.sessions = sessions;

  logger.info('Initialized App Janus Event Tracer');
  callback();
};

FilterAppJanusTracer.prototype.process = function(data) {
   // bypass
   if (this.bypass) this.emit('output', data)

   if (!data.message) return;
   var line = JSON.parse(data.message);
   if (!line.session_id || !line.handle_id) return;

   if (line.type == 1){
	var event = { name: line.event.name, event: line.event.name, id: line.session_id }
	event.traceId = uuid()
	event.duration = 0
	if (line.event.name == "created"){
		// start root trace, do not update
		this.sessions.add(event.session_id, just_now(line.timestamp));
		this.session.add('uuid_'+event.session_id, event.traceId)
	} else if (line.event.name == "destroyed"){
		// end root trace
		this.sessions.remove(event.session_id);
		this.sessions.remove('uuid_'+event.session_id);
	}

   } else if (line.type == 2) {
	if (!line.event.data) return;
	var event = { name: line.event.name, event: line.event.name, id: line.session_id, handle: line.handle_id }
	// session tracing + reset
	event.traceId = this.sessions.get('uuid_'+event.session_id, 1)[0] || uuid();
	var previous_ts = this.sessions.get(event.session_id, 1)[0] || 0;
	event.duration = just_now(line.timestamp) - parseInt(previous_ts);
	this.sessions.add(event.session_id, just_now(line.timestamp));

	if(event.name == "attached") {
		// session_id, handle_id, opaque_id
	} else if (event.name == "detached") {
		// session_id, handle_id, opaque_id
		this.sessions.remove(event.handle_id);
	}
	event.parentId = event.id

   } else if (line.type == 64){
	if (!line.event.data) return;
	var event = { name: line.event.plugin, event: line.event.data.event, id: line.event.data.id, handle: line.handle_id }
	// session tracing + reset
	event.traceId = this.sessions.get('uuid_'+event.session_id, 1)[0] || uuid();
	var previous_ts = this.sessions.get(event.session_id, 1)[0] || 0;
	event.duration = just_now(event.timestamp) - parseInt(previous_ts);
	this.sessions.add(event.session_id, just_now(line.timestamp));

	if (event.event == "joined"){
		// session_id, handle_id, opaque_id, event.data.id
		// correlate: session_id --> event.data.id
		this.cache.add(event.id, event.session_id);
	} else if (event.event == "configured"){
		// session_id, handle_id, opaque_id, event.data.id
	} else if (event.event == "published"){
		// session_id, handle_id, opaque_id, event.data.id
		this.cache.add(event.id, event.session_id);
	} else if (event.event == "unpublished"){
		// correlate: event.data.id --> session_id
		event.session_id = this.cache.get(fingerprint_event, 1)[0] || false;
		line.session_id = event.session_id;
	} else if (event.event == "leaving"){
		// correlate: event.data.id --> session_id
		event.session_id = this.cache.get(fingerprint_event, 1)[0] || false;
		line.session_id = event.session_id;
		this.cache.delete(event.id)
	}
        event.parentId = event.session_id
   }

   if(event){
	event.timestamp = line.timestamp;
	event.body = line;
	tracegen(event, this.endpoint)
   }

};

exports.create = function() {
  return new FilterAppJanusTracer();
};

async function tracegen(event, endpoint){
    // mock a zipkin span
    var trace = [{
	 "id": event.id,
	 "traceId": event.traceId,
	 "timestamp": nano_now(event.timestamp),
	 "duration": event.duration,
	 "name": event.name,
	  "localEndpoint": {
	    "serviceName": event.event
	  }
    }]
    if (event.parentId){ trace[0].parentId = event.parentId }
    if (event.tags){ trace[0].tags = event.tags }
    logger.info("trace: ", trace);
    // send event to endpoint
    if(endpoint){
	const response = fetch(endpoint, {
	  method: 'POST',
	  body: JSON.stringify(trace),
	  headers: {'Content-Type': 'application/json'}
	})
  .then(res => {
    logger.info(res.json())
  })
  .catch(err => {
    logger.error(err)
  });

  }

}
<|endoftext|>


<commit_before>/*
 *  awwnime - Generates a random anime picture.
 *
 *  Contributed by Capuccino and Ovyerus
 */

/* eslint-env node */

const got = require('got');

exports.commands = [
    'awwnime'
];

exports.awwnime = {
    desc: 'Gets you a random anime picture outside of yorium.moe',
    usage: '[query]',
    main: (bot, ctx) => {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.sendTyping();
                got('https://raw-api.now.sh/').then(res => {
                    let images = JSON.parse(res.body);
                    let image = images[Math.floor(Math.random() * images.length)];

                    if (!image) return ctx.createMessage('No results found.');
                    return ctx.createMessage(image.full);
                }).then(resolve).catch(reject);
            } else {
                let query = encodeURIComponent(ctx.suffix).replace(/%20/g, '+');
                ctx.sendTyping();
                got(`https://raw-api.now.sh/?q=${query}`).then(res => {
                    let images = JSON.parse(res.body);
                    let image = images[Math.floor(Math.random() * images.length)];

                    if (!image) return ctx.createMessage('No results found.');
                    return ctx.createMessage(image.full);
                }).then(resolve).catch(reject);
            }
        });
    }
};<commit_msg>ovypls<commit_after>/*
 *  awwnime - Generates a random anime picture.
 *
 *  Contributed by Capuccino and Ovyerus
 */

/* eslint-env node */

const got = require('got');

exports.commands = [
    'awwnime'
];

exports.awwnime = {
    desc: 'Gets you a random anime picture outside of yorium.moe',
    usage: '[query]',
    main: (bot, ctx) => {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.channel.sendTyping();
                got('https://raw-api.now.sh/').then(res => {
                    let images = JSON.parse(res.body);
                    let image = images[Math.floor(Math.random() * images.length)];

                    if (!image) return ctx.createMessage('No results found.');
                    return ctx.createMessage(image.full);
                }).then(resolve).catch(reject);
            } else {
                let query = encodeURIComponent(ctx.suffix).replace(/%20/g, '+');
                ctx.channel.sendTyping();
                got(`https://raw-api.now.sh/?q=${query}`).then(res => {
                    let images = JSON.parse(res.body);
                    let image = images[Math.floor(Math.random() * images.length)];

                    if (!image) return ctx.createMessage('No results found.');
                    return ctx.createMessage(image.full);
                }).then(resolve).catch(reject);
            }
        });
    }
};<|endoftext|>


<commit_before>function createServiceConfiguration(service, clientId, secret) {
    ServiceConfiguration.configurations.upsert(
        {"service": service},
        {
            $set: {
                "clientId": clientId,
                "secret": secret,
                "loginStyle": "popup"
            }
        });
}

Meteor.startup(function() {
    var settings = Meteor.settings[process.env.NODE_ENV];
    console.log("Node.js environment: "+process.env.NODE_ENV);
    if (settings) {
        console.log("Loading tokens...");
        createServiceConfiguration("google", settings.google.oauth_key, settings.google.oauth_secret);
        createServiceConfiguration("meetup", settings.meetup.oauth_key, settings.meetup.oauth_secret);
        //createServiceConfiguration("facebook", settings.facebook.oauth_key, settings.facebook.oauth_secret);
        //createServiceConfiguration("twitter", settings.twitter.oauth_key, settings.twitter.oauth_secret);
        ServiceConfiguration.configurations.upsert(
            {"service": "twitter"},
            {
                $set: {
                    "consumerKey": settings.twitter.oauth_key,
                    "secret": settings.twitter.oauth_secret,
                    "loginStyle": "popup"
                }
            });
        ServiceConfiguration.configurations.upsert(
            {"service": "facebook"},
            {
                $set: {
                    "appId": settings.facebook.oauth_key,
                    "secret": settings.facebook.oauth_secret,
                    "loginStyle": "popup"
                }
            });
    }
});

Accounts.onCreateUser(function(options, user) {
    if (options.profile) user.profile = options.profile;
    if (options.email) user.profile = {"name" : options.email};
    return user;
});<commit_msg>debugging commit<commit_after>function createServiceConfiguration(service, clientId, secret) {
    ServiceConfiguration.configurations.upsert(
        {"service": service},
        {
            $set: {
                "clientId": clientId,
                "secret": secret,
                "loginStyle": "popup"
            }
        });
}

Meteor.startup(function() {
    var settings = Meteor.settings[process.env.NODE_ENV];
    console.log("Node.js environment: "+process.env.NODE_ENV);
    console.log("settings: " + settings);
    console.log("settings type: " + typeof settings);
    if (settings!=undefined) {
        console.log("Loading tokens...") ;
        createServiceConfiguration("google", settings.google.oauth_key, settings.google.oauth_secret);
        createServiceConfiguration("meetup", settings.meetup.oauth_key, settings.meetup.oauth_secret);
        //createServiceConfiguration("facebook", settings.facebook.oauth_key, settings.facebook.oauth_secret);
        //createServiceConfiguration("twitter", settings.twitter.oauth_key, settings.twitter.oauth_secret);
        ServiceConfiguration.configurations.upsert(
            {"service": "twitter"},
            {
                $set: {
                    "consumerKey": settings.twitter.oauth_key,
                    "secret": settings.twitter.oauth_secret,
                    "loginStyle": "popup"
                }
            });
        ServiceConfiguration.configurations.upsert(
            {"service": "facebook"},
            {
                $set: {
                    "appId": settings.facebook.oauth_key,
                    "secret": settings.facebook.oauth_secret,
                    "loginStyle": "popup"
                }
            });
    }
});

Accounts.onCreateUser(function(options, user) {
    if (options.profile) user.profile = options.profile;
    if (options.email) user.profile = {"name" : options.email};
    return user;
});<|endoftext|>


<commit_before>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend("{% include lenovo.html %}".replace(/\n/g, "\n\\"));
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<commit_msg>. [ci skip]<commit_after>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend('{% include lenovo.html %}'.replace("\n" "\n\\"));
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<|endoftext|>


<commit_before>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': '#000000',
    'fillColor': '#000000',
    'fillOpacity': 0.5,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'red',
    'fillColor': '#f03',
    'fillOpacity': 0.5,
    'radius': 75000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var lastUpdated = null;

// Displays the points data provided.
function displayPoints(data) {
  for (var i = 0; i < data.length; i++) {

    // Create LatLng object
    var LatLng = new google.maps.LatLng({
      lat: data[i].Coordinates[0],
      lng: data[i].Coordinates[1]
    });

    var circle = new google.maps.Circle({
      fillColor: pointStyles[data[i].Action].fillColor,
      fillOpacity: pointStyles[data[i].Action].fillOpacity,
      map: map,
      center: LatLng,
      radius: pointStyles[data[i].Action].radius,
      strokeWeight: 0
    });

    if (data[i].Action === 'view') {
      pageviews++;
    }
    if (data[i].Action === 'commitment') {
      commitments++;
    }
  }
  document.getElementById("pageviews").innerText = pageviews;
  document.getElementById("commitments").innerText = commitments;
}

function responseCheck() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      var response = JSON.parse(httpRequest.responseText);
      displayPoints(response);
    } else {
    }
  }
}

// Updates map with latest real time data
function updateMap() {

  httpRequest = new XMLHttpRequest();

  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  var lastUpdatedString = '';
  if (lastUpdated != null) {
    lastUpdatedString = '?lastupdated=' + lastUpdated;
  }

  lastUpdated = new Date() / 1000;

  // Send API GET request for data
  httpRequest.onreadystatechange = responseCheck;
  httpRequest.open('GET', '/rest/live/read' + lastUpdatedString, true);
  httpRequest.send();

}

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds

  updateMap();

  setTimeout(refreshData, x * 1000);
}

refreshData(); // execute function
<commit_msg>Use console.error instead of alert if XMLHTTP cannot be created<commit_after>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': '#000000',
    'fillColor': '#000000',
    'fillOpacity': 0.5,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'red',
    'fillColor': '#f03',
    'fillOpacity': 0.5,
    'radius': 75000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var lastUpdated = null;

// Displays the points data provided.
function displayPoints(data) {
  for (var i = 0; i < data.length; i++) {

    // Create LatLng object
    var LatLng = new google.maps.LatLng({
      lat: data[i].Coordinates[0],
      lng: data[i].Coordinates[1]
    });

    var circle = new google.maps.Circle({
      fillColor: pointStyles[data[i].Action].fillColor,
      fillOpacity: pointStyles[data[i].Action].fillOpacity,
      map: map,
      center: LatLng,
      radius: pointStyles[data[i].Action].radius,
      strokeWeight: 0
    });

    if (data[i].Action === 'view') {
      pageviews++;
    }
    if (data[i].Action === 'commitment') {
      commitments++;
    }
  }
  document.getElementById("pageviews").innerText = pageviews;
  document.getElementById("commitments").innerText = commitments;
}

function responseCheck() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      var response = JSON.parse(httpRequest.responseText);
      displayPoints(response);
    } else {
    }
  }
}

// Updates map with latest real time data
function updateMap() {

  httpRequest = new XMLHttpRequest();

  if (!httpRequest) {
    console.error('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  var lastUpdatedString = '';
  if (lastUpdated != null) {
    lastUpdatedString = '?lastupdated=' + lastUpdated;
  }

  lastUpdated = new Date() / 1000;

  // Send API GET request for data
  httpRequest.onreadystatechange = responseCheck;
  httpRequest.open('GET', '/rest/live/read' + lastUpdatedString, true);
  httpRequest.send();

}

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds

  updateMap();

  setTimeout(refreshData, x * 1000);
}

refreshData(); // execute function
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import { DropFiles } from './DragAndDrop'
import FileUploadInput from './FileUploadInput'

import { submitFormOnCtrlEnter } from './utility/dom'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

class FileUpload extends PureComponent
{
	static propTypes =
	{
		// On file(s) chosen.
		onChange  : PropTypes.func,

		// (deprecated, use `onChange` instead).
		// On file(s) chosen.
		action    : PropTypes.func,

		// Allows choosing multiple files if `true`.
		multiple  : PropTypes.bool,

		// Can be used to restrict the file MIME-types or extensions available for selection.
		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-accept
		accept: PropTypes.string,

		// Disables the file input.
		disabled  : PropTypes.bool,

		// `onClick` handler.
		onClick   : PropTypes.func,

		// Whether choosing a file is required.
		required : PropTypes.bool,

		// Renders an error message below the `<input/>`.
		error     : PropTypes.string,

		tabIndex  : PropTypes.number.isRequired,

		// The clickable area, like "Click here to choose a file".
		children  : PropTypes.node,

		// CSS class
		className : PropTypes.string,

		// CSS style object
		style     : PropTypes.object,

		// A hack for `React.forwardRef()`.
		// Could be rewritten in "hooks" instead.
		// A hack for providing `.focus()` method on `<DropFileUpload/>`.
		ref_: PropTypes.object
	}

	static defaultProps =
	{
		tabIndex : 0
	}

	state =
	{
		draggedOver : false
	}

	onClick = (event) => {
		const {
			disabled,
			onClick
		} = this.props
		if (disabled) {
			if (event) {
				event.preventDefault()
			}
			return
		}
		if (onClick) {
			onClick()
		}
		this.fileInput.click()
	}

	onKeyDown = (event) => {
		if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
			return
		}
		switch (event.keyCode) {
			// "Enter".
			case 13:
			// Spacebar.
			case 32:
				event.preventDefault()
				// Emulate `:active` on key press.
				// setTimeout(() => {
				// 	if (this._isMounted) {
				// 		this.setState({
				// 			isActive: true
				// 		})
				// 	}
				// })
				return this.onClick()
		}
	}

	setDraggedOver = (draggedOver) => this.setState({ draggedOver })

	storeFileInputRef = (ref) => this.fileInput = ref

	render() {
		const {
			ref_,
			required,
			error,
			disabled,
			tabIndex,
			onChange,
			multiple,
			accept,
			style,
			className,
			children
		} = this.props

		const { draggedOver } = this.state

		return (

				{/* Hidden. */}
				{/* "action" property is deprecated. */}
				<FileUploadInput
					ref={ this.storeFileInputRef }
					multiple={ multiple }
					onChange={ onChange || this.props.action }
					error={ error }
					required={ required }
					disabled={ disabled }
					accept={ accept }
					aria-label={ this.props['aria-label'] }/>

				<DropFiles
					ref={ref_}
					role="button"
					tabIndex={ tabIndex }
					aria-label={ this.props['aria-label'] }
					accept={ accept }
					multiple={ multiple }
					onDrop={ onChange }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					setDraggedOver={ this.setDraggedOver }
					className={ classNames(
						/* Developers should define `:focus` styles for `<FileUpload/>`s. */
						'rrui__outline',
						'rrui__file-upload__area',
						{
							'rrui__file-upload__area--disabled' : disabled,
							'rrui__file-upload__area--invalid' : error,
							'rrui__file-upload__area--dragged-over' : draggedOver
						}
					) }>
					{ children }
				</DropFiles>

				{/* Error message (e.g. "Required"). */}
				{ error &&

						{ error }

				}

		)
	}
}

// A hack for providing `.focus()` method on `<DropFileUpload/>`.
export default React.forwardRef((props, ref) => (
	<FileUpload ref_={ref} {...props}/>
))<commit_msg>FileUpload: Added `acceptExtensions` property<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import { DropFiles } from './DragAndDrop'
import FileUploadInput from './FileUploadInput'

import { submitFormOnCtrlEnter } from './utility/dom'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

class FileUpload extends PureComponent
{
	static propTypes =
	{
		// On file(s) chosen.
		onChange  : PropTypes.func,

		// (deprecated, use `onChange` instead).
		// On file(s) chosen.
		action    : PropTypes.func,

		// Allows choosing multiple files if `true`.
		multiple  : PropTypes.bool,

		// Can be used to restrict the file MIME-types or extensions available for selection.
		// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-accept
		accept: PropTypes.string,

		// `acceptExtensions` will be transformed to `accept`.
		acceptExtensions: PropTypes.arrayOf(PropTypes.string),

		// Disables the file input.
		disabled  : PropTypes.bool,

		// `onClick` handler.
		onClick   : PropTypes.func,

		// Whether choosing a file is required.
		required : PropTypes.bool,

		// Renders an error message below the `<input/>`.
		error     : PropTypes.string,

		tabIndex  : PropTypes.number.isRequired,

		// The clickable area, like "Click here to choose a file".
		children  : PropTypes.node,

		// CSS class
		className : PropTypes.string,

		// CSS style object
		style     : PropTypes.object,

		// Deprecated.
		// Rewrite this component in hooks instead.
		// A hack for `React.forwardRef()`.
		// Could be rewritten in "hooks" instead.
		// A hack for providing `.focus()` method on `<DropFileUpload/>`.
		ref_: PropTypes.object
	}

	static defaultProps =
	{
		tabIndex : 0
	}

	state =
	{
		draggedOver : false
	}

	onClick = (event) => {
		const {
			disabled,
			onClick
		} = this.props
		if (disabled) {
			if (event) {
				event.preventDefault()
			}
			return
		}
		if (onClick) {
			onClick()
		}
		this.fileInput.click()
	}

	onKeyDown = (event) => {
		if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
			return
		}
		switch (event.keyCode) {
			// "Enter".
			case 13:
			// Spacebar.
			case 32:
				event.preventDefault()
				// Emulate `:active` on key press.
				// setTimeout(() => {
				// 	if (this._isMounted) {
				// 		this.setState({
				// 			isActive: true
				// 		})
				// 	}
				// })
				return this.onClick()
		}
	}

	setDraggedOver = (draggedOver) => this.setState({ draggedOver })

	storeFileInputRef = (ref) => this.fileInput = ref

	render() {
		const {
			ref_,
			required,
			error,
			disabled,
			tabIndex,
			onChange,
			multiple,
			accept,
			acceptExtensions,
			style,
			className,
			children
		} = this.props

		const { draggedOver } = this.state

		return (

				{/* Hidden. */}
				{/* "action" property is deprecated. */}
				<FileUploadInput
					ref={ this.storeFileInputRef }
					multiple={ multiple }
					onChange={ onChange || this.props.action }
					error={ error }
					required={ required }
					disabled={ disabled }
					accept={ accept || (acceptExtensions && acceptExtensions.map(ext => '.' + ext).join(',')) }
					aria-label={ this.props['aria-label'] }/>

				<DropFiles
					ref={ref_}
					role="button"
					tabIndex={ tabIndex }
					aria-label={ this.props['aria-label'] }
					accept={ accept }
					multiple={ multiple }
					onDrop={ onChange }
					onClick={ this.onClick }
					onKeyDown={ this.onKeyDown }
					setDraggedOver={ this.setDraggedOver }
					className={ classNames(
						/* Developers should define `:focus` styles for `<FileUpload/>`s. */
						'rrui__outline',
						'rrui__file-upload__area',
						{
							'rrui__file-upload__area--disabled' : disabled,
							'rrui__file-upload__area--invalid' : error,
							'rrui__file-upload__area--dragged-over' : draggedOver
						}
					) }>
					{ children }
				</DropFiles>

				{/* Error message (e.g. "Required"). */}
				{ error &&

						{ error }

				}

		)
	}
}

// A hack for providing `.focus()` method on `<DropFileUpload/>`.
export default React.forwardRef((props, ref) => (
	<FileUpload ref_={ref} {...props}/>
))<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Buefy from 'buefy'
import db from 'baqend'
import App from './app'
import router from './router'

db.connect('restless-bolt-1').then(() => {
  Vue.use(VueRouter, Buefy.default)

  /* eslint-disable no-new */
  new Vue({
    el: '#app',
    router,
    template: '<app/>',
    components: { App }
  })
})
<commit_msg>fix app to App<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Buefy from 'buefy'
import db from 'baqend'
import App from './App'
import router from './router'

db.connect('restless-bolt-1').then(() => {
  Vue.use(VueRouter, Buefy.default)

  /* eslint-disable no-new */
  new Vue({
    el: '#app',
    router,
    template: '<app/>',
    components: { App }
  })
})
<|endoftext|>


<commit_before>/* global define, window */
define(['jquery', 'tmclasses/tmclasses'], function(jQuery, tmclasses){
	var __ParallaxBackground = tmclasses.create({
		init: function(){
			this.__parent(arguments);
			if(this.elm){
				this.constructor.window.on('load resize scroll', jQuery.proxy(this._changeHandler, this));
			}
		}
		,properties: {
			elm: undefined
			,calcType: 'centeredStart'
			,movementRatio: 0.8
			,_changeHandler: function(){
				var _viewportHeight = this.constructor.window.height();
				var _viewportTop = this.constructor.window.scrollTop();
				var _elmHeight = this.elm.outerHeight();
				var _elmTop = this.elm.offset().top;
				var _range = _elmHeight + _viewportHeight;
				var _calcOffset = _elmTop - _viewportHeight;
				var _diff = -((_viewportTop - _calcOffset) - _range);
				var _bgPosition;
				if(_diff > _range){
					_bgPosition = 100;
				}else if(_diff < 0){
					_bgPosition = 0;
				}else{
					_bgPosition = (_diff / _range) * 100;
				}
				switch(this.calcType){
					case 'centered':
						_bgPosition = 50 + (_bgPosition - 50) * this.movementRatio;
					break;
					case 'centeredStart':
						if(typeof this._startOffset === 'undefined'){
							var _startingPosition = this.elm.css('background-position-y');
							if(_startingPosition.indexOf('%') !== -1){
								_startingPosition = parseInt(_startingPosition,10);
							}
							this._startOffset = -1 * (50 + (_bgPosition - 50) * this.movementRatio - _startingPosition);
						}
						_bgPosition = 50 + (_bgPosition - 50) * this.movementRatio + this._startOffset;
					break;
				}

				this.elm.css('background-position', 'center ' + _bgPosition + '%');
			}
			,_startOffset: undefined
		}
		,statics: {
			window: jQuery(window)
		}
	});
	return __ParallaxBackground;
});
<commit_msg>ui/parallaxbg: fix error calculating starting bg position in FF with 'centeredStart' calcType !BUGFIX<commit_after>/* global define, window */
define(['jquery', 'tmclasses/tmclasses'], function(jQuery, tmclasses){
	var __ParallaxBackground = tmclasses.create({
		init: function(){
			this.__parent(arguments);
			if(this.elm){
				this.constructor.window.on('load resize scroll', jQuery.proxy(this._changeHandler, this));
			}
		}
		,properties: {
			elm: undefined
			,calcType: 'centeredStart'
			,movementRatio: 0.8
			,_changeHandler: function(){
				var _viewportHeight = this.constructor.window.height();
				var _viewportTop = this.constructor.window.scrollTop();
				var _elmHeight = this.elm.outerHeight();
				var _elmTop = this.elm.offset().top;
				var _range = _elmHeight + _viewportHeight;
				var _calcOffset = _elmTop - _viewportHeight;
				var _diff = -((_viewportTop - _calcOffset) - _range);
				var _bgPosition;
				if(_diff > _range){
					_bgPosition = 100;
				}else if(_diff < 0){
					_bgPosition = 0;
				}else{
					_bgPosition = (_diff / _range) * 100;
				}
				switch(this.calcType){
					case 'centered':
						_bgPosition = 50 + (_bgPosition - 50) * this.movementRatio;
					break;
					case 'centeredStart':
						if(typeof this._startOffset === 'undefined'){
							var _startingPosition = this.elm.css('background-position-y');
							//-- FF doesn't return the 'background-position-y', derive from regular 'background-position'
							if(typeof _startingPosition === 'undefined'){
								_startingPosition = this.elm.css('background-position').split(' ')[1];
							}
							if(_startingPosition.indexOf('%') !== -1){
								_startingPosition = parseInt(_startingPosition,10);
							}
							this._startOffset = -1 * (50 + (_bgPosition - 50) * this.movementRatio - _startingPosition);
						}
						_bgPosition = 50 + (_bgPosition - 50) * this.movementRatio + this._startOffset;
					break;
				}

				this.elm.css('background-position', 'center ' + _bgPosition + '%');
			}
			,_startOffset: undefined
		}
		,statics: {
			window: jQuery(window)
		}
	});
	return __ParallaxBackground;
});
<|endoftext|>


<commit_before>
  /**
   *  Geocoding estimation for a table
   *
   *  - It will show the estimate price of geocoding that table.
   *
   */

  cdb.admin.GeocodingDialog.EstimationModel = cdb.core.Model.extend({

    // defaults: {
    //   rows:       0,
    //   estimation: 0
    // },

    initialize: function() {
      var self = this;
    },

    urlRoot: function() {
      var version = cdb.config.urlVersion('geocoding', 'read');
      return "/api/" + version + "/geocodings/estimation_for/";
    }

  })
<commit_msg>Removed orphan initialize<commit_after>
  /**
   *  Geocoding estimation for a table
   *
   *  - It will show the estimate price of geocoding that table.
   *
   */

  cdb.admin.GeocodingDialog.EstimationModel = cdb.core.Model.extend({

    // defaults: {
    //   rows:       0,
    //   estimation: 0
    // },

    urlRoot: function() {
      var version = cdb.config.urlVersion('geocoding', 'read');
      return "/api/" + version + "/geocodings/estimation_for/";
    }

  })
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AdvancedVariables = require('postcss-advanced-variables');
var merge = require('webpack-merge');
var prettyjson = require('prettyjson');
var config = require('../src/utils/config');

module.exports = function(env) {
	var isProd = env === 'production';

	var includes = [
		__dirname,
		config.rootDir
	];
	var codeMirrorPath = path.join(__dirname, '../node_modules/react-codemirror/node_modules/codemirror');
	var webpackConfig = {
		output: {
			path: config.styleguideDir,
			filename: 'build/bundle.js'
		},
		resolve: {
			root: [
				__dirname
			],
			alias: {
				'codemirror': codeMirrorPath
			}
		},
		resolveLoader: {
			modulesDirectories: [
				'loaders',
				'node_modules'
			]
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: config.title,
				template: './src/templates/index.html',
				inject: true
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env)
				}
			})
		],
		module: {
			loaders: [
				{
					test: /\.js$/,
					include: includes,
					loader: 'babel'
				}
			]
		},
		postcss: function() {
			return [
				AdvancedVariables
			];
		}
	};

	var entryScript = './src/index';

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			entry: [
				entryScript
			],
			devtool: false,
			debug: false,
			cache: false,
			plugins: [
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						warnings: false
					},
					output: {
						comments: false
					},
					mangle: false
				}),
				new webpack.optimize.DedupePlugin(),
				new ExtractTextPlugin('build/styles.css', {
					allChunks: true
				})
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: ExtractTextPlugin.extract('style', 'css')
					},
					{
						test: /\.css$/,
						include: includes,
						loader: ExtractTextPlugin.extract('style', 'css?modules&-minimize&importLoaders=1!postcss')
					}
				]
			}
		});
	}
	else {
		webpackConfig = merge(webpackConfig, {
			entry: [
				'webpack-hot-middleware/client',
				entryScript
			],
			debug: true,
			cache: true,
			devtool: 'eval-source-map',
			stats: {
				colors: true,
				reasons: true
			},
			plugins: [
				new webpack.HotModuleReplacementPlugin(),
				new webpack.NoErrorsPlugin()
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: 'style!css'
					},
					{
						test: /\.css$/,
						include: includes,
						loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
					}
				]
			}
		});
	}

	if (config.updateWebpackConfig) {
		webpackConfig = config.updateWebpackConfig(webpackConfig, env);
	}

	if (config.verbose) {
		console.log();
		console.log('Using Webpack config:');
		console.log(prettyjson.render(webpackConfig));
		console.log();
	}

	return webpackConfig;
};
<commit_msg>Tweak hot reload setup.<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AdvancedVariables = require('postcss-advanced-variables');
var merge = require('webpack-merge');
var prettyjson = require('prettyjson');
var config = require('../src/utils/config');

module.exports = function(env) {
	var isProd = env === 'production';

	var includes = [
		__dirname,
		config.rootDir
	];
	var codeMirrorPath = path.join(__dirname, '../node_modules/react-codemirror/node_modules/codemirror');
	var webpackConfig = {
		output: {
			path: config.styleguideDir,
			filename: 'build/bundle.js'
		},
		resolve: {
			root: [
				__dirname
			],
			alias: {
				'codemirror': codeMirrorPath
			}
		},
		resolveLoader: {
			modulesDirectories: [
				'loaders',
				'node_modules'
			]
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: config.title,
				template: './src/templates/index.html',
				inject: true
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env)
				}
			})
		],
		module: {
			loaders: [
				{
					test: /\.js$/,
					include: includes,
					loader: 'babel'
				}
			]
		},
		postcss: function() {
			return [
				AdvancedVariables
			];
		}
	};

	var entryScript = './src/index';

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			entry: [
				entryScript
			],
			devtool: false,
			debug: false,
			cache: false,
			plugins: [
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						warnings: false
					},
					output: {
						comments: false
					},
					mangle: false
				}),
				new webpack.optimize.DedupePlugin(),
				new ExtractTextPlugin('build/styles.css', {
					allChunks: true
				})
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: ExtractTextPlugin.extract('style', 'css')
					},
					{
						test: /\.css$/,
						include: includes,
						loader: ExtractTextPlugin.extract('style', 'css?modules&-minimize&importLoaders=1!postcss')
					}
				]
			}
		});
	}
	else {
		webpackConfig = merge(webpackConfig, {
			entry: [
				'webpack-hot-middleware/client',
				entryScript
			],
			debug: true,
			cache: true,
			devtool: 'eval-source-map',
			stats: {
				colors: true,
				reasons: true
			},
			plugins: [
				new webpack.optimize.OccurenceOrderPlugin(),
				new webpack.HotModuleReplacementPlugin(),
				new webpack.NoErrorsPlugin()
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: 'style!css'
					},
					{
						test: /\.css$/,
						include: includes,
						loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
					}
				]
			}
		});
	}

	if (config.updateWebpackConfig) {
		webpackConfig = config.updateWebpackConfig(webpackConfig, env);
	}

	if (config.verbose) {
		console.log();
		console.log('Using Webpack config:');
		console.log(prettyjson.render(webpackConfig));
		console.log();
	}

	return webpackConfig;
};
<|endoftext|>


<commit_before>'use strict';

$(function() {

    //
    // Period for simple moving average.
    //
    var smaPeriod = 30;

    //
    // Data loaded for the current graph.
    //
    var curDataFrame = null;

    //
    // Default company code.
    //
    var defaultCompanyCode = 'ABC.AX';

    //
    // Used to suppress chart reload while resizing the chart.
    //
    var resizingChart = false;

    //
    // Load data in format required by highstock.
    //
    var loadHighstockData = function (code, options) {

        var extendedOptions = $.extend({}, options, {
            proxyUrl: 'http://crossorigin.me/', // Proxy to avoid CORS restrictions.
        });

        return dataForge.fromYahoo(code, extendedOptions)
            .then(function (dataFrame) {
                curDataFrame = dataFrame;

                //todo: data-forge needs a reverse fn.
                var reversed = Enumerable.from(dataFrame.toObjects())
                    .reverse()
                    .toArray();

                return new dataForge.DataFrame({ rows: reversed });
            });
    };

    //
    // Destroy the existing chart.
    //
    var destroyChart = function () {
        var chart = $('#container').highcharts();
        if (chart) {
            chart.destroy();
        }
    };

    //
    // Destroy and reload the chart.
    //
    var reloadChart = function () {
        destroyChart();
        loadChart();
    };

    $("#company").change(function() {
        reloadChart();
    });

    $('#loadChart').click(function () {
        reloadChart();
    });

    $('#SMA-period').change(function () {
        smaPeriod = $('#SMA-period').val();
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    $('#recalcSMA').click(function () {
        smaPeriod = parseInt($('#SMA-period').val());
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    //
    // Load new data depending on the selected date range.
    //
    var afterSetExtremes = function(e) {

        if (resizingChart) {
            // Don't need to reload data when resizing the chart.
            return;
        }

        var chart = $('#container').highcharts();

        chart.showLoading('Loading data...');

        var fromDate = new Date(e.min);
        var toDate = new Date(e.max);
        var elapsedMonths = moment(toDate).diff(fromDate, 'months');
        var interval = 'daily';
        if (elapsedMonths > 50) {
            interval = 'monthly';
        }
        else if (elapsedMonths > 18) {
            interval = 'weekly';
        }

        loadHighstockData(defaultCompanyCode, {
                fromDate: fromDate,
                toDate: toDate,
                interval: interval,
            })
            .then(function (dataFrame) {
                var price = dataFrame.getColumnsSubset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.getColumnsSubset(["Date", "Volume"]).toHighstock();

                chart.series[0].setData(price);
                chart.series[2].setData(volume);

                computeSMA(chart, dataFrame);
                chart.hideLoading();
            })
            .catch(function (err) {
                chart.hideLoading();
                console.error(err);
            });
    };

    //
    // Compute simple moving average of the price.
    //
    var computeSMA = function (chart, dataFrame) {
        var sma = dataFrame.setSeries("SMA",
                dataFrame
                    .getSeries("Close")
                    .sma(smaPeriod)
            )
            .getColumnsSubset(["Date", "SMA"])
            .toHighstock();
        chart.series[1].setData(sma);
    };

    //
    // Resize the chart to fit the page.
    //
    var resizeChart = function () {
        try {
            resizingChart = true;
            var chart = $('#container').highcharts();
            chart.setSize($(window).width(), $(window).height()-50);
        }
        finally {
            resizingChart = false;
        }
    };

    //
    // Load the chart.
    //
    var loadChart = function () {

        var code = $("#company").val();
        console.log('Loading ' + code);

        loadHighstockData(code, {
                interval: 'monthly'
            })
            .then(function (dataFrame) {
                dataFrame = dataFrame.setIndex("Date");
                var price = dataFrame.subset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.getSeries("Volume").toHighstock();
                var sma = dataFrame.getSeries("Close")
                    .sma(smaPeriod)
                    .toHighstock();

                var groupingUnits = [
                    [
                        'day',
                        [1]
                    ],
                    [
                        'week',                         // unit name
                        [1]                             // allowed multiples
                    ],
                    [
                        'month',
                        [1, 2, 3, 4, 6]
                    ]
                ];

                var chartOptions =
                {
                    chart: {
                        width: $(window).width(),
                        height: $(window).height()-50
                    },

                    navigator: {
                        adaptToUpdatedData: false,
                        series: [
                            {
                                data: price
                            },
                        ]
                    },

                    scrollbar: {
                        liveRedraw: false
                    },

                    title: {
                        text: code.toUpperCase() + ' price history'
                    },

                    subtitle: {
                        text: 'A demo of Highstock using Data-Forge with data loaded from Yahoo.'
                    },

                    rangeSelector: {
                        buttons: [
                            {
                                type: 'hour',
                                count: 1,
                                text: '1h'
                            },
                            {
                                type: 'day',
                                count: 1,
                                text: '1d'
                            },
                            {
                                type: 'month',
                                count: 1,
                                text: '1m'
                            },
                            {
                                type: 'year',
                                count: 1,
                                text: '1y'
                                }, {
                                type: 'all',
                                text: 'All'
                            }
                        ],
                        inputEnabled: true,
                        selected: 4 // all
                    },

                    xAxis: {
                        events: {
                            afterSetExtremes: afterSetExtremes
                        },
                        minRange: 3600 * 1000 * 24 * 5 // 1 week
                    },

                    yAxis: [
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Price'
                            },
                            height: '60%',
                            lineWidth: 2
                        },
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Volume'
                            },
                            top: '65%',
                            height: '35%',
                            offset: 0,
                            lineWidth: 2
                        }
                    ],

                    series: [
                        {
                            type: 'candlestick',
                            name: 'Price',
                            data: price,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        },
                        {
                            type: 'line',
                            name: 'SMA',
                            color: 'red',
                            data: sma,
                            dataGrouping: {
                                units: groupingUnits
                            },
                            tooltip: {
                                valueDecimals: 5
                            }
                        },
                        {
                            type: 'column',
                            name: 'Volume',
                            data: volume,
                            yAxis: 1,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        }
                    ]
                };

                // create the chart
                $('#container').highcharts('StockChart', chartOptions);
            })
            .catch(function (err) {
                console.error(err.stack || err);
            });
    };

    loadChart();

    //
    // Resize chart when window size changes.
    //
    $(window).resize(function() {
        resizeChart();
    });
});
<commit_msg>Now using own server instead of a proxy.<commit_after>'use strict';

$(function() {

    //
    // Period for simple moving average.
    //
    var smaPeriod = 30;

    //
    // Data loaded for the current graph.
    //
    var curDataFrame = null;

    //
    // Default company code.
    //
    var defaultCompanyCode = 'ABC.AX';

    //
    // Used to suppress chart reload while resizing the chart.
    //
    var resizingChart = false;

    //
    // Load data in format required by highstock.
    //
    var loadHighstockData = function (code, options) {

        var extendedOptions = $.extend({}, options, {
            baseUrl: location.protocol + '//' + location.hostname + ':' + location.port + '/yahoo',
        });

        return dataForge.fromYahoo(code, extendedOptions)
            .then(function (dataFrame) {
                curDataFrame = dataFrame;

                //todo: data-forge needs a reverse fn.
                var reversed = Enumerable.from(dataFrame.toObjects())
                    .reverse()
                    .toArray();

                return new dataForge.DataFrame({ rows: reversed });
            });
    };

    //
    // Destroy the existing chart.
    //
    var destroyChart = function () {
        var chart = $('#container').highcharts();
        if (chart) {
            chart.destroy();
        }
    };

    //
    // Destroy and reload the chart.
    //
    var reloadChart = function () {
        destroyChart();
        loadChart();
    };

    $("#company").change(function() {
        reloadChart();
    });

    $('#loadChart').click(function () {
        reloadChart();
    });

    $('#SMA-period').change(function () {
        smaPeriod = $('#SMA-period').val();
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    $('#recalcSMA').click(function () {
        smaPeriod = parseInt($('#SMA-period').val());
        var chart = $('#container').highcharts();
        if (chart && curDataFrame) {
            computeSMA(chart, curDataFrame);
        }
    });

    //
    // Load new data depending on the selected date range.
    //
    var afterSetExtremes = function(e) {

        if (resizingChart) {
            // Don't need to reload data when resizing the chart.
            return;
        }

        var chart = $('#container').highcharts();

        chart.showLoading('Loading data...');

        var fromDate = new Date(e.min);
        var toDate = new Date(e.max);
        var elapsedMonths = moment(toDate).diff(fromDate, 'months');
        var interval = 'daily';
        if (elapsedMonths > 50) {
            interval = 'monthly';
        }
        else if (elapsedMonths > 18) {
            interval = 'weekly';
        }

        loadHighstockData(defaultCompanyCode, {
                fromDate: fromDate,
                toDate: toDate,
                interval: interval,
            })
            .then(function (dataFrame) {
                var price = dataFrame.getColumnsSubset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.getColumnsSubset(["Date", "Volume"]).toHighstock();

                chart.series[0].setData(price);
                chart.series[2].setData(volume);

                computeSMA(chart, dataFrame);
                chart.hideLoading();
            })
            .catch(function (err) {
                chart.hideLoading();
                console.error(err);
            });
    };

    //
    // Compute simple moving average of the price.
    //
    var computeSMA = function (chart, dataFrame) {
        var sma = dataFrame.setSeries("SMA",
                dataFrame
                    .getSeries("Close")
                    .sma(smaPeriod)
            )
            .getColumnsSubset(["Date", "SMA"])
            .toHighstock();
        chart.series[1].setData(sma);
    };

    //
    // Resize the chart to fit the page.
    //
    var resizeChart = function () {
        try {
            resizingChart = true;
            var chart = $('#container').highcharts();
            chart.setSize($(window).width(), $(window).height()-50);
        }
        finally {
            resizingChart = false;
        }
    };

    //
    // Load the chart.
    //
    var loadChart = function () {

        var code = $("#company").val();
        console.log('Loading ' + code);

        loadHighstockData(code, {
                interval: 'monthly'
            })
            .then(function (dataFrame) {
                dataFrame = dataFrame.setIndex("Date");
                var price = dataFrame.subset(["Date", "Open", "High", "Low", "Close"]).toHighstockOHLC();
                var volume = dataFrame.getSeries("Volume").toHighstock();
                var sma = dataFrame.getSeries("Close")
                    .sma(smaPeriod)
                    .toHighstock();

                var groupingUnits = [
                    [
                        'day',
                        [1]
                    ],
                    [
                        'week',                         // unit name
                        [1]                             // allowed multiples
                    ],
                    [
                        'month',
                        [1, 2, 3, 4, 6]
                    ]
                ];

                var chartOptions =
                {
                    chart: {
                        width: $(window).width(),
                        height: $(window).height()-50
                    },

                    navigator: {
                        adaptToUpdatedData: false,
                        series: [
                            {
                                data: price
                            },
                        ]
                    },

                    scrollbar: {
                        liveRedraw: false
                    },

                    title: {
                        text: code.toUpperCase() + ' price history'
                    },

                    subtitle: {
                        text: 'A demo of Highstock using Data-Forge with data loaded from Yahoo.'
                    },

                    rangeSelector: {
                        buttons: [
                            {
                                type: 'hour',
                                count: 1,
                                text: '1h'
                            },
                            {
                                type: 'day',
                                count: 1,
                                text: '1d'
                            },
                            {
                                type: 'month',
                                count: 1,
                                text: '1m'
                            },
                            {
                                type: 'year',
                                count: 1,
                                text: '1y'
                                }, {
                                type: 'all',
                                text: 'All'
                            }
                        ],
                        inputEnabled: true,
                        selected: 4 // all
                    },

                    xAxis: {
                        events: {
                            afterSetExtremes: afterSetExtremes
                        },
                        minRange: 3600 * 1000 * 24 * 5 // 1 week
                    },

                    yAxis: [
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Price'
                            },
                            height: '60%',
                            lineWidth: 2
                        },
                        {
                            labels: {
                                align: 'right',
                                x: -3
                            },
                            title: {
                                text: 'Volume'
                            },
                            top: '65%',
                            height: '35%',
                            offset: 0,
                            lineWidth: 2
                        }
                    ],

                    series: [
                        {
                            type: 'candlestick',
                            name: 'Price',
                            data: price,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        },
                        {
                            type: 'line',
                            name: 'SMA',
                            color: 'red',
                            data: sma,
                            dataGrouping: {
                                units: groupingUnits
                            },
                            tooltip: {
                                valueDecimals: 5
                            }
                        },
                        {
                            type: 'column',
                            name: 'Volume',
                            data: volume,
                            yAxis: 1,
                            dataGrouping: {
                                units: groupingUnits
                            }
                        }
                    ]
                };

                // create the chart
                $('#container').highcharts('StockChart', chartOptions);
            })
            .catch(function (err) {
                console.error(err.stack || err);
            });
    };

    loadChart();

    //
    // Resize chart when window size changes.
    //
    $(window).resize(function() {
        resizeChart();
    });
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
  return gulp.src('generators/index.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('generators/index.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<commit_msg>fix gulp<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
  return gulp.src('generators/index.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('generators/index.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  gulp.src('coverage/**/lcov.info')
    .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<|endoftext|>


<commit_before>/**
 * Validate the composition of a path, course, lesson identifier
 *
 * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of invalid id's. Those containing something other than lowercase letters and digits.
 */
const validateIdComposition = (jsonData) => {
  const invalidIds = [];
  Object.keys(jsonData).forEach((itemId) => {
    if (!itemId.match(/^[0-9a-z]+$/)) {
      invalidIds.push(itemId);
    }
  });
  return invalidIds;
};

/**
 * Validate the length of a path, course, lesson identifier
 *
 * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of id's exceeding 16 characters
 */
const validateIdLength = (jsonData) => {
  const invalidIds = [];
  Object.keys(jsonData).forEach((itemId) => {
    if (itemId.length > 16) {
      invalidIds.push(itemId);
    }
  });
  return invalidIds;
};

/**
 * Validate a relationship between two data elements.
 *
 * @param {String} childAttrNm - Attribute name in the child JSON object
 * @param {Object} childJSON - JSON object containing the child data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @param {String} parentAttrNm - Attribute name in the child JSON object
 * @param {Object} parentJSON - JSON object containing the parent data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of id's exceeding 16 characters
 */
const validateRelationship = (childAttrNm, childJSON, parentAttrNm, parentJSON) => {
  const invalidIds = [];

  Object.values(childJSON).forEach((currentPath) => {
    currentPath[childAttrNm].forEach((itemId) => {
      if (parentJSON[itemId] === undefined) {
        invalidIds.push([currentPath[parentAttrNm], itemId]);
      }
    });
  });
  return invalidIds;
};

export { validateIdComposition, validateIdLength, validateRelationship };
<commit_msg>Generalize parameter name in validateRelationship function<commit_after>/**
 * Validate the composition of a path, course, lesson identifier
 *
 * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of invalid id's. Those containing something other than lowercase letters and digits.
 */
const validateIdComposition = (jsonData) => {
  const invalidIds = [];
  Object.keys(jsonData).forEach((itemId) => {
    if (!itemId.match(/^[0-9a-z]+$/)) {
      invalidIds.push(itemId);
    }
  });
  return invalidIds;
};

/**
 * Validate the length of a path, course, lesson identifier
 *
 * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of id's exceeding 16 characters
 */
const validateIdLength = (jsonData) => {
  const invalidIds = [];
  Object.keys(jsonData).forEach((itemId) => {
    if (itemId.length > 16) {
      invalidIds.push(itemId);
    }
  });
  return invalidIds;
};

/**
 * Validate a relationship between two data elements.
 *
 * @param {String} childAttrNm - Attribute name in the child JSON object
 * @param {Object} childJSON - JSON object containing the child data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @param {String} parentAttrNm - Attribute name in the child JSON object
 * @param {Object} parentJSON - JSON object containing the parent data elements. This must be formatted as {"<id>": {...id: "<id>"...}...}
 * @returns {String[]} invalidIds - Array of id's exceeding 16 characters
 */
const validateRelationship = (childAttrNm, childJSON, parentAttrNm, parentJSON) => {
  const invalidIds = [];

  Object.values(childJSON).forEach((childElement) => {
    childElement[childAttrNm].forEach((itemId) => {
      if (parentJSON[itemId] === undefined) {
        invalidIds.push([childElement[parentAttrNm], itemId]);
      }
    });
  });
  return invalidIds;
};

export { validateIdComposition, validateIdLength, validateRelationship };
<|endoftext|>


<commit_before>
App.Router.map(function() {
    this.route('today-stats', {path: '/'});
    this.route('week-stats', {path: '/week'});
    this.route('month-stats', {path: '/month'});
    this.route('settings', {path: '/settings'});
});

App.ApplicationRoute = Ember.Route.extend({

    model: function() {
        return App.timer;
    }
});

App.IndexRoute = Ember.Route.extend({
    redirect: function(){
        this.transitionTo('today-stats');
    },
});

App.TodayStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
            var today = new Date().toDateString();
            var date = new Date(pomodoro.get('date')).toDateString();
              return pomodoro.get('userKey') === userKey && date === today;
        });
    }
});

App.WeekStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
              return pomodoro.get('userKey') === userKey;
        });
    }
});

App.MonthStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
              return pomodoro.get('userKey') === userKey;
        });
    }
});

App.SettingsRoute = Ember.Route.extend({
    model: function() {
        return App.settings;
    }
});<commit_msg>better filter models<commit_after>
App.Router.map(function() {
    this.route('today-stats', {path: '/'});
    this.route('week-stats', {path: '/week'});
    this.route('month-stats', {path: '/month'});
    this.route('settings', {path: '/settings'});
});

App.ApplicationRoute = Ember.Route.extend({

    model: function() {
        return App.timer;
    }
});

App.IndexRoute = Ember.Route.extend({
    redirect: function(){
        this.transitionTo('today-stats');
    },
});

App.TodayStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
            var today = new Date().toDateString();
            var date = new Date(pomodoro.get('date')).toDateString();
            return pomodoro.get('userKey') === userKey && date === today;
        });
    }
});

App.WeekStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        var today = new Date();
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
            var date = new Date(pomodoro.get('date'));
            return (pomodoro.get('userKey') === userKey) && (
                date.getWeek() === today.getWeek()) && (
                date.getFullYear() == today.getFullYear());
        });
    }
});

App.MonthStatsRoute = Ember.Route.extend({
    model: function() {
        var userKey = App.settings.get('parseKey');
        var today = new Date();
        return this.store.filter('pomodoro', { userKey: userKey}, function(pomodoro) {
              var date = new Date(pomodoro.get('date'));
              return (pomodoro.get('userKey') === userKey) && (
                date.getMonth() === today.getMonth()) && (
                date.getFullYear() == today.getFullYear());
        });
    }
});

App.SettingsRoute = Ember.Route.extend({
    model: function() {
        return App.settings;
    }
});<|endoftext|>