<commit_before>var gulp = require('gulp');
var ts = require('gulp-typescript');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var ddescribeIit = require('gulp-ddescribe-iit');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var gulpFile = require('gulp-file');
var del = require('del');
var merge = require('merge2');
var clangFormat = require('clang-format');
var gulpFormat = require('gulp-clang-format');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var webpack = require('webpack');

var PATHS = {
  src: 'src/**/*.ts',
  srcIndex: 'src/index.ts',
  specs: 'src/**/*.spec.ts',
  testHelpers: 'src/util/matchers.ts',
  demo: 'demo/**/*.ts',
  demoDist: 'demo/dist/**/*',
  typings: 'typings/index.d.ts',
  jasmineTypings: 'typings/globals/jasmine/index.d.ts',
  demoApiDocs: 'demo/src'
};

function webpackCallBack(taskName, gulpDone) {
  return function(err, stats) {
    if (err) throw new gutil.PluginError(taskName, err);
    gutil.log("[" + taskName + "]", stats.toString());
    gulpDone();
  }
}

// Transpiling & Building

var cjsProject = ts.createProject('tsconfig.json', {declaration: true});
var esmProject = ts.createProject('tsconfig-es2015.json');

gulp.task('clean:build', function() { return del('dist/'); });

gulp.task('cjs', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(cjsProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/'), tsResult.js.pipe(gulp.dest('dist/')))
  ]);
});

gulp.task('esm', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.jasmineTypings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(esmProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/esm')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/esm'), tsResult.js.pipe(gulp.dest('dist/esm')))
  ]);
});

gulp.task('umd', function(cb) {
  function ngExternal(ns) {
    var ng2Ns = '@angular/' + ns;
    return {root: ['ng', ns], commonjs: ng2Ns, commonjs2: ng2Ns, amd: ng2Ns};
  }

  webpack(
      {
        entry: './dist/index.js',
        output: {filename: 'dist/bundles/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'},
        devtool: 'source-map',
        externals: {'@angular/core': ngExternal('core'), '@angular/common': ngExternal('common')}
      },
      webpackCallBack('webpack', cb));
});

gulp.task('npm', function() {
  var pkgJson = require('./package.json');
  var targetPkgJson = {};
  var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

  targetPkgJson['name'] = '@ng-bootstrap/ng-bootstrap';

  fieldsToCopy.forEach(function(field) { targetPkgJson[field] = pkgJson[field]; });

  targetPkgJson['main'] = 'index.js';
  targetPkgJson['jsnext:main'] = 'esm/index.js';

  targetPkgJson.peerDependencies = {};
  Object.keys(pkgJson.dependencies).forEach(function(dependency) {
    targetPkgJson.peerDependencies[dependency] = '^' + pkgJson.dependencies[dependency];
  });

  return gulp.src('README.md')
      .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
      .pipe(gulp.dest('dist'));
});

gulp.task('changelog', function() {
  var conventionalChangelog = require('gulp-conventional-changelog');
  return gulp.src('CHANGELOG.md', {})
      .pipe(conventionalChangelog({preset: 'angular', releaseCount: 1}))
      .pipe(gulp.dest('./'));
});

// Testing

var testProject = ts.createProject('tsconfig.json');

function startKarmaServer(isTddMode, done) {
  var karmaServer = require('karma').Server;
  var travis = process.env.TRAVIS;

  var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode};

  if (travis) {
    config['reporters'] = ['dots'];
    config['browsers'] = ['Firefox'];
  }

  new karmaServer(config, done).start();
}

gulp.task('clean:tests', function() { return del('temp/'); });

gulp.task('build:tests', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings]).pipe(sourcemaps.init()).pipe(ts(testProject));

  return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp'));
});

gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); });

gulp.task(
    'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); });

gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); });

gulp.task('tdd', ['clean:build-tests'], function(done) {
  startKarmaServer(true, function(err) {
    done(err);
    process.exit(1);
  });

  gulp.watch(PATHS.src, ['build:tests']);
});

// Formatting

gulp.task('lint', function() {
  return gulp.src([PATHS.src, PATHS.demo, '!demo/src/api-docs.ts'])
      .pipe(tslint({configuration: require('./tslint.json'), formatter: 'prose'}))
      .pipe(tslint.report({summarizeFailureOutput: true}));
});

gulp.task('check-format', function() {
  return doCheckFormat().on(
      'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/ng-bootstrap/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

function doCheckFormat() {
  return gulp
      .src([
        'gulpfile.js', 'karma-test-shim.js', 'misc/api-doc.js', 'misc/api-doc.spec.js', 'misc/demo-gen.js', PATHS.src
      ])
      .pipe(gulpFormat.checkFormat('file', clangFormat));
}

// Demo

gulp.task('generate-docs', function() {
  var getApiDocs = require('./misc/get-doc');
  var docs = `const API_DOCS = ${JSON.stringify(getApiDocs(), null, 2)};\n\nexport default API_DOCS;`;

  return gulpFile('api-docs.ts', docs, {src: true}).pipe(gulp.dest(PATHS.demoApiDocs));
});

gulp.task('clean:demo', function() { return del('demo/dist'); });

gulp.task('clean:demo-cache', function() { return del('.publish/'); });

gulp.task(
    'demo-server', ['generate-docs'],
    shell.task(['webpack-dev-server --port 9090 --config webpack.demo.js --hot --inline --progress']));

gulp.task(
    'build:demo', ['clean:demo', 'generate-docs'],
    shell.task(['MODE=build webpack --config webpack.demo.js --progress --profile --bail']));

gulp.task('demo-push', function() {
  return gulp.src(PATHS.demoDist)
      .pipe(ghPages({remoteUrl: "https://github.com/ng-bootstrap/ng-bootstrap.github.io.git", branch: "master"}));
});

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:tests', 'clean:demo', 'clean:demo-cache']);

gulp.task('build', function(done) {
  runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'esm', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function(done) { runSequence('clean:demo', 'build:demo', 'demo-push', 'clean:demo-cache', done); });

gulp.task('default', function(done) { runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', done); });
<commit_msg>fix(build): generate changelog without 'v' version prefix<commit_after>var gulp = require('gulp');
var ts = require('gulp-typescript');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var ddescribeIit = require('gulp-ddescribe-iit');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var gulpFile = require('gulp-file');
var del = require('del');
var merge = require('merge2');
var clangFormat = require('clang-format');
var gulpFormat = require('gulp-clang-format');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var webpack = require('webpack');

var PATHS = {
  src: 'src/**/*.ts',
  srcIndex: 'src/index.ts',
  specs: 'src/**/*.spec.ts',
  testHelpers: 'src/util/matchers.ts',
  demo: 'demo/**/*.ts',
  demoDist: 'demo/dist/**/*',
  typings: 'typings/index.d.ts',
  jasmineTypings: 'typings/globals/jasmine/index.d.ts',
  demoApiDocs: 'demo/src'
};

function webpackCallBack(taskName, gulpDone) {
  return function(err, stats) {
    if (err) throw new gutil.PluginError(taskName, err);
    gutil.log("[" + taskName + "]", stats.toString());
    gulpDone();
  }
}

// Transpiling & Building

var cjsProject = ts.createProject('tsconfig.json', {declaration: true});
var esmProject = ts.createProject('tsconfig-es2015.json');

gulp.task('clean:build', function() { return del('dist/'); });

gulp.task('cjs', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(cjsProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/'), tsResult.js.pipe(gulp.dest('dist/')))
  ]);
});

gulp.task('esm', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.jasmineTypings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(esmProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/esm')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/esm'), tsResult.js.pipe(gulp.dest('dist/esm')))
  ]);
});

gulp.task('umd', function(cb) {
  function ngExternal(ns) {
    var ng2Ns = '@angular/' + ns;
    return {root: ['ng', ns], commonjs: ng2Ns, commonjs2: ng2Ns, amd: ng2Ns};
  }

  webpack(
      {
        entry: './dist/index.js',
        output: {filename: 'dist/bundles/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'},
        devtool: 'source-map',
        externals: {'@angular/core': ngExternal('core'), '@angular/common': ngExternal('common')}
      },
      webpackCallBack('webpack', cb));
});

gulp.task('npm', function() {
  var pkgJson = require('./package.json');
  var targetPkgJson = {};
  var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

  targetPkgJson['name'] = '@ng-bootstrap/ng-bootstrap';

  fieldsToCopy.forEach(function(field) { targetPkgJson[field] = pkgJson[field]; });

  targetPkgJson['main'] = 'index.js';
  targetPkgJson['jsnext:main'] = 'esm/index.js';

  targetPkgJson.peerDependencies = {};
  Object.keys(pkgJson.dependencies).forEach(function(dependency) {
    targetPkgJson.peerDependencies[dependency] = '^' + pkgJson.dependencies[dependency];
  });

  return gulp.src('README.md')
      .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
      .pipe(gulp.dest('dist'));
});

gulp.task('changelog', function() {
  var conventionalChangelog = require('gulp-conventional-changelog');
  return gulp.src('CHANGELOG.md', {})
      .pipe(conventionalChangelog({preset: 'angular', releaseCount: 1}, {
        // Override release version to avoid `v` prefix for git comparison
        // See https://github.com/conventional-changelog/conventional-changelog-core/issues/10
        currentTag: require('./package.json').version
      }))
      .pipe(gulp.dest('./'));
});

// Testing

var testProject = ts.createProject('tsconfig.json');

function startKarmaServer(isTddMode, done) {
  var karmaServer = require('karma').Server;
  var travis = process.env.TRAVIS;

  var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode};

  if (travis) {
    config['reporters'] = ['dots'];
    config['browsers'] = ['Firefox'];
  }

  new karmaServer(config, done).start();
}

gulp.task('clean:tests', function() { return del('temp/'); });

gulp.task('build:tests', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings]).pipe(sourcemaps.init()).pipe(ts(testProject));

  return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp'));
});

gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); });

gulp.task(
    'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); });

gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); });

gulp.task('tdd', ['clean:build-tests'], function(done) {
  startKarmaServer(true, function(err) {
    done(err);
    process.exit(1);
  });

  gulp.watch(PATHS.src, ['build:tests']);
});

// Formatting

gulp.task('lint', function() {
  return gulp.src([PATHS.src, PATHS.demo, '!demo/src/api-docs.ts'])
      .pipe(tslint({configuration: require('./tslint.json'), formatter: 'prose'}))
      .pipe(tslint.report({summarizeFailureOutput: true}));
});

