<commit_before>var async = require('async');
var _ = require('lodash');
var spawn = require('child_process').spawn;
var fs = require('fs');
var jsonfile = require('jsonfile');
jsonfile.spaces = 2;

var robotsDataFile = 'robots_data.json';

var numCores = require('os').cpus().length;
var numJobs = parseInt(numCores / 2);
// var numJobs = 1;
console.log('numJobs', numJobs);

var runCommand = function(command, args, callback, _timeout) {
  // _timeout = _timeout || 12 * 60 * 60 * 1000; // 12 hours
  _timeout = _timeout || 30 * 60 * 1000; // 30 minutes

  var cmd = spawn(command, args);

  var printData = function(data) {
    console.log(data.toString());
  };

  cmd.stdout.on('data', printData);
  cmd.stderr.on('data', printData);

  var timeout = setTimeout(function() {
    console.log('killing child process');
    cmd.stdin.pause();
    cmd.kill();
    callback(null);
  }, _timeout);

  cmd.on('close', function(code) {
    console.log('child process exited with code ' + code);
    clearTimeout(timeout);
    callback(null);
  });
};

var invokeSolverGenerator = function(data, callback) {
  var args = _.map(data, function(val, key) {
    return '--' + key + '=' + val;
  });
  var cmd = runCommand('python', ['solver_generator.py'].concat(args), callback);
};

var invokeEmscripten = function(data, callback) {
  var solverPath = './solvers/';
  var basePath = solverPath + data.robotname + '_' + data.manipname;
  var postPath = './post.cpp';
  var cppPath = basePath + '.cpp';
  var tmpPath = basePath + '.tmp.cpp';
  var jsPath = basePath + '.js';
  fs.exists(cppPath, function(exists) {
    if (exists) {

      var cpp = fs.readFileSync(cppPath);
      var post = fs.readFileSync(postPath);
      var program = cpp + '\n' + post;

      fs.writeFileSync(tmpPath, program);

      var cmd = runCommand('em++', [

        //'-g',
        '-O2',

        // ikfast
        '-DIKFAST_NO_MAIN',

        tmpPath,

        // emscripten (https://github.com/kripken/emscripten/blob/1.33.2/src/settings.js)
        '--pre-js', 'pre.js',
        '--post-js', 'post.js',
        '-s', 'INVOKE_RUN=0',
        '-s', 'ASSERTIONS=1',
        '-s', 'NO_EXIT_RUNTIME=1',
        '-s', 'NO_FILESYSTEM=1',
        '-s', 'NO_BROWSER=1',
        '-s', 'PRECISE_F32=1',
        '-s', 'DEMANGLE_SUPPORT=1',
        // '-s', 'EXPORT_ALL=1',
        '-s', "EXPORTED_FUNCTIONS=['__Z16ComputeFkWrapperPKd', '__Z12GetNumJointsv']",

        '-o', jsPath], function() {
          try {
            fs.unlinkSync(tmpPath);
          } catch (e) {
          }
          console.log('Done ' + jsPath);
          // process.exit(0)
          callback(null);
        });
    } else {
      callback(null);
    }
  });
};

var computeInitialRobotsData = function(callback) {
  runCommand('python', ['get_robots_data.py'], callback);
};

var getRobotsData = function() {
    var robotsData = jsonfile.readFileSync(robotsDataFile).robots;

    robotsData = _.uniq(robotsData, function(robotItem) {
        return robotItem.robotname + robotItem.manipname;
    });
    return robotsData
}

var rewriteRobotsData = function() {

  var robotsData = getRobotsData();

  var robots = [];
  robotsData.forEach(function(data) {
    var basePath = './solvers/' + data.robotname + '_' + data.manipname;
    var cppPath = basePath + '.cpp';

    if (fs.existsSync(cppPath)) {
      data.basePath = basePath;
      robots.push(data);
    }
  });

  jsonfile.writeFileSync(robotsDataFile, {
    robots: robots
  });
};

//computeInitialRobotsData(function() {
    var robotsData = getRobotsData()

  // async.eachLimit(robotsData, numJobs, invokeSolverGenerator, function() {
    async.eachLimit(robotsData, numJobs, invokeEmscripten, function() {
      rewriteRobotsData();
      console.log('done');
    });
  // });
//});
<commit_msg>only use zae files, also write solver info to solver<commit_after>var async = require('async');
var _ = require('lodash');
var spawn = require('child_process').spawn;
var fs = require('fs');
var jsonfile = require('jsonfile');
jsonfile.spaces = 2;

var robotsDataFile = 'robots_data.json';

var numCores = require('os').cpus().length;
var numJobs = parseInt(numCores / 2);
// var numJobs = 1;
console.log('numJobs', numJobs);

var runCommand = function(command, args, callback, _timeout) {
  // _timeout = _timeout || 12 * 60 * 60 * 1000; // 12 hours
  _timeout = _timeout || 30 * 60 * 1000; // 30 minutes

  var cmd = spawn(command, args);

  var printData = function(data) {
    console.log(data.toString());
  };

  cmd.stdout.on('data', printData);
  cmd.stderr.on('data', printData);

  var timeout = setTimeout(function() {
    console.log('killing child process');
    cmd.stdin.pause();
    cmd.kill();
    callback(null);
  }, _timeout);

  cmd.on('close', function(code) {
    console.log('child process exited with code ' + code);
    clearTimeout(timeout);
    callback(null);
  });
};

var invokeSolverGenerator = function(data, callback) {
  var args = _.map(data, function(val, key) {
    return '--' + key + '=' + val;
  });
  var cmd = runCommand('python', ['solver_generator.py'].concat(args), callback);
};

var invokeEmscripten = function(data, callback) {
  var solverDir = './solvers/';
  var basePath = solverDir + data.robotname + '_' + data.manipname;

  var postCppPath = './post.cpp';
  var postJSPath = './post.js';

  var solverCppPath = basePath + '.cpp';
  var solverJSPath = basePath + '.js';

  var tmpCppPath = basePath + '.tmp.cpp';
  var tmpJSPostPath = basePath + '-post.tmp.js';

  fs.exists(solverCppPath, function(exists) {
    if (exists) {

      var solverCpp = fs.readFileSync(solverCppPath);
      var postCpp = fs.readFileSync(postCppPath);
      var cppSolver = solverCpp + '\n' + postCpp;
      fs.writeFileSync(tmpCppPath, cppSolver);

      var postJS = fs.readFileSync(postJSPath);
      postJS = 'Module["solverInfo"] = ' + JSON.stringify(data) + ';\n' + postJS;
      fs.writeFileSync(tmpJSPostPath, postJS);

      var cmd = runCommand('em++', [

        //'-g',
        '-O2',

        // ikfast
        '-DIKFAST_NO_MAIN',

        tmpCppPath,

        // emscripten (https://github.com/kripken/emscripten/blob/1.33.2/src/settings.js)
        '--pre-js', 'pre.js',
        '--post-js', tmpJSPostPath,
        '-s', 'INVOKE_RUN=0',
        '-s', 'ASSERTIONS=1',
        '-s', 'NO_EXIT_RUNTIME=1',
        '-s', 'NO_FILESYSTEM=1',
        '-s', 'NO_BROWSER=1',
        '-s', 'PRECISE_F32=1',
        '-s', 'DEMANGLE_SUPPORT=1',
        // '-s', 'EXPORT_ALL=1',
        '-s', "EXPORTED_FUNCTIONS=['__Z16ComputeFkWrapperPKd', '__Z12GetNumJointsv']",
        '-o', solverJSPath], function() {
          try {
            fs.unlinkSync(tmpCppPath);
            fs.unlinkSync(tmpJSPostPath);
          } catch (e) {
          }
          console.log('Done ' + solverJSPath);
          // process.exit(0)
          callback(null);
        });
    } else {
      callback(null);
    }
  });
};

var computeInitialRobotsData = function(callback) {
  runCommand('python', ['get_robots_data.py'], callback);
};

var getRobotsData = function() {
    var robotsData = jsonfile.readFileSync(robotsDataFile).robots;

    robotsData = _.filter(robotsData, function(robotItem) {
      return robotItem.scene.split('.').pop() === 'zae';
    });

    robotsData = _.uniq(robotsData, function(robotItem) {
        return robotItem.robotname + robotItem.manipname;
    });
    return robotsData;
};

var rewriteRobotsData = function() {

  var robotsData = getRobotsData();

  var robots = [];
  robotsData.forEach(function(data) {
    var basePath = './solvers/' + data.robotname + '_' + data.manipname;
    var cppPath = basePath + '.cpp';

    if (fs.existsSync(cppPath)) {
      data.basePath = basePath;
      robots.push(data);
    }
  });

  jsonfile.writeFileSync(robotsDataFile, {
    robots: robots
  });
};

//computeInitialRobotsData(function() {
    var robotsData = getRobotsData();

  // async.eachLimit(robotsData, numJobs, invokeSolverGenerator, function() {
    async.eachLimit(robotsData, numJobs, invokeEmscripten, function() {
      rewriteRobotsData();
      console.log('done');
    });
  // });
//});
<|endoftext|>


<commit_before>import _ from "lodash";
import app from "app";
import Marionette from "backbone.marionette";
import Toast from "libs/toast";
import Request from "libs/request";
import SelectionView from "admin/views/selection_view";
import TeamCollection from "admin/models/team/team_collection";
import DatastoreCollection from "admin/models/datastore/datastore_collection";

class DatasetUploadView extends Marionette.View {
  static initClass() {
    this.prototype.template = _.template(`\

Upload Dataset

    <form action="/api/datasets/upload" method="POST" class="form-horizontal" enctype="multipart/form-data">

        Name

        <input type="text" required name="name" value="" class="form-control" autofocus pattern="^[0-9a-zA-Z_-]+$" title="Dataset names may only contain letters, numbers, _ and -">

        Team

        Scale

          <input type="text" required name="scale.scale" value="12.0, 12.0, 24.0" class="form-control" pattern="\\s*([0-9]+(?:\\.[0-9]+)?),\\s*([0-9]+(?:\\.[0-9]+)?),\\s*([0-9]+(?:\\.[0-9]+)?)\\s*" title="Specify dataset scale like "XX, YY, ZZ"">

        Datastore

        Dataset ZIP File

              Browse...
              Change
              <input type="file" required accept="application/zip" name="zipFile">

            Remove

          <button type="submit" class="form-control btn btn-primary">

            Import
          </button>

    </form>

\
`);

    this.prototype.className = "container dataset-administration";

    this.prototype.regions = {
      team: ".team",
      datastore: ".datastore",
    };

    this.prototype.events = {
      "submit form": "uploadDataset",
      "change input[type=file]": "createProject",
    };

    this.prototype.ui = {
      form: "form",
      spinner: ".fa-spinner",
    };
  }

  initialize() {
    this.teamSelectionView = new SelectionView({
      collection: new TeamCollection(),
      name: "team",
      childViewOptions: {
        modelValue() { return `${this.model.get("name")}`; },
      },
      data: "amIAnAdmin=true",
    });

    this.datastoreSelectionView = new SelectionView({
      collection: new DatastoreCollection(),
      name: "datastore",
      filter(item) { return item.get("url") !== null; },
      childViewOptions: {
        modelValue() { return `${this.model.get("url")}`; },
        modelLabel() { return `${this.model.get("name")}`; },
      },
    });
  }

  onRender() {
    this.showChildView("team", this.teamSelectionView);
    this.showChildView("datastore", this.datastoreSelectionView);
  }

