<commit_before>// define indexOf for IE (code from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
if($('#commit_graph')){
    var data;
    var offset = 0;
    var selected_commit = -1;
    var y_offset = 0;
    var page_size = 14;
    var limit = 14;
    var tree, next_column, max_x_pos, max_row;

    // graph size settings
    var x_space = 10;
    var y_space = 20;
    var point_offset = 5;
    var point_size = 10;

    var $first = $('#first');
    var $last = $('#last');
    var $canvas = $('#commit_graph');
    var $highlighter = $('#commit_highlighter');
    var highlighter = $highlighter[0];
    var canvas = $canvas[0];
    var highlighter_ctx = highlighter.getContext('2d');
    var canvas_ctx = canvas.getContext('2d');

    // graph set up
    var height = (limit + 0.5) * y_space;
    var commit_rows = [];
    var taken_coords = {};
    canvas.height=height;

    // highlighter set up
    highlighter.height=height;
    highlighter_ctx.fillStyle = "#ccc";

    $.getJSON(document.location.href+'_data', function(data) {
        data = data;
        tree = data['built_tree'];
        next_column = data['next_column'];
        max_x_pos = x_space*next_column;
        max_row = data['max_row']

        // Calculate the (x,y) positions of all the commits
        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row)*y_space);
            if (!taken_coords[x_pos]){
                taken_coords[x_pos] = [y_pos]
            }
            else if(taken_coords[x_pos].indexOf(y_pos) == -1){
                taken_coords[x_pos].push(y_pos);
            }
            commit_rows[commit.row] = {
                url: commit.url,
                x_pos: x_pos,
                y_pos: y_pos }
        }
        updateOffset(0);
        selectCommit(0);
    });
    updateOffset = function(x) {
        $first.removeClass('disabled');
        $last.removeClass('disabled');
        offset = x;
        if(offset <= 1) {
            offset = 1;
            $last.addClass('disabled');
        }
        else if(offset > (max_row-page_size)) {
            offset = max_row - page_size;
            $first.addClass('disabled');
        }
        y_offset = offset * y_space;
        drawGraph(offset);
        if (selected_commit >= offset-1 && selected_commit <= offset + page_size) {
          selectCommit(selected_commit);
        }
        return false;
    };
    $last.click(function() {
        return updateOffset(0);
    });
    $first.click(function() {
        return updateOffset(max_row);
    });

    function selectCommit(index) {
        var commit = commit_rows[index];
        highlighter_ctx.clearRect(0, 0, canvas.width, canvas.height);
        // active_ys = [commit.y_pos-y_space/4,y_space]
        highlighter_ctx.fillRect(
            0, (commit.y_pos - y_offset) - y_space/4,
            750, y_space)
        if (selected_commit != index) {
          $('#commit_view').html('Loading commit details...');
          $.get(commit.url+'basic',function(result){
              $('#commit_view').html(result);
          });
        }
        selected_commit = index;
    }

    $canvas.click(function(evt) {
        var y = Math.floor((evt.pageY-$canvas.offset().top) / y_space);
        selectCommit(offset+y-1);
    });

    function color(index) {
      /* choose color for colorblind users (according to http://jfly.iam.u-tokyo.ac.jp/color/#pallet) */
      switch(index){
        case 0: return "rgb(213,94,0)";
        case 1: return "rgb(0,114,178)";
        case 2: return "rgb(240,228,66)";
        case 3: return "rgb(0,158,115)";
        case 4: return "rgb(230,159,0)";
        default: return "rgb(86,180,223)";
      }
    }

    function drawGraph(offset) {
        // Clear the canvas and set the contetx
        var canvas_ctx = canvas.getContext('2d');
        highlighter_ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas_ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas_ctx.fillStyle = "rgb(0,0,0)";
        canvas_ctx.lineWidth = 1;
        canvas_ctx.lineJoin = 'round';
        canvas_ctx.textBaseline = "top";
        canvas_ctx.font = "12px sans-serif";

        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row-offset)*y_space);

            for(var i=0,len=commit.parents.length;i<len;i++){
                var parent = tree[commit.parents[i]];
                var parent_x = x_space+parent.column*x_space
                var parent_y = y_space+(parent.row-offset)*y_space;

                canvas_ctx.strokeStyle = color(parent.column % 6);

                // Vertical
                canvas_ctx.beginPath();
                canvas_ctx.moveTo(parent_x+point_offset, y_pos+y_space);
                canvas_ctx.lineTo(parent_x+point_offset, parent_y+point_offset);
                canvas_ctx.stroke();

                // Diagonal
                canvas_ctx.beginPath()
                canvas_ctx.moveTo(x_pos + point_offset, y_pos+point_offset);
                canvas_ctx.lineTo(parent_x+point_offset, y_pos+y_space);
                canvas_ctx.stroke();
            }
        }
        // draw commit points and message text
        canvas_ctx.fillStyle = "rgb(0,0,0)";
        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row-offset)*y_space);

            canvas_ctx.strokeStyle = canvas_ctx.fillStyle = color(commit.column % 6);
            canvas_ctx.beginPath();
            canvas_ctx.arc(x_pos + point_offset, y_pos + point_offset, point_offset, 0, 2 * Math.PI, false);
            canvas_ctx.fill();
            canvas_ctx.stroke();
            canvas_ctx.fillStyle = "#000";
            canvas_ctx.fillText(commit.message, (1+next_column) * x_space, y_pos);
        }
    }

    function scroll(event) {
      var delta = 0;
      var e = event.originalEvent;
      if (e.type == "mousewheel") {
        delta = -(e.wheelDelta / 40);
      } else if (e.type == "DOMMouseScroll") {
        // firefox
        delta = e.detail;
      }
      updateOffset(offset + delta);
      return false;
    }

    $canvas.bind("mousewheel", scroll);
    $canvas.bind("DOMMouseScroll", scroll);
}
<commit_msg>[#3751] ticket:153 small fixes<commit_after>// define indexOf for IE (code from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
if($('#commit_graph')){
    var data;
    var offset = 0;
    var selected_commit = -1;
    var y_offset = 0;
    var page_size = 14;
    var limit = 14;
    var tree, next_column, max_x_pos, max_row;

    // graph size settings
    var x_space = 10;
    var y_space = 20;
    var point_offset = 5;
    var point_size = 10;

    var $first = $('#first');
    var $last = $('#last');
    var $canvas = $('#commit_graph');
    var $highlighter = $('#commit_highlighter');
    var highlighter = $highlighter[0];
    var canvas = $canvas[0];
    var highlighter_ctx = highlighter.getContext('2d');
    var canvas_ctx = canvas.getContext('2d');

    // graph set up
    var height = (limit + 0.5) * y_space;
    var commit_rows = [];
    var taken_coords = {};
    canvas.height=height;

    // highlighter set up
    highlighter.height=height;
    highlighter_ctx.fillStyle = "#ccc";

    $.getJSON(document.location.href+'_data', function(data) {
        data = data;
        tree = data['built_tree'];
        next_column = data['next_column'];
        max_x_pos = x_space*next_column;
        max_row = data['max_row']

        // Calculate the (x,y) positions of all the commits
        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row)*y_space);
            if (!taken_coords[x_pos]){
                taken_coords[x_pos] = [y_pos]
            }
            else if(taken_coords[x_pos].indexOf(y_pos) == -1){
                taken_coords[x_pos].push(y_pos);
            }
            commit_rows[commit.row] = {
                url: commit.url,
                x_pos: x_pos,
                y_pos: y_pos }
        }
        updateOffset(0);
        selectCommit(0);
    });
    updateOffset = function(x) {
        $first.removeClass('disabled');
        $last.removeClass('disabled');
        offset = x;
        if (max_row <= page_size) {
            offset = 1;
            $first.addClass('disabled');
            $last.addClass('disabled');
        } else if (offset <= 1) {
            offset = 1;
            $last.addClass('disabled');
        } else if (offset > (max_row-page_size)) {
            offset = max_row - page_size + 1;
            $first.addClass('disabled');
        }
        y_offset = offset * y_space;
        drawGraph(offset);
        if (selected_commit >= offset-1 && selected_commit <= offset + page_size) {
          selectCommit(selected_commit);
        }
        return false;
    };
    $last.click(function() {
        return updateOffset(0);
    });
    $first.click(function() {
        return updateOffset(max_row);
    });

    function selectCommit(index) {
        var commit = commit_rows[index];
        highlighter_ctx.clearRect(0, 0, canvas.width, canvas.height);
        // active_ys = [commit.y_pos-y_space/4,y_space]
        highlighter_ctx.fillRect(
            0, (commit.y_pos - y_offset) - y_space/4,
            750, y_space)
        if (selected_commit != index) {
          $('#commit_view').html('Loading commit details...');
          $.get(commit.url+'basic',function(result){
              $('#commit_view').html(result);
          });
        }
        selected_commit = index;
    }

    $canvas.click(function(evt) {
        var y = Math.floor((evt.pageY-$canvas.offset().top) / y_space);
        selectCommit(offset+y-1);
    });

    function color(index) {
      /* choose color for colorblind users (according to http://jfly.iam.u-tokyo.ac.jp/color/#pallet) */
      switch(index){
        case 0: return "rgb(213,94,0)";
        case 1: return "rgb(0,114,178)";
        case 2: return "rgb(240,228,66)";
        case 3: return "rgb(0,158,115)";
        case 4: return "rgb(230,159,0)";
        default: return "rgb(86,180,223)";
      }
    }

    function drawGraph(offset) {
        // Clear the canvas and set the contetx
        var canvas_ctx = canvas.getContext('2d');
        highlighter_ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas_ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas_ctx.fillStyle = "rgb(0,0,0)";
        canvas_ctx.lineWidth = 1;
        canvas_ctx.lineJoin = 'round';
        canvas_ctx.textBaseline = "top";
        canvas_ctx.font = "12px sans-serif";

        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row-offset)*y_space);

            for(var i=0,len=commit.parents.length;i<len;i++){
                var parent = tree[commit.parents[i]];
                var parent_x = x_space+parent.column*x_space
                var parent_y = y_space+(parent.row-offset)*y_space;

                canvas_ctx.strokeStyle = color(parent.column % 6);

                // Vertical
                canvas_ctx.beginPath();
                canvas_ctx.moveTo(parent_x+point_offset, y_pos+y_space);
                canvas_ctx.lineTo(parent_x+point_offset, parent_y+point_offset);
                canvas_ctx.stroke();

                // Diagonal
                canvas_ctx.beginPath()
                canvas_ctx.moveTo(x_pos + point_offset, y_pos+point_offset);
                canvas_ctx.lineTo(parent_x+point_offset, y_pos+y_space);
                canvas_ctx.stroke();
            }
        }
        // draw commit points and message text
        canvas_ctx.fillStyle = "rgb(0,0,0)";
        for(var c in tree){
            var commit = tree[c];
            var x_pos = x_space+(commit.column*x_space);
            var y_pos = y_space+((commit.row-offset)*y_space);

            canvas_ctx.strokeStyle = canvas_ctx.fillStyle = color(commit.column % 6);
            canvas_ctx.beginPath();
            canvas_ctx.arc(x_pos + point_offset, y_pos + point_offset, point_offset, 0, 2 * Math.PI, false);
            canvas_ctx.fill();
            canvas_ctx.stroke();
            canvas_ctx.fillStyle = "#000";
            canvas_ctx.fillText(commit.message, (1+next_column) * x_space, y_pos);
        }
    }

    function scroll(event) {
      var delta = 0;
      var e = event.originalEvent;
      if (e.type == "mousewheel") {
        delta = -(e.wheelDelta / 40);
      } else if (e.type == "DOMMouseScroll") {
        // firefox
        delta = e.detail;
      }
      updateOffset(offset + delta);
      return false;
    }

    $canvas.bind("mousewheel", scroll);
    $canvas.bind("DOMMouseScroll", scroll);
}
<|endoftext|>