gulp.task('check-format', function() {
  return doCheckFormat().on(
      'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/ng-bootstrap/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

function doCheckFormat() {
  return gulp
      .src([
        'gulpfile.js', 'karma-test-shim.js', 'misc/api-doc.js', 'misc/api-doc.spec.js', 'misc/demo-gen.js', PATHS.src
      ])
      .pipe(gulpFormat.checkFormat('file', clangFormat));
}

// Demo

gulp.task('generate-docs', function() {
  var getApiDocs = require('./misc/get-doc');
  var docs = `const API_DOCS = ${JSON.stringify(getApiDocs(), null, 2)};\n\nexport default API_DOCS;`;

  return gulpFile('api-docs.ts', docs, {src: true}).pipe(gulp.dest(PATHS.demoApiDocs));
});

gulp.task('clean:demo', function() { return del('demo/dist'); });

gulp.task('clean:demo-cache', function() { return del('.publish/'); });

gulp.task(
    'demo-server', ['generate-docs'],
    shell.task(['webpack-dev-server --port 9090 --config webpack.demo.js --hot --inline --progress']));

gulp.task(
    'build:demo', ['clean:demo', 'generate-docs'],
    shell.task(['MODE=build webpack --config webpack.demo.js --progress --profile --bail']));

gulp.task('demo-push', function() {
  return gulp.src(PATHS.demoDist)
      .pipe(ghPages({remoteUrl: "https://github.com/ng-bootstrap/ng-bootstrap.github.io.git", branch: "master"}));
});

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:tests', 'clean:demo', 'clean:demo-cache']);

gulp.task('build', function(done) {
  runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'esm', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function(done) { runSequence('clean:demo', 'build:demo', 'demo-push', 'clean:demo-cache', done); });

gulp.task('default', function(done) { runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', done); });
<|endoftext|>


<commit_before>'use strict';
angular
  .module('core')
  .directive('a', preventClickDirective)
  .directive('a', cardExpandDirective)
  .directive('a', asideMenuToggleDirective)
  .directive('body', asideMenuHideDirective)
  .directive('backToTop', backToTopDirective)
  .directive('button', asidePanelToggleDirective);

//Prevent click if href="#"
function preventClickDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    if (attrs.href === '#') {
      element.on('click', function (event) {
        event.preventDefault();
      });
    }
  }
}

//Card Collapse
function cardExpandDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function () {
      if (element.hasClass('card-expand-toggle')) {
        element.find('i').toggleClass('r180');
        element.parent().parent().toggleClass('open');
      }
      //
    });
  }
}

//LayoutToggle
asideMenuToggleDirective.$inject = ['$interval'];
function asideMenuToggleDirective($interval) {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-menu-toggler')) {
        angular.element('body').toggleClass('aside-menu-show');
      }
    });
  }
}
function asideMenuHideDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(document).bind("mouseup touchend", function (e) {
      var container = angular.element("#aside-menu");
      var btn = angular.element("#aside-menu-toggler");
      if (!container.is(e.target) && container.has(e.target).length === 0 && !btn.is(e.target) && btn.has(e.target).length === 0) {
        if (element.hasClass('aside-menu-show')) {
          element.removeClass('aside-menu-show');
        }
      }
    });
  }
}
function backToTopDirective() {
  var directive = {
    restrict: 'E',
    replace: true,
    template: '<button class="md-fab md-button md-ink-ripple back-to-top"></button>',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(window).scroll(function () {
      if (angular.element(window).scrollTop() <= 0) {
        angular.element(element).fadeOut();
      }
      else {
        angular.element(element).fadeIn();
      }
    });
    angular.element(element).on('click', function () {
      angular.element('html, body').animate({ scrollTop: 0 }, 'fast');
    });
  }
}
function backToTopDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-panel-toggle')) {
        angular.element('body').toggleClass('aside-menu-open');
      }
    });
  }
}<commit_msg>Commited from lenh at Fri, Aug 18, 2017  9:04:47 AM<commit_after>'use strict';
angular
  .module('core')
  .directive('a', preventClickDirective)
  .directive('a', cardExpandDirective)
  .directive('a', asideMenuToggleDirective)
  .directive('body', asideMenuHideDirective)
  .directive('backToTop', backToTopDirective)
  .directive('button', asidePanelToggleDirective);

//Prevent click if href="#"
function preventClickDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    if (attrs.href === '#') {
      element.on('click', function (event) {
        event.preventDefault();
      });
    }
  }
}

//Card Collapse
function cardExpandDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function () {
      if (element.hasClass('card-expand-toggle')) {
        element.find('i').toggleClass('r180');
        element.parent().parent().toggleClass('open');
      }
      //
    });
  }
}

//LayoutToggle
asideMenuToggleDirective.$inject = ['$interval'];
function asideMenuToggleDirective($interval) {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-menu-toggler')) {
        angular.element('body').toggleClass('aside-menu-show');
      }
    });
  }
}
function asideMenuHideDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(document).bind("mouseup touchend", function (e) {
      var container = angular.element("#aside-menu");
      var btn = angular.element("#aside-menu-toggler");
      if (!container.is(e.target) && container.has(e.target).length === 0 && !btn.is(e.target) && btn.has(e.target).length === 0) {
        if (element.hasClass('aside-menu-show')) {
          element.removeClass('aside-menu-show');
        }
      }
    });
  }
}
function backToTopDirective() {
  var directive = {
    restrict: 'E',
    replace: true,
    template: '<button class="md-fab md-button md-ink-ripple back-to-top"></button>',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(window).scroll(function () {
      if (angular.element(window).scrollTop() <= 0) {
        angular.element(element).fadeOut();
      }
      else {
        angular.element(element).fadeIn();
      }
    });
    angular.element(element).on('click', function () {
      angular.element('html, body').animate({ scrollTop: 0 }, 'fast');
    });
  }
}
function asidePanelToggleDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-panel-toggle')) {
        angular.element('body').toggleClass('aside-menu-open');
      }
    });
  }
}<|endoftext|>


<commit_before>var querystring = require('querystring'),
  crypto = require('crypto'),
  https = require('https'),
  http = require('http'),
  URL = require('url'),
  OAuthUtils = require('./_utils'),
  ResponseStatusError = require('./response_status_error');

exports.OAuth2 = function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) {
  this._clientId = clientId;
  this._clientSecret = clientSecret;
  this._baseSite = baseSite;
  this._authorizeUrl = authorizePath || "/oauth/authorize";
  this._accessTokenUrl = accessTokenPath || "/oauth/access_token";
  this._accessTokenName = "access_token";
  this._authMethod = "Bearer";
  this._customHeaders = customHeaders || {};
  this._useAuthorizationHeaderForGET = false;
}

// This 'hack' method is required for sites that don't use
// 'access_token' as the name of the access token (for requests).
// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 )
// it isn't clear what the correct value should be atm, so allowing
// for specific (temporary?) override for now.
exports.OAuth2.prototype.setAccessTokenName = function(name) {
  this._accessTokenName = name;
}

// Sets the authorization method for Authorization header.
// e.g. Authorization: Bearer <token>  # "Bearer" is the authorization method.
exports.OAuth2.prototype.setAuthMethod = function(authMethod) {
  this._authMethod = authMethod;
};

// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call )
// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter
exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) {
  this._useAuthorizationHeaderForGET = useIt;
}

exports.OAuth2.prototype._getAccessTokenUrl = function() {
  return this._baseSite + this._accessTokenUrl; /* + "?" + querystring.stringify(params); */
}

// Build the authorization header. In particular, build the part after the colon.
// e.g. Authorization: Bearer <token>  # Build "Bearer <token>"
exports.OAuth2.prototype.buildAuthHeader = function(token) {
  return this._authMethod + ' ' + token;
};

exports.OAuth2.prototype._chooseHttpLibrary = function(parsedUrl) {
  var http_library = https;
  // As this is OAUth2, we *assume* https unless told explicitly otherwise.
  if (parsedUrl.protocol != "https:") {
    http_library = http;
  }
  return http_library;
};

exports.OAuth2.prototype._request = function(method, url, headers, post_body, access_token, callback) {

  var parsedUrl = URL.parse(url, true);
  if (parsedUrl.protocol == "https:" && !parsedUrl.port) {
    parsedUrl.port = 443;
  }

  var http_library = this._chooseHttpLibrary(parsedUrl);

  var realHeaders = {};
  for (var key in this._customHeaders) {
    realHeaders[key] = this._customHeaders[key];
  }
  if (headers) {
    for (var key in headers) {
      realHeaders[key] = headers[key];
    }
  }
  realHeaders['Host'] = parsedUrl.host;

  if (!realHeaders['User-Agent']) {
    realHeaders['User-Agent'] = 'Node-oauth';
  }

  if (post_body) {
    if (Buffer.isBuffer(post_body)) {
      realHeaders["Content-Length"] = post_body.length;
    } else {
      realHeaders["Content-Length"] = Buffer.byteLength(post_body);
    }
  } else {
    realHeaders["Content-length"] = 0;
  }

  if (access_token && !('Authorization' in realHeaders)) {
    if (!parsedUrl.query) parsedUrl.query = {};
    parsedUrl.query[this._accessTokenName] = access_token;
  }

  var queryStr = querystring.stringify(parsedUrl.query);
  if (queryStr) queryStr = "?" + queryStr;
  var options = {
    host: parsedUrl.hostname,
    port: parsedUrl.port,
    path: parsedUrl.pathname + queryStr,
    method: method,
    headers: realHeaders
  };

  this._executeRequest(http_library, options, post_body, callback);
}

exports.OAuth2.prototype._executeRequest = function(http_library, options, post_body, callback) {
  // Some hosts *cough* google appear to close the connection early / send no content-length header
  // allow this behaviour.
  var allowEarlyClose= OAuthUtils.isAnEarlyCloseHost(options.host);
  var callbackCalled= false;
  function passBackControl( response, result ) {
    if(!callbackCalled) {
      callbackCalled=true;
      if( !(response.statusCode >= 200 && response.statusCode <= 299) && (response.statusCode != 301) && (response.statusCode != 302) ) {
        var error = new ResponseStatusError("an unexpected response of " + response.statusCode + " was returned", {
          statusCode: response.statusCode,
          data: data
        });
        error.statusCode = response.statusCode;
        error.data = data;
        callback(error, data, response);
      } else {
        callback(null, result, response);
      }
    }
  }

  var result = "";

  var request = http_library.request(options);
  request.on('response', function (response) {
    response.on("data", function (chunk) {
      result+= chunk
    });
    response.on("close", function(err) {
      if (allowEarlyClose) {
        passBackControl(response, result);
      }
    });
    response.addListener("end", function() {
      passBackControl(response, result);
    });
  });
  request.on('error', function(e) {
    callbackCalled = true;
    callback(e);
  });

  if ((options.method == 'POST' || options.method == 'PUT') && post_body) {
    request.write(post_body);
  }
  request.end();
}