  uploadDataset(evt) {
    evt.preventDefault();
    const form = this.ui.form[0];

    if (form.checkValidity()) {
      Toast.info("Uploading datasets", false);
      this.ui.spinner.removeClass("hidden");

      Request.receiveJSON("/api/dataToken/generate")
      .then(({ token }) =>
        Request.sendMultipartFormReceiveJSON(`/data/datasets?token=${token}`, {
          data: new FormData(form),
          host: form.datastore.value,
        }),
      )
      .then(
        ({ messages }) => {
          Toast.message(messages);
          app.router.navigate("/dashboard", { trigger: true });
        },
        () => {}, // NOOP
      )
      .then(
        () =>  // always do
           this.ui.spinner.addClass("hidden"),
      );
    }
  }
}
DatasetUploadView.initClass();

export default DatasetUploadView;
<commit_msg>Remove scale field from dataset upload form<commit_after>import _ from "lodash";
import app from "app";
import Marionette from "backbone.marionette";
import Toast from "libs/toast";
import Request from "libs/request";
import SelectionView from "admin/views/selection_view";
import TeamCollection from "admin/models/team/team_collection";
import DatastoreCollection from "admin/models/datastore/datastore_collection";

class DatasetUploadView extends Marionette.View {
  static initClass() {
    this.prototype.template = _.template(`\

Upload Dataset

    <form action="/api/datasets/upload" method="POST" class="form-horizontal" enctype="multipart/form-data">

        Name

        <input type="text" required name="name" value="" class="form-control" autofocus pattern="^[0-9a-zA-Z_-]+$" title="Dataset names may only contain letters, numbers, _ and -">

        Team

        Datastore

        Dataset ZIP File

              Browse...
              Change
              <input type="file" required accept="application/zip" name="zipFile">

            Remove

          <button type="submit" class="form-control btn btn-primary">

            Import
          </button>

    </form>

\
`);

    this.prototype.className = "container dataset-administration";

    this.prototype.regions = {
      team: ".team",
      datastore: ".datastore",
    };

    this.prototype.events = {
      "submit form": "uploadDataset",
      "change input[type=file]": "createProject",
    };

    this.prototype.ui = {
      form: "form",
      spinner: ".fa-spinner",
    };
  }

  initialize() {
    this.teamSelectionView = new SelectionView({
      collection: new TeamCollection(),
      name: "team",
      childViewOptions: {
        modelValue() { return `${this.model.get("name")}`; },
      },
      data: "amIAnAdmin=true",
    });

    this.datastoreSelectionView = new SelectionView({
      collection: new DatastoreCollection(),
      name: "datastore",
      filter(item) { return item.get("url") !== null; },
      childViewOptions: {
        modelValue() { return `${this.model.get("url")}`; },
        modelLabel() { return `${this.model.get("name")}`; },
      },
    });
  }

  onRender() {
    this.showChildView("team", this.teamSelectionView);
    this.showChildView("datastore", this.datastoreSelectionView);
  }

  uploadDataset(evt) {
    evt.preventDefault();
    const form = this.ui.form[0];

    if (form.checkValidity()) {
      Toast.info("Uploading datasets", false);
      this.ui.spinner.removeClass("hidden");

      Request.receiveJSON("/api/dataToken/generate")
      .then(({ token }) =>
        Request.sendMultipartFormReceiveJSON(`/data/datasets?token=${token}`, {
          data: new FormData(form),
          host: form.datastore.value,
        }),
      )
      .then(
        ({ messages }) => {
          Toast.message(messages);
          app.router.navigate("/dashboard", { trigger: true });
        },
        () => {}, // NOOP
      )
      .then(
        () =>  // always do
           this.ui.spinner.addClass("hidden"),
      );
    }
  }
}
DatasetUploadView.initClass();

export default DatasetUploadView;
<|endoftext|>


<commit_before>/*
  feedback.js: Provides feedback to the user like help messages, errors, etc.
*/

module.exports = (function feedback () {
  function errorFeedback (message) {
    console.log("Taskline: [error] " + message);
    process.exit(1);
  }

  return {
    error: errorFeedback
  };
} ());<commit_msg>Simplified feedback.js<commit_after>/*
  feedback.js: Provides feedback to the user like help messages, errors, etc.
*/

module.exports.error = function (message) {
  console.log("Taskline: [error] " + message);
  process.exit(1);
};
<|endoftext|>


<commit_before>/* eslint no-console: 0 */
const isDev = process.env.NODE_ENV !== 'production';

export const warn = (condition, format, a, b, c, d, e, f) => {
  if (isDev && typeof console !== 'undefined' && console.warn) {
    if (format === undefined) {
      console.warn('LogUtils requires an error message argument');
    }

    if (!condition) {
      if (format === undefined) {
        console.warn(
          'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.'
        );
      } else {
        const args = [a, b, c, d, e, f];
        let argIndex = 0;

        console.warn(format.replace(/%s/g, () => args[argIndex++]));
      }
    }
  }
};
<commit_msg>Added more log arguments.<commit_after>/* eslint no-console: 0 */
const isDev = process.env.NODE_ENV !== 'production';

export const warn = (condition, format, ...args) => {
  if (isDev && typeof console !== 'undefined' && console.warn) {
    if (format === undefined) {
      console.warn('LogUtils requires an error message argument');
    }

    if (!condition) {
      if (format === undefined) {
        console.warn(
          'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.'
        );
      } else {
        let argIndex = 0;

        console.warn(format.replace(/%s/g, () => args[argIndex++]));
      }
    }
  }
};
<|endoftext|>


<commit_before>(function($) {

var fengshui = {};

function removePrefix(selector) {
  if (selector[0] === '.' || selector[0] === '#') {
    selector = selector.slice(1);
  }
  return selector;
}

function selectorToVar(selector, separator) {
  return selector.replace(
    new RegExp(separator+'([a-z])', 'g'), function(g) {
      return g[1].toUpperCase();
    });
}

function processName(component, separator, useComponentVars) {
  var selectorVar = removePrefix(component);
  if (useComponentVars) {
    selectorVar = selectorToVar(selectorVar, separator);
  }
  return selectorVar;
}

function System(blueprint) {
  // settle blueprint.options' default values
  var options = blueprint.options === undefined
    ? {} : blueprint.options;
  var useComponentVars = options.componentVars === undefined
    ? true
    : options.componentVars;
  var separator = options.separator === undefined
    ? '-'
    : options.separator;
  var aliases = blueprint.aliases === undefined
    ? {} : blueprint.aliases;
  var types = blueprint.types === undefined
    ? {} : blueprint.types;

  // having System inherit some props from blueprint
  // TODO: add aliases
  blueprint.root = '.'+blueprint.root; // add class prefix
  this.fsRootStr = blueprint.root;
  this.fsRoot = $(this.fsRootStr);
  this.fsComponents = [];
  this.fsSeparator = separator;
  this.fsUseVars = useComponentVars;
  this.aliases = aliases;
  this.types = types;
  var system = this;

  var $root = $(blueprint.root);
  // just sample one
  // somehow jQuery will skip the first one in array
  // when using jQuery collection as context,
  // so use element instead
  var $topRoot = $root[0];

  // get everything with class attr
  var $hasClass = $('*[class]', $topRoot);
  $hasClass.each(function() {
    var classes = $.trim($(this).attr('class')).split(/\s+/g);
    // ['btn', 'btn-lg', 'btn-default']
    $.each(classes, function(index) {
      var component = classes[index];
      var componentVar = processName(component, separator,
        useComponentVars);
      // add only if it's not there
      if (system[componentVar] === undefined) {
        system.fsComponents.push(component);
        system[componentVar] = $('.'+component, $root);
      }

      // create an alias
      if (aliases[component] !== undefined) {
        system[aliases[component]] = system[componentVar];
      }
    });
  });
}

function setCtx(context) {
  var $context = $(context);
  var $root = $context.closest(this.fsRootStr);
  var aliases = this.aliases;
  var types = this.types;
  var system = this;

  for (var i = 0; i < this.fsComponents.length; i++) {
    var component = this.fsComponents[i];
    var componentVar = processName(component,
      this.fsSeparator, this.fsUseVars);
    this[componentVar] = $root.find('.'+component);

    // create an alias
    if (aliases[component] !== undefined) {
      this[aliases[component]] = this[componentVar];
    }
  }

  $.each(types, function(type, componentVars) {
    switch (type) {
      case "text":
        componentVars.map(function(componentVar) {
          system[componentVar] = system[componentVar].text();
        });
        break;
      case "number":
        componentVars.map(function(componentVar) {
          system[componentVar] = parseInt(
            system[componentVar].text(), 10);
        });
        break;
      default:
        throw new TypeError('Only number and text type available');
    }
  });

  function handleText(jq) {
    return jq.text();
  }

  return this;
}

System.prototype = {
  setCtx: setCtx
};

// function attachments
fengshui.System = System;
window.fengshui = fengshui;

})(jQuery); // fengshui

// extra jQuery plugins
(function($) {
$.fn.incr = function increment(diff) {
  diff === undefined ? diff = 1 : diff;
  var number = parseInt(this.text(), 10);
  number += diff;
  this.text(number.toString());
};
})(jQuery);
<commit_msg>Removed unneeded function<commit_after>(function($) {

var fengshui = {};

function removePrefix(selector) {
  if (selector[0] === '.' || selector[0] === '#') {
    selector = selector.slice(1);
  }
  return selector;
}

function selectorToVar(selector, separator) {
  return selector.replace(
    new RegExp(separator+'([a-z])', 'g'), function(g) {
      return g[1].toUpperCase();
    });
}

function processName(component, separator, useComponentVars) {
  var selectorVar = removePrefix(component);
  if (useComponentVars) {
    selectorVar = selectorToVar(selectorVar, separator);
  }
  return selectorVar;
}

function System(blueprint) {
  // settle blueprint.options' default values
  var options = blueprint.options === undefined
    ? {} : blueprint.options;
  var useComponentVars = options.componentVars === undefined
    ? true
    : options.componentVars;
  var separator = options.separator === undefined
    ? '-'
    : options.separator;
  var aliases = blueprint.aliases === undefined
    ? {} : blueprint.aliases;
  var types = blueprint.types === undefined
    ? {} : blueprint.types;

  // having System inherit some props from blueprint
  // TODO: add aliases
  blueprint.root = '.'+blueprint.root; // add class prefix
  this.fsRootStr = blueprint.root;
  this.fsRoot = $(this.fsRootStr);
  this.fsComponents = [];
  this.fsSeparator = separator;
  this.fsUseVars = useComponentVars;
  this.aliases = aliases;
  this.types = types;
  var system = this;

  var $root = $(blueprint.root);
  // just sample one
  // somehow jQuery will skip the first one in array
  // when using jQuery collection as context,
  // so use element instead
  var $topRoot = $root[0];

  // get everything with class attr
  var $hasClass = $('*[class]', $topRoot);
  $hasClass.each(function() {
    var classes = $.trim($(this).attr('class')).split(/\s+/g);
    // ['btn', 'btn-lg', 'btn-default']
    $.each(classes, function(index) {
      var component = classes[index];
      var componentVar = processName(component, separator,
        useComponentVars);
      // add only if it's not there
      if (system[componentVar] === undefined) {
        system.fsComponents.push(component);
        system[componentVar] = $('.'+component, $root);
      }

      // create an alias
      if (aliases[component] !== undefined) {
        system[aliases[component]] = system[componentVar];
      }
    });
  });
}

function setCtx(context) {
  var $context = $(context);
  var $root = $context.closest(this.fsRootStr);
  var aliases = this.aliases;
  var types = this.types;
  var system = this;

  for (var i = 0; i < this.fsComponents.length; i++) {
    var component = this.fsComponents[i];
    var componentVar = processName(component,
      this.fsSeparator, this.fsUseVars);
    this[componentVar] = $root.find('.'+component);

    // create an alias
    if (aliases[component] !== undefined) {
      this[aliases[component]] = this[componentVar];
    }
  }

  $.each(types, function(type, componentVars) {
    switch (type) {
      case "text":
        componentVars.map(function(componentVar) {
          system[componentVar] = system[componentVar].text();
        });
        break;
      case "number":
        componentVars.map(function(componentVar) {
          system[componentVar] = parseInt(
            system[componentVar].text(), 10);
        });
        break;
      default:
        throw new TypeError('Only number and text type available');
    }
  });

  return this;
}

System.prototype = {
  setCtx: setCtx
};

// function attachments
fengshui.System = System;
window.fengshui = fengshui;

})(jQuery); // fengshui