<commit_before>var config = require('./config');
var gulp = require('gulp');
var gutil = require('gulp-util');
var frep = require('gulp-frep');
var fs = require('fs');
var args = require('minimist')(process.argv.slice(2));
var path = require('path');
var rename = require('gulp-rename');
var filter = require('gulp-filter');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var series = require('stream-series');
var lazypipe = require('lazypipe');
var glob = require('glob').sync;
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var ngAnnotate = require('gulp-ng-annotate');
var minifyCss = require('gulp-minify-css');
var insert = require('gulp-insert');
var gulpif = require('gulp-if');
var constants = require('./const');
var VERSION = constants.VERSION;
var BUILD_MODE = constants.BUILD_MODE;
var IS_DEV = constants.IS_DEV;
var ROOT = constants.ROOT;
var utils = require('../scripts/gulp-utils.js');

exports.buildJs = buildJs;
exports.autoprefix = autoprefix;
exports.buildModule = buildModule;
exports.filterNonCodeFiles = filterNonCodeFiles;
exports.readModuleArg = readModuleArg;
exports.themeBuildStream = themeBuildStream;
exports.args = args;

/**
 * Builds the entire component library javascript.
 * @param {boolean} isRelease Whether to build in release mode.
 */
function buildJs () {
  var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]);

  gutil.log("building js files...");

  var jsBuildStream = gulp.src( jsFiles )
      .pipe(filterNonCodeFiles())
      .pipe(utils.buildNgMaterialDefinition())
      .pipe(plumber())
      .pipe(ngAnnotate())
      .pipe(utils.addJsWrapper(true));

  var jsProcess = series(jsBuildStream, themeBuildStream() )
      .pipe(concat('angular-material.js'))
      .pipe(BUILD_MODE.transform())
      .pipe(insert.prepend(config.banner))
      .pipe(insert.append('window.ngMaterial={version:{full: "' + VERSION +'"}}'))
      .pipe(gulp.dest(config.outputDir))
      .pipe(gulpif(!IS_DEV, uglify({ preserveComments: 'some' })))
      .pipe(rename({ extname: '.min.js' }))
      .pipe(gulp.dest(config.outputDir));

  return series(jsProcess, deployMaterialMocks());

  // Deploy the `angular-material-mocks.js` file to the `dist` directory
  function deployMaterialMocks() {
    return gulp.src(config.mockFiles)
        .pipe(gulp.dest(config.outputDir));
  }
}

function autoprefix () {
  return autoprefixer({browsers: [
    'last 2 versions', 'last 4 Android versions'
  ]});
}

function buildModule(module, opts) {
  opts = opts || {};
  if ( module.indexOf(".") < 0) {
    module = "material.components." + module;
  }
  gutil.log('Building ' + module + (opts.isRelease && ' minified' || '') + ' ...');

  var name = module.split('.').pop();
  utils.copyDemoAssets(name, 'src/components/', 'dist/demos/');

  var stream = utils.filesForModule(module)
      .pipe(filterNonCodeFiles())
      .pipe(gulpif('*.scss', buildModuleStyles(name)))
      .pipe(gulpif('*.js', buildModuleJs(name)));
  if (module === 'material.core') {
    stream = splitStream(stream);
  }
  return stream
      .pipe(BUILD_MODE.transform())
      .pipe(insert.prepend(config.banner))
      .pipe(gulpif(opts.minify, buildMin()))
      .pipe(gulpif(opts.useBower, buildBower()))
      .pipe(gulp.dest(BUILD_MODE.outputDir + name));

  function splitStream (stream) {
    var js = series(stream, themeBuildStream())
        .pipe(filter('*.js'))
        .pipe(concat('core.js'));
    var css = stream.pipe(filter('*.css'));
    return series(js, css);
  }

  function buildMin() {
    return lazypipe()
        .pipe(gulpif, /.css$/, minifyCss(),
        uglify({ preserveComments: 'some' })
            .on('error', function(e) {
              console.log('\x07',e.message);
              return this.end();
            }
        )
    )
        .pipe(rename, function(path) {
          path.extname = path.extname
              .replace(/.js$/, '.min.js')
              .replace(/.css$/, '.min.css');
        })
    ();
  }

  function buildBower() {
    return lazypipe()
      .pipe(utils.buildModuleBower, name, VERSION)();
  }

  function buildModuleJs(name) {
    var patterns = [
      {
        pattern: /\@ngInject/g,
        replacement: 'ngInject'
      }
    ];
    return lazypipe()
        .pipe(plumber)
        .pipe(ngAnnotate)
        .pipe(frep, patterns)
        .pipe(concat, name + '.js')
    ();
  }

  function buildModuleStyles(name) {
    var files = [];
    config.themeBaseFiles.forEach(function(fileGlob) {
      files = files.concat(glob(fileGlob, { cwd: ROOT }));
    });
    var baseStyles = files.map(function(fileName) {
      return fs.readFileSync(fileName, 'utf8').toString();
    }).join('\n');

    return lazypipe()
        .pipe(insert.prepend, baseStyles)
        .pipe(gulpif, /theme.scss/,
        rename(name + '-default-theme.scss'), concat(name + '.scss')
    )
        .pipe(sass)
        .pipe(autoprefix)
    (); // invoke the returning fn to create our pipe
  }

}

function readModuleArg() {
  var module = args.c ? 'material.components.' + args.c : (args.module || args.m);
  if (!module) {
    gutil.log('\nProvide a compnent argument via `-c`:',
        '\nExample: -c toast');
    gutil.log('\nOr provide a module argument via `--module` or `-m`.',
        '\nExample: --module=material.components.toast or -m material.components.dialog');
    process.exit(1);
  }
  return module;
}

function filterNonCodeFiles() {
  return filter(function(file) {
    return !/demo|module\.json|script\.js|\.spec.js|README/.test(file.path);
  });
}

// builds the theming related css and provides it as a JS const for angular
function themeBuildStream() {
  return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) )
      .pipe(concat('default-theme.scss'))
      .pipe(utils.hoistScssVariables())
      .pipe(sass())
      .pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
}
<commit_msg>fix(build): add missing semi-colon.<commit_after>var config = require('./config');
var gulp = require('gulp');
var gutil = require('gulp-util');
var frep = require('gulp-frep');
var fs = require('fs');
var args = require('minimist')(process.argv.slice(2));
var path = require('path');
var rename = require('gulp-rename');
var filter = require('gulp-filter');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var series = require('stream-series');
var lazypipe = require('lazypipe');
var glob = require('glob').sync;
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var ngAnnotate = require('gulp-ng-annotate');
var minifyCss = require('gulp-minify-css');
var insert = require('gulp-insert');
var gulpif = require('gulp-if');
var constants = require('./const');
var VERSION = constants.VERSION;
var BUILD_MODE = constants.BUILD_MODE;
var IS_DEV = constants.IS_DEV;
var ROOT = constants.ROOT;
var utils = require('../scripts/gulp-utils.js');

exports.buildJs = buildJs;
exports.autoprefix = autoprefix;
exports.buildModule = buildModule;
exports.filterNonCodeFiles = filterNonCodeFiles;
exports.readModuleArg = readModuleArg;
exports.themeBuildStream = themeBuildStream;
exports.args = args;

/**
 * Builds the entire component library javascript.
 * @param {boolean} isRelease Whether to build in release mode.
 */
function buildJs () {
  var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]);

  gutil.log("building js files...");

  var jsBuildStream = gulp.src( jsFiles )
      .pipe(filterNonCodeFiles())
      .pipe(utils.buildNgMaterialDefinition())
      .pipe(plumber())
      .pipe(ngAnnotate())
      .pipe(utils.addJsWrapper(true));

  var jsProcess = series(jsBuildStream, themeBuildStream() )
      .pipe(concat('angular-material.js'))
      .pipe(BUILD_MODE.transform())
      .pipe(insert.prepend(config.banner))
      .pipe(insert.append('window.ngMaterial={version:{full: "' + VERSION +'"}};'))
      .pipe(gulp.dest(config.outputDir))
      .pipe(gulpif(!IS_DEV, uglify({ preserveComments: 'some' })))
      .pipe(rename({ extname: '.min.js' }))
      .pipe(gulp.dest(config.outputDir));

  return series(jsProcess, deployMaterialMocks());

  // Deploy the `angular-material-mocks.js` file to the `dist` directory
  function deployMaterialMocks() {
    return gulp.src(config.mockFiles)
        .pipe(gulp.dest(config.outputDir));
  }
}

function autoprefix () {
  return autoprefixer({browsers: [
    'last 2 versions', 'last 4 Android versions'
  ]});
}