exports.OAuth2.prototype.getAuthorizeUrl = function(params) {
  var params = params || {};
  params['client_id'] = this._clientId;
  return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params);
}

exports.OAuth2.prototype.getOAuthAccessToken = function(code, params, callback) {
  var params = params || {};
  params['client_id'] = this._clientId;
  params['client_secret'] = this._clientSecret;
  var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code';
  params[codeParam] = code;

  var post_data = querystring.stringify(params);
  var post_headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) {
    if (error) callback(error);
    else {
      var results;
      try {
        // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07
        // responses should be in JSON
        results = JSON.parse(data);
      } catch (e) {
        // .... However both Facebook + Github currently use rev05 of the spec
        // and neither seem to specify a content-type correctly in their response headers :(
        // clients of these services will suffer a *minor* performance cost of the exception
        // being thrown
        results = querystring.parse(data);
      }
      var access_token = results["access_token"];
      var refresh_token = results["refresh_token"];
      delete results["refresh_token"];
      callback(null, access_token, refresh_token, results); // callback results =-=
    }
  });
}

// Deprecated
exports.OAuth2.prototype.getProtectedResource = function(url, access_token, callback) {
  this._request("GET", url, {}, "", access_token, callback);
}

exports.OAuth2.prototype.get = function(url, access_token, callback) {
  if (this._useAuthorizationHeaderForGET) {
    var headers = {
      'Authorization': this.buildAuthHeader(access_token)
    }
    access_token = null;
  } else {
    headers = {};
  }
  this._request("GET", url, headers, "", access_token, callback);
}<commit_msg>copy paste error<commit_after>var querystring = require('querystring'),
  crypto = require('crypto'),
  https = require('https'),
  http = require('http'),
  URL = require('url'),
  OAuthUtils = require('./_utils'),
  ResponseStatusError = require('./response_status_error');

exports.OAuth2 = function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) {
  this._clientId = clientId;
  this._clientSecret = clientSecret;
  this._baseSite = baseSite;
  this._authorizeUrl = authorizePath || "/oauth/authorize";
  this._accessTokenUrl = accessTokenPath || "/oauth/access_token";
  this._accessTokenName = "access_token";
  this._authMethod = "Bearer";
  this._customHeaders = customHeaders || {};
  this._useAuthorizationHeaderForGET = false;
}

// This 'hack' method is required for sites that don't use
// 'access_token' as the name of the access token (for requests).
// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 )
// it isn't clear what the correct value should be atm, so allowing
// for specific (temporary?) override for now.
exports.OAuth2.prototype.setAccessTokenName = function(name) {
  this._accessTokenName = name;
}

// Sets the authorization method for Authorization header.
// e.g. Authorization: Bearer <token>  # "Bearer" is the authorization method.
exports.OAuth2.prototype.setAuthMethod = function(authMethod) {
  this._authMethod = authMethod;
};

// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call )
// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter
exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) {
  this._useAuthorizationHeaderForGET = useIt;
}

exports.OAuth2.prototype._getAccessTokenUrl = function() {
  return this._baseSite + this._accessTokenUrl; /* + "?" + querystring.stringify(params); */
}

// Build the authorization header. In particular, build the part after the colon.
// e.g. Authorization: Bearer <token>  # Build "Bearer <token>"
exports.OAuth2.prototype.buildAuthHeader = function(token) {
  return this._authMethod + ' ' + token;
};

exports.OAuth2.prototype._chooseHttpLibrary = function(parsedUrl) {
  var http_library = https;
  // As this is OAUth2, we *assume* https unless told explicitly otherwise.
  if (parsedUrl.protocol != "https:") {
    http_library = http;
  }
  return http_library;
};

exports.OAuth2.prototype._request = function(method, url, headers, post_body, access_token, callback) {

  var parsedUrl = URL.parse(url, true);
  if (parsedUrl.protocol == "https:" && !parsedUrl.port) {
    parsedUrl.port = 443;
  }

  var http_library = this._chooseHttpLibrary(parsedUrl);

  var realHeaders = {};
  for (var key in this._customHeaders) {
    realHeaders[key] = this._customHeaders[key];
  }
  if (headers) {
    for (var key in headers) {
      realHeaders[key] = headers[key];
    }
  }
  realHeaders['Host'] = parsedUrl.host;

  if (!realHeaders['User-Agent']) {
    realHeaders['User-Agent'] = 'Node-oauth';
  }

  if (post_body) {
    if (Buffer.isBuffer(post_body)) {
      realHeaders["Content-Length"] = post_body.length;
    } else {
      realHeaders["Content-Length"] = Buffer.byteLength(post_body);
    }
  } else {
    realHeaders["Content-length"] = 0;
  }

  if (access_token && !('Authorization' in realHeaders)) {
    if (!parsedUrl.query) parsedUrl.query = {};
    parsedUrl.query[this._accessTokenName] = access_token;
  }

  var queryStr = querystring.stringify(parsedUrl.query);
  if (queryStr) queryStr = "?" + queryStr;
  var options = {
    host: parsedUrl.hostname,
    port: parsedUrl.port,
    path: parsedUrl.pathname + queryStr,
    method: method,
    headers: realHeaders
  };

  this._executeRequest(http_library, options, post_body, callback);
}

exports.OAuth2.prototype._executeRequest = function(http_library, options, post_body, callback) {
  // Some hosts *cough* google appear to close the connection early / send no content-length header
  // allow this behaviour.
  var allowEarlyClose= OAuthUtils.isAnEarlyCloseHost(options.host);
  var callbackCalled= false;
  function passBackControl( response, result ) {
    if(!callbackCalled) {
      callbackCalled=true;
      if( !(response.statusCode >= 200 && response.statusCode <= 299) && (response.statusCode != 301) && (response.statusCode != 302) ) {
        var error = new ResponseStatusError("an unexpected response of " + response.statusCode + " was returned", {
          statusCode: response.statusCode,
          data: result
        });
        error.statusCode = response.statusCode;
        error.data = result;
        callback(error, result, response);
      } else {
        callback(null, result, response);
      }
    }
  }

  var result = "";

  var request = http_library.request(options);
  request.on('response', function (response) {
    response.on("data", function (chunk) {
      result+= chunk
    });
    response.on("close", function(err) {
      if (allowEarlyClose) {
        passBackControl(response, result);
      }
    });
    response.addListener("end", function() {
      passBackControl(response, result);
    });
  });
  request.on('error', function(e) {
    callbackCalled = true;
    callback(e);
  });

  if ((options.method == 'POST' || options.method == 'PUT') && post_body) {
    request.write(post_body);
  }
  request.end();
}

exports.OAuth2.prototype.getAuthorizeUrl = function(params) {
  var params = params || {};
  params['client_id'] = this._clientId;
  return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params);
}

exports.OAuth2.prototype.getOAuthAccessToken = function(code, params, callback) {
  var params = params || {};
  params['client_id'] = this._clientId;
  params['client_secret'] = this._clientSecret;
  var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code';
  params[codeParam] = code;

  var post_data = querystring.stringify(params);
  var post_headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) {
    if (error) callback(error);
    else {
      var results;
      try {
        // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07
        // responses should be in JSON
        results = JSON.parse(data);
      } catch (e) {
        // .... However both Facebook + Github currently use rev05 of the spec
        // and neither seem to specify a content-type correctly in their response headers :(
        // clients of these services will suffer a *minor* performance cost of the exception
        // being thrown
        results = querystring.parse(data);
      }
      var access_token = results["access_token"];
      var refresh_token = results["refresh_token"];
      delete results["refresh_token"];
      callback(null, access_token, refresh_token, results); // callback results =-=
    }
  });
}

// Deprecated
exports.OAuth2.prototype.getProtectedResource = function(url, access_token, callback) {
  this._request("GET", url, {}, "", access_token, callback);
}

exports.OAuth2.prototype.get = function(url, access_token, callback) {
  if (this._useAuthorizationHeaderForGET) {
    var headers = {
      'Authorization': this.buildAuthHeader(access_token)
    }
    access_token = null;
  } else {
    headers = {};
  }
  this._request("GET", url, headers, "", access_token, callback);
}<|endoftext|>


<commit_before>import ControlledModalWrapper from 'components/Modals/ControlledModalWrapper';
import mapActions from 'actions/MapActions';
import React, { Component, PropTypes } from 'react';
import text from '../../../js/languages';
import SVGIcon from '../../utils/svgIcon';

let count = 3;

export default class AnalysisModal extends Component {

  static contextTypes = {
    settings: PropTypes.object.isRequired,
    language: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
    this.state = {
      coordinatesFormat: '',
      countArray: [1, 2, 3],
      dmsLatValues: {},
      dmsLngValues: {}
    };
  }

  close = () => {
    mapActions.toggleCoordinatesModal({ visible: false });
    mapActions.toggleAnalysisModal({visible: false});
    this.count = 3;
    this.setState({
      coordinatesFormat: '',
      countArray: [1, 2, 3],
      dmsLatValues: {},
      dmsLngValues: {}
    });
  };

  switchCoordinatesFormat = evt => {
    this.setState({
      coordinatesFormat: evt.target.value
    });
  };

  updateDMSLatValues = (evt) => {
    // Get all latitude inputs and convert into a regular array
    let dmsLats = [...document.querySelectorAll(`[name=${evt.target.name}]`)];

    // Create array with only the input values
    dmsLats = dmsLats.map(dmsLat => dmsLat.value);

    // Create an object copy of the current dmsLatValues state to preserve any latitude arrays already stored
    const dmsLatValuesCopy = Object.assign({}, this.state.dmsLatValues);

    // Assign latitude array as new property on the copy object or overwrite if it already exists
    dmsLatValuesCopy[evt.target.name] = dmsLats;

    // Update state of dmsLatValues to the copy object
    this.setState({
      dmsLatValues: dmsLatValuesCopy
    });
  };