// extra jQuery plugins
(function($) {
$.fn.incr = function increment(diff) {
  diff === undefined ? diff = 1 : diff;
  var number = parseInt(this.text(), 10);
  number += diff;
  this.text(number.toString());
};
})(jQuery);
<|endoftext|>


<commit_before>var path = require('path');
var FastBootServer = require('ember-fastboot-server');
var outputPath = 'fastboot-dist';
var appName = 'bustle';

var server = new FastBootServer({
  distPath: 'fastboot-dist'
});

function insertIntoIndexHTML(res) {
  return server.insertIntoIndexHTML(res.title, res.body, res.head);
}

exports.handler = function(event, context) {
  server.app.visit(event.path, { request: { get: function() {} }, response: {} })
    .then(insertIntoIndexHTML)
    .then(context.succeed)
    .catch(context.fail);
};
<commit_msg>throw explicit, generic error string from lambda function for use with API gateway<commit_after>var path = require('path');
var FastBootServer = require('ember-fastboot-server');
var outputPath = 'fastboot-dist';
var appName = 'bustle';

var server = new FastBootServer({
  distPath: 'fastboot-dist'
});

function insertIntoIndexHTML(res) {
  return server.insertIntoIndexHTML(res.title, res.body, res.head);
}

exports.handler = function(event, context) {
  server.app.visit(event.path, { request: { get: function() {} }, response: {} })
    .then(insertIntoIndexHTML)
    .then(context.succeed)
    .catch(function() {
      context.fail('AWS Lambda Error')
    });
};
<|endoftext|>


<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
/** Helper functions start **/

var RiakHelper = function() {
  return {
    numericSorter: function(first, second) {
      return first - second;
    }
  };
}();

/** Helper functions end **/

var Riak = function() {

  return {
    getClassName: function(obj) {
      if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(/function\s*(\w+)/);
        if (arr && arr.length == 2) {
          return arr[1];
        }
      }
      return undefined;
    },
    filterNotFound: function(values) {
      return values.filter(function(value, index, data) {
        if (typeof value === 'object') {
          return value['not_found'] === undefined;
        }
        else {
          return true;
        } });
    },
    mapValues: function(value, keyData, arg) {
      if (value["not_found"]) {
        return [value];
      }
      var data = value["values"][0]["data"];
      if (Riak.getClassName(data) !== "Array") {
        return [data];
      }
      else {
        return data;
      }},
    mapValuesJson: function(value, keyData, arg) {
      if (value["not_found"]) {
        return [value];
      }
      var newValues = Riak.mapValues(value, keyData, arg);
      return newValues.map(function(nv) { return JSON.parse(nv); });
    },
    mapByFields: function(value, keyData, fields) {
      if(!value.not_found) {
        var object = Riak.mapValuesJson(value)[0];
        for(field in fields) {
          if(object[field] != fields[field]) {
            return [];
          }
        }
        return [object];
      }
      else {
        return [];
      }
    },
    reduceSum: function(values, arg) {
      values = Riak.filterNotFound(values);
      if (values.length > 0) {
        return [values.reduce(function(prev, curr, index, array) { return prev + curr; } )];
      }
      else {
        return [0];
      }},
    reduceMin: function(values, arg) {
      if(values.length == 0)
        return [];
      else
        return [values.reduce(function(prev,next){
          return (prev < next) ? prev : next;
        })];
    },
    reduceMax: function(values, arg) {
      if(values.length == 0)
        return [];
      else
        return [values.reduce(function(prev,next){
          return (prev > next) ? prev : next;
        })];
    },
    reduceSort: function(value, arg) {
      try {
        var c = eval(arg);
        return value.sort(c);
      }
      catch (e) {
        return value.sort();
      }
    },
    reduceNumericSort: function(value, arg) {
      value.sort(RiakHelper.numericSorter);
      return value;
    },
    reduceLimit: function(value, arg) {
      return value.slice(0, arg - 1);
    },
    reduceSlice: function(value, arg) {
      var start = arg[0];
      var end = arg[1];
      if (end > value.length) {
        return value;
      }
      else {
        return value.slice(start, end);
      }
    }
  };
}();
<commit_msg>Removed assets/riak<commit_after><|endoftext|>


<commit_before>if (!PhoneGap.hasResource("network")) {
	PhoneGap.addResource("network");

// //////////////////////////////////////////////////////////////////

Connection = function() {
	/*
	 * One of the connection constants below.
	 */
	this.type = Connection.UNKNOWN;

	/* initialize from the extended DeviceInfo properties */
    try {
		this.type	= DeviceInfo.connection.type;
    }
	catch(e) {
    }
};

Connection.UNKNOWN = "unknown"; // Unknown connection type
Connection.ETHERNET = "ethernet";
Connection.WIFI = "wifi";
Connection.CELL_2G = "2g"; // the default for iOS, for any cellular connection
Connection.CELL_3G = "3g";
Connection.CELL_4G = "4g";
Connection.NONE = "none"; // NO connectivity

PhoneGap.addConstructor(function() {
    if (typeof navigator.network.connection == "undefined") navigator.network.connection = new Connection();
});

};<commit_msg>Fixed null navigator.network (for navigator.network.connection constructor)<commit_after>if (!PhoneGap.hasResource("network")) {
	PhoneGap.addResource("network");

// //////////////////////////////////////////////////////////////////

Connection = function() {
	/*
	 * One of the connection constants below.
	 */
	this.type = Connection.UNKNOWN;

	/* initialize from the extended DeviceInfo properties */
    try {
		this.type	= DeviceInfo.connection.type;
    }
	catch(e) {
    }
};

Connection.UNKNOWN = "unknown"; // Unknown connection type
Connection.ETHERNET = "ethernet";
Connection.WIFI = "wifi";
Connection.CELL_2G = "2g"; // the default for iOS, for any cellular connection
Connection.CELL_3G = "3g";
Connection.CELL_4G = "4g";
Connection.NONE = "none"; // NO connectivity

PhoneGap.addConstructor(function() {
    if (typeof navigator.network == "undefined") navigator.network = {};
    if (typeof navigator.network.connection == "undefined") navigator.network.connection = new Connection();
});

};<|endoftext|>


<commit_before>'use strict';

/* Filters */

angular.module('lexicon.filters', [])
	.filter('orderAsArray', function() {
		return function(obj, keyName) {
			var result = [];
			angular.forEach(obj, function(val, key) {
				// if keyName defined, include key in val object
				if (keyName) {
					val[keyName] = key;
				}
				result.push(val);
			});
			return result;
		};
	})
	;
<commit_msg>fix filter so it doesn't modify original<commit_after>'use strict';

/* Filters */

angular.module('lexicon.filters', [])
	.filter('orderAsArray', function() {
		return function(obj, keyName) {
			var result = [];
			angular.forEach(obj, function(val, key) {
				var newVal = angular.copy(val);
				// if keyName defined, include key in val object
				if (keyName) {
					newVal[keyName] = key;
				}
				result.push(newVal);
			});
			return result;
		};
	})
	;
<|endoftext|>


<commit_before>import gulp from 'gulp';
import minimatch from 'minimatch';
import gulpWatch from 'gulp-watch';
import debounce from 'debounce';
import { build } from 'aurelia-cli';
import project from '../aurelia.json';
import transpile from './transpile';
import processMarkup from './process-markup';
import processCSS from './process-css';
import copyFiles from './copy-files';

const debounceWaitTime = 100;
let isBuilding = false;
let pendingRefreshPaths = [];
let watches = {};
let watchCallback = () => { };

watches[project.transpiler.source] = { name: 'transpile', callback: transpile };
watches[project.markupProcessor.source] = { name: 'markup', callback: processMarkup };
watches[project.cssProcessor.source] = { name: 'CSS', callback: processCSS };
if (typeof project.build.copyFiles === 'object') {
  for (let src of Object.keys(project.build.copyFiles)) {
    watches[src] = { name: 'file copy', callback: copyFiles };
  }
}

let watch = (callback) => {
  watchCallback = callback || watchCallback;
  return gulpWatch(
    Object.keys(watches),
    {
      read: false, // performance optimization: do not read actual file contents
      verbose: true
    },
    (vinyl) => {
      if (vinyl.path && vinyl.cwd && vinyl.path.startsWith(vinyl.cwd)) {
        let pathToAdd = vinyl.path.substr(vinyl.cwd.length + 1);
        log(`Watcher: Adding path ${pathToAdd} to pending build changes...`);
        pendingRefreshPaths.push(pathToAdd);
        refresh();
      }
    });
};

let refresh = debounce(() => {
  if (isBuilding) {
    log('Watcher: A build is already in progress, deferring change detection...');
    return;
  }

  isBuilding = true;

  let paths = pendingRefreshPaths.splice(0);
  let refreshTasks = [];

  // Dynamically compose tasks
  for (let src of Object.keys(watches)) {
    if (paths.find((x) => minimatch(x, src))) {
      log(`Watcher: Adding ${watches[src].name} task to next build...`);
      refreshTasks.push(watches[src].callback);
    }
  }

  if (refreshTasks.length === 0) {
    log('Watcher: No relevant changes found, skipping next build.');
    isBuilding = false;
    return;
  }

  let toExecute = gulp.series(
    readProjectConfiguration,
    gulp.parallel(refreshTasks),
    writeBundles,
    (done) => {
      isBuilding = false;
      watchCallback();
      done();
      if (pendingRefreshPaths.length > 0) {
        log('Watcher: Found more pending changes after finishing build, triggering next one...');
        refresh();
      }
    }
  );

  toExecute();
}, debounceWaitTime);

function log(message) {
  console.log(message);
}

function readProjectConfiguration() {
  return build.src(project);
}

function writeBundles() {
  return build.dest();
}

export default watch;<commit_msg>chore(aurelia): update watch task<commit_after>import gulp from 'gulp';
import minimatch from 'minimatch';
import gulpWatch from 'gulp-watch';
import debounce from 'debounce';
import { build } from 'aurelia-cli';
import project from '../aurelia.json';
import transpile from './transpile';
import processMarkup from './process-markup';
import processCSS from './process-css';
import copyFiles from './copy-files';

const debounceWaitTime = 100;
let isBuilding = false;
let pendingRefreshPaths = [];
let watchCallback = () => { };
let watches = [
  { name: 'transpile', callback: transpile, source: project.transpiler.source },
  { name: 'markup', callback: processMarkup, source: project.markupProcessor.source },
  { name: 'CSS', callback: processCSS, source: project.cssProcessor.source }
];

if (typeof project.build.copyFiles === 'object') {
  for (let src of Object.keys(project.build.copyFiles)) {
    watches.push({ name: 'file copy', callback: copyFiles, source: src });
  }
}

let watch = (callback) => {
  watchCallback = callback || watchCallback;

  // watch every glob individually
  for(let watcher of watches) {
    if (Array.isArray(watcher.source)) {
      for(let glob of watcher.source) {
        watchPath(glob);
      }
    } else {
      watchPath(watcher.source);
    }
  }
};

let watchPath = (p) => {
  gulpWatch(
    p,
    {
      read: false, // performance optimization: do not read actual file contents
      verbose: true
    },
    (vinyl) => processChange(vinyl));
};

let processChange = (vinyl) => {
  if (vinyl.path && vinyl.cwd && vinyl.path.startsWith(vinyl.cwd)) {
    let pathToAdd = vinyl.path.substr(vinyl.cwd.length + 1);
    log(`Watcher: Adding path ${pathToAdd} to pending build changes...`);
    pendingRefreshPaths.push(pathToAdd);
    refresh();
  }
}