function buildModule(module, opts) {
  opts = opts || {};
  if ( module.indexOf(".") < 0) {
    module = "material.components." + module;
  }
  gutil.log('Building ' + module + (opts.isRelease && ' minified' || '') + ' ...');

  var name = module.split('.').pop();
  utils.copyDemoAssets(name, 'src/components/', 'dist/demos/');

  var stream = utils.filesForModule(module)
      .pipe(filterNonCodeFiles())
      .pipe(gulpif('*.scss', buildModuleStyles(name)))
      .pipe(gulpif('*.js', buildModuleJs(name)));
  if (module === 'material.core') {
    stream = splitStream(stream);
  }
  return stream
      .pipe(BUILD_MODE.transform())
      .pipe(insert.prepend(config.banner))
      .pipe(gulpif(opts.minify, buildMin()))
      .pipe(gulpif(opts.useBower, buildBower()))
      .pipe(gulp.dest(BUILD_MODE.outputDir + name));

  function splitStream (stream) {
    var js = series(stream, themeBuildStream())
        .pipe(filter('*.js'))
        .pipe(concat('core.js'));
    var css = stream.pipe(filter('*.css'));
    return series(js, css);
  }

  function buildMin() {
    return lazypipe()
        .pipe(gulpif, /.css$/, minifyCss(),
        uglify({ preserveComments: 'some' })
            .on('error', function(e) {
              console.log('\x07',e.message);
              return this.end();
            }
        )
    )
        .pipe(rename, function(path) {
          path.extname = path.extname
              .replace(/.js$/, '.min.js')
              .replace(/.css$/, '.min.css');
        })
    ();
  }

  function buildBower() {
    return lazypipe()
      .pipe(utils.buildModuleBower, name, VERSION)();
  }

  function buildModuleJs(name) {
    var patterns = [
      {
        pattern: /\@ngInject/g,
        replacement: 'ngInject'
      }
    ];
    return lazypipe()
        .pipe(plumber)
        .pipe(ngAnnotate)
        .pipe(frep, patterns)
        .pipe(concat, name + '.js')
    ();
  }

  function buildModuleStyles(name) {
    var files = [];
    config.themeBaseFiles.forEach(function(fileGlob) {
      files = files.concat(glob(fileGlob, { cwd: ROOT }));
    });
    var baseStyles = files.map(function(fileName) {
      return fs.readFileSync(fileName, 'utf8').toString();
    }).join('\n');

    return lazypipe()
        .pipe(insert.prepend, baseStyles)
        .pipe(gulpif, /theme.scss/,
        rename(name + '-default-theme.scss'), concat(name + '.scss')
    )
        .pipe(sass)
        .pipe(autoprefix)
    (); // invoke the returning fn to create our pipe
  }

}

function readModuleArg() {
  var module = args.c ? 'material.components.' + args.c : (args.module || args.m);
  if (!module) {
    gutil.log('\nProvide a compnent argument via `-c`:',
        '\nExample: -c toast');
    gutil.log('\nOr provide a module argument via `--module` or `-m`.',
        '\nExample: --module=material.components.toast or -m material.components.dialog');
    process.exit(1);
  }
  return module;
}

function filterNonCodeFiles() {
  return filter(function(file) {
    return !/demo|module\.json|script\.js|\.spec.js|README/.test(file.path);
  });
}

// builds the theming related css and provides it as a JS const for angular
function themeBuildStream() {
  return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) )
      .pipe(concat('default-theme.scss'))
      .pipe(utils.hoistScssVariables())
      .pipe(sass())
      .pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
}
<|endoftext|>


<commit_before>/*
---
description: Extensions to the Function class that allow a more functional programming style
license: LGPL
authors: ['Michael Ficarra']
requires: [Core,Function,Class]
provides: [
	FunctionTools, Function._, Function.empty, Function.identity, Function.lambda,
	Function.combine, Function.compose, Function.overload, Function::wrap, Function::memoize,
	Function::partial, Function::curry, Function::not, Function::prepend, Function::append,
	Function::overload, Function::getArgs, Function::getArity, Array::toFunction, Hash::toFunction
]
... */

// class properties and globals
this._ = Function._ = function(_){
	if(!arguments.callee.caller) return;
	var args = arguments.callee.caller.arguments;
	if(_===undefined) args._ = (args._===undefined ? 0 : args._+1);
	return args[_===undefined ? args._ : _];
};

// class methods
Function.extend({

	empty: function(){},

	identity: function(_){ return _; },

	lambda: function(_){
		return function(){ return _; };
	},

	combine: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var result;
			args.each(function(fn){
				result = fn.apply(this,arguments);
			});
			return result;
		};
	},

	compose: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var lastReturn = Array.prototype.slice.call(arguments);
			args.reverse().each(function(fn){
				lastReturn = [fn.apply(this,lastReturn)]
			});
			return lastReturn[0];
		}
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function'){
			var newTable = [];
			for(var i=0, l=arguments.length; i<l; i++){
				newTable[arguments[i].arity] = arguments[i];
			}
			funcTable = newTable;
		}
		return function(){
			var fn = funcTable[arguments.length];
			if(!fn || typeof fn !== 'function') return undefined;
			return fn.apply(this,arguments);
		};
	}
});

// instance methods
Function.implement({

	wrap: function(fn){
		var that = this;
		var ret = function(){
			var args = Array.prototype.slice.call(arguments);
			return fn.call(this,that.bind(this),args);
		};
		ret._origin = this;
		return ret;
	},

	memoize: function(memos){
		memos = memos || {};
		return this.wrap(function(original,args){
			var origin = this;
			while(origin._origin) origin = origin._origin;
			var key = [origin,args];
			if(memos[key] !== undefined) return memos[key];
			if(memos[args] !== undefined) return memos[args];
			return (memos[key] = original.apply(this,args));
		});
	},

	partial: function(){
		var partialArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			var collectedArgs = [];
			partialArgs.each(function(arg){
				collectedArgs.push([undefined,Function._].contains(arg) ? passedArgs.shift() : arg);
			});
			return original.apply(this,collectedArgs.concat(passedArgs));
		});
	},

	curry: function(){
		var curriedArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			return original.apply(this,curriedArgs.concat(passedArgs));
		});
	},

	not: function(){
		if(arguments.length) return this.not().apply(this,arguments);
		return this.wrap(function(fn,args){
			return !fn.apply(this,args);
		});
	},

	prepend: function(fn){
		return this.wrap(function(self,args){
			fn.apply(this,args);
			return self.apply(this,args);
		});
	},

	append: function(fn){
		return this.wrap(function(self,args){
			self.apply(this,args);
			return fn.apply(this,args);
		});
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function') {
			var others = Array.prototype.slice.call(arguments);
			return Function.overload.apply(null,others.concat(this));
		} else {
			funcTable[this.arity] = this;
			return Function.overload(funcTable);
		}
	},

	getArgs: function(){
		var fn = this;
		while(fn._origin) fn = fn._origin;
		var args = fn.toString().match(/function\s*\S*?\((.*?)\)/)[1].split(/\s*,\s*/);
		return args.filter(function(_){ return _ !== ""; });
	},

	getArity: function(){
		return this.arity || this.getArgs().length;
	}

});

// cache arglists
(function(){
	var original = Function.prototype.getArgs;
	Function.prototype.getArgs = (function(){ return original.apply(this,arguments); }).memoize();
})();

// implement array methods
['forEach','each','every','some','filter','map','reduce','sort'].each(function(fnStr){
	var fn = function(){
		var args = Array.prototype.slice.call(arguments);
		var arr = args.shift();
		return arr[fnStr].apply(arr,[this].concat(args));
	};
	fn._origin = Array.prototype[fnStr];
	Function.implement(fnStr,fn);
});

// Array.toFunction, Hash.toFunction
(function(){
	var toFunction = function(){
		var self = this;
		return function(index){ return self[index]; };
	};
	Array.implement('toFunction',toFunction);
	if(Hash) Hash.implement('toFunction',toFunction);
})();

/* Copyright 2010 Michael Ficarra
This program is distributed under the (very open)
terms of the GNU Lesser General Public License */
<commit_msg>Fixed some scope issues, wrong arguments were being passed to `combine`, and attempted to fix underscore function<commit_after>/*
---
description: Extensions to the Function class that allow a more functional programming style
license: LGPL
authors: ['Michael Ficarra']
requires: [Core,Function,Class]
provides: [
	FunctionTools, Function._, Function.empty, Function.identity, Function.lambda,
	Function.combine, Function.compose, Function.overload, Function::wrap, Function::memoize,
	Function::partial, Function::curry, Function::not, Function::prepend, Function::append,
	Function::overload, Function::getArgs, Function::getArity, Array::toFunction, Hash::toFunction
]
... */

// class properties and globals
this._ = Function._ = function(_){
	var caller = arguments.callee.caller || arguments.caller;
	if(!caller) return;
	var args = caller.arguments;
	if(_===undefined) args._ = (args._===undefined ? 0 : args._+1);
	return args[_===undefined ? args._ : _];
};

// class methods
Function.extend({

	empty: function(){},

	identity: function(_){ return _; },

	lambda: function(_){
		return function(){ return _; };
	},

	combine: function(){
		var functions = Array.prototype.slice.call(arguments);
		return function(){
			var result,
				args = Array.prototype.slice.call(arguments);
			functions.each(function(fn){
				result = fn.apply(this,args);
			},this);
			return result;
		};
	},

	compose: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var lastReturn = Array.prototype.slice.call(arguments);
			args.reverse().each(function(fn){
				lastReturn = [fn.apply(this,lastReturn)]
			},this);
			return lastReturn[0];
		}
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function'){
			var newTable = [];
			for(var i=0, l=arguments.length; i<l; i++){
				newTable[arguments[i].arity] = arguments[i];
			}
			funcTable = newTable;
		}
		var that = this;
		return function(){
			var fn = funcTable[arguments.length];
			if(!fn || typeof fn !== 'function') return undefined;
			return fn.apply(that,arguments);
		};
	}
});

// instance methods
Function.implement({

	wrap: function(fn){
		var that = this;
		var ret = function(){
			var args = Array.prototype.slice.call(arguments);
			return fn.call(this,that.bind(this),args);
		};
		ret._origin = this;
		return ret;
	},

	memoize: function(memos){
		memos = memos || {};
		return this.wrap(function(original,args){
			var origin = this;
			while(origin._origin) origin = origin._origin;
			var key = [origin,args];
			if(memos[key] !== undefined) return memos[key];
			if(memos[args] !== undefined) return memos[args];
			return (memos[key] = original.apply(this,args));
		});
	},

	partial: function(){
		var partialArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			var collectedArgs = [];
			partialArgs.each(function(arg){
				collectedArgs.push([undefined,Function._].contains(arg) ? passedArgs.shift() : arg);
			});
			return original.apply(this,collectedArgs.concat(passedArgs));
		});
	},

	curry: function(){
		var curriedArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			return original.apply(this,curriedArgs.concat(passedArgs));
		});
	},

	not: function(){
		if(arguments.length) return this.not().apply(this,arguments);
		return this.wrap(function(fn,args){
			return !fn.apply(this,args);
		});
	},

	prepend: function(fn){
		return this.wrap(function(self,args){
			fn.apply(this,args);
			return self.apply(this,args);
		});
	},

	append: function(fn){
		return this.wrap(function(self,args){
			self.apply(this,args);
			return fn.apply(this,args);
		});
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function') {
			var others = Array.prototype.slice.call(arguments);
			return Function.overload.apply(null,others.concat(this));
		} else {
			funcTable[this.arity] = this;
			return Function.overload(funcTable);
		}
	},

	getArgs: function(){
		var fn = this;
		while(fn._origin) fn = fn._origin;
		var args = fn.toString().match(/function\s*\S*?\((.*?)\)/)[1].split(/\s*,\s*/);
		return args.filter(function(_){ return _ !== ""; });
	},

	getArity: function(){
		return this.arity || this.getArgs().length;
	}

});