  updateDMSLngValues = (evt) => {
    // Get all longitude inputs and convert into a regular array
    let dmsLngs = [...document.querySelectorAll(`[name=${evt.target.name}]`)];

    // Create array with only the input values
    dmsLngs = dmsLngs.map(dmsLng => dmsLng.value);

    // Create an object copy of the current dmsLngValues state to preserve any longitude arrays already stored
    const dmsLngValuesCopy = Object.assign({}, this.state.dmsLngValues);

    // Assign longitude array as new property on the copy object or overwrite if it already exists
    dmsLngValuesCopy[evt.target.name] = dmsLngs;

    // Update state of dmsLngValues to the copy object
    this.setState({
      dmsLngValues: dmsLngValuesCopy
    });
  };

  renderDMS = (item, index) => {
    const {language} = this.context;
    const latitudeDirectionOptions = text[language].ANALYSIS_COORDINATES_LATITUDE_DIRECTIONS;
    const longitudeDirectionOptions = text[language].ANALYSIS_COORDINATES_LONGITUDE_DIRECTIONS;

    return (
      <div key={`DMS-${index}`}>
      {index === 0 &&

}

          {text[language].ANALYSIS_COORDINATES_LABELS[0]}

            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-degrees-${item}`} name={`dms-latitude-${item}`} />
            °
            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-decimals-${item}`} name={`dms-latitude-${item}`} />
            '
            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-minutes-${item}`} name={`dms-latitude-${item}`} />
            "
            <select
              value={latitudeDirectionOptions && latitudeDirectionOptions[0]}
              className='analysis-coordinates-directions__select pointer'
              onChange={this.updateDMSLatValues}
              id={`dms-latitude-direction-${item}`}
              name={`dms-latitude-${item}`}
            >
              {latitudeDirectionOptions && latitudeDirectionOptions.map(this.createOptions)}
            </select>

          {text[language].ANALYSIS_COORDINATES_LABELS[1]}

            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-degrees-${item}`} name={`dms-longitude-${item}`} />
            °
            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-decimals-${item}`} name={`dms-longitude-${item}`} />
            '
            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-minutes-${item}`} name={`dms-longitude-${item}`} />
            "
            <select
              value={longitudeDirectionOptions && longitudeDirectionOptions[0]}
              className='analysis-coordinates-directions__select pointer'
              onChange={this.updateDMSLngValues}
              id={`dms-longitude-direction-${item}`}
              name={`dms-longitude-${item}`}
            >
              {longitudeDirectionOptions && longitudeDirectionOptions.map(this.createOptions)}
            </select>

    );
  };

  renderDD = (item, index) => {
    const {language} = this.context;
    return (
      <div key={`DD-${index}`} className="analysis-coordinates__inputs-container-dd">
        {index > 0 &&

}

          {text[language].ANALYSIS_COORDINATES_LABELS[0]}

            <input className="analysis-coordinates__latitude-measurement" type='number' id='latitude-degrees' name='latitude-degrees' />
            °

          {text[language].ANALYSIS_COORDINATES_LABELS[1]}

            <input className="analysis-coordinates__longitude-measurement" type='number' id='latitude-decimals' name='latitude-decimals' />
            °

    );
  };

  createOptions = (option, index) => {
    return (
      <option
        key={`option-${index}`}
        value={option}
      >
        {option}
      </option>
    );
  };

  addMore = () => {
    count = count + 1;
    const countArray = this.state.countArray;
    countArray.push(count);
    console.log('countArray', countArray);
    console.log('current count:', count);
    this.setState({
      countArray
    });
  };

  makeShape = () => {
    console.log('make shape!!!');
  };

  render () {
    const {language} = this.context;
    const {coordinatesFormat, countArray} = this.state;
    const coordinateFormatOptions = text[language].ANALYSIS_COORDINATES_FORMATS;
    console.log('LAT', this.state.dmsLatValues);
    console.log('LNG', this.state.dmsLngValues);
    return (
      <ControlledModalWrapper onClose={this.close}>

{text[language].ANALYSIS_COORDINATES_HEADER}

          {text[language].ANALYSIS_COORDINATES_LABELS[2]}
          <select
            value={coordinatesFormat ? coordinatesFormat : coordinateFormatOptions[0]}
            className='analysis-coordinates__select pointer'
            onChange={evt => this.switchCoordinatesFormat(evt)}
            id="coordinates-formats"
          >
            {coordinateFormatOptions && coordinateFormatOptions.map(this.createOptions)}
          </select>

        {coordinatesFormat === 'Decimal Degrees (DD)' &&

}
        {(coordinatesFormat === 'Degrees Decimal Minutes (DMS)' || coordinatesFormat === '') &&
        countArray.map((item, index) => this.renderDMS(item, index))}
        {coordinatesFormat === 'Decimal Degrees (DD)' &&
        countArray.map((item, index) => this.renderDD(item, index))}
        {coordinatesFormat === 'Decimal Degrees (DD)' &&

}

          <SVGIcon id={'icon-add-more'} />
          {text[language].ANALYSIS_COORDINATES_BUTTONS[1]}

          {/* <SVGIcon id={'icon-shape'} /> */}
          {text[language].ANALYSIS_COORDINATES_BUTTONS[2]}

      </ControlledModalWrapper>
    );
  }

}
<commit_msg>Store state for DD lat & long values<commit_after>import ControlledModalWrapper from 'components/Modals/ControlledModalWrapper';
import mapActions from 'actions/MapActions';
import React, { Component, PropTypes } from 'react';
import text from '../../../js/languages';
import SVGIcon from '../../utils/svgIcon';

let count = 3;

export default class AnalysisModal extends Component {

  static contextTypes = {
    settings: PropTypes.object.isRequired,
    language: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
    this.state = {
      coordinatesFormat: '',
      countArray: [1, 2, 3],
      dmsLatValues: {},
      dmsLngValues: {},
      ddValues: {}
    };
  }

  close = () => {
    mapActions.toggleCoordinatesModal({ visible: false });
    mapActions.toggleAnalysisModal({visible: false});
    this.count = 3;
    this.setState({
      coordinatesFormat: '',
      countArray: [1, 2, 3],
      dmsLatValues: {},
      dmsLngValues: {}
    });
  };

  switchCoordinatesFormat = evt => {
    this.setState({
      coordinatesFormat: evt.target.value
    });
  };

  updateDMSLatValues = evt => {
    // Get all latitude inputs and convert into a regular array
    let dmsLats = [...document.querySelectorAll(`[name=${evt.target.name}]`)];

    // Create array with only the input values
    dmsLats = dmsLats.map(dmsLat => dmsLat.value);

    // Create an object copy of the current dmsLatValues state to preserve any latitude arrays already stored
    const dmsLatValuesCopy = Object.assign({}, this.state.dmsLatValues);

    // Assign latitude array as new property on the copy object or overwrite if it already exists
    dmsLatValuesCopy[evt.target.name] = dmsLats;

    // Update state of dmsLatValues to the copy object
    this.setState({
      dmsLatValues: dmsLatValuesCopy
    });
  };

  updateDMSLngValues = evt => {
    // Get all longitude inputs and convert into a regular array
    let dmsLngs = [...document.querySelectorAll(`[name=${evt.target.name}]`)];

    // Create array with only the input values
    dmsLngs = dmsLngs.map(dmsLng => dmsLng.value);

    // Create an object copy of the current dmsLngValues state to preserve any longitude arrays already stored
    const dmsLngValuesCopy = Object.assign({}, this.state.dmsLngValues);

    // Assign longitude array as new property on the copy object or overwrite if it already exists
    dmsLngValuesCopy[evt.target.name] = dmsLngs;

    // Update state of dmsLngValues to the copy object
    this.setState({
      dmsLngValues: dmsLngValuesCopy
    });
  };

  renderDMS = (item, index) => {
    const {language} = this.context;
    const latitudeDirectionOptions = text[language].ANALYSIS_COORDINATES_LATITUDE_DIRECTIONS;
    const longitudeDirectionOptions = text[language].ANALYSIS_COORDINATES_LONGITUDE_DIRECTIONS;

    return (
      <div key={`DMS-${index}`}>
      {index === 0 &&

}

          {text[language].ANALYSIS_COORDINATES_LABELS[0]}

            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-degrees-${item}`} name={`dms-latitude-${item}`} />
            °
            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-minutes-${item}`} name={`dms-latitude-${item}`} />
            '
            <input onChange={this.updateDMSLatValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dms-latitude-seconds-${item}`} name={`dms-latitude-${item}`} />
            "
            <select
              value={latitudeDirectionOptions && latitudeDirectionOptions[0]}
              className='analysis-coordinates-directions__select pointer'
              onChange={this.updateDMSLatValues}
              id={`dms-latitude-direction-${item}`}
              name={`dms-latitude-${item}`}
            >
              {latitudeDirectionOptions && latitudeDirectionOptions.map(this.createOptions)}
            </select>

          {text[language].ANALYSIS_COORDINATES_LABELS[1]}

            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-degrees-${item}`} name={`dms-longitude-${item}`} />
            °
            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-minutes-${item}`} name={`dms-longitude-${item}`} />
            '
            <input onChange={this.updateDMSLngValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dms-longitude-seconds-${item}`} name={`dms-longitude-${item}`} />
            "
            <select
              value={longitudeDirectionOptions && longitudeDirectionOptions[0]}
              className='analysis-coordinates-directions__select pointer'
              onChange={this.updateDMSLngValues}
              id={`dms-longitude-direction-${item}`}
              name={`dms-longitude-${item}`}
            >
              {longitudeDirectionOptions && longitudeDirectionOptions.map(this.createOptions)}
            </select>

    );
  };

  updateDDValues = evt => {
    let ddVals = [...document.querySelectorAll(`[name=${evt.target.name}]`)];
    ddVals = ddVals.map(ddVal => ddVal.value);
    const ddValuesCopy = Object.assign({}, this.state.ddValues);
    ddValuesCopy[evt.target.name] = ddVals;
    this.setState({
      ddValues: ddValuesCopy
    });
  };

  renderDD = (item, index) => {
    const {language} = this.context;
    return (
      <div key={`DD-${index}`} className="analysis-coordinates__inputs-container-dd">
        {index > 0 &&

}

          {text[language].ANALYSIS_COORDINATES_LABELS[0]}

            <input onChange={this.updateDDValues} className="analysis-coordinates__latitude-measurement" type='number' id={`dd-latitude-degrees-${item}`} name={`dd-${item}`} />
            °

          {text[language].ANALYSIS_COORDINATES_LABELS[1]}

            <input onChange={this.updateDDValues} className="analysis-coordinates__longitude-measurement" type='number' id={`dd-longitude-degrees-${item}`} name={`dd-${item}`} />
            °

    );
  };

  createOptions = (option, index) => {
    return (
      <option
        key={`option-${index}`}
        value={option}
      >
        {option}
      </option>
    );
  };

  addMore = () => {
    count = count + 1;
    const countArray = this.state.countArray;
    countArray.push(count);
    console.log('countArray', countArray);
    console.log('current count:', count);
    this.setState({
      countArray
    });
  };

  makeShape = () => {
    console.log('make shape!!!');
  };

  render () {
    const {language} = this.context;
    const {coordinatesFormat, countArray} = this.state;
    const coordinateFormatOptions = text[language].ANALYSIS_COORDINATES_FORMATS;
    // console.log('LAT', this.state.dmsLatValues);
    // console.log('LNG', this.state.dmsLngValues);
    console.log('DD', this.state.ddValues);
    return (
      <ControlledModalWrapper onClose={this.close}>

{text[language].ANALYSIS_COORDINATES_HEADER}

          {text[language].ANALYSIS_COORDINATES_LABELS[2]}
          <select
            value={coordinatesFormat ? coordinatesFormat : coordinateFormatOptions[0]}
            className='analysis-coordinates__select pointer'
            onChange={evt => this.switchCoordinatesFormat(evt)}
            id="coordinates-formats"
          >
            {coordinateFormatOptions && coordinateFormatOptions.map(this.createOptions)}
          </select>

        {coordinatesFormat === 'Decimal Degrees (DD)' &&

}
        {(coordinatesFormat === 'Degrees Decimal Minutes (DMS)' || coordinatesFormat === '') &&
        countArray.map((item, index) => this.renderDMS(item, index))}
        {coordinatesFormat === 'Decimal Degrees (DD)' &&
        countArray.map((item, index) => this.renderDD(item, index))}
        {coordinatesFormat === 'Decimal Degrees (DD)' &&

}

          <SVGIcon id={'icon-add-more'} />
          {text[language].ANALYSIS_COORDINATES_BUTTONS[1]}

          {/* <SVGIcon id={'icon-shape'} /> */}
          {text[language].ANALYSIS_COORDINATES_BUTTONS[2]}

      </ControlledModalWrapper>
    );
  }

}
<|endoftext|>