let refresh = debounce(() => {
  if (isBuilding) {
    log('Watcher: A build is already in progress, deferring change detection...');
    return;
  }

  isBuilding = true;

  let paths = pendingRefreshPaths.splice(0);
  let refreshTasks = [];

  // determine which tasks need to be executed
  // based on the files that have changed
  for (let watcher of watches) {
    if (Array.isArray(watcher.source)) {
      for(let source of watcher.source) {
        if (paths.find(path => minimatch(path, source))) {
          refreshTasks.push(watcher);
        }
      }
    }
    else {
      if (paths.find(path => minimatch(path, watcher.source))) {
        refreshTasks.push(watcher);
      }
    }
  }

  if (refreshTasks.length === 0) {
    log('Watcher: No relevant changes found, skipping next build.');
    isBuilding = false;
    return;
  }

  log(`Watcher: Running ${refreshTasks.map(x => x.name).join(', ')} tasks on next build...`);

  let toExecute = gulp.series(
    readProjectConfiguration,
    gulp.parallel(refreshTasks.map(x => x.callback)),
    writeBundles,
    (done) => {
      isBuilding = false;
      watchCallback();
      done();
      if (pendingRefreshPaths.length > 0) {
        log('Watcher: Found more pending changes after finishing build, triggering next one...');
        refresh();
      }
    }
  );

  toExecute();
}, debounceWaitTime);

function log(message) {
  console.log(message);
}

function readProjectConfiguration() {
  return build.src(project);
}

function writeBundles() {
  return build.dest();
}

export default watch;
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// -------------
// Menu Display
// -------------

// $(cur_frm.wrapper).on("grid-row-render", function(e, grid_row) {
// 	if(grid_row.doc && grid_row.doc.fieldtype=="Section Break") {
// 		$(grid_row.row).css({"font-weight": "bold"});
// 	}
// })

frappe.ui.form.on('DocType', {
	refresh: function(frm) {
		if(frappe.session.user !== "Administrator" || !frappe.boot.developer_mode) {
			if(frm.is_new()) {
				frm.set_value("custom", 1);
			}
			frm.toggle_enable("custom", 0);
			frm.toggle_enable("beta", 0);
		}

		if (!frm.is_new() && !frm.doc.istable) {
			if (frm.doc.issingle) {
				frm.add_custom_button(__('Go to {0}', [frm.doc.name]), () => {
					frappe.set_route('Form', frm.doc.name);
				});
			} else {
				frm.add_custom_button(__('Go to {0} List', [frm.doc.name]), () => {
					frappe.set_route('List', frm.doc.name, 'List');
				});
			}
		}

		if(!frappe.boot.developer_mode && !frm.doc.custom) {
			// make the document read-only
			frm.set_read_only();
		}

		if(frm.is_new()) {
			if (!(frm.doc.permissions && frm.doc.permissions.length)) {
				frm.add_child('permissions', {role: 'System Manager'});
			}
		} else {
			frm.toggle_enable("engine", 0);
		}

		// set label for "In List View" for child tables
		frm.get_docfield('fields', 'in_list_view').label = frm.doc.istable ?
			__('In Grid View') : __('In List View');

		frm.events.autoname(frm);
	},

	before_save: function(frm) {
		frappe.flags.reload_bootinfo = frm.is_new();
	},

	after_save: function(frm) {
		if (frappe.flags.reload_bootinfo) {
			frappe.boot.user.can_create.push(frm.doc.name);
			frappe.flags.reload_bootinfo = false;
		}
	},

	autoname(frm) {
		frm.set_df_property('fields', 'reqd', frm.doc.autoname !== 'Prompt');
	}
})
<commit_msg>refactor: Rename frappe.flags.reload_bootinfo to frappe.flags.update_bootinfo<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// -------------
// Menu Display
// -------------

// $(cur_frm.wrapper).on("grid-row-render", function(e, grid_row) {
// 	if(grid_row.doc && grid_row.doc.fieldtype=="Section Break") {
// 		$(grid_row.row).css({"font-weight": "bold"});
// 	}
// })

frappe.ui.form.on('DocType', {
	refresh: function(frm) {
		if(frappe.session.user !== "Administrator" || !frappe.boot.developer_mode) {
			if(frm.is_new()) {
				frm.set_value("custom", 1);
			}
			frm.toggle_enable("custom", 0);
			frm.toggle_enable("beta", 0);
		}

		if (!frm.is_new() && !frm.doc.istable) {
			if (frm.doc.issingle) {
				frm.add_custom_button(__('Go to {0}', [frm.doc.name]), () => {
					frappe.set_route('Form', frm.doc.name);
				});
			} else {
				frm.add_custom_button(__('Go to {0} List', [frm.doc.name]), () => {
					frappe.set_route('List', frm.doc.name, 'List');
				});
			}
		}

		if(!frappe.boot.developer_mode && !frm.doc.custom) {
			// make the document read-only
			frm.set_read_only();
		}

		if(frm.is_new()) {
			if (!(frm.doc.permissions && frm.doc.permissions.length)) {
				frm.add_child('permissions', {role: 'System Manager'});
			}
		} else {
			frm.toggle_enable("engine", 0);
		}

		// set label for "In List View" for child tables
		frm.get_docfield('fields', 'in_list_view').label = frm.doc.istable ?
			__('In Grid View') : __('In List View');

		frm.events.autoname(frm);
	},

	before_save: function(frm) {
		frappe.flags.update_bootinfo = frm.is_new();
	},

	after_save: function(frm) {
		if (frappe.flags.update_bootinfo) {
			frappe.boot.user.can_create.push(frm.doc.name);
			frappe.flags.update_bootinfo = false;
		}
	},

	autoname(frm) {
		frm.set_df_property('fields', 'reqd', frm.doc.autoname !== 'Prompt');
	}
})
<|endoftext|>


<commit_before>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// __("Form")