// cache arglists
(function(){
	var original = Function.prototype.getArgs;
	Function.prototype.getArgs = (function(){ return original.apply(this,arguments); }).memoize();
})();

// implement array methods
['forEach','each','every','some','filter','map','reduce','sort'].each(function(fnStr){
	var fn = function(){
		var args = Array.prototype.slice.call(arguments);
		var arr = args.shift();
		return arr[fnStr].apply(arr,[this].concat(args));
	};
	fn._origin = Array.prototype[fnStr];
	Function.implement(fnStr,fn);
});

// Array.toFunction, Hash.toFunction
(function(){
	var toFunction = function(){
		var self = this;
		return function(index){ return self[index]; };
	};
	Array.implement('toFunction',toFunction);
	if(Hash) Hash.implement('toFunction',toFunction);
})();

/* Copyright 2010 Michael Ficarra
This program is distributed under the (very open)
terms of the GNU Lesser General Public License */
<|endoftext|>


<commit_before>'use strict'

const Route = require('./route')
const Serializer = require('./jsonapi-serializer')

module.exports = class JSONAPIRoute extends Route {
  /**
   * @method serialize
   * @param {Object} model
   */
  serialize (model) {
    // workout from model instance what type of model it is
    if (model.modelName) {
      const Model = this.store.modelFor(model.modelName)
      const serializer = new Serializer()
      model = serializer.serialize(Model, model)
    }
  }
}
<commit_msg>Delete zombie code<commit_after><|endoftext|>


<commit_before>/**
 *    Harlequin.js
 *    Highlighting for data tables
 *
 *    @author       Luke Williams (http://www.red-root.com)
 *    @version      0.2
*/