<commit_before>"use strict";
var ORG = window.ORG ? window.ORG : {};
ORG.NETMELODY = ORG.NETMELODY ? ORG.NETMELODY : {};
ORG.NETMELODY.CIEYE = {};

ORG.NETMELODY.CIEYE.newBuildWidget = function(buildJson) {
    var buildDiv = $("

").addClass("progress-bar"),
        barDiv   = $("

");

    function updateProgress(percent) {
        barDiv.attr("style", "width: " + percent + "%");
    }

    function updateStatus(status) {
        barDiv.removeClass();
        barDiv.addClass(status);
    }

    function refresh(newBuildJson) {
        updateProgress(newBuildJson.progress);
        updateStatus(newBuildJson.status);
    }

    function initialise() {
        buildDiv.append(barDiv);
        refresh(buildJson);
    }

    initialise();

    return {
        "updateFrom": refresh,
        "getContent": function() { return buildDiv; }
    };
};

ORG.NETMELODY.CIEYE.newMugshotWidget = function(sponsorJson, sizeCalculator) {
    var image = $(""),
        heightFactor = 1.0,
        widthFactor = 1.0,
        currentMaxSize = -1;

    function resizeImage() {
        var maxSize = sizeCalculator();

        if (maxSize === currentMaxSize) {
            return;
        }

        currentMaxSize = maxSize;
        image.height(maxSize * heightFactor);
        image.width(maxSize * widthFactor);
    }

    function initialiseImage() {
        var width = image.width(),
            height = image.height();

        if (width > height) {
            heightFactor = height / width;
        }
        else {
            widthFactor = width / height;
        }

        resizeImage();
    }

    function initialise() {
        image.attr({ "src": sponsorJson.picture,
                     "title": sponsorJson.name })
             .load(initialiseImage);
    }

    initialise();

    return {
        "getContent": function() { return image; },
        "refresh": resizeImage
    };
};

ORG.NETMELODY.CIEYE.newTargetWidget = function(targetJson) {
    var currentTargetJson = { builds:[] },
        targetDiv = $("

"),
        titleSpan = $(""),
        sponsorDiv = $("

").addClass("sponsors"),
        buildsDiv = $("

"),
        sponsorMugshots = {};

    function sortedSponsors(unsortedSponsors) {
        return unsortedSponsors.sort(function(a, b) {
            return (a.name === b.name) ? 0 : (a.name < b.name) ? -1 : 1;
        });
    }

    function calculateImageSize() {
        return parseInt(titleSpan.css("font-size"), 10) + 5;
    }

    function updateFrom(newTargetJson) {
        var lastTargetJson = currentTargetJson;

        currentTargetJson = newTargetJson;
        if (lastTargetJson.status !== newTargetJson.status) {
            if (lastTargetJson.status) {
                targetDiv.removeClass(lastTargetJson.status);
            }
            targetDiv.addClass(newTargetJson.status);
        }

        buildsDiv.empty();
        $.each(newTargetJson.builds, function(index, buildJson) {
            buildsDiv.append(ORG.NETMELODY.CIEYE.newBuildWidget(buildJson).getContent());
        });

        if (newTargetJson.builds.length === 0) {
            targetDiv.removeClass("building");
        }
        else {
            targetDiv.addClass("building");
        }

        if (newTargetJson.builds.length === 0 && newTargetJson.status === "GREEN") {
            sponsorDiv.empty();
            return;
        }

        $.each(sortedSponsors(newTargetJson.sponsors), function(index, sponsorJson) {
            if (!sponsorMugshots[sponsorJson.picture]) {
                sponsorMugshots[sponsorJson.picture] = ORG.NETMELODY.CIEYE.newMugshotWidget(sponsorJson, calculateImageSize);
            }
            sponsorDiv.append(sponsorMugshots[sponsorJson.picture].getContent());
        });
    }

    function viewDetails() {
        window.open(targetJson.webUrl);
    }

    function markAs(note) {
        return function() { $.post("addNote", { "id": targetJson.id, "note": note }); };
    }

    function doh() {
        $.post("doh", { "active": true });
    }

    function getMenuItems() {
        var result = [];

        if (targetDiv.css("cursor") !== "pointer") {
            return result;
        }

        result.push({"label": "View Details", "handler": viewDetails});
        if (currentTargetJson.status !== "GREEN") {
            result.push({"label": "Mark as Under Investigation", "handler": markAs("Under Investigation")});
            result.push({"label": "Mark as Fixed", "handler": markAs("Fixed")});
        }
        result.push({"label": "D'OH", "handler": doh});
        return result;
    }

    function refreshImages() {
        $.each(sponsorMugshots, function(key, mugshotWidget) {
            mugshotWidget.refresh();
        });
    }

    function initialise() {
        titleSpan.text(targetJson.name);
        targetDiv.append(titleSpan);
        targetDiv.append(sponsorDiv);
        targetDiv.append(buildsDiv);
        targetDiv.addClass("target");
        targetDiv.popupMenu(getMenuItems);

        updateFrom(targetJson);
    }

    initialise();

    return {
        "refresh": refreshImages,
        "updateFrom": updateFrom,
        "getContent": function() { return targetDiv; }
    };
};

ORG.NETMELODY.CIEYE.newRadiatorWidget = function() {
    var radiatorDiv = $("

"),
        dohDiv = $("

").addClass("doh").hide(),
        targetWidgets = {},
        dohMugshots = {},
        statusRanks = ["BROKEN", "UNKNOWN", "UNDER_INVESTIGATION", "GREEN", "DISABLED"];

    function targetComparator(a, b) {
        function compare(obj1, obj2) {
            return (obj1 < obj2) ? -1 : ((obj1 === obj2) ? 0 : 1);
        }

        if (a.status !== b.status) {
            return compare(statusRanks.indexOf(a.status), statusRanks.indexOf(b.status));
        }

        if (a.builds.length !== b.builds.length) {
            return compare(b.builds.length, a.builds.length);
        }

        if (a.lastStartTime !== b.lastStartTime) {
            return compare(b.lastStartTime, a.lastStartTime);
        }

        return compare(a.name, b.name);
    }

    function updateFrom(targetGroupJson) {
        var targets = targetGroupJson.targets.sort(targetComparator),
            deadTargetWidgets = $.extend({}, targetWidgets);

        function dohSizeCalculator() {
            return (radiatorDiv.width() / targetGroupJson.dohGroup.length) - 50;
        }

        function unDoh() {
            $.post("doh", { "active": false });
        }

        if (targetGroupJson.dohGroup) {
            if (dohDiv.is(":hidden")) {
                $.each(targetGroupJson.dohGroup, function(index, sponsorJson) {
                    dohMugshots[sponsorJson.picture] = ORG.NETMELODY.CIEYE.newMugshotWidget(sponsorJson, dohSizeCalculator);
                    dohDiv.append(dohMugshots[sponsorJson.picture].getContent());
                    radiatorDiv.append(dohDiv);
                    dohDiv.show();
                    dohDiv.popupMenu(function() { return [{"label": "D'OH OVER", "handler": unDoh}]; });
                });
            }
        }
        else {
            dohDiv.hide();
            dohDiv.empty();
        }

        $.each(targets, function(index, targetJson) {
            if (targetWidgets[targetJson.id]) {
                targetWidgets[targetJson.id].updateFrom(targetJson);
                delete deadTargetWidgets[targetJson.id];
            }
            else {
                targetWidgets[targetJson.id] = ORG.NETMELODY.CIEYE.newTargetWidget(targetJson);
            }
            radiatorDiv.append(targetWidgets[targetJson.id].getContent());
        });
        $.each(deadTargetWidgets, function(index, deadTargetWidget) {
            deadTargetWidget.getContent().remove();
            delete targetWidgets[index];
        });
    }

    function refresh() {
        $.each(dohMugshots, function(key, mugshotWidget) {
            mugshotWidget.refresh();
        });
        $.each(targetWidgets, function(index, targetWidget) {
            targetWidget.refresh();
        });
    }

    return {
        "refresh": refresh,
        "updateFrom": updateFrom,
        "getContent": function() { return radiatorDiv; }
    };
};

ORG.NETMELODY.CIEYE.scheduler = function(browser) {
    var protector = undefined,
        alarm = false;

    function reloadPage() {
        browser.location.reload();
    }

    function safeCallableFor(callback) {
        return function() {
            try {
                callback();
            }
            catch (ex) {
                // ignore
            }
        };
    }

    function raiseAlarm() {
        alarm = true;
        $().announcer("announce", "Lost contact with Ci-Eye server");
    }

    function repeat(callback, interval) {
        browser.setInterval(safeCallableFor(callback), interval);
    }

    function guard(timeout) {
        if (!protector) {
            protector = browser.setTimeout(raiseAlarm, timeout);
        }
    }

    function relax() {
        if (alarm) {
            reloadPage();
        }
        if (protector) {
            browser.clearTimeout(protector);
            protector = undefined;
        }
    }

    return {
        "repeat": repeat,
        "guard": guard,
        "relax": relax,
        "reload": reloadPage
    };
};

ORG.NETMELODY.CIEYE.newRadiator = function(radiatorDiv, scheduler) {
    var radiatorWidget = ORG.NETMELODY.CIEYE.newRadiatorWidget();

    function update() {
        scheduler.guard(60000);
        $.getJSON("landscapeobservation.json", function(targetList) {
            scheduler.relax();
            radiatorWidget.updateFrom(targetList);
        });
    }

    function refresh() {
        radiatorWidget.refresh();
    }

    function startup() {
        radiatorDiv.append(radiatorWidget.getContent());
        update();
        scheduler.repeat(update, 2000);
    }

    return {
        "start": startup,
        "refresh": refresh
    };
};

ORG.NETMELODY.CIEYE.newVersionChecker = function(scheduler) {
    var currentVersion = undefined;

    function assessVersion(versionString) {
        if (!currentVersion) {
            currentVersion = versionString;
            return;
        }

        if (currentVersion !== versionString) {
            scheduler.reload();
        }
    }

    function checkForNewVersion() {
        $.getJSON("/version.json", function(versionJson) {
            assessVersion(versionJson.currentServerVersion);
        });
    }

    function startup() {
        checkForNewVersion();
        scheduler.repeat(checkForNewVersion, 30000);
    }

    return {
        "start": startup
    };
};

$(document).ready(function() {
    if (!$("#radiator").length) {
        return;
    }

    var scheduler = ORG.NETMELODY.CIEYE.scheduler(window),
        radiator = ORG.NETMELODY.CIEYE.newRadiator($("#radiator"), scheduler),
        updater = ORG.NETMELODY.CIEYE.newVersionChecker(scheduler);

    $(window).bind("resize", function() {
        radiator.refresh();
    });

    radiator.start();
    updater.start();
});
<commit_msg>update title bar fixes gh-1.<commit_after>"use strict";
var ORG = window.ORG ? window.ORG : {};
ORG.NETMELODY = ORG.NETMELODY ? ORG.NETMELODY : {};
ORG.NETMELODY.CIEYE = {};

ORG.NETMELODY.CIEYE.newBuildWidget = function(buildJson) {
    var buildDiv = $("

").addClass("progress-bar"),
        barDiv   = $("

");

    function updateProgress(percent) {
        barDiv.attr("style", "width: " + percent + "%");
    }

    function updateStatus(status) {
        barDiv.removeClass();
        barDiv.addClass(status);
    }

    function refresh(newBuildJson) {
        updateProgress(newBuildJson.progress);
        updateStatus(newBuildJson.status);
    }

    function initialise() {
        buildDiv.append(barDiv);
        refresh(buildJson);
    }

    initialise();

    return {
        "updateFrom": refresh,
        "getContent": function() { return buildDiv; }
    };
};

ORG.NETMELODY.CIEYE.newMugshotWidget = function(sponsorJson, sizeCalculator) {
    var image = $(""),
        heightFactor = 1.0,
        widthFactor = 1.0,
        currentMaxSize = -1;

    function resizeImage() {
        var maxSize = sizeCalculator();

        if (maxSize === currentMaxSize) {
            return;
        }

        currentMaxSize = maxSize;
        image.height(maxSize * heightFactor);
        image.width(maxSize * widthFactor);
    }

    function initialiseImage() {
        var width = image.width(),
            height = image.height();

        if (width > height) {
            heightFactor = height / width;
        }
        else {
            widthFactor = width / height;
        }

        resizeImage();
    }

    function initialise() {
        image.attr({ "src": sponsorJson.picture,
                     "title": sponsorJson.name })
             .load(initialiseImage);
    }

    initialise();

    return {
        "getContent": function() { return image; },
        "refresh": resizeImage
    };
};

ORG.NETMELODY.CIEYE.newTargetWidget = function(targetJson) {
    var currentTargetJson = { builds:[] },
        targetDiv = $("

"),
        titleSpan = $(""),
        sponsorDiv = $("

").addClass("sponsors"),
        buildsDiv = $("

"),
        sponsorMugshots = {};

    function sortedSponsors(unsortedSponsors) {
        return unsortedSponsors.sort(function(a, b) {
            return (a.name === b.name) ? 0 : (a.name < b.name) ? -1 : 1;
        });
    }

    function calculateImageSize() {
        return parseInt(titleSpan.css("font-size"), 10) + 5;
    }

    function updateFrom(newTargetJson) {
        var lastTargetJson = currentTargetJson;

        currentTargetJson = newTargetJson;
        if (lastTargetJson.status !== newTargetJson.status) {
            if (lastTargetJson.status) {
                targetDiv.removeClass(lastTargetJson.status);
            }
            targetDiv.addClass(newTargetJson.status);
        }

        buildsDiv.empty();
        $.each(newTargetJson.builds, function(index, buildJson) {
            buildsDiv.append(ORG.NETMELODY.CIEYE.newBuildWidget(buildJson).getContent());
        });

        if (newTargetJson.builds.length === 0) {
            targetDiv.removeClass("building");
        }
        else {
            targetDiv.addClass("building");
        }

        if (newTargetJson.builds.length === 0 && newTargetJson.status === "GREEN") {
            sponsorDiv.empty();
            return;
        }

        $.each(sortedSponsors(newTargetJson.sponsors), function(index, sponsorJson) {
            if (!sponsorMugshots[sponsorJson.picture]) {
                sponsorMugshots[sponsorJson.picture] = ORG.NETMELODY.CIEYE.newMugshotWidget(sponsorJson, calculateImageSize);
            }
            sponsorDiv.append(sponsorMugshots[sponsorJson.picture].getContent());
        });
    }

    function viewDetails() {
        window.open(targetJson.webUrl);
    }

    function markAs(note) {
        return function() { $.post("addNote", { "id": targetJson.id, "note": note }); };
    }

    function doh() {
        $.post("doh", { "active": true });
    }

    function getMenuItems() {
        var result = [];

        if (targetDiv.css("cursor") !== "pointer") {
            return result;
        }

        result.push({"label": "View Details", "handler": viewDetails});
        if (currentTargetJson.status !== "GREEN") {
            result.push({"label": "Mark as Under Investigation", "handler": markAs("Under Investigation")});
            result.push({"label": "Mark as Fixed", "handler": markAs("Fixed")});
        }
        result.push({"label": "D'OH", "handler": doh});
        return result;
    }

    function refreshImages() {
        $.each(sponsorMugshots, function(key, mugshotWidget) {
            mugshotWidget.refresh();
        });
    }

    function initialise() {
        titleSpan.text(targetJson.name);
        targetDiv.append(titleSpan);
        targetDiv.append(sponsorDiv);
        targetDiv.append(buildsDiv);
        targetDiv.addClass("target");
        targetDiv.popupMenu(getMenuItems);

        updateFrom(targetJson);
    }

    initialise();

    return {
        "refresh": refreshImages,
        "updateFrom": updateFrom,
        "getContent": function() { return targetDiv; }
    };
};

ORG.NETMELODY.CIEYE.newRadiatorWidget = function() {
    var radiatorDiv = $("

"),
        dohDiv = $("

").addClass("doh").hide(),
        targetWidgets = {},
        dohMugshots = {},
        statusRanks = ["BROKEN", "UNKNOWN", "UNDER_INVESTIGATION", "GREEN", "DISABLED"];

    function targetComparator(a, b) {
        function compare(obj1, obj2) {
            return (obj1 < obj2) ? -1 : ((obj1 === obj2) ? 0 : 1);
        }

        if (a.status !== b.status) {
            return compare(statusRanks.indexOf(a.status), statusRanks.indexOf(b.status));
        }

        if (a.builds.length !== b.builds.length) {
            return compare(b.builds.length, a.builds.length);
        }

        if (a.lastStartTime !== b.lastStartTime) {
            return compare(b.lastStartTime, a.lastStartTime);
        }

        return compare(a.name, b.name);
    }

    function updateFrom(targetGroupJson) {
        var targets = targetGroupJson.targets.sort(targetComparator),
            deadTargetWidgets = $.extend({}, targetWidgets);

        function dohSizeCalculator() {
            return (radiatorDiv.width() / targetGroupJson.dohGroup.length) - 50;
        }

        function unDoh() {
            $.post("doh", { "active": false });
        }

        if (targetGroupJson.dohGroup) {
            if (dohDiv.is(":hidden")) {
                $.each(targetGroupJson.dohGroup, function(index, sponsorJson) {
                    dohMugshots[sponsorJson.picture] = ORG.NETMELODY.CIEYE.newMugshotWidget(sponsorJson, dohSizeCalculator);
                    dohDiv.append(dohMugshots[sponsorJson.picture].getContent());
                    radiatorDiv.append(dohDiv);
                    dohDiv.show();
                    dohDiv.popupMenu(function() { return [{"label": "D'OH OVER", "handler": unDoh}]; });
                });
            }
        }
        else {
            dohDiv.hide();
            dohDiv.empty();
        }

        $.each(targets, function(index, targetJson) {
            if (targetWidgets[targetJson.id]) {
                targetWidgets[targetJson.id].updateFrom(targetJson);
                delete deadTargetWidgets[targetJson.id];
            }
            else {
                targetWidgets[targetJson.id] = ORG.NETMELODY.CIEYE.newTargetWidget(targetJson);
            }
            radiatorDiv.append(targetWidgets[targetJson.id].getContent());
        });
        $.each(deadTargetWidgets, function(index, deadTargetWidget) {
            deadTargetWidget.getContent().remove();
            delete targetWidgets[index];
        });
    }

    function refresh() {
        $.each(dohMugshots, function(key, mugshotWidget) {
            mugshotWidget.refresh();
        });
        $.each(targetWidgets, function(index, targetWidget) {
            targetWidget.refresh();
        });
    }

    return {
        "refresh": refresh,
        "updateFrom": updateFrom,
        "getContent": function() { return radiatorDiv; }
    };
};

ORG.NETMELODY.CIEYE.scheduler = function(browser) {
    var protector = undefined,
        alarm = false;

    function reloadPage() {
        browser.location.reload();
    }

    function safeCallableFor(callback) {
        return function() {
            try {
                callback();
            }
            catch (ex) {
                // ignore
            }
        };
    }

    function raiseAlarm() {
        alarm = true;
        $().announcer("announce", "Lost contact with Ci-Eye server");
    }

    function repeat(callback, interval) {
        browser.setInterval(safeCallableFor(callback), interval);
    }

    function guard(timeout) {
        if (!protector) {
            protector = browser.setTimeout(raiseAlarm, timeout);
        }
    }

    function relax() {
        if (alarm) {
            reloadPage();
        }
        if (protector) {
            browser.clearTimeout(protector);
            protector = undefined;
        }
    }

    return {
        "repeat": repeat,
        "guard": guard,
        "relax": relax,
        "reload": reloadPage
    };
};

ORG.NETMELODY.CIEYE.newRadiator = function(radiatorDiv, scheduler) {
    var radiatorWidget = ORG.NETMELODY.CIEYE.newRadiatorWidget();

    function update() {
        scheduler.guard(60000);
        $.getJSON("landscapeobservation.json", function(targetList) {
            scheduler.relax();
            radiatorWidget.updateFrom(targetList);
        });
    }

    function refresh() {
        radiatorWidget.refresh();
    }

    function startup() {
        radiatorDiv.append(radiatorWidget.getContent());
        update();
        scheduler.repeat(update, 2000);
    }

    return {
        "start": startup,
        "refresh": refresh
    };
};

ORG.NETMELODY.CIEYE.newVersionChecker = function(scheduler) {
    var currentVersion = undefined;

    function assessVersion(versionString) {
        if (!currentVersion) {
            currentVersion = versionString;
            return;
        }

        if (currentVersion !== versionString) {
            scheduler.reload();
        }
    }

    function checkForNewVersion() {
        $.getJSON("/version.json", function(versionJson) {
            assessVersion(versionJson.currentServerVersion);
        });
    }

    function startup() {
        checkForNewVersion();
        scheduler.repeat(checkForNewVersion, 30000);
    }

    return {
        "start": startup
    };
};

$(document).ready(function() {
    if (!$("#radiator").length) {
        return;
    }

    var scheduler = ORG.NETMELODY.CIEYE.scheduler(window),
        radiator = ORG.NETMELODY.CIEYE.newRadiator($("#radiator"), scheduler),
        updater = ORG.NETMELODY.CIEYE.newVersionChecker(scheduler),
        path = $(location).attr("pathname");

    if (path.match(/\/$/)) {
        path = path.slice(0, -1);
    }
    document.title = decodeURIComponent(path.substr((path.lastIndexOf("/") + 1))) + " - " + document.title;

    $(window).bind("resize", function() {
        radiator.refresh();
    });

    radiator.start();
    updater.start();
});
<|endoftext|>


<commit_before>Ext.namespace('Vpc.Directories.Item.Directory');
Vpc.Directories.Item.Directory.Panel = Ext.extend(Vps.Auto.GridPanel,
{
    initComponent: function() {
        if (this.componentPlugins) {
            this.plugins = [ ];
            this.componentPlugins.each(function(v) {
                var pluginClass = eval(v.pluginClass);
                var plugin = new pluginClass(v);
                this.plugins.push(plugin);
            }, this);
        }

        this.columnsConfig = {
            edit: {
                clickHandler: function(grid, rowIndex) {
                    var row = grid.getStore().getAt(rowIndex);
                    this.fireEditComponent(row);
                },
                scope: this
            }
        };
        this.fireEvent('gotComponentConfigs', this.componentConfigs);

        Vpc.Directories.Item.Directory.Panel.superclass.initComponent.call(this);
    },

    fireEditComponent : function(row)
    {
        this.fireEvent('editcomponent', {
            componentClass: this.contentClass,
            type: this.contentType,
            editComponents: this.contentEditComponents,
            componentId: this.idTemplate.replace('{0}', row.data.id),
            text: trlVps('Details')
        });
    }
});

Ext.reg('vpc.directories.item.directory', Vpc.Directories.Item.Directory.Panel);
<commit_msg>Vpc_Directories_Item_Directory: Panel funktioniert auch ohne dbId<commit_after>Ext.namespace('Vpc.Directories.Item.Directory');
Vpc.Directories.Item.Directory.Panel = Ext.extend(Vps.Auto.GridPanel,
{
    initComponent: function() {
        if (this.componentPlugins) {
            this.plugins = [ ];
            this.componentPlugins.each(function(v) {
                var pluginClass = eval(v.pluginClass);
                var plugin = new pluginClass(v);
                this.plugins.push(plugin);
            }, this);
        }

        this.columnsConfig = {
            edit: {
                clickHandler: function(grid, rowIndex) {
                    var row = grid.getStore().getAt(rowIndex);
                    this.fireEditComponent(row);
                },
                scope: this
            }
        };
        this.fireEvent('gotComponentConfigs', this.componentConfigs);

        Vpc.Directories.Item.Directory.Panel.superclass.initComponent.call(this);
    },

    fireEditComponent : function(row)
    {
    	if (!this.idTemplate) {
    		componentId = this.initialConfig.baseParams.componentId + this.idSeparator + row.data.id;
    	} else {
    		componentId = this.idTemplate.replace('{0}', row.data.id);
    	}
        this.fireEvent('editcomponent', {
            componentClass: this.contentClass,
            type: this.contentType,
            editComponents: this.contentEditComponents,
            componentId: componentId,
            text: trlVps('Details')
        });
    }
});

Ext.reg('vpc.directories.item.directory', Vpc.Directories.Item.Directory.Panel);
<|endoftext|>


<commit_before>app.controller("SwitchController", [
    "$scope",
    "$location",
    "$log",
    "$window",
    function ($scope, $location, $log, $window) {
        'use strict';

        $scope.hello = function () {
            // body...
            $window.alert("hELLO");
        };

        $log.debug("Switch Controller Initialized");
    }]);
<commit_msg>Update public/app/controllers/account/switchController.js<commit_after><|endoftext|>


<commit_before>var _gdotdesign$elm_ui$Native_Styles = function() {
  var currentStyles = {}

  if(window.MutationObserver) {
    new MutationObserver(function (mutations) {
      patchStyles()
    }).observe(document.body, { childList: true, subtree: true });
  } else {
    var patch = function(){
      patchStyles()
      if(document.querySelector('[class^=container-]')) { return }
      requestAnimationFrame(patch)
    }
    requestAnimationFrame(patch)
  }

  function patchStyles(){
    var currentNode
    var tags = {}
    var iterator =
      document
        .createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT)

    var nextStyles = {}

    while(currentNode = iterator.nextNode()) {
      if (!currentNode.__styles) { continue }
      if (nextStyles[currentNode.__styles.id]) { continue }
      nextStyles[currentNode.__styles.id] = currentNode.__styles.value
    }

    for(var id in nextStyles) {
      if(currentStyles[id]) {
        nextStyles[id] = currentStyles[id]
        delete currentStyles[id]
      } else {
        var style = document.createElement('style')
        style.innerHTML = nextStyles[id]
        style.setAttribute('id', id)
        document.head.appendChild(style)
        nextStyles[id] = style
      }
    }

    for(var id in currentStyles) {
      currentStyles[id].remove()
    }

    currentStyles = nextStyles
  }

  /* Interface */
  return {
    patchStyles: patchStyles
  }
}()
<commit_msg>Setup mutation observer when the document loads or if it has a body at the time it runs.<commit_after>var _gdotdesign$elm_ui$Native_Styles = function() {
  var currentStyles = {}

  var setupObserver = function () {
    if(window.MutationObserver) {
      new MutationObserver(function (mutations) {
        patchStyles()
      }).observe(document.body, { childList: true, subtree: true });
    } else {
      var patch = function(){
        patchStyles()
        if(document.querySelector('[class^=container-]')) { return }
        requestAnimationFrame(patch)
      }
      requestAnimationFrame(patch)
    }
  }

  if (document.body) {
    setupObserver()
  } else {
    document.addEventListener('DOMContentLoaded', setupObserver)
  }

  function patchStyles(){
    var currentNode
    var tags = {}
    var iterator =
      document
        .createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT)

    var nextStyles = {}

    while(currentNode = iterator.nextNode()) {
      if (!currentNode.__styles) { continue }
      if (nextStyles[currentNode.__styles.id]) { continue }
      nextStyles[currentNode.__styles.id] = currentNode.__styles.value
    }

    for(var id in nextStyles) {
      if(currentStyles[id]) {
        nextStyles[id] = currentStyles[id]
        delete currentStyles[id]
      } else {
        var style = document.createElement('style')
        style.innerHTML = nextStyles[id]
        style.setAttribute('id', id)
        document.head.appendChild(style)
        nextStyles[id] = style
      }
    }

    for(var id in currentStyles) {
      currentStyles[id].remove()
    }

    currentStyles = nextStyles
  }

  /* Interface */
  return {
    patchStyles: patchStyles
  }
}()
<|endoftext|>


<commit_before>//= require_self

$(document).ready(function(){

// edit name
  (function(){
    var $edit_name = $('#js-edit-name');

    $edit_name.on('keydown', 'input', function(){
      if ($(this).val() === '') {
        $edit_name.removeClass('edit');
      }
      else {
        $edit_name.addClass('edit');
      }
    });

    $edit_name.on('blur', 'input', function(){
      $edit_name.removeClass('edit');
    });
  }());

// tooltips
  (function(){
    var tooltip = $('');

    $('body').append(tooltip);

    var item = $('[data-tooltip]');

    item.hover(function(){
      var $this = $(this),
          offset = $this.offset(),
          tooltip_str = $this.data('tooltip');

      tooltip.html(tooltip_str);

      tooltip.removeClass('hidden');

      var width = tooltip.innerWidth(),
          width_this = $this.innerWidth(),
          height = tooltip.innerHeight();

      tooltip.css({
        'left': (offset.left - (width / 2)) + (width_this / 2),
        'top': offset.top - height - 10
      })
    }, function(){
      tooltip.addClass('hidden');
    });

  }());

// $change-password
  (function(){
    var change_password = $('#change-password'),
        form = $('.fpassword', change_password);

    $('.open', change_password).click(function(){
      $(this).hide();
      $('.fpassword', change_password).removeClass('hide');
      return false;
    });
  }());

  function create_ajax_form(block){
    block.on('submit', 'form', function(){
      $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(data) {
          block.html(data);
        }
      });
      return false;
    });
  }
  create_ajax_form($('#js-edit-name'));
});
<commit_msg>Add check on blank company name<commit_after>//= require_self

$(document).ready(function(){

// edit name
  (function(){
    var $edit_name = $('#js-edit-name');

    $edit_name.on('keydown', 'input', function(){
      if ($(this).val() === '') {
        $edit_name.removeClass('edit');
      }
      else {
        $edit_name.addClass('edit');
      }
    });

    $edit_name.on('blur', 'input', function(){
      $edit_name.removeClass('edit');
    });
  }());

// tooltips
  (function(){
    var tooltip = $('');

    $('body').append(tooltip);

    var item = $('[data-tooltip]');

    item.hover(function(){
      var $this = $(this),
          offset = $this.offset(),
          tooltip_str = $this.data('tooltip');

      tooltip.html(tooltip_str);

      tooltip.removeClass('hidden');

      var width = tooltip.innerWidth(),
          width_this = $this.innerWidth(),
          height = tooltip.innerHeight();

      tooltip.css({
        'left': (offset.left - (width / 2)) + (width_this / 2),
        'top': offset.top - height - 10
      })
    }, function(){
      tooltip.addClass('hidden');
    });

  }());

// $change-password
  (function(){
    var change_password = $('#change-password'),
        form = $('.fpassword', change_password);

    $('.open', change_password).click(function(){
      $(this).hide();
      $('.fpassword', change_password).removeClass('hide');
      return false;
    });
  }());

  function create_ajax_form(block){
    block.on('submit', 'form', function(){
      if ($('.field input', block).val() === '')
        return false;
      $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(data) {
          block.html(data);
        }
      });
      return false;
    });
  }
  create_ajax_form($('#js-edit-name'));
});
<|endoftext|>


<commit_before>Box.Application.addModule('radiator-controller', function(context) {
  'use strict';

  var utils, store, windowSvc, intercom, d3, $, moduleElem, cubismGraphs;

  var render = {
    horizon: function(config) {
      cubismGraphs.resetCubismContext();
      moduleElem.call(createHorizonGraph, config.chart);
      context.broadcast("reload-graph-configuration");
      windowSvc.setTitle(config.chart.metric.toUpperCase() + " for " + config.host);
    },
    access: function(config) {
      moduleElem.call(createAccessGraph, config.chart);
    },
    filesystem: function(config) {
      moduleElem.call(createFilesystemGraph, config.chart);
    },
    heap: function(config) {
      moduleElem.call(createHeapGraph, config.chart);
    }
  };

  function initGraph(config) {
    var type = config.chart.type;
    if (!render[type]) {
      throw new Error('Graph type not found.');
    }

    render[type](config);

    // re-render the graph on resize
    $(window).resize(utils.debouncer(function() {
      moduleElem.html('');
      render[type](config);
    }));
  }

  function radiatorGraphIdPrefix(radiatorId) {
    return "live:radiator:" + radiatorId + ":graph-";
  }

  function injectModuleConfiguration(graphElement, radiatorIdPrefix, chartConfig) {
    var radiatorConfig = {
      configurationIdPrefix: radiatorIdPrefix,
      disableTerminalButton: true,
      disableRadiatorShareButton: false,
      chart: chartConfig
    };
    utils.setConfigurationElement(graphElement, radiatorConfig);
  }

  function createHorizonGraph(parentElement, chartConfig) {
    var axisElement = parentElement.append("div")
      .attr("data-module", "horizon-ruler");

    axisElement.append("div").classed("axis", true);
    axisElement.append("div").classed("rule", true);
    Box.Application.start(axisElement[0][0]);

    var horizonGraphElement = parentElement.append("div")
      .attr("data-module", "horizon-graph");
    injectModuleConfiguration(horizonGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(horizonGraphElement[0][0]);
  }

  function createAccessGraph(parentElement, chartConfig) {
    var accessGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "access-graph");
    injectModuleConfiguration(accessGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(accessGraphElement[0][0]);
  }

  function createFilesystemGraph(parentElement, chartConfig) {
    var filesystemGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "filesystem-graph");
    injectModuleConfiguration(filesystemGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(filesystemGraphElement[0][0]);
  }

  function createHeapGraph(parentElement, chartConfig) {
    var heapGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "heap-graph");
    injectModuleConfiguration(heapGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(heapGraphElement[0][0]);
  }

  return {
    init: function() {
      intercom   = context.getGlobal("Intercom").getInstance();
      d3         = context.getGlobal("d3");
      $          = context.getGlobal("jQuery");
      moduleElem = d3.select(context.getElement());

      utils          = context.getService("utils");
      windowSvc      = context.getService("window");
      store          = context.getService("configuration-store");
      cubismGraphs   = context.getService("cubism-graphs");

      var radiatorName = windowSvc.getHashVariable("name");
      var configs = store.customRadiators.readConfiguration(radiatorName);
      configs.forEach(function(config) {
        // init all graphs found in radiator configuration
        initGraph(config);
        // wipe config if it is marked for deletion (e.g. single graph)
        console.log(config)
        if (config.removeAfterUse) {
          store.customRadiators.removeConfiguration(radiatorName);
        }
      });
    },

    messages: ["timescale-changed"],

    onmessage: function(name, timescale) {
      switch (name) {
        case 'timescale-changed':
          cubismGraphs.resetCubismContext();
          break;
      }
    }
  };
});
<commit_msg>removed console.log()<commit_after>Box.Application.addModule('radiator-controller', function(context) {
  'use strict';

  var utils, store, windowSvc, intercom, d3, $, moduleElem, cubismGraphs;

  var render = {
    horizon: function(config) {
      cubismGraphs.resetCubismContext();
      moduleElem.call(createHorizonGraph, config.chart);
      context.broadcast("reload-graph-configuration");
      windowSvc.setTitle(config.chart.metric.toUpperCase() + " for " + config.host);
    },
    access: function(config) {
      moduleElem.call(createAccessGraph, config.chart);
    },
    filesystem: function(config) {
      moduleElem.call(createFilesystemGraph, config.chart);
    },
    heap: function(config) {
      moduleElem.call(createHeapGraph, config.chart);
    }
  };

  function initGraph(config) {
    var type = config.chart.type;
    if (!render[type]) {
      throw new Error('Graph type not found.');
    }

    render[type](config);

    // re-render the graph on resize
    $(window).resize(utils.debouncer(function() {
      moduleElem.html('');
      render[type](config);
    }));
  }

  function radiatorGraphIdPrefix(radiatorId) {
    return "live:radiator:" + radiatorId + ":graph-";
  }

  function injectModuleConfiguration(graphElement, radiatorIdPrefix, chartConfig) {
    var radiatorConfig = {
      configurationIdPrefix: radiatorIdPrefix,
      disableTerminalButton: true,
      disableRadiatorShareButton: false,
      chart: chartConfig
    };
    utils.setConfigurationElement(graphElement, radiatorConfig);
  }

  function createHorizonGraph(parentElement, chartConfig) {
    var axisElement = parentElement.append("div")
      .attr("data-module", "horizon-ruler");

    axisElement.append("div").classed("axis", true);
    axisElement.append("div").classed("rule", true);
    Box.Application.start(axisElement[0][0]);

    var horizonGraphElement = parentElement.append("div")
      .attr("data-module", "horizon-graph");
    injectModuleConfiguration(horizonGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(horizonGraphElement[0][0]);
  }

  function createAccessGraph(parentElement, chartConfig) {
    var accessGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "access-graph");
    injectModuleConfiguration(accessGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(accessGraphElement[0][0]);
  }

  function createFilesystemGraph(parentElement, chartConfig) {
    var filesystemGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "filesystem-graph");
    injectModuleConfiguration(filesystemGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(filesystemGraphElement[0][0]);
  }

  function createHeapGraph(parentElement, chartConfig) {
    var heapGraphElement = parentElement.append("div")
      .classed("nv-graph scalable", true)
      .attr("data-module", "heap-graph");
    injectModuleConfiguration(heapGraphElement, radiatorGraphIdPrefix('custom'), chartConfig);
    Box.Application.start(heapGraphElement[0][0]);
  }

  return {
    init: function() {
      intercom   = context.getGlobal("Intercom").getInstance();
      d3         = context.getGlobal("d3");
      $          = context.getGlobal("jQuery");
      moduleElem = d3.select(context.getElement());

      utils          = context.getService("utils");
      windowSvc      = context.getService("window");
      store          = context.getService("configuration-store");
      cubismGraphs   = context.getService("cubism-graphs");

      var radiatorName = windowSvc.getHashVariable("name");
      var configs = store.customRadiators.readConfiguration(radiatorName);
      configs.forEach(function(config) {
        // init all graphs found in radiator configuration
        initGraph(config);
        // wipe config if it is marked for deletion (e.g. single graph)
        if (config.removeAfterUse) {
          store.customRadiators.removeConfiguration(radiatorName);
        }
      });
    },

    messages: ["timescale-changed"],

    onmessage: function(name, timescale) {
      switch (name) {
        case 'timescale-changed':
          cubismGraphs.resetCubismContext();
          break;
      }
    }
  };
});
<|endoftext|>


<commit_before>import React from 'react'
import createHelper from './createHelper'
import createEagerFactory from './createEagerFactory'

const identity = component => component

const branch = (test, left, right = identity) => BaseComponent =>
  class extends React.Component {
    constructor(props, context) {
      super(props, context)
      this.computeChildComponent(this.props)
    }

    computeChildComponent(props) {
      if (test(props)) {
        this.leftFactory =
          this.leftFactory || createEagerFactory(left(BaseComponent))
        this.factory = this.leftFactory
      } else {
        this.rightFactory =
          this.rightFactory || createEagerFactory(right(BaseComponent))
        this.factory = this.rightFactory
      }
    }

    componentWillReceiveProps(nextProps) {
      this.computeChildComponent(nextProps)
    }

    render() {
      return this.factory(this.props)
    }
  }

export default createHelper(branch, 'branch')
<commit_msg>Make branch return a stateless functional component (#273)<commit_after>import createHelper from './createHelper'
import createEagerFactory from './createEagerFactory'

const identity = Component => Component

const branch = (test, left, right = identity) => BaseComponent => {
  let leftFactory
  let rightFactory
  return props => {
    if (test(props)) {
      leftFactory = leftFactory || createEagerFactory(left(BaseComponent))
      return leftFactory(props)
    }
    rightFactory = rightFactory || createEagerFactory(right(BaseComponent))
    return rightFactory(props)
  }
}

export default createHelper(branch, 'branch')
<|endoftext|>