frappe.ui.AppFrame = Class.extend({
	init: function(parent, title, module) {
		this.set_document_title = true;
		this.buttons = {};
		this.fields_dict = {};
		this.parent = parent;

		var $center = parent.find(".titlebar-center-item");
		this.$title_area = $('\
				\
				\
			').appendTo($center);

		this.$sub_title_area = $('

')
			.appendTo($center);

		this.setup_iconbar();

		if(title)
			this.set_title(title);

	},

	setup_iconbar: function() {
		var me = this;
		this.iconbar = new frappe.ui.IconBar(this.parent.find(".appframe-iconbar .container"), 3);
		this.iconbar.$wrapper.find(".iconbar-3").addClass("pull-right");

		this.iconbar.$wrapper.on("shown", function() {
			me.parent.find(".appframe-iconbar").removeClass("hide")
		})
		this.iconbar.$wrapper.on("hidden", function() {
			me.parent.find(".appframe-iconbar").addClass("hide")
		})
	},

	// appframe::title
	get_title_area: function() {
		return this.$title_area;
	},

	set_title: function(txt) {
		// strip icon
		this.title = txt;
		document.title = txt.replace(/<[^>]*>/g, "");
		this.$title_area.find(".title-text").html(txt);
	},

	set_title_sub: function(txt) {
		// strip icon
		this.$sub_title_area.html(txt).toggleClass("hide", !!!txt);
	},

	set_title_left: function(click) {
		return $("")
			.html('')
			.on("click", function() { click.apply(this); })
			.appendTo(this.parent.find(".titlebar-left-item").empty());
	},

	set_title_right: function(txt, click, icon, btn_class) {
		if(!btn_class) btn_class="btn-primary"
		var $right = this.parent.find(".titlebar-item.text-right")
		if(txt) {
			this.title_right && this.title_right.remove();
			this.title_right = $("")
				.html((icon ? ' ' : "") + txt)
				.click(click)
				.appendTo($right.attr("data-text", txt));
			return this.title_right;
		} else {
			$right.empty().attr("data-text", "");
			this.title_right = null;
			this.primary_dropdown = null;
			this.primary_action = null;
		}
	},

	get_title_right_text: function() {
		return this.parent.find(".titlebar-item.text-right").attr("data-text");
	},

	add_primary_action: function(label, click, icon, toolbar_or_class) {
		this.sidebar.add_user_action(label, click);
		return;

		if(toolbar_or_class===true) {
			this.add_icon_btn("4", icon, label, click);
			return;
		}

		var wrapper = this.parent.find(".appframe-primary-actions .container");
		this.parent.find(".appframe-primary-actions").removeClass("hide");

		if($.isArray(click)) {
			// if onclick is an array, add a dropdown button
			var $btn_group = $('
\
				<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">\
					'+label+' \
				</button>\

\

').appendTo(wrapper);

			var $ul = $btn_group.find(".dropdown-menu");
			$.each(click, function(i, v) {
				var $a = $('
'+v.label+'
')
					.appendTo($ul)
					.find('a').on('click', v.click);
				if(v.value) $a.attr('data-value', v.value);
			});

			// activate dropdown
			$btn_group.find(".dropdown-toggle").dropdown();
		} else {
			return $(repl('<button class="btn %(klass)s btn-sm">\
				 %(label)s</button>', {label:label, icon:icon,
					klass: toolbar_or_class || "btn-primary"}))
				.on("click", click)
				.appendTo(wrapper);
		};

	},

	add_module_icon: function(module, doctype, onclick, sub_title) {
		var module_info = frappe.get_module(module);
		if(!module_info) {
			module_info = {
				icon: "icon-question-sign",
				color: "#ddd"
			}
		}
		var icon = frappe.boot.doctype_icons[doctype] || module_info.icon;

		this.get_main_icon(icon)
			.attr("doctype-name", doctype);

		this.set_title_left(function() {
			var route = frappe.get_route()[0]==module_info.link ? "" : module_info.link;
			frappe.set_route(route);
		});
	},

	get_main_icon: function(icon) {
		return this.$title_area.find(".title-icon")
			.html(' ')
			.toggle(true);
		},

	add_help_button: function(txt) {
		this.add_icon_btn("2", "icon-question-sign", __("Help"),
			function() { msgprint($(this).data('help-text'), 'Help'); })
			.data("help-text", txt);
	},

	add_icon_btn: function(group, icon, label, click) {
		if(this.sidebar_links.length) {
			return $('' + label + '').appendTo($('
')
				.appendTo(this.sidebar_links)).click(click);
		} else {
			return this.iconbar.add_btn(group, icon, label, click);
		}
	},

	add_button: function(label, click, icon, is_title) {
		return this.add_icon_btn("1", icon, __(label), click);
	},

	add_dropdown_button: function(parent, label, click, icon) {
		frappe.ui.toolbar.add_dropdown_button(parent, label, click, icon);
	},

	// appframe::form
	add_label: function(label) {
		this.show_form();
		return $(""+label+" ")
			.appendTo(this.parent.find(".appframe-form .container"));
	},
	add_select: function(label, options) {
		var field = this.add_field({label:label, fieldtype:"Select"})
		return field.$wrapper.find("select").empty().add_options(options);
	},
	add_data: function(label) {
		var field = this.add_field({label: label, fieldtype: "Data"});
		return field.$wrapper.find("input").attr("placeholder", label);
	},
	add_date: function(label, date) {
		var field = this.add_field({label: label, fieldtype: "Date", "default": date});
		return field.$wrapper.find("input").attr("placeholder", label);
	},
	add_check: function(label) {
		return $("
<input type='checkbox'>" + label + "
")
			.appendTo(this.parent.find(".appframe-form .container"))
			.find("input");
	},
	add_break: function() {
		// add further fields in the next line
		this.parent.find(".appframe-form .container")
			.append('

');
	},
	add_field: function(df) {
		this.show_form();
		var f = frappe.ui.form.make_control({
			df: df,
			parent: this.parent.find(".appframe-form .container"),
			only_input: df.fieldtype=="Check" ? false : true,
		})
		f.refresh();
		$(f.wrapper)
			.addClass('col-md-2')
			.css({
				"padding-left": "0px",
				"padding-right": "7px",
			})
			.attr("title", __(df.label)).tooltip();
		f.$input.attr("placeholder", __(df.label));

		if(df.fieldtype==="Check") {
			$(f.wrapper).find(":first-child")
				.removeClass("col-md-offset-4 col-md-8");
		} else {
			$(f.wrapper)
				.prepend('' + __(df.label) + '');
		}

		if(df.fieldtype=="Button") {
			$(f.wrapper).find(".appframe-control-label").html(" ")
			f.$input.addClass("btn-sm").css({"width": "100%", "margin-top": "-1px"});
		}

		if(df["default"])
			f.set_input(df["default"])
		this.fields_dict[df.fieldname || df.label] = f;
		return f;
	},
	show_form: function() {
		this.parent.find(".appframe-form").removeClass("hide");
	},
	views: {},
	add_view: function(name, html) {
		this.views[name] = $(html).appendTo($(this.parent).find(".appframe"));
		if(!this.current_view) {
			this.current_view = this.views[name];
		} else {
			this.views[name].toggle(false);
		}
		return this.views[name];
	},
	set_view: function(name) {
		this.current_view && this.current_view.toggle(false);
		this.views[name].toggle(true);
		this.current_view = this.views[name];
	}
});

// parent, title, single_column
// standard page with appframe

frappe.ui.make_app_page = function(opts) {
	/* help: make a standard page layout with a toolbar and title */
	/* options: [
			"parent: [HTMLElement] parent element",
			"single_column: [Boolean] false/true",
			"title: [optional] set this title"
		]
	*/
	var $wrapper = $(opts.parent)
	$(frappe.templates.appframe).appendTo($wrapper);

	var $appframe = $wrapper.find(".appframe");

	opts.parent.appframe = new frappe.ui.AppFrame($wrapper);

	if(opts.single_column) {
		opts.parent.body = opts.parent.appframe.add_view("main", '
');
	} else {
		var main = opts.parent.appframe.add_view("main", '
\

\

\

\

\

');
		opts.parent.body = main.find(".layout-main-section");
	}

	if(opts.set_document_title!==undefined)
		opts.parent.appframe.set_document_title = opts.set_document_title;

	if(opts.title)
		opts.parent.appframe.set_title(opts.title);

	if(opts.icon)
		opts.parent.appframe.get_main_icon(opts.icon);
}
<commit_msg>[design] timeline, print preview, pos<commit_after>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// __("Form")

frappe.ui.AppFrame = Class.extend({
	init: function(parent, title, module) {
		this.set_document_title = true;
		this.buttons = {};
		this.fields_dict = {};
		this.parent = parent;

		var $center = parent.find(".titlebar-center-item");
		this.$title_area = $('\
				\
				\
			').appendTo($center);

		this.$sub_title_area = $('

')
			.appendTo($center);

		this.setup_iconbar();

		if(title)
			this.set_title(title);

	},

	setup_iconbar: function() {
		var me = this;
		this.iconbar = new frappe.ui.IconBar(this.parent.find(".appframe-iconbar .container"), 3);
		this.iconbar.$wrapper.find(".iconbar-3").addClass("pull-right");

		this.iconbar.$wrapper.on("shown", function() {
			me.parent.find(".appframe-iconbar").removeClass("hide")
		})
		this.iconbar.$wrapper.on("hidden", function() {
			me.parent.find(".appframe-iconbar").addClass("hide")
		})
	},

	// appframe::title
	get_title_area: function() {
		return this.$title_area;
	},

	set_title: function(txt) {
		// strip icon
		this.title = txt;
		document.title = txt.replace(/<[^>]*>/g, "");
		this.$title_area.find(".title-text").html(txt);
	},

	set_title_sub: function(txt) {
		// strip icon
		this.$sub_title_area.html(txt).toggleClass("hide", !!!txt);
	},

	set_title_left: function(click) {
		return $("")
			.html('')
			.on("click", function() { click.apply(this); })
			.appendTo(this.parent.find(".titlebar-left-item").empty());
	},

	set_title_right: function(txt, click, icon, btn_class) {
		if(!btn_class) btn_class="btn-primary"
		var $right = this.parent.find(".titlebar-item.text-right")
		if(txt) {
			this.title_right && this.title_right.remove();
			this.title_right = $("")
				.html((icon ? ' ' : "") + txt)
				.click(click)
				.appendTo($right.attr("data-text", txt));
			return this.title_right;
		} else {
			$right.empty().attr("data-text", "");
			this.title_right = null;
			this.primary_dropdown = null;
			this.primary_action = null;
		}
	},

	get_title_right_text: function() {
		return this.parent.find(".titlebar-item.text-right").attr("data-text");
	},

	add_primary_action: function(label, click, icon, toolbar_or_class) {
		this.sidebar.add_user_action(label, click);
		return;

		if(toolbar_or_class===true) {
			this.add_icon_btn("4", icon, label, click);
			return;
		}

		var wrapper = this.parent.find(".appframe-primary-actions .container");
		this.parent.find(".appframe-primary-actions").removeClass("hide");

		if($.isArray(click)) {
			// if onclick is an array, add a dropdown button
			var $btn_group = $('
\
				<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">\
					'+label+' \
				</button>\

\

').appendTo(wrapper);

			var $ul = $btn_group.find(".dropdown-menu");
			$.each(click, function(i, v) {
				var $a = $('
'+v.label+'
')
					.appendTo($ul)
					.find('a').on('click', v.click);
				if(v.value) $a.attr('data-value', v.value);
			});

			// activate dropdown
			$btn_group.find(".dropdown-toggle").dropdown();
		} else {
			return $(repl('<button class="btn %(klass)s btn-sm">\
				 %(label)s</button>', {label:label, icon:icon,
					klass: toolbar_or_class || "btn-primary"}))
				.on("click", click)
				.appendTo(wrapper);
		};

	},

	add_module_icon: function(module, doctype, onclick, sub_title) {
		var module_info = frappe.get_module(module);
		if(!module_info) {
			module_info = {
				icon: "icon-question-sign",
				color: "#ddd"
			}
		}
		var icon = frappe.boot.doctype_icons[doctype] || module_info.icon;

		this.get_main_icon(icon)
			.attr("doctype-name", doctype);

		this.set_title_left(function() {
			var route = frappe.get_route()[0]==module_info.link ? "" : module_info.link;
			frappe.set_route(route);
		});
	},

	get_main_icon: function(icon) {
		return this.$title_area.find(".title-icon")
			.html(' ')
			.toggle(true);
		},

	add_help_button: function(txt) {
		this.add_icon_btn("2", "icon-question-sign", __("Help"),
			function() { msgprint($(this).data('help-text'), 'Help'); })
			.data("help-text", txt);
	},

	add_icon_btn: function(group, icon, label, click) {
		return this.iconbar.add_btn(group, icon, label, click);
	},

	add_button: function(label, click, icon, is_title) {
		return this.add_icon_btn("1", icon, __(label), click);
	},

	add_dropdown_button: function(parent, label, click, icon) {
		frappe.ui.toolbar.add_dropdown_button(parent, label, click, icon);
	},

	// appframe::form
	add_label: function(label) {
		this.show_form();
		return $(""+label+" ")
			.appendTo(this.parent.find(".appframe-form .container"));
	},
	add_select: function(label, options) {
		var field = this.add_field({label:label, fieldtype:"Select"})
		return field.$wrapper.find("select").empty().add_options(options);
	},
	add_data: function(label) {
		var field = this.add_field({label: label, fieldtype: "Data"});
		return field.$wrapper.find("input").attr("placeholder", label);
	},
	add_date: function(label, date) {
		var field = this.add_field({label: label, fieldtype: "Date", "default": date});
		return field.$wrapper.find("input").attr("placeholder", label);
	},
	add_check: function(label) {
		return $("
<input type='checkbox'>" + label + "
")
			.appendTo(this.parent.find(".appframe-form .container"))
			.find("input");
	},
	add_break: function() {
		// add further fields in the next line
		this.parent.find(".appframe-form .container")
			.append('

');
	},
	add_field: function(df) {
		this.show_form();
		var f = frappe.ui.form.make_control({
			df: df,
			parent: this.parent.find(".appframe-form .container"),
			only_input: df.fieldtype=="Check" ? false : true,
		})
		f.refresh();
		$(f.wrapper)
			.addClass('col-md-2')
			.css({
				"padding-left": "0px",
				"padding-right": "7px",
			})
			.attr("title", __(df.label)).tooltip();
		f.$input.attr("placeholder", __(df.label));

		if(df.fieldtype==="Check") {
			$(f.wrapper).find(":first-child")
				.removeClass("col-md-offset-4 col-md-8");
		} else {
			$(f.wrapper)
				.prepend('' + __(df.label) + '');
		}

		if(df.fieldtype=="Button") {
			$(f.wrapper).find(".appframe-control-label").html(" ")
			f.$input.addClass("btn-sm").css({"width": "100%", "margin-top": "-1px"});
		}

		if(df["default"])
			f.set_input(df["default"])
		this.fields_dict[df.fieldname || df.label] = f;
		return f;
	},
	show_form: function() {
		this.parent.find(".appframe-form").removeClass("hide");
	},
	views: {},
	add_view: function(name, html) {
		this.views[name] = $(html).appendTo($(this.parent).find(".appframe"));
		if(!this.current_view) {
			this.current_view = this.views[name];
		} else {
			this.views[name].toggle(false);
		}
		return this.views[name];
	},
	set_view: function(name) {
		this.current_view && this.current_view.toggle(false);
		this.views[name].toggle(true);
		this.current_view = this.views[name];
	}
});

// parent, title, single_column
// standard page with appframe

frappe.ui.make_app_page = function(opts) {
	/* help: make a standard page layout with a toolbar and title */
	/* options: [
			"parent: [HTMLElement] parent element",
			"single_column: [Boolean] false/true",
			"title: [optional] set this title"
		]
	*/
	var $wrapper = $(opts.parent)
	$(frappe.templates.appframe).appendTo($wrapper);

	var $appframe = $wrapper.find(".appframe");

	opts.parent.appframe = new frappe.ui.AppFrame($wrapper);

	if(opts.single_column) {
		opts.parent.body = opts.parent.appframe.add_view("main", '
');
	} else {
		var main = opts.parent.appframe.add_view("main", '
\

\

\

\

\

');
		opts.parent.body = main.find(".layout-main-section");
	}

	if(opts.set_document_title!==undefined)
		opts.parent.appframe.set_document_title = opts.set_document_title;

	if(opts.title)
		opts.parent.appframe.set_title(opts.title);

	if(opts.icon)
		opts.parent.appframe.get_main_icon(opts.icon);
}
<|endoftext|>


<commit_before>import Ember from 'ember';
const { service } = Ember.inject;
import BaseValidator from 'ember-cp-validations/validators/base';
import fetch from 'fetch';
import ENV from 'bracco/config/environment';

const validUrl = BaseValidator.extend({
  currentUser: service(),

  validate(value, options) {
    const { allowBlank } = options;

    if (allowBlank && Ember.isEmpty(value)) {
      return true;
    }

    let url = ENV.APP_URL + '/dois/status?url=' + value;
    return fetch(url, {
      method: 'post',
      timeout: 5000,
      headers: {
        'Authorization': 'Bearer ' + this.get('currentUser').get('jwt')
      }
    }).then(function(response) {
      if (response.ok) {
        return response.json().then(function(result) {
          if (parseInt(result.status) === 403) {
            return "Access to landing page was forbidden (status code " + result.status + ").";
          } else if (result.status === 404) {
            return "Landing page was not found (status code " + result.status + ").";
          } else if (result.status === 408) {
            return "Request timed out reaching the landing page (status code " + result.status + ").";
          } else if (result.status !== 200) {
            return "An error has occured (status code " + result.status + ").";
          } else if (result['content-type'] !== "text/html") {
            return "Landing page should be a web page, but was content type " + result['content-type'] + ".";
          } else {
            return true;
          }
        });
      } else {
        Ember.Logger.assert(false, response)
      }
    }).catch(function(error) {
      Ember.Logger.assert(false, error)
    });
  }
});

validUrl.reopenClass({
  getDependentsFor() {
    return ['url'];
  }
});

export default validUrl;
<commit_msg>disable url checks<commit_after>import Ember from 'ember';
const { service } = Ember.inject;
import BaseValidator from 'ember-cp-validations/validators/base';
import fetch from 'fetch';
import ENV from 'bracco/config/environment';

const validUrl = BaseValidator.extend({
  currentUser: service(),

  validate(value, options) {
    const { allowBlank } = options;

    if (allowBlank && Ember.isEmpty(value)) {
      return true;
    }

    let url = ENV.APP_URL + '/dois/status?url=' + value;
    return fetch(url, {
      method: 'post',
      timeout: 5000,
      headers: {
        'Authorization': 'Bearer ' + this.get('currentUser').get('jwt')
      }
    }).then(function(response) {
      if (response.ok) {
        return response.json().then(function(result) {
          if (parseInt(result.status) === 403) {
            return "Access to landing page was forbidden (status code " + result.status + ").";
          } else if (result.status === 404) {
            return "Landing page was not found (status code " + result.status + ").";
          } else if (result.status === 408) {
            return "Request timed out reaching the landing page (status code " + result.status + ").";
          } else if (result.status !== 200) {
            return "An unknown error has occured (status code " + result.status + ") and will be investigated.";
          } else if (result['content-type'] !== "text/html") {
            return "Landing page should be a web page, but was content type " + result['content-type'] + ".";
          } else {
            return true;
          }
        });
      } else {
        Ember.Logger.assert(false, response)
      }
    }).catch(function(error) {
      Ember.Logger.assert(false, error)
    });
  }
});

validUrl.reopenClass({
  getDependentsFor() {
    return ['url'];
  }
});

export default validUrl;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Apple Inc.  All rights reserved.
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import * as BrowserSDK from '../browser_sdk/browser_sdk.js';
import * as Common from '../common/common.js';
import * as CookieTable from '../cookie_table/cookie_table.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

import {StorageItemsView} from './StorageItemsView.js';

class CookiePreviewWidget extends UI.Widget.VBox {
  constructor() {
    super();
    this.setMinimumSize(230, 45);
    /** @type {?SDK.Cookie.Cookie} cookie */
    this._cookie = null;
    this._showDecodedSetting = Common.Settings.Settings.instance().createSetting('cookieViewShowDecoded', false);

    const header = document.createElement('div');
    header.classList.add('cookie-preview-widget-header');
    const span = document.createElement('span');
    span.classList.add('cookie-preview-widget-header-label');
    span.textContent = 'Cookie Value';
    header.appendChild(span);
    this.contentElement.appendChild(header);

    const toggle = UI.UIUtils.CheckboxLabel.create(ls`Show URL decoded`, this._showDecodedSetting.get());
    toggle.classList.add('cookie-preview-widget-toggle');
    toggle.checkboxElement.addEventListener('click', () => this.showDecoded(!this._showDecodedSetting.get()));
    header.appendChild(toggle);
    this._toggle = toggle;

    const value = document.createElement('div');
    value.classList.add('cookie-preview-widget-cookie-value');
    value.textContent = '';
    value.addEventListener('dblclick', this.handleDblClickOnCookieValue.bind(this));
    this._value = value;

    this.contentElement.classList.add('cookie-preview-widget');
    this.contentElement.appendChild(value);
  }

  /**
   *
   * @param {boolean} decoded
   */
  showDecoded(decoded) {
    if (!this._cookie) {
      return;
    }
    this._showDecodedSetting.set(decoded);
    this._toggle.checkboxElement.checked = decoded;
    this._updatePreview();
  }

  _updatePreview() {
    if (this._cookie) {
      this._value.textContent =
          this._showDecodedSetting.get() ? decodeURIComponent(this._cookie.value()) : this._cookie.value();
    } else {
      this._value.textContent = '';
    }
  }

  /**
   * @param {!SDK.Cookie.Cookie} cookie
   */
  setCookie(cookie) {
    this._cookie = cookie;
    this._updatePreview();
  }

  /**
   * Select all text even if there a spaces in it
   * @param {!Event} event
   */
  handleDblClickOnCookieValue(event) {
    event.preventDefault();
    const range = document.createRange();
    range.selectNode(this._value);
    const selection = window.getSelection();
    if (!selection) {
      return;
    }
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

export class CookieItemsView extends StorageItemsView {
  /**
   * @param {!SDK.CookieModel.CookieModel} model
   * @param {string} cookieDomain
   */
  constructor(model, cookieDomain) {
    super(Common.UIString.UIString('Cookies'), 'cookiesPanel');

    this.registerRequiredCSS('resources/cookieItemsView.css', {enableLegacyPatching: false});
    this.element.classList.add('storage-view');

    /** @type {!SDK.CookieModel.CookieModel} */
    this._model = model;
    this._cookieDomain = cookieDomain;

    this._totalSize = 0;
    /** @type {!CookieTable.CookiesTable.CookiesTable} */
    this._cookiesTable = new CookieTable.CookiesTable.CookiesTable(
        /* renderInline */ false, this._saveCookie.bind(this), this.refreshItems.bind(this),
        this._handleCookieSelected.bind(this), this._deleteCookie.bind(this));

    this._cookiesTable.setMinimumSize(0, 50);

    this._splitWidget = new UI.SplitWidget.SplitWidget(
        /* isVertical: */ false, /* secondIsSidebar: */ true, 'cookieItemsSplitViewState');
    this._splitWidget.show(this.element);

    this._previewPanel = new UI.Widget.VBox();
    const resizer = this._previewPanel.element.createChild('div', 'preview-panel-resizer');

    this._splitWidget.setMainWidget(this._cookiesTable);
    this._splitWidget.setSidebarWidget(this._previewPanel);
    this._splitWidget.installResizer(resizer);

    this._previewWidget = new CookiePreviewWidget();
    this._emptyWidget = new UI.EmptyWidget.EmptyWidget(ls`Select a cookie to preview its value`);
    this._emptyWidget.show(this._previewPanel.contentElement);

    this._onlyIssuesFilterUI = new UI.Toolbar.ToolbarCheckbox(
        ls`Only show cookies with an issue`, ls`Only show cookies which have an associated issue`, () => {
          this._updateWithCookies(this._allCookies);
        });
    this.appendToolbarItem(this._onlyIssuesFilterUI);

    this._refreshThrottler = new Common.Throttler.Throttler(300);
    /** @type {!Array<!Common.EventTarget.EventDescriptor>} */
    this._eventDescriptors = [];

    /** @type {!Array<!SDK.Cookie.Cookie>} */
    this._allCookies = [];
    /** @type {!Array<!SDK.Cookie.Cookie>} */
    this._shownCookies = [];
    /** @type {?SDK.Cookie.Cookie} */
    this._selectedCookie = null;

    this.setCookiesDomain(model, cookieDomain);
  }

  /**
   * @param {!SDK.CookieModel.CookieModel} model
   * @param {string} domain
   */
  setCookiesDomain(model, domain) {
    this._model = model;
    this._cookieDomain = domain;
    this.refreshItems();
    Common.EventTarget.EventTarget.removeEventListeners(this._eventDescriptors);
    const networkManager = model.target().model(SDK.NetworkManager.NetworkManager);
    if (networkManager) {
      this._eventDescriptors = [
        networkManager.addEventListener(SDK.NetworkManager.Events.ResponseReceived, this._onResponseReceived, this),
        networkManager.addEventListener(SDK.NetworkManager.Events.LoadingFinished, this._onLoadingFinished, this),
      ];
    }

    this._showPreview(null);
  }

  /**
   * @param {?SDK.Cookie.Cookie} cookie
   */
  _showPreview(cookie) {
    if (cookie === this._selectedCookie) {
      return;
    }
    this._selectedCookie = cookie;

    if (!cookie) {
      this._previewWidget.detach();
      this._emptyWidget.show(this._previewPanel.contentElement);
    } else {
      this._emptyWidget.detach();
      this._previewWidget.setCookie(cookie);
      this._previewWidget.show(this._previewPanel.contentElement);
    }
  }

  _handleCookieSelected() {
    const cookie = this._cookiesTable.selectedCookie();
    this.setCanDeleteSelected(!!cookie);

    this._showPreview(cookie);
  }

  /**
   * @param {!SDK.Cookie.Cookie} newCookie
   * @param {?SDK.Cookie.Cookie} oldCookie
   * @return {!Promise<boolean>}
   */
  async _saveCookie(newCookie, oldCookie) {
    if (oldCookie && newCookie.key() !== oldCookie.key()) {
      await this._model.deleteCookie(oldCookie);
    }
    return this._model.saveCookie(newCookie);
  }

  /**
   * @param {!SDK.Cookie.Cookie} cookie
   * @param {function():void} callback
   */
  _deleteCookie(cookie, callback) {
    this._model.deleteCookie(cookie).then(callback);
  }

  /**
   * @param {!Array<!SDK.Cookie.Cookie>} allCookies
   */
  _updateWithCookies(allCookies) {
    this._allCookies = allCookies;
    this._totalSize = allCookies.reduce((size, cookie) => size + cookie.size(), 0);

    const parsedURL = Common.ParsedURL.ParsedURL.fromString(this._cookieDomain);
    const host = parsedURL ? parsedURL.host : '';
    this._cookiesTable.setCookieDomain(host);

    this._shownCookies = this.filter(allCookies, cookie => `${cookie.name()} ${cookie.value()} ${cookie.domain()}`);
    if (this.hasFilter()) {
      this.setDeleteAllTitle(ls`Clear filtered cookies`);
      this.setDeleteAllGlyph('largeicon-delete-filter');
    } else {
      this.setDeleteAllTitle(ls`Clear all cookies`);
      this.setDeleteAllGlyph('largeicon-delete-list');
    }
    this._cookiesTable.setCookies(this._shownCookies, this._model.getCookieToBlockedReasonsMap());
    UI.ARIAUtils.alert(ls`Number of cookies shown in table: ${this._shownCookies.length}`, this.element);
    this.setCanFilter(true);
    this.setCanDeleteAll(this._shownCookies.length > 0);
    this.setCanDeleteSelected(!!this._cookiesTable.selectedCookie());
  }

  /**
   * @override
   * @template T
   * @param {!Array<!T>} items
   * @param {function(!T): string} keyFunction
   * @return {!Array<!T>}
   * @protected
   */
  filter(items, keyFunction) {
    /** @param {T|null} object */
    const predicate = object => {
      if (!this._onlyIssuesFilterUI.checked()) {
        return true;
      }
      if (object instanceof SDK.Cookie.Cookie) {
        return BrowserSDK.RelatedIssue.hasIssues(object);
      }
      return false;
    };
    return super.filter(items, keyFunction).filter(predicate);
  }

  /**
   * This will only delete the currently visible cookies.
   *
   * @override
   */
  deleteAllItems() {
    this._showPreview(null);
    this._model.deleteCookies(this._shownCookies).then(() => this.refreshItems());
  }

  /**
   * @override
   */
  deleteSelectedItem() {
    const selectedCookie = this._cookiesTable.selectedCookie();
    if (selectedCookie) {
      this._showPreview(null);
      this._model.deleteCookie(selectedCookie).then(() => this.refreshItems());
    }
  }

  /**
   * @override
   */
  refreshItems() {
    this._model.getCookiesForDomain(this._cookieDomain).then(this._updateWithCookies.bind(this));
  }

  refreshItemsThrottled() {
    this._refreshThrottler.schedule(() => Promise.resolve(this.refreshItems()));
  }

  _onResponseReceived() {
    this.refreshItemsThrottled();
  }

  _onLoadingFinished() {
    this.refreshItemsThrottled();
  }
}
<commit_msg>Keep currently selected cookie preview visible while changing domains<commit_after>/*
 * Copyright (C) 2009 Apple Inc.  All rights reserved.
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import * as BrowserSDK from '../browser_sdk/browser_sdk.js';
import * as Common from '../common/common.js';
import * as CookieTable from '../cookie_table/cookie_table.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

import {StorageItemsView} from './StorageItemsView.js';

class CookiePreviewWidget extends UI.Widget.VBox {
  constructor() {
    super();
    this.setMinimumSize(230, 45);
    /** @type {?SDK.Cookie.Cookie} cookie */
    this._cookie = null;
    this._showDecodedSetting = Common.Settings.Settings.instance().createSetting('cookieViewShowDecoded', false);

    const header = document.createElement('div');
    header.classList.add('cookie-preview-widget-header');
    const span = document.createElement('span');
    span.classList.add('cookie-preview-widget-header-label');
    span.textContent = 'Cookie Value';
    header.appendChild(span);
    this.contentElement.appendChild(header);

    const toggle = UI.UIUtils.CheckboxLabel.create(ls`Show URL decoded`, this._showDecodedSetting.get());
    toggle.classList.add('cookie-preview-widget-toggle');
    toggle.checkboxElement.addEventListener('click', () => this.showDecoded(!this._showDecodedSetting.get()));
    header.appendChild(toggle);
    this._toggle = toggle;

    const value = document.createElement('div');
    value.classList.add('cookie-preview-widget-cookie-value');
    value.textContent = '';
    value.addEventListener('dblclick', this.handleDblClickOnCookieValue.bind(this));
    this._value = value;

    this.contentElement.classList.add('cookie-preview-widget');
    this.contentElement.appendChild(value);
  }

  /**
   *
   * @param {boolean} decoded
   */
  showDecoded(decoded) {
    if (!this._cookie) {
      return;
    }
    this._showDecodedSetting.set(decoded);
    this._toggle.checkboxElement.checked = decoded;
    this._updatePreview();
  }

  _updatePreview() {
    if (this._cookie) {
      this._value.textContent =
          this._showDecodedSetting.get() ? decodeURIComponent(this._cookie.value()) : this._cookie.value();
    } else {
      this._value.textContent = '';
    }
  }

  /**
   * @param {!SDK.Cookie.Cookie} cookie
   */
  setCookie(cookie) {
    this._cookie = cookie;
    this._updatePreview();
  }

  /**
   * Select all text even if there a spaces in it
   * @param {!Event} event
   */
  handleDblClickOnCookieValue(event) {
    event.preventDefault();
    const range = document.createRange();
    range.selectNode(this._value);
    const selection = window.getSelection();
    if (!selection) {
      return;
    }
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

export class CookieItemsView extends StorageItemsView {
  /**
   * @param {!SDK.CookieModel.CookieModel} model
   * @param {string} cookieDomain
   */
  constructor(model, cookieDomain) {
    super(Common.UIString.UIString('Cookies'), 'cookiesPanel');

    this.registerRequiredCSS('resources/cookieItemsView.css', {enableLegacyPatching: false});
    this.element.classList.add('storage-view');

    /** @type {!SDK.CookieModel.CookieModel} */
    this._model = model;
    this._cookieDomain = cookieDomain;

    this._totalSize = 0;
    /** @type {!CookieTable.CookiesTable.CookiesTable} */
    this._cookiesTable = new CookieTable.CookiesTable.CookiesTable(
        /* renderInline */ false, this._saveCookie.bind(this), this.refreshItems.bind(this),
        this._handleCookieSelected.bind(this), this._deleteCookie.bind(this));

    this._cookiesTable.setMinimumSize(0, 50);

    this._splitWidget = new UI.SplitWidget.SplitWidget(
        /* isVertical: */ false, /* secondIsSidebar: */ true, 'cookieItemsSplitViewState');
    this._splitWidget.show(this.element);

    this._previewPanel = new UI.Widget.VBox();
    const resizer = this._previewPanel.element.createChild('div', 'preview-panel-resizer');

    this._splitWidget.setMainWidget(this._cookiesTable);
    this._splitWidget.setSidebarWidget(this._previewPanel);
    this._splitWidget.installResizer(resizer);

    this._previewWidget = new CookiePreviewWidget();
    this._emptyWidget = new UI.EmptyWidget.EmptyWidget(ls`Select a cookie to preview its value`);
    this._emptyWidget.show(this._previewPanel.contentElement);

    this._onlyIssuesFilterUI = new UI.Toolbar.ToolbarCheckbox(
        ls`Only show cookies with an issue`, ls`Only show cookies which have an associated issue`, () => {
          this._updateWithCookies(this._allCookies);
        });
    this.appendToolbarItem(this._onlyIssuesFilterUI);

    this._refreshThrottler = new Common.Throttler.Throttler(300);
    /** @type {!Array<!Common.EventTarget.EventDescriptor>} */
    this._eventDescriptors = [];

    /** @type {!Array<!SDK.Cookie.Cookie>} */
    this._allCookies = [];
    /** @type {!Array<!SDK.Cookie.Cookie>} */
    this._shownCookies = [];
    /** @type {?SDK.Cookie.Cookie} */
    this._selectedCookie = null;

    this.setCookiesDomain(model, cookieDomain);
  }

  /**
   * @param {!SDK.CookieModel.CookieModel} model
   * @param {string} domain
   */
  setCookiesDomain(model, domain) {
    this._model = model;
    this._cookieDomain = domain;
    this.refreshItems();
    Common.EventTarget.EventTarget.removeEventListeners(this._eventDescriptors);
    const networkManager = model.target().model(SDK.NetworkManager.NetworkManager);
    if (networkManager) {
      this._eventDescriptors = [
        networkManager.addEventListener(SDK.NetworkManager.Events.ResponseReceived, this._onResponseReceived, this),
        networkManager.addEventListener(SDK.NetworkManager.Events.LoadingFinished, this._onLoadingFinished, this),
      ];
    }
  }

  /**
   * @param {?SDK.Cookie.Cookie} cookie
   */
  _showPreview(cookie) {
    if (cookie === this._selectedCookie) {
      return;
    }
    this._selectedCookie = cookie;

    if (!cookie) {
      this._previewWidget.detach();
      this._emptyWidget.show(this._previewPanel.contentElement);
    } else {
      this._emptyWidget.detach();
      this._previewWidget.setCookie(cookie);
      this._previewWidget.show(this._previewPanel.contentElement);
    }
  }

  _handleCookieSelected() {
    const cookie = this._cookiesTable.selectedCookie();
    this.setCanDeleteSelected(!!cookie);

    this._showPreview(cookie);
  }

  /**
   * @param {!SDK.Cookie.Cookie} newCookie
   * @param {?SDK.Cookie.Cookie} oldCookie
   * @return {!Promise<boolean>}
   */
  async _saveCookie(newCookie, oldCookie) {
    if (oldCookie && newCookie.key() !== oldCookie.key()) {
      await this._model.deleteCookie(oldCookie);
    }
    return this._model.saveCookie(newCookie);
  }

  /**
   * @param {!SDK.Cookie.Cookie} cookie
   * @param {function():void} callback
   */
  _deleteCookie(cookie, callback) {
    this._model.deleteCookie(cookie).then(callback);
  }

  /**
   * @param {!Array<!SDK.Cookie.Cookie>} allCookies
   */
  _updateWithCookies(allCookies) {
    this._allCookies = allCookies;
    this._totalSize = allCookies.reduce((size, cookie) => size + cookie.size(), 0);

    const parsedURL = Common.ParsedURL.ParsedURL.fromString(this._cookieDomain);
    const host = parsedURL ? parsedURL.host : '';
    this._cookiesTable.setCookieDomain(host);

    this._shownCookies = this.filter(allCookies, cookie => `${cookie.name()} ${cookie.value()} ${cookie.domain()}`);
    if (this.hasFilter()) {
      this.setDeleteAllTitle(ls`Clear filtered cookies`);
      this.setDeleteAllGlyph('largeicon-delete-filter');
    } else {
      this.setDeleteAllTitle(ls`Clear all cookies`);
      this.setDeleteAllGlyph('largeicon-delete-list');
    }
    this._cookiesTable.setCookies(this._shownCookies, this._model.getCookieToBlockedReasonsMap());
    UI.ARIAUtils.alert(ls`Number of cookies shown in table: ${this._shownCookies.length}`, this.element);
    this.setCanFilter(true);
    this.setCanDeleteAll(this._shownCookies.length > 0);
    this.setCanDeleteSelected(!!this._cookiesTable.selectedCookie());

    if (!this._cookiesTable.selectedCookie()) {
      this._showPreview(null);
    }
  }

  /**
   * @override
   * @template T
   * @param {!Array<!T>} items
   * @param {function(!T): string} keyFunction
   * @return {!Array<!T>}
   * @protected
   */
  filter(items, keyFunction) {
    /** @param {T|null} object */
    const predicate = object => {
      if (!this._onlyIssuesFilterUI.checked()) {
        return true;
      }
      if (object instanceof SDK.Cookie.Cookie) {
        return BrowserSDK.RelatedIssue.hasIssues(object);
      }
      return false;
    };
    return super.filter(items, keyFunction).filter(predicate);
  }

  /**
   * This will only delete the currently visible cookies.
   *
   * @override
   */
  deleteAllItems() {
    this._showPreview(null);
    this._model.deleteCookies(this._shownCookies).then(() => this.refreshItems());
  }

  /**
   * @override
   */
  deleteSelectedItem() {
    const selectedCookie = this._cookiesTable.selectedCookie();
    if (selectedCookie) {
      this._showPreview(null);
      this._model.deleteCookie(selectedCookie).then(() => this.refreshItems());
    }
  }

  /**
   * @override
   */
  refreshItems() {
    this._model.getCookiesForDomain(this._cookieDomain).then(this._updateWithCookies.bind(this));
  }

  refreshItemsThrottled() {
    this._refreshThrottler.schedule(() => Promise.resolve(this.refreshItems()));
  }

  _onResponseReceived() {
    this.refreshItemsThrottled();
  }

  _onLoadingFinished() {
    this.refreshItemsThrottled();
  }
}
<|endoftext|>


<commit_before>define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
"use strict";

exports.isDark = false;
exports.cssClass = "ace-tm";
exports.cssText = ".ace-tm .ace_gutter {\
background: #f0f0f0;\
color: #333;\
}\
.ace-tm .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-tm .ace_fold {\
background-color: #6B72E6;\
}\
.ace-tm {\
background-color: #FFFFFF;\
color: black;\
}\
.ace-tm .ace_cursor {\
color: black;\
}\
.ace-tm .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-tm .ace_storage,\
.ace-tm .ace_keyword {\
color: blue;\
}\
.ace-tm .ace_constant {\
color: rgb(197, 6, 11);\
}\
.ace-tm .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-tm .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-tm .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_invalid {\
background-color: rgba(255, 0, 0, 0.1);\
color: red;\
}\
.ace-tm .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-tm .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_support.ace_type,\
.ace-tm .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
.ace-tm .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-tm .ace_string {\
color: rgb(3, 106, 7);\
}\
.ace-tm .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-tm .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-tm .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-tm .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-tm .ace_variable {\
color: rgb(49, 132, 149);\
}\
.ace-tm .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-tm .ace_entity.ace_name.ace_function {\
color: #0000A2;\
}\
.ace-tm .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-tm .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-tm .ace_meta.ace_tag {\
color:rgb(0, 22, 142);\
}\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-tm.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px white;\
}\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-tm .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-tm .ace_gutter-active-line {\
background-color : #dcdcdc;\
}\
.ace-tm .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-tm .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}\
";

var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});

define("ace/ext/textarea",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/net","ace/ace","ace/theme/textmate"], function(require, exports, module) {
"use strict";

var event = require("../lib/event");
var UA = require("../lib/useragent");
var net = require("../lib/net");
var ace = require("../ace");

require("../theme/textmate");

module.exports = exports = ace;
var getCSSProperty = function(element, container, property) {
    var ret = element.style[property];

    if (!ret) {
        if (window.getComputedStyle) {
            ret = window.getComputedStyle(element, '').getPropertyValue(property);
        } else {
            ret = element.currentStyle[property];
        }
    }

    if (!ret || ret == 'auto' || ret == 'intrinsic') {
        ret = container.style[property];
    }
    return ret;
};

function applyStyles(elm, styles) {
    for (var style in styles) {
        elm.style[style] = styles[style];
    }
}

function setupContainer(element, getValue) {
    if (element.type != 'textarea') {
        throw new Error("Textarea required!");
    }

    var parentNode = element.parentNode;
    var container = document.createElement('div');
    var resizeEvent = function() {
        var style = 'position:relative;';
        [
            'margin-top', 'margin-left', 'margin-right', 'margin-bottom'
        ].forEach(function(item) {
            style += item + ':' +
                        getCSSProperty(element, container, item) + ';';
        });
        var width = getCSSProperty(element, container, 'width') || (element.clientWidth + "px");
        var height = getCSSProperty(element, container, 'height')  || (element.clientHeight + "px");
        style += 'height:' + height + ';width:' + width + ';';
        style += 'display:inline-block;';
        container.setAttribute('style', style);
    };
    event.addListener(window, 'resize', resizeEvent);
    resizeEvent();
    parentNode.insertBefore(container, element.nextSibling);
    while (parentNode !== document) {
        if (parentNode.tagName.toUpperCase() === 'FORM') {
            var oldSumit = parentNode.onsubmit;
            parentNode.onsubmit = function(evt) {
                element.value = getValue();
                if (oldSumit) {
                    oldSumit.call(this, evt);
                }
            };
            break;
        }
        parentNode = parentNode.parentNode;
    }
    return container;
}

exports.transformTextarea = function(element, options) {
    var session;
    var container = setupContainer(element, function() {
        return session.getValue();
    });
    element.style.display = 'none';
    container.style.background = 'white';
    var editorDiv = document.createElement("div");
    applyStyles(editorDiv, {
        top: "0px",
        left: "0px",
        right: "0px",
        bottom: "0px",
        border: "1px solid gray",
        position: "absolute"
    });
    container.appendChild(editorDiv);

    var settingOpener = document.createElement("div");
    applyStyles(settingOpener, {
        position: "absolute",
        right: "0px",
        bottom: "0px",
        background: "red",
        cursor: "nw-resize",
        borderStyle: "solid",
        borderWidth: "9px 8px 10px 9px",
        width: "2px",
        borderColor: "lightblue gray gray lightblue",
        zIndex: 101
    });

    var settingDiv = document.createElement("div");
    var settingDivStyles = {
        top: "0px",
        left: "20%",
        right: "0px",
        bottom: "0px",
        position: "absolute",
        padding: "5px",
        zIndex: 100,
        color: "white",
        display: "none",
        overflow: "auto",
        fontSize: "14px",
        boxShadow: "-5px 2px 3px gray"
    };
    if (!UA.isOldIE) {
        settingDivStyles.backgroundColor = "rgba(0, 0, 0, 0.6)";
    } else {
        settingDivStyles.backgroundColor = "#333";
    }

    applyStyles(settingDiv, settingDivStyles);
    container.appendChild(settingDiv);

    options = options || exports.defaultOptions;
    var editor = ace.edit(editorDiv);
    session = editor.getSession();

    session.setValue(element.value || element.innerHTML);
    editor.focus();
    container.appendChild(settingOpener);
    setupApi(editor, editorDiv, settingDiv, ace, options, load);
    setupSettingPanel(settingDiv, settingOpener, editor);

    var state = "";
    event.addListener(settingOpener, "mousemove", function(e) {
        var rect = this.getBoundingClientRect();
        var x = e.clientX - rect.left, y = e.clientY - rect.top;
        if (x + y < (rect.width + rect.height)/2) {
            this.style.cursor = "pointer";
            state = "toggle";
        } else {
            state = "resize";
            this.style.cursor = "nw-resize";
        }
    });

    event.addListener(settingOpener, "mousedown", function(e) {
        if (state == "toggle") {
            editor.setDisplaySettings();
            return;
        }
        container.style.zIndex = 100000;
        var rect = container.getBoundingClientRect();
        var startX = rect.width  + rect.left - e.clientX;
        var startY = rect.height  + rect.top - e.clientY;
        event.capture(settingOpener, function(e) {
            container.style.width = e.clientX - rect.left + startX + "px";
            container.style.height = e.clientY - rect.top + startY + "px";
            editor.resize();
        }, function() {});
    });

    return editor;
};

function load(url, module, callback) {
    net.loadScript(url, function() {
        require([module], callback);
    });
}

function setupApi(editor, editorDiv, settingDiv, ace, options, loader) {
    var session = editor.getSession();
    var renderer = editor.renderer;
    loader = loader || load;

    function toBool(value) {
        return value === "true" || value == true;
    }

    editor.setDisplaySettings = function(display) {
        if (display == null)
            display = settingDiv.style.display == "none";
        if (display) {
            settingDiv.style.display = "block";
            settingDiv.hideButton.focus();
            editor.on("focus", function onFocus() {
                editor.removeListener("focus", onFocus);
                settingDiv.style.display = "none";
            });
        } else {
            editor.focus();
        }
    };

    editor.$setOption = editor.setOption;
    editor.$getOption = editor.getOption;
    editor.setOption = function(key, value) {
        switch (key) {
            case "mode":
                editor.$setOption("mode", "ace/mode/" + value)
            break;
            case "theme":
                editor.$setOption("theme", "ace/theme/" + value)
            break;
            case "keybindings":
                switch (value) {
                    case "vim":
                        editor.setKeyboardHandler("ace/keyboard/vim");
                        break;
                    case "emacs":
                        editor.setKeyboardHandler("ace/keyboard/emacs");
                        break;
                    default:
                        editor.setKeyboardHandler(null);
                }
            break;

            case "softWrap":
            case "fontSize":
                editor.$setOption(key, value);
            break;

            default:
                editor.$setOption(key, toBool(value));
        }
    };

    editor.getOption = function(key) {
        switch (key) {
            case "mode":
                return editor.$getOption("mode").substr("ace/mode/".length)
            break;

            case "theme":
                return editor.$getOption("theme").substr("ace/theme/".length)
            break;

            case "keybindings":
                var value = editor.getKeyboardHandler()
                switch (value && value.$id) {
                    case "ace/keyboard/vim":
                        return "vim";
                    case "ace/keyboard/emacs":
                        return "emacs";
                    default:
                        return "ace";
                }
            break;

            default:
                return editor.$getOption(key);
        }
    };

    editor.setOptions(options);
    return editor;
}

function setupSettingPanel(settingDiv, settingOpener, editor) {
    var BOOL = null;

    var desc = {
        mode:            "Mode:",
        wrap:            "Soft Wrap:",
        theme:           "Theme:",
        fontSize:        "Font Size:",
        showGutter:      "Display Gutter:",
        keybindings:     "Keyboard",
        showPrintMargin: "Show Print Margin:",
        useSoftTabs:     "Use Soft Tabs:",
        showInvisibles:  "Show Invisibles"
    };

    var optionValues = {
        mode: {
            text:       "Plain",
            javascript: "JavaScript",
            xml:        "XML",
            html:       "HTML",
            css:        "CSS",
            scss:       "SCSS",
            python:     "Python",
            php:        "PHP",
            java:       "Java",
            ruby:       "Ruby",
            c_cpp:      "C/C++",
            coffee:     "CoffeeScript",
            json:       "json",
            perl:       "Perl",
            clojure:    "Clojure",
            ocaml:      "OCaml",
            csharp:     "C#",
            haxe:       "haXe",
            svg:        "SVG",
            textile:    "Textile",
            groovy:     "Groovy",
            liquid:     "Liquid",
            Scala:      "Scala"
        },
        theme: {
            clouds:           "Clouds",
            clouds_midnight:  "Clouds Midnight",
            cobalt:           "Cobalt",
            crimson_editor:   "Crimson Editor",
            dawn:             "Dawn",
            eclipse:          "Eclipse",
            idle_fingers:     "Idle Fingers",
            kr_theme:         "Kr Theme",
            merbivore:        "Merbivore",
            merbivore_soft:   "Merbivore Soft",
            mono_industrial:  "Mono Industrial",
            monokai:          "Monokai",
            pastel_on_dark:   "Pastel On Dark",
            solarized_dark:   "Solarized Dark",
            solarized_light:  "Solarized Light",
            textmate:         "Textmate",
            twilight:         "Twilight",
            vibrant_ink:      "Vibrant Ink"
        },
        showGutter: BOOL,
        fontSize: {
            "10px": "10px",
            "11px": "11px",
            "12px": "12px",
            "14px": "14px",
            "16px": "16px"
        },
        wrap: {
            off:    "Off",
            40:     "40",
            80:     "80",
            free:   "Free"
        },
        keybindings: {
            ace: "ace",
            vim: "vim",
            emacs: "emacs"
        },
        showPrintMargin:    BOOL,
        useSoftTabs:        BOOL,
        showInvisibles:     BOOL
    };

    var table = [];
    table.push("

Setting	Value
");

    function renderOption(builder, option, obj, cValue) {
        if (!obj) {
            builder.push(
                "<input type='checkbox' title='", option, "' ",
                    cValue + "" == "true" ? "checked='true'" : "",
               "'></input>"
            );
            return;
        }
        builder.push("<select title='" + option + "'>");
        for (var value in obj) {
            builder.push("<option value='" + value + "' ");

            if (cValue == value) {
                builder.push(" selected ");
            }

            builder.push(">",
                obj[value],
                "</option>");
        }
        builder.push("</select>");
    }

    for (var option in exports.defaultOptions) {
        table.push("
", desc[option], "	");
        table.push("");
        renderOption(table, option, optionValues[option], editor.getOption(option));
        table.push("
");
    }
    table.push("
");
    settingDiv.innerHTML = table.join("");

    var onChange = function(e) {
        var select = e.currentTarget;
        editor.setOption(select.title, select.value);
    };
    var onClick = function(e) {
        var cb = e.currentTarget;
        editor.setOption(cb.title, cb.checked);
    };
    var selects = settingDiv.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++)
        selects[i].onchange = onChange;
    var cbs = settingDiv.getElementsByTagName("input");
    for (var i = 0; i < cbs.length; i++)
        cbs[i].onclick = onClick;

    var button = document.createElement("input");
    button.type = "button";
    button.value = "Hide";
    event.addListener(button, "click", function() {
        editor.setDisplaySettings(false);
    });
    settingDiv.appendChild(button);
    settingDiv.hideButton = button;
}
exports.defaultOptions = {
    mode:               "javascript",
    theme:              "textmate",
    wrap:               "off",
    fontSize:           "12px",
    showGutter:         "false",
    keybindings:        "ace",
    showPrintMargin:    "false",
    useSoftTabs:        "true",
    showInvisibles:     "false"
};

});
                (function() {
                    window.require(["ace/ext/textarea"], function() {});
                })();
            <commit_msg>Update public/libs/bower_components/ace-builds/src/ext-textarea.js<commit_after><|endoftext|>