Harlequin = (function(){

   var table = null,
       segments = [],
       useHsl = true;

   // config options

   var config = {},
       defaults = {
        color_class: "color",
        start_hue: 0,
        end_hue: 120,
        sat: 90,
        lightness: 70,
        colors: null,
      }

    // fix for webkit bug on nth-child and descendents
    // until we don't need jQuery anymore or a find a better fix
    $.expr[":"].harlequin = function() {
        return true;
    };

    // lets find some cells

    populateCells = function(direction){

      if(direction == "both"){
        segments.push({
          index: -1,
          sort: table.data("sort") || "low-to-high"
        });
      }else{

        var i = 0;

        var query = (direction == "column") ? "thead th" :
                    (direction == "row") ? "tbody tr" : false;

        if(query == false) return;

          $(query,table).each(function(){
            if($(this).hasClass(config.color_class)){
                  segments.push({
                      index: i,
                      sort: $(this).data("sort") || "low-to-high"
                  });
            }
             i++;

          });
      }
    }

    // lets stripe some cells

    stripeCells = function(direction){
      for(i = 0, len = segments.length; i < len; i++){

          var seg = segments[i],
              seg_index = seg.index
              seg_max = null,
              seg_min = null,
              cells = [];

          var query = (direction == "column") ? "tbody tr td:nth-child("+(seg_index+1)+")" :
                      (direction == "row") ? "tbody tr:nth-child("+(seg_index+1)+") td:harlequin" :
                      (direction == "both") ? "tbody td" : false;

          if(query == false) return;

          $(query,table).each(function(){

            var element = $(this);
            var new_cell = {
                value: parseFloat(element.text()),
                el: element
            }

            if(new_cell.value.length < 1){
                return true;
            }

            if(seg_min == null){
               seg_min = new_cell.value
            }else if(new_cell.value < seg_min){
               seg_min = new_cell.value
            }

            if(seg_max == null){
               seg_max = new_cell.value
            }else if(new_cell.value > seg_max){
               seg_max = new_cell.value
            }

            cells.push(new_cell);
          });

          for(j = 0, jlen = cells.length; j < jlen; j++){
               cells[j].el.css("background-color",getColor(cells[j].value,seg_min,seg_max,seg.sort));
          }
      }
    }

    // color functions

    getColor = function(value,min,max,sort){
        var color;
        if(config.colors != null && typeof config.colors == "object"){

          var len = config.colors.length,
              index = Math.floor(((value-min)/(max-min)) * len) - 1;

          if(index == -1) index = 0;

          color = config.colors[index];

        }else{

          var range = config.end_hue - config.start_hue;
          if(sort == "high-to-low"){
              var hue = Math.ceil(config.end_hue - (((value - min)/(max-min)) * range));
          }else{
              var hue = Math.ceil(config.start_hue + (((value - min)/(max-min)) * range));
          }

          color = "hsl("+hue+","+config.sat+"%,"+config.lightness+"%)";

          if(!useHsl){
            color = hsl2hex(hue,config.sat,config.lightness);
          }

        }

        return color;
    }

    testHsl = function(){
      var el = document.createElement("harlequin");
      el.style.cssText = "background-color:hsla(120,40%,100%,.5)";
      return !!~('' + el.style.backgroundColor).indexOf("rgba") || !!~('' + el.style.backgroundColor).indexOf("hsla");
    }

    useHsl = testHsl();

    hsl2hex = function(h,s,l){
        h = (h % 360) / 360;
        s = s/100;
        l = l/100;

        if(s == 0){
             l = Math.round(l * 255)
             return { r: l, g: l, b: l  };
        }

        var m2 = l >= 0.5 ? ((l+s)-(l*s)) : l*(1+s);
        var m1 = (2 * l) - m2;

        return '#'+ ( Math.round(hue(h - 1/3) * 255) | Math.round(hue(h) * 255) << 8 | Math.round(hue(h + 1/3) * 255) << 16 ).toString(16)

        function hue(h) {
                h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
                if      (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
                else if (h * 2 < 1) return m2;
                else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
                else                return m1;
        }
    }

    // init function

    start = function(table_id,direction,options){
        table = $("#"+table_id);
        segments = [];
        config = {}

        if(options != undefined){
          for(k in defaults){
            config[k] = (options[k] != undefined) ? options[k] : defaults[k];
          }
        }else{
          config = defaults;
        }

        populateCells(direction);
        stripeCells(direction);
    }

    return {
        stripe: function(table_id,direction,options){
            start(table_id,direction,options);
        }
    }

})();

<commit_msg>Allows commas in values now<commit_after>/**
 *    Harlequin.js
 *    Highlighting for data tables
 *
 *    @author       Luke Williams (http://www.red-root.com)
 *    @version      0.2
*/

Harlequin = (function(){

   var table = null,
       segments = [],
       useHsl = true;

   // config options

   var config = {},
       defaults = {
        color_class: "color",
        start_hue: 0,
        end_hue: 120,
        sat: 90,
        lightness: 70,
        colors: null,
      }

    // fix for webkit bug on nth-child and descendents
    // until we don't need jQuery anymore or a find a better fix
    $.expr[":"].harlequin = function() {
        return true;
    };

    // lets find some cells

    populateCells = function(direction){

      if(direction == "both"){
        segments.push({
          index: -1,
          sort: table.data("sort") || "low-to-high"
        });
      }else{

        var i = 0;

        var query = (direction == "column") ? "thead th" :
                    (direction == "row") ? "tbody tr" : false;

        if(query == false) return;

          $(query,table).each(function(){
            if($(this).hasClass(config.color_class)){
                  segments.push({
                      index: i,
                      sort: $(this).data("sort") || "low-to-high"
                  });
            }
             i++;

          });
      }
    }

    // lets stripe some cells

    stripeCells = function(direction){
      for(i = 0, len = segments.length; i < len; i++){

          var seg = segments[i],
              seg_index = seg.index
              seg_max = null,
              seg_min = null,
              cells = [];

          var query = (direction == "column") ? "tbody tr td:nth-child("+(seg_index+1)+")" :
                      (direction == "row") ? "tbody tr:nth-child("+(seg_index+1)+") td:harlequin" :
                      (direction == "both") ? "tbody td" : false;

          if(query == false) return;

          $(query,table).each(function(){

            var element = $(this);
            var new_cell = {
                value: parseFloat(element.text().replace(",","")),
                el: element
            }

            if(new_cell.value.length < 1){
                return true;
            }

            if(seg_min == null){
               seg_min = new_cell.value
            }else if(new_cell.value < seg_min){
               seg_min = new_cell.value
            }

            if(seg_max == null){
               seg_max = new_cell.value
            }else if(new_cell.value > seg_max){
               seg_max = new_cell.value
            }

            cells.push(new_cell);
          });

          for(j = 0, jlen = cells.length; j < jlen; j++){
               cells[j].el.css("background-color",getColor(cells[j].value,seg_min,seg_max,seg.sort));
          }
      }
    }

    // color functions

    getColor = function(value,min,max,sort){
        var color;
        if(config.colors != null && typeof config.colors == "object"){

          var len = config.colors.length,
              index = Math.floor(((value-min)/(max-min)) * len) - 1;

          if(index == -1) index = 0;

          color = config.colors[index];

        }else{

          var range = config.end_hue - config.start_hue;
          if(sort == "high-to-low"){
              var hue = Math.ceil(config.end_hue - (((value - min)/(max-min)) * range));
          }else{
              var hue = Math.ceil(config.start_hue + (((value - min)/(max-min)) * range));
          }

          color = "hsl("+hue+","+config.sat+"%,"+config.lightness+"%)";

          if(!useHsl){
            color = hsl2hex(hue,config.sat,config.lightness);
          }

        }

        return color;
    }

    testHsl = function(){
      var el = document.createElement("harlequin");
      el.style.cssText = "background-color:hsla(120,40%,100%,.5)";
      return !!~('' + el.style.backgroundColor).indexOf("rgba") || !!~('' + el.style.backgroundColor).indexOf("hsla");
    }

    useHsl = testHsl();

    hsl2hex = function(h,s,l){
        h = (h % 360) / 360;
        s = s/100;
        l = l/100;

        if(s == 0){
             l = Math.round(l * 255)
             return { r: l, g: l, b: l  };
        }

        var m2 = l >= 0.5 ? ((l+s)-(l*s)) : l*(1+s);
        var m1 = (2 * l) - m2;

        return '#'+ ( Math.round(hue(h - 1/3) * 255) | Math.round(hue(h) * 255) << 8 | Math.round(hue(h + 1/3) * 255) << 16 ).toString(16)

        function hue(h) {
                h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
                if      (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
                else if (h * 2 < 1) return m2;
                else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
                else                return m1;
        }
    }

    // init function

    start = function(table_id,direction,options){
        table = $("#"+table_id);
        segments = [];
        config = {}

        if(options != undefined){
          for(k in defaults){
            config[k] = (options[k] != undefined) ? options[k] : defaults[k];
          }
        }else{
          config = defaults;
        }

        populateCells(direction);
        stripeCells(direction);
    }

    return {
        stripe: function(table_id,direction,options){
            start(table_id,direction,options);
        }
    }

})();

<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';
import _ from 'lodash';
import { createAction } from 'redux-actions';
import { createAsyncActionType } from '../helpers/stateHelpers';

export const GET_TRENDING_TOPICS = '@app/GET_TRENDING_TOPICS';
export const GET_TRENDING_TOPICS_START = '@app/GET_TRENDING_TOPICS_START';
export const GET_TRENDING_TOPICS_SUCCESS = '@app/GET_TRENDING_TOPICS_SUCCESS';
export const GET_TRENDING_TOPICS_ERROR = '@app/GET_TRENDING_TOPICS_ERROR';

export const GET_REWARD_FUND = '@app/GET_REWARD_FUND';
export const GET_REWARD_FUND_START = '@app/GET_REWARD_FUND_START';
export const GET_REWARD_FUND_SUCCESS = '@app/GET_REWARD_FUND_SUCCESS';
export const GET_REWARD_FUND_ERROR = '@app/GET_REWARD_FUND_ERROR';

export const RATE_REQUEST = createAsyncActionType('@app/RATE_REQUEST');

export const CLOSE_BANNER = '@app/CLOSE_BANNER';
export const closeBanner = createAction(CLOSE_BANNER);

export const SET_APP_URL = '@app/SET_APP_URL';
export const setAppUrl = createAction(SET_APP_URL);

export const SET_USED_LOCALE = '@app/SET_USED_LOCALE';
export const setUsedLocale = createAction(SET_USED_LOCALE);

export const GET_CRYPTO_PRICE_HISTORY = createAsyncActionType('@app/GET_CRYPTOS_PRICE_HISTORY');
export const REFRESH_CRYPTO_PRICE_HISTORY = '@app/REFRESH_CRYPTO_PRICE_HISTORY';
export const refreshCryptoPriceHistory = createAction(REFRESH_CRYPTO_PRICE_HISTORY);

export const getRate = () => (dispatch, getState, { steemAPI }) => {
  dispatch({
    type: RATE_REQUEST.ACTION,
    payload: {
      promise: steemAPI
        .sendAsync('get_current_median_history_price', [])
        .then(resp => parseFloat(resp.base)),
    },
  });
};

export const getRewardFund = () => (dispatch, getSelection, { steemAPI }) =>
  dispatch({
    type: GET_REWARD_FUND,
    payload: { promise: steemAPI.sendAsync('get_reward_fund', ['post']) },
  });

export const getTrendingTopics = () => (dispatch, getState, { steemAPI }) => {
  dispatch({
    type: GET_TRENDING_TOPICS,
    payload: {
      promise: steemAPI.sendAsync('get_trending_tags', [undefined, 50]).then(result =>
        Object.values(result)
          .map(tag => tag.name)
          .filter(tag => tag !== ''),
      ),
    },
  });
};

export const getCryptoPriceHistory = (symbol, refresh = false) => dispatch => {
  if (refresh) {
    dispatch(refreshCryptoPriceHistory(symbol));
  }
  dispatch({
    type: GET_CRYPTO_PRICE_HISTORY.ACTION,
    payload: {
      promise: Promise.all([
        fetch(
          `https://min-api.cryptocompare.com/data/histoday?fsym=${symbol}&tsym=USD&limit=6`,
        ).then(res => res.json()),
        fetch(
          `https://min-api.cryptocompare.com/data/histoday?fsym=${symbol}&tsym=BTC&limit=6`,
        ).then(res => res.json()),
      ]).then(response => {
        const usdPriceHistory = _.get(response, 0, {});
        const btcPriceHistory = _.get(response, 1, {});
        return {
          usdPriceHistory,
          btcPriceHistory,
          symbol,
        };
      }),
    },
  });
};

export const ADD_NEW_NOTIFICATION = '@user/ADD_NEW_NOTIFICATION';
export const addNewNotification = createAction(ADD_NEW_NOTIFICATION);

export const SHOW_POST_MODAL = '@app/SHOW_POST_MODAL';
export const HIDE_POST_MODAL = '@app/HIDE_POST_MODAL';

export const showPostModal = createAction(SHOW_POST_MODAL);
export const hidePostModal = createAction(HIDE_POST_MODAL);
<commit_msg>fix: rate calculation (#2128)<commit_after>import fetch from 'isomorphic-fetch';
import _ from 'lodash';
import { createAction } from 'redux-actions';
import { createAsyncActionType } from '../helpers/stateHelpers';

export const GET_TRENDING_TOPICS = '@app/GET_TRENDING_TOPICS';
export const GET_TRENDING_TOPICS_START = '@app/GET_TRENDING_TOPICS_START';
export const GET_TRENDING_TOPICS_SUCCESS = '@app/GET_TRENDING_TOPICS_SUCCESS';
export const GET_TRENDING_TOPICS_ERROR = '@app/GET_TRENDING_TOPICS_ERROR';

export const GET_REWARD_FUND = '@app/GET_REWARD_FUND';
export const GET_REWARD_FUND_START = '@app/GET_REWARD_FUND_START';
export const GET_REWARD_FUND_SUCCESS = '@app/GET_REWARD_FUND_SUCCESS';
export const GET_REWARD_FUND_ERROR = '@app/GET_REWARD_FUND_ERROR';

export const RATE_REQUEST = createAsyncActionType('@app/RATE_REQUEST');

export const CLOSE_BANNER = '@app/CLOSE_BANNER';
export const closeBanner = createAction(CLOSE_BANNER);

export const SET_APP_URL = '@app/SET_APP_URL';
export const setAppUrl = createAction(SET_APP_URL);

export const SET_USED_LOCALE = '@app/SET_USED_LOCALE';
export const setUsedLocale = createAction(SET_USED_LOCALE);

export const GET_CRYPTO_PRICE_HISTORY = createAsyncActionType('@app/GET_CRYPTOS_PRICE_HISTORY');
export const REFRESH_CRYPTO_PRICE_HISTORY = '@app/REFRESH_CRYPTO_PRICE_HISTORY';
export const refreshCryptoPriceHistory = createAction(REFRESH_CRYPTO_PRICE_HISTORY);

export const getRate = () => (dispatch, getState, { steemAPI }) => {
  dispatch({
    type: RATE_REQUEST.ACTION,
    payload: {
      promise: steemAPI
        .sendAsync('get_current_median_history_price', [])
        .then(resp => parseFloat(resp.base) / parseFloat(resp.quote)),
    },
  });
};

export const getRewardFund = () => (dispatch, getSelection, { steemAPI }) =>
  dispatch({
    type: GET_REWARD_FUND,
    payload: { promise: steemAPI.sendAsync('get_reward_fund', ['post']) },
  });

export const getTrendingTopics = () => (dispatch, getState, { steemAPI }) => {
  dispatch({
    type: GET_TRENDING_TOPICS,
    payload: {
      promise: steemAPI.sendAsync('get_trending_tags', [undefined, 50]).then(result =>
        Object.values(result)
          .map(tag => tag.name)
          .filter(tag => tag !== ''),
      ),
    },
  });
};

export const getCryptoPriceHistory = (symbol, refresh = false) => dispatch => {
  if (refresh) {
    dispatch(refreshCryptoPriceHistory(symbol));
  }
  dispatch({
    type: GET_CRYPTO_PRICE_HISTORY.ACTION,
    payload: {
      promise: Promise.all([
        fetch(
          `https://min-api.cryptocompare.com/data/histoday?fsym=${symbol}&tsym=USD&limit=6`,
        ).then(res => res.json()),
        fetch(
          `https://min-api.cryptocompare.com/data/histoday?fsym=${symbol}&tsym=BTC&limit=6`,
        ).then(res => res.json()),
      ]).then(response => {
        const usdPriceHistory = _.get(response, 0, {});
        const btcPriceHistory = _.get(response, 1, {});
        return {
          usdPriceHistory,
          btcPriceHistory,
          symbol,
        };
      }),
    },
  });
};

export const ADD_NEW_NOTIFICATION = '@user/ADD_NEW_NOTIFICATION';
export const addNewNotification = createAction(ADD_NEW_NOTIFICATION);

export const SHOW_POST_MODAL = '@app/SHOW_POST_MODAL';
export const HIDE_POST_MODAL = '@app/HIDE_POST_MODAL';

export const showPostModal = createAction(SHOW_POST_MODAL);
export const hidePostModal = createAction(HIDE_POST_MODAL);
<|endoftext|>


<commit_before>/**
 *    Harlequin.js
 *    Highlighting for data tables
 *
 *    @author       Luke Williams (http://www.red-root.com)
 *    @version      0.2
*/

Harlequin = (function(){

   var table = null,
       segments = [],
       useHsl = true;

   // config options

   var config = {},
       defaults = {
        color_class: "color",
        start_hue: 0,
        end_hue: 120,
        sat: 90,
        lightness: 70,
        colors: null,
      }

    // fix for webkit bug on nth-child and descendents
    // until we don't need jQuery anymore or a find a better fix
    $.expr[":"].harlequin = function() {
        return true;
    };

    // lets find some cells

    populateCells = function(direction){

      if(direction == "both"){
        segments.push({
          index: -1,
          sort: table.data("sort") || "low-to-high"
        });
      }else{

        var i = 0;

        var query = (direction == "column") ? "thead th" :
                    (direction == "row") ? "tbody tr" : false;

        if(query == false) return;

          $(query,table).each(function(){
            if($(this).hasClass(config.color_class)){
                  segments.push({
                      index: i,
                      sort: $(this).data("sort") || "low-to-high"
                  });
            }
             i++;

          });
      }
    }

    // lets stripe some cells

    stripeCells = function(direction){
      for(i = 0, len = segments.length; i < len; i++){

          var seg = segments[i],
              seg_index = seg.index
              seg_max = null,
              seg_min = null,
              cells = [];

          var query = (direction == "column") ? "tbody tr td:nth-child("+(seg_index+1)+")" :
                      (direction == "row") ? "tbody tr:nth-child("+(seg_index+1)+") td:harlequin" :
                      (direction == "both") ? "tbody td" : false;

          if(query == false) return;

          $(query,table).each(function(){

            var element = $(this);
            var new_cell = {
                value: parseFloat(element.text()),
                el: element
            }

            if(new_cell.value.length < 1){
                return true;
            }

            if(seg_min == null){
               seg_min = new_cell.value
            }else if(new_cell.value < seg_min){
               seg_min = new_cell.value
            }

            if(seg_max == null){
               seg_max = new_cell.value
            }else if(new_cell.value > seg_max){
               seg_max = new_cell.value
            }

            cells.push(new_cell);
          });

          for(j = 0, jlen = cells.length; j < jlen; j++){
               cells[j].el.css("background-color",getColor(cells[j].value,seg_min,seg_max,seg.sort));
          }
      }
    }

    // color functions

    getColor = function(value,min,max,sort){
        var color;
        if(config.colors != null && typeof config.colors == "object"){

          var len = config.colors.length,
              index = Math.floor(((value-min)/(max-min)) * len) - 1;

          if(index == -1) index = 0;

          color = config.colors[index];

        }else{

          var range = config.end_hue - config.start_hue;
          if(sort == "high-to-low"){
              var hue = Math.ceil(config.end_hue - (((value - min)/(max-min)) * range));
          }else{
              var hue = Math.ceil(config.start_hue + (((value - min)/(max-min)) * range));
          }

          color = "hsl("+hue+","+config.sat+"%,"+config.lightness+"%)";

          if(!useHsl){
            color = hsl2hex(hue,config.sat,config.lightness);
          }

        }
        return color;
    }

    testHsl = function(){
      var el = document.createElement("harlequin");
      el.style.cssText = "background-color:hsla(120,40%,100%,.5)";
      return !!~('' + el.style.backgroundColor).indexOf("rgba") || !!~('' + el.style.backgroundColor).indexOf("hsla");
    }

    useHsl = testHsl();

    hsl2hex = function(h,s,l){
        h = (h % 360) / 360;
        s = s/100;
        l = l/100;

        if(s == 0){
             l = Math.round(l * 255)
             return { r: l, g: l, b: l  };
        }

        var m2 = l >= 0.5 ? ((l+s)-(l*s)) : l*(1+s);
        var m1 = (2 * l) - m2;

        return '#'+ ( Math.round(hue(h - 1/3) * 255) | Math.round(hue(h) * 255) << 8 | Math.round(hue(h + 1/3) * 255) << 16 ).toString(16)

        function hue(h) {
                h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
                if      (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
                else if (h * 2 < 1) return m2;
                else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
                else                return m1;
        }
    }

    // init function

    start = function(table_id,direction,options){
        table = $("#"+table_id);
        segments = [];
        config = {}

        if(options != undefined){
          for(k in defaults){
            config[k] = (options[k] != undefined) ? options[k] : defaults[k];
          }
        }else{
          config = defaults;
        }

        populateCells(direction);
        stripeCells(direction);
    }

    return {
        stripe: function(table_id,direction,options){
            start(table_id,direction,options);
        }
    }

})();

<commit_msg>Further testing of hsl support<commit_after>/**
 *    Harlequin.js
 *    Highlighting for data tables
 *
 *    @author       Luke Williams (http://www.red-root.com)
 *    @version      0.2
*/

Harlequin = (function(){

   var table = null,
       segments = [],
       useHsl = true;

   // config options

   var config = {},
       defaults = {
        color_class: "color",
        start_hue: 0,
        end_hue: 120,
        sat: 90,
        lightness: 70,
        colors: null,
      }

    // fix for webkit bug on nth-child and descendents
    // until we don't need jQuery anymore or a find a better fix
    $.expr[":"].harlequin = function() {
        return true;
    };

    // lets find some cells

    populateCells = function(direction){

      if(direction == "both"){
        segments.push({
          index: -1,
          sort: table.data("sort") || "low-to-high"
        });
      }else{

        var i = 0;

        var query = (direction == "column") ? "thead th" :
                    (direction == "row") ? "tbody tr" : false;

        if(query == false) return;

          $(query,table).each(function(){
            if($(this).hasClass(config.color_class)){
                  segments.push({
                      index: i,
                      sort: $(this).data("sort") || "low-to-high"
                  });
            }
             i++;

          });
      }
    }

    // lets stripe some cells

    stripeCells = function(direction){
      for(i = 0, len = segments.length; i < len; i++){

          var seg = segments[i],
              seg_index = seg.index
              seg_max = null,
              seg_min = null,
              cells = [];

          var query = (direction == "column") ? "tbody tr td:nth-child("+(seg_index+1)+")" :
                      (direction == "row") ? "tbody tr:nth-child("+(seg_index+1)+") td:harlequin" :
                      (direction == "both") ? "tbody td" : false;

          if(query == false) return;

          $(query,table).each(function(){

            var element = $(this);
            var new_cell = {
                value: parseFloat(element.text()),
                el: element
            }

            if(new_cell.value.length < 1){
                return true;
            }

            if(seg_min == null){
               seg_min = new_cell.value
            }else if(new_cell.value < seg_min){
               seg_min = new_cell.value
            }

            if(seg_max == null){
               seg_max = new_cell.value
            }else if(new_cell.value > seg_max){
               seg_max = new_cell.value
            }

            cells.push(new_cell);
          });

          for(j = 0, jlen = cells.length; j < jlen; j++){
               cells[j].el.css("background-color",getColor(cells[j].value,seg_min,seg_max,seg.sort));
          }
      }
    }

    // color functions

    getColor = function(value,min,max,sort){
        var color;
        if(config.colors != null && typeof config.colors == "object"){

          var len = config.colors.length,
              index = Math.floor(((value-min)/(max-min)) * len) - 1;

          if(index == -1) index = 0;

          color = config.colors[index];

        }else{

          var range = config.end_hue - config.start_hue;
          if(sort == "high-to-low"){
              var hue = Math.ceil(config.end_hue - (((value - min)/(max-min)) * range));
          }else{
              var hue = Math.ceil(config.start_hue + (((value - min)/(max-min)) * range));
          }

          color = "hsl("+hue+","+config.sat+"%,"+config.lightness+"%)";

          if(!useHsl){
            color = hsl2hex(hue,config.sat,config.lightness);
          }

        }

        return color;
    }

    testHsl = function(){
      var el = document.createElement("harlequin");
      el.style.cssText = "background-color:hsla(120,40%,100%,.5)";
      return !!~('' + el.style.backgroundColor).indexOf("rgba") || !!~('' + el.style.backgroundColor).indexOf("hsla");
    }

    useHsl = testHsl();
    alert(useHsl);

    hsl2hex = function(h,s,l){
        h = (h % 360) / 360;
        s = s/100;
        l = l/100;

        if(s == 0){
             l = Math.round(l * 255)
             return { r: l, g: l, b: l  };
        }

        var m2 = l >= 0.5 ? ((l+s)-(l*s)) : l*(1+s);
        var m1 = (2 * l) - m2;

        return '#'+ ( Math.round(hue(h - 1/3) * 255) | Math.round(hue(h) * 255) << 8 | Math.round(hue(h + 1/3) * 255) << 16 ).toString(16)

        function hue(h) {
                h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
                if      (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
                else if (h * 2 < 1) return m2;
                else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
                else                return m1;
        }
    }

    // init function

    start = function(table_id,direction,options){
        table = $("#"+table_id);
        segments = [];
        config = {}

        if(options != undefined){
          for(k in defaults){
            config[k] = (options[k] != undefined) ? options[k] : defaults[k];
          }
        }else{
          config = defaults;
        }

        populateCells(direction);
        stripeCells(direction);
    }

    return {
        stripe: function(table_id,direction,options){
            start(table_id,direction,options);
        }
    }

})();

<|endoftext|>


<commit_before>/**
 * Updates the document title
 *
 * @param  {String} title - the new title of the document
 */
export default function updateTitle (title) {
  if (title === undefined) {
    return
  }

  document.title = title
}
<commit_msg>fix: dont update title on client with falsy value except empty string<commit_after>/**
 * Updates the document title
 *
 * @param  {String} title - the new title of the document
 */
export default function updateTitle (title) {
  if (!title && title !== '') {
    return
  }

  document.title = title
}
<|endoftext|>


<commit_before>Kwf.FrontendForm.Checkbox = Ext.extend(Kwf.FrontendForm.Field, {
    initField: function() {
        this.el.select('input').each(function(input) {
            input.on('click', function() {
                this.fireEvent('change', this.getValue());
            }, this);
        }, this);
    },
    clearValue: function() {
        var inp = this.el.child('input');
        inp.dom.checked = false;
    },
    setValue: function(value) {
        var inp = this.el.child('input');
        inp.dom.checked = !!value;
    }
});

Kwf.FrontendForm.fields['kwfFormFieldCheckbox'] = Kwf.FrontendForm.Checkbox;
<commit_msg>Add getValue for checkbox-form-field to return the correct value<commit_after>Kwf.FrontendForm.Checkbox = Ext.extend(Kwf.FrontendForm.Field, {
    initField: function() {
        this.el.select('input').each(function(input) {
            input.on('click', function() {
                this.fireEvent('change', this.getValue());
            }, this);
        }, this);
    },
    clearValue: function() {
        var inp = this.el.child('input');
        inp.dom.checked = false;
    },
    setValue: function(value) {
        var inp = this.el.child('input');
        inp.dom.checked = !!value;
    },
    getValue: function(value) {
        var inp = this.el.child('input');
        return inp.dom.checked;
    }
});

Kwf.FrontendForm.fields['kwfFormFieldCheckbox'] = Kwf.FrontendForm.Checkbox;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule truncate
 * @flow
 */
'use strict';

var merge = require('merge');

type truncateOptions = {
  breakOnWords: boolean;
  minDelta: number;
  elipsis: string;
}

var defaultOptions = {
  breakOnWords: true,
  minDelta: 10, // Prevents truncating a tiny bit off the end
  elipsis: '...',
};

// maxChars (including ellipsis)
var truncate = function(
  str: ?string,
  maxChars: number,
  options: truncateOptions
): ?string {
  options = merge(defaultOptions, options);
  if (str && str.length &&
      str.length - options.minDelta + options.elipsis.length >= maxChars) {
    str = str.slice(0, maxChars - options.elipsis.length + 1);
    if (options.breakOnWords) {
      var ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n'));
      str = str.slice(0, ii);
    }
    str = str.trim() + options.elipsis;
  }
  return str;
};

module.exports = truncate;
<commit_msg>Fix truncate tests<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule truncate
 * @flow
 */
'use strict';

type truncateOptions = {
  breakOnWords: boolean;
  minDelta: number;
  elipsis: string;
}

const defaultOptions = {
  breakOnWords: true,
  minDelta: 10, // Prevents truncating a tiny bit off the end
  elipsis: '...',
};

// maxChars (including ellipsis)
const truncate = function(
  str: ?string,
  maxChars: number,
  options: truncateOptions
): ?string {
  options = Object.assign({}, defaultOptions, options);
  if (str && str.length &&
      str.length - options.minDelta + options.elipsis.length >= maxChars) {
    str = str.slice(0, maxChars - options.elipsis.length + 1);
    if (options.breakOnWords) {
      var ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n'));
      str = str.slice(0, ii);
    }
    str = str.trim() + options.elipsis;
  }
  return str;
};

module.exports = truncate;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'
import {getAsyncComponent} from 'async-react-component';

const APIOnBoarding = () => import('./components/Apis/OnBoarding/listing');
const Indexpage = () => import('../pages/index');

class Publisher extends  Component  {

    render(){
        return(
            <Router basename="/publisher">
                <Switch>
                    <Route path={"/apis/"} component={getAsyncComponent(APIOnBoarding)}/>
                    <Route path={"/"} component={getAsyncComponent(Indexpage)}/>
                </Switch>
            </Router>
        );
    };
}

export default Publisher;<commit_msg>clean up the main App<commit_after>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { Component } from 'react';
import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'
import {getAsyncComponent} from 'async-react-component';

const APIOnBoarding = () => import('./components/Apis/OnBoarding/listing');
const Indexpage = () => import('../pages/index');
const Login = () => import('./components/Login/login')

class Publisher extends  Component  {

    render(){
        return(
            <Router basename="/publisher">
                <Switch>
                    <Route path={"/login"} component={getAsyncComponent(Login)}/>
                    <Route path={"/apis"} component={getAsyncComponent(APIOnBoarding)}/>
                    <Route path={"/"} component={getAsyncComponent(Indexpage)}/>
                </Switch>
            </Router>
        );
    };
}

export default Publisher;<|endoftext|>


<commit_before>/*
* Copyright (c) 2012 Sprymix Inc.
* All rights reserved.
*
* See LICENSE for details.
**/

$SXJSP = (function() {
    'use strict';

    var modules = {};

    var StdObject = {}.constructor,
        StdArray = [].constructor,
        hop = StdObject.prototype.hasOwnProperty,
        tos = StdObject.prototype.toString;

    var Array_some = StdArray.prototype.some;
    if (typeof Array_some == 'undefined') {
        Array_some = function(cb, scope) {
            'use strict';

            var i = 0, len = this.length >>> 0;
            for (; i < len; i++) {
                if (cb.call(scope, this[i], i)) {
                    return true;
                }
            }
        }
    }

    function Module(name, dct) {
        this.$name = name;
        this.$initialized = dct != null;

        for (var i in dct) {
            if (hop.call(dct, i) && i.length && i[0] != '$') {
                this[i] = dct[i];
            }
        }
    }

    function error(msg) {
        throw '$SXJSP: ' + msg;
    }

    return {
        module: function(name, dct) {
            var parts = name.split('.'),
                i, len = parts.length,
                next = modules,
                next_sub,
                iter_name = [],
                part,
                mod,
                mod_name,
                mod_dct;

            if (!len) {
                error('invalid module name: "' +name + '"');
            }

            for (i = 0; i < len - 1; i++) {
                part = parts[i];
                iter_name.push(part);
                next_sub = next;
                if (next_sub.hasOwnProperty(part)) {
                    next = next_sub[part];
                } else {
                    next = next_sub[part] = new Module(iter_name.join('.'));
                }
            }

            mod_name = parts[len - 1];
            mod = next[mod_name];
            if (mod != null) {
                if (mod.$initialized) {
                    error('duplicate module? (' + name + ')');
                }
                for (i in dct) {
                    if (!mod.hasOwnProperty(i) && dct.hasOwnProperty(i)) {
                        mod[i] = dct[i];
                    }
                }
            } else {
                next[mod_name] = new Module(name, dct);
            }
        },

        each: function(arg_cnt, it, cb, scope) {
            var t = tos.call(it);

            if (t == '[object Array]') {
                if (arg_cnt != 1) {
                    error('foreach supports only one iterator variable when iterating over arrays');
                }
                Array_some.call(it, cb, scope);
                return;
            }

            if (t == '[object Object]') {
                var k;
                if (arg_cnt == 2) {
                    for (k in it) {
                        if (hop.call(it, k)) {
                            if (cb.call(scope, k, it[k])) {
                                return;
                            }
                        }
                    }
                } else {
                    // arg_cnt == 1
                    for (k in it) {
                        if (hop.call(it, k)) {
                            if (cb.call(scope, [k, it[k]])) {
                                return;
                            }
                        }
                    }
                }
                return;
            }

            if (t == '[object String]' || t == '[object NodeList]') {
                if (arg_cnt != 1) {
                    error('foreach supports only one iterator variable when iterating over '
                          + 'strings or NodeList');
                }

                var len = it.length >>> 0, i = 0;

                for (; i < len; i++) {
                    if (cb.call(scope, it[i])) {
                        return;
                    }
                }
                return;
            }

            error('foreach: unsupported iterable: ' + it);
        },

        validate_with: function(obj) {
            if (!obj.enter || tos.call(obj.enter) != '[object Function]'
                   || !obj.exit || tos.call(obj.exit) != '[object Function]') {
                error('with: context managers must have "enter" and "exit" methods');
            }
        },

        slice1: function(obj, num) {
            return StdArray.prototype.slice.call(obj, num);
        }
    };
})();
<commit_msg>utils.lang.jp.support.base: Micro-optimize $SXJSP.slice1<commit_after>/*
* Copyright (c) 2012 Sprymix Inc.
* All rights reserved.
*
* See LICENSE for details.
**/

$SXJSP = (function() {
    'use strict';

    var modules = {};

    var StdObject = {}.constructor,
        StdArray = [].constructor,
        hop = StdObject.prototype.hasOwnProperty,
        tos = StdObject.prototype.toString;

    var Array_some = StdArray.prototype.some;
    if (typeof Array_some == 'undefined') {
        Array_some = function(cb, scope) {
            'use strict';

            var i = 0, len = this.length >>> 0;
            for (; i < len; i++) {
                if (cb.call(scope, this[i], i)) {
                    return true;
                }
            }
        }
    }
    var Array_slice = StdArray.prototype.slice;

    function Module(name, dct) {
        this.$name = name;
        this.$initialized = dct != null;

        for (var i in dct) {
            if (hop.call(dct, i) && i.length && i[0] != '$') {
                this[i] = dct[i];
            }
        }
    }

    function error(msg) {
        throw '$SXJSP: ' + msg;
    }

    return {
        module: function(name, dct) {
            var parts = name.split('.'),
                i, len = parts.length,
                next = modules,
                next_sub,
                iter_name = [],
                part,
                mod,
                mod_name,
                mod_dct;

            if (!len) {
                error('invalid module name: "' +name + '"');
            }

            for (i = 0; i < len - 1; i++) {
                part = parts[i];
                iter_name.push(part);
                next_sub = next;
                if (next_sub.hasOwnProperty(part)) {
                    next = next_sub[part];
                } else {
                    next = next_sub[part] = new Module(iter_name.join('.'));
                }
            }

            mod_name = parts[len - 1];
            mod = next[mod_name];
            if (mod != null) {
                if (mod.$initialized) {
                    error('duplicate module? (' + name + ')');
                }
                for (i in dct) {
                    if (!mod.hasOwnProperty(i) && dct.hasOwnProperty(i)) {
                        mod[i] = dct[i];
                    }
                }
            } else {
                next[mod_name] = new Module(name, dct);
            }
        },

        each: function(arg_cnt, it, cb, scope) {
            var t = tos.call(it);

            if (t == '[object Array]') {
                if (arg_cnt != 1) {
                    error('foreach supports only one iterator variable when iterating over arrays');
                }
                Array_some.call(it, cb, scope);
                return;
            }

            if (t == '[object Object]') {
                var k;
                if (arg_cnt == 2) {
                    for (k in it) {
                        if (hop.call(it, k)) {
                            if (cb.call(scope, k, it[k])) {
                                return;
                            }
                        }
                    }
                } else {
                    // arg_cnt == 1
                    for (k in it) {
                        if (hop.call(it, k)) {
                            if (cb.call(scope, [k, it[k]])) {
                                return;
                            }
                        }
                    }
                }
                return;
            }

            if (t == '[object String]' || t == '[object NodeList]') {
                if (arg_cnt != 1) {
                    error('foreach supports only one iterator variable when iterating over '
                          + 'strings or NodeList');
                }

                var len = it.length >>> 0, i = 0;

                for (; i < len; i++) {
                    if (cb.call(scope, it[i])) {
                        return;
                    }
                }
                return;
            }

            error('foreach: unsupported iterable: ' + it);
        },

        validate_with: function(obj) {
            if (!obj.enter || tos.call(obj.enter) != '[object Function]'
                   || !obj.exit || tos.call(obj.exit) != '[object Function]') {
                error('with: context managers must have "enter" and "exit" methods');
            }
        },

        slice1: function(obj, num) {
            return Array_slice.call(obj, num);
        }
    };
})();
<|endoftext|>


<commit_before>import React from 'react';
import {findDOMNode} from 'react-dom';

const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead';

const GitHubStarsButton = React.createClass({
  componentDidMount() {
    const node = findDOMNode(this);
    node.dataset.style = window.innerWidth > 480 ? 'mega': null;
  },

  render() {
    return (
      <a
        aria-label={`Star ${AUTHOR_REPO} on GitHub`}
        className="github-button"
        data-count-api={`/repos/${AUTHOR_REPO}#stargazers_count`}
        data-count-aria-label="# stargazers on GitHub"
        data-count-href={`/${AUTHOR_REPO}/stargazers`}
        href={`https://github.com/${AUTHOR_REPO}`}>
        Star
      </a>
    );
  },
});

export default GitHubStarsButton;
<commit_msg>Fix deprecation warning for Github button on examples page<commit_after>import React from 'react';
import {findDOMNode} from 'react-dom';

const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead';

const GitHubStarsButton = React.createClass({
  componentDidMount() {
    const node = findDOMNode(this);
    node.dataset.style = window.innerWidth > 480 ? 'mega': null;
  },

  render() {
    return (
      <a
        aria-label={`Star ${AUTHOR_REPO} on GitHub`}
        className="github-button"
        data-count-aria-label="# stargazers on GitHub"
        data-count-href={`/${AUTHOR_REPO}/stargazers`}
        data-show-count={true}
        href={`https://github.com/${AUTHOR_REPO}`}>
        Star
      </a>
    );
  },
});

export default GitHubStarsButton;
<|endoftext|>


<commit_before>define([
	'sl',
	'dataGenerator',
	'controllers/scottLogicChartCtrl'
	],

	function(sl, dataGenerator, scottLogicChartCtrl) {

		var app = angular.module('slChartDemoApp', []);

		app.controller('slChartDemoAppCtrl', [ '$rootScope', '$http', function($rootScope, $http) {
			// Root Scope Initialisation
			$rootScope.chartData = null;

			this.generateChartData = function() {
				if(!$rootScope.chartData) {
		    		$rootScope.chartData = sl.utilities.dataGenerator()
				      .mu(0.1)
				      .sigma(0.1)
				      .startingPrice(100)
				      .intraDaySteps(50)
				      .fromDate(new Date(2013, 10, 1))
				      .toDate(new Date(2014, 10, 30))
				      .generate();
			    }
				return $rootScope.chartData;
			};

			this.generateChartData(dataGenerator);
		}]);

		app.controller('scottLogicChartCtrl', [ '$rootScope', scottLogicChartCtrl ]);

		app.directive('slChart', function() {
			return {
				restrict: 'E',
				templateUrl: 'inc/scottLogicChart.html',
				controller: 'scottLogicChartCtrl',
				controllerAs: 'chart'
			};
		});

		app.directive('slChartOptions', function() {
			return {
				restrict: 'E',
				templateUrl: 'inc/scottLogicChartOptions.html'
			};
		});
	}
);<commit_msg>Fixed filter on generated data series<commit_after>define([
	'sl',
	'dataGenerator',
	'controllers/scottLogicChartCtrl'
	],

	function(sl, dataGenerator, scottLogicChartCtrl) {

		var app = angular.module('slChartDemoApp', []);

		app.controller('slChartDemoAppCtrl', [ '$rootScope', '$http', function($rootScope, $http) {
			// Root Scope Initialisation
			$rootScope.chartData = null;

			this.generateChartData = function() {
				if(!$rootScope.chartData) {
		    		$rootScope.chartData = sl.utilities.dataGenerator()
				      .mu(0.1)
				      .sigma(0.1)
				      .startingPrice(100)
				      .intraDaySteps(50)
				      .fromDate(new Date(2013, 10, 1))
				      .toDate(new Date(2014, 10, 30))
				      .filter(function (moment) { return !(moment.day() === 0 || moment.day() === 6); })
				      .generate();
			    }
				return $rootScope.chartData;
			};

			this.generateChartData(dataGenerator);
		}]);

		app.controller('scottLogicChartCtrl', [ '$rootScope', scottLogicChartCtrl ]);

		app.directive('slChart', function() {
			return {
				restrict: 'E',
				templateUrl: 'inc/scottLogicChart.html',
				controller: 'scottLogicChartCtrl',
				controllerAs: 'chart'
			};
		});

		app.directive('slChartOptions', function() {
			return {
				restrict: 'E',
				templateUrl: 'inc/scottLogicChartOptions.html'
			};
		});
	}
);<|endoftext|>


<commit_before>/*
  bodyDecoder-middleware.js: Basic example of `connect.bodyParser()` middleware in node-http-proxy

  Copyright (c) Nodejitsu 2013

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var http = require('http'),
    connect = require('connect'),
    request = require('request'),
    colors = require('colors'),
    util = require('util'),
    Store = require('../helpers/store'),
    httpProxy = require('../../lib/http-proxy'),
    proxy = httpProxy.createProxyServer({});

http.createServer(new Store().handler()).listen(7531, function () {
  util.puts('http '.blue + 'greetings '.green + 'server'.blue + ' started '.green.bold + 'on port '.blue + '7531'.yellow);
//try these commands:
// get index:
// curl localhost:7531
// []
//
// get a doc:
// curl localhost:7531/foo
// {"error":"not_found"}
//
// post an doc:
// curl -X POST localhost:7531/foo -d '{"content": "hello", "type": "greeting"}'
// {"ok":true}
//
// get index (now, not empty)
// curl localhost:7531
// ["/foo"]
//
// get doc
// curl localhost:7531/foo
// {"content": "hello", "type": "greeting"}

//
// now, suppose we wanted to direct all objects where type == "greeting" to a different store
// than where type == "insult"
//
// we can use connect connect-bodyDecoder and some custom logic to send insults to another Store.

//insult server:

  http.createServer(new Store().handler()).listen(2600, function () {
    util.puts('http '.blue + 'insults '.red + 'server'.blue + ' started '.green.bold + 'on port '.blue + '2600'.yellow);

  //greetings -> 7531, insults-> 2600

  // now, start a proxy server.

    //don't worry about incoming contont type
    //bodyParser.parse[''] = JSON.parse

    connect.createServer(
      //refactor the body parser and re-streamer into a separate package
      connect.bodyParser(),
      //body parser absorbs the data and end events before passing control to the next
      // middleware. if we want to proxy it, we'll need to re-emit these events after
      //passing control to the middleware.
      require('connect-restreamer')(),
      function (req, res) {
        //if your posting an obect which contains type: "insult"
        //it will get redirected to port 2600.
        //normal get requests will go to 7531 nad will not return insults.
        var port = (req.body && req.body.type === 'insult' ? 2600 : 7531)
        proxy.web(req, res, { target: { host: 'localhost', port: port }});
      }
    ).listen(1337, function () {
      util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '1337'.yellow);
      //bodyParser needs content-type set to application/json
      //if we use request, it will set automatically if we use the 'json:' field.
      function post (greeting, type) {
        request.post({
          url: 'http://localhost:1337/' + greeting,
          json: {content: greeting, type: type || "greeting"}
        })
      }
      post("hello")
      post("g'day")
      post("kiora")
      post("houdy")
      post("java", "insult")

      //now, the insult should have been proxied to 2600

      //curl localhost:2600
      //["/java"]

      //but the greetings will be sent to 7531

      //curl localhost:7531
      //["/hello","/g%27day","/kiora","/houdy"]

    })
  })
});<commit_msg>update modify request body eg<commit_after>/*
  bodyDecoder-middleware.js: Basic example of `connect.bodyParser()` middleware in node-http-proxy

  Copyright (c) Nodejitsu 2013

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var http = require('http'),
    connect = require('connect'),
    request = require('request'),
    colors = require('colors'),
    util = require('util'),
    bodyParser = require('body-parser'),
    httpProxy = require('../../lib/http-proxy'),
    proxy = httpProxy.createProxyServer({});

//restreame
var restreamer = function (){
  return function (req, res, next) { //restreame
    req.removeAllListeners('data')
    req.removeAllListeners('end')
    next()
    process.nextTick(function () {
      rawBody = new Buffer(req.body)
      console.log('dsfgsdgsdgsdrtwergtsdgf', JSON.stringify(req.body).length)
      if(req.body) {
        req.emit('data', JSON.stringify(req.body))
      }
      req.emit('end')
    })
  }
}

//
//  Basic Http Proxy Server
//
var app = connect()
  .use(bodyParser.json())//json
  .use(restreamer())//restreame
  .use(function(req, res){
    // modify body here,
    // eg: req.body = {a: 1}.
    console.log('proxy body:',req.body)
    proxy.web(req, res, {
      target: 'http://127.0.0.1:9013'
    })
  });

http.createServer(app).listen(8013, function(){
  console.log('proxy linsten 8013');
});

//
//  Target Http Server
//
var app1 = connect()
  .use(bodyParser.json())
  .use(function(req, res){
    console.log('app1:',req.body)
    res.end('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  });
http.createServer(app1).listen(9013, function(){
  //request to 8013 to proxy
  request.post({//
    url: 'http://127.0.0.1:8013',
    json: {content: 123, type: "greeting"}
  },function(err, res,data){
    console.log('return:' ,err, data)
  })
});

<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { addTodo } from '../actions/todos';

import type { Dispatch } from '../types';

export type Props = {
  dispatch: Dispatch
};

export type State = {
  value: string
};

class AddTodo extends Component<Props, State> {
  input: HTMLInputElement;
  state = {
    value: ''
  };
  handleChange = (event: SyntheticKeyboardEvent<HTMLInputElement>) => {
    this.setState({ value: event.currentTarget.value });
  };
  handleSubmit = (event: Event) => {
    event.preventDefault();
    if (!this.state.value.trim()) {
      return;
    }
    this.props.dispatch(addTodo(this.state.value));
    this.setState({ value: '' });
  };
  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          <input value={this.state.value} onChange={this.handleChange} />
          <button type="submit">
            Add Todo
          </button>
        </form>

    );
  }
}

export default connect()(AddTodo);
<commit_msg>Cleanup todos-flow container (#3365)<commit_after>// @flow

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { addTodo } from '../actions/todos';

import type { Dispatch } from '../types';

export type Props = {
  dispatch: Dispatch
};

export type State = {
  value: string
};

class AddTodo extends Component<Props, State> {
  state = {
    value: ''
  };
  handleChange = (event: SyntheticKeyboardEvent<HTMLInputElement>) => {
    this.setState({ value: event.currentTarget.value });
  };
  handleSubmit = (event: Event) => {
    event.preventDefault();
    if (!this.state.value.trim()) {
      return;
    }
    this.props.dispatch(addTodo(this.state.value));
    this.setState({ value: '' });
  };
  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          <input value={this.state.value} onChange={this.handleChange} />
          <button type="submit">
            Add Todo
          </button>
        </form>

    );
  }
}

export default connect()(AddTodo);
<|endoftext|>


<commit_before>var static = require('node-static'),
    util = require('util');

//
// Create a node-static server to serve the current directory
//
var file = new static.Server('./public', { cache: -1, headers: {'Cache-Control': 'no-cache, must-revalidate'} });

require('http').createServer(function (request, response) {

    // automatically respond to the /env url, with a JSON string of our environment
    if (request.url === '/env') {

        response.writeHead(200,
            {
                'Content-Type': 'application/json'
            }
        );

        return response.end(util.inspect(process.env));

    }

    file.serve(request, response, function (err, res) {
        if (err) { // An error as occured
            console.error("> Error serving " + request.url + " - " + err.message);
            response.writeHead(err.status, err.headers);
            response.end();
        } else { // The file was served successfully
            console.log("> " + request.url + " - " + res.message);
        }
    });

}).listen(process.env.NODE_PORT);

console.log("> Node.js app is listening on port %s running Node.js %s", process.env.NODE_PORT, process.version);
<commit_msg>Updated the user-nginx-nodejs to properly serve JSON.<commit_after>var static = require('node-static'),
    util = require('util');

//
// Create a node-static server to serve the current directory
//
var file = new static.Server('./public', { cache: -1, headers: {'Cache-Control': 'no-cache, must-revalidate'} });

require('http').createServer(function (request, response) {

    // automatically respond to the /env url, with a JSON string of our environment
    if (request.url === '/env') {

        response.writeHead(200,
            {
                'Content-Type': 'application/json'
            }
        );

        return response.end(JSON.stringify(process.env));

    }

    file.serve(request, response, function (err, res) {
        if (err) { // An error as occured
            console.error("> Error serving " + request.url + " - " + err.message);
            response.writeHead(err.status, err.headers);
            response.end();
        } else { // The file was served successfully
            console.log("> " + request.url + " - " + res.message);
        }
    });

}).listen(process.env.NODE_PORT);

console.log("> Node.js app is listening on port %s running Node.js %s", process.env.NODE_PORT, process.version);
<|endoftext|>