<commit_before>/* globals jQuery, window, document */

(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownStyle);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);

          // Create the option
          var $option = $("

");

          // Style the option
          $option.addClass(options.optionStyle);

          // If the option has some text then transfer it
          if ($this.text()) {
            $option.text($this.text());
          }
          // Otherwise set the empty label and set it as an empty option
          else {
            $option.html(" ");
          }
          // Set the value of the option
          $option.attr("value", $this.val());

          // Ss it selected?
          if ($this.attr("selected")) {
            $option.attr("selected", true);
          }

          // Append option to our dropdown
          $ul.append($option);
        });

        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
          var $selected;
          if ($ul.find("[selected]").length) {
            $selected = $ul.find("[selected]").last();
          }
          else {
            $selected = $ul.find("li").first();
          }
          methods._select($dropdown, $selected);
        } else {
          methods._select($dropdown, $ul.find("[selected]"));
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        selectOptions.on("click", function(e) {
          methods._select($dropdown, $(this));
        });
        selectOptions.on("keydown", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32) {
            methods._select($dropdown, $(this));
            return false;
          }
        });

        selectOptions.on("focus", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          selectOptions.each(function() { $(this).attr("tabindex", 0); });

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        $(document).on("click", function() {
          $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if ($this.is("select") && $this.is(options.autoinit)) {
            initElement($this);
          }
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {
      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input");

      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        var $selected = $select.find("[value=\"" + $target.attr("value") + "\"]");
        if ($selected.attr("selected")) {
          $selected.attr("selected", true);
        } else {
          $selected.attr("selected", false);
        }
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        // Unselect options except the one that will be selected
        selectOptions.not($target).removeClass("selected");
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

    }
  };

  $.fn.dropdown = function(params) {
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

})(jQuery);
<commit_msg>Listen to original "change" event<commit_after>/* globals jQuery, window, document */

(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownStyle);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);

          // Create the option
          var $option = $("

");

          // Style the option
          $option.addClass(options.optionStyle);

          // If the option has some text then transfer it
          if ($this.text()) {
            $option.text($this.text());
          }
          // Otherwise set the empty label and set it as an empty option
          else {
            $option.html(" ");
          }
          // Set the value of the option
          $option.attr("value", $this.val());

          // Ss it selected?
          if ($this.attr("selected")) {
            $option.attr("selected", true);
          }

          // Append option to our dropdown
          $ul.append($option);
        });

        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
          var $selected;
          if ($ul.find("[selected]").length) {
            $selected = $ul.find("[selected]").last();
          }
          else {
            $selected = $ul.find("li").first();
          }
          methods._select($dropdown, $selected);
        } else {
          methods._select($dropdown, $ul.find("[selected]"));
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        selectOptions.on("click", function(e) {
          methods._select($dropdown, $(this));
          // trigger change event, if declared on the original selector
          $select.change();
        });
        selectOptions.on("keydown", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32) {
            methods._select($dropdown, $(this));
            return false;
          }
        });

        selectOptions.on("focus", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          selectOptions.each(function() { $(this).attr("tabindex", 0); });

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        $(document).on("click", function() {
          $(".dropdownjs > ul > li").each(function() { $(this).attr("tabindex", -1); });
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if ($this.is("select") && $this.is(options.autoinit)) {
            initElement($this);
          }
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {
      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input");

      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        var $selected = $select.find("[value=\"" + $target.attr("value") + "\"]");
        if ($selected.attr("selected")) {
          $selected.attr("selected", true);
        } else {
          $selected.attr("selected", false);
        }
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        // Unselect options except the one that will be selected
        selectOptions.not($target).removeClass("selected");
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

    }
  };

  $.fn.dropdown = function(params) {
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

})(jQuery);
<|endoftext|>


<commit_before>import MobxReactForm from 'mobx-react-form';
import validatorjs from 'validatorjs';

const plugins = { dvr: validatorjs };

const fields = [
    'title',
    'lines',
    'lines[]'
];

const labels = {
    'title': 'Title',
    'lines': 'New lines',
    'lines[]': 'New line'
};

const placeholders = {
    'title': 'Title',
    'lines[]': 'New line'
};

const rules = {
    'title': 'required|string|between:1,140',
    'lines': 'required|array|between:1,10',
    'lines[]': 'required|string|between:1,140'
};

class ListForm extends MobxReactForm {

    constructor(settings, { plugins }, onSuccessCallback) {
        super(settings, { plugins });
        this.onSuccessCallback = onSuccessCallback;
    }

    errorMessages = [];

    onSuccess(form) {
        this.errorMessages = [];
        let requestData = form.values();

        this.onSuccessCallback(requestData);
    }

    onError(form) {
        this.errorMessages = [];
        if(form.errors().title) {
            if(form.errors().title === "The Title field is required.") {
                this.errorMessages.push(form.errors().title);//Don't do anything, this message is fine.
            } else if(form.errors().title === "The Title field must be between 1 and 140.") {
                this.errorMessages.push(`The Title must be between 1 and 140 characters.`);
            } else {
                this.errorMessages.push(`Error at title: ${form.errors().title}`);
            }
        }
        form.errors().lines.forEach((lineError, index) => {
            if(lineError) {
                if(lineError === "The New line field is required.") {
                    this.errorMessages.push(`Line ${index} can't be empty.`);
                } else if(lineError === "The New line field must be between 1 and 140.") {
                    this.errorMessages.push(`Line ${index} must be between 1 and 140 characters.`);
                } else {
                    this.errorMessages.push(`Error at line ${index}: ${lineError}`);
                }
            }
        });
        form.invalidate('There were errors with your submission.');
    }
}

export const createListFormWithInitialState = (values, onSuccessCallback) =>
    new ListForm({ fields, values, labels, placeholders, rules}, { plugins }, onSuccessCallback);

export const createEmptyListForm = (onSuccessCallback) =>
    createListFormWithInitialState({ 'lines': [''] }, onSuccessCallback);<commit_msg>not sure if that needed to be a string at some point or not<commit_after>import MobxReactForm from 'mobx-react-form';
import validatorjs from 'validatorjs';

const plugins = { dvr: validatorjs };

const fields = [
    'title',
    'lines',
    'lines[]'
];

const labels = {
    'title': 'Title',
    'lines': 'New lines',
    'lines[]': 'New line'
};

const placeholders = {
    'title': 'Title',
    'lines[]': 'New line'
};

const rules = {
    'title': 'required|string|between:1,140',
    'lines': 'required|array|between:1,10',
    'lines[]': 'required|string|between:1,140'
};

class ListForm extends MobxReactForm {

    constructor(settings, { plugins }, onSuccessCallback) {
        super(settings, { plugins });
        this.onSuccessCallback = onSuccessCallback;
    }

    errorMessages = [];

    onSuccess(form) {
        this.errorMessages = [];
        let requestData = form.values();

        this.onSuccessCallback(requestData);
    }

    onError(form) {
        this.errorMessages = [];
        if(form.errors().title) {
            if(form.errors().title === "The Title field is required.") {
                this.errorMessages.push(form.errors().title);//Don't do anything, this message is fine.
            } else if(form.errors().title === "The Title field must be between 1 and 140.") {
                this.errorMessages.push(`The Title must be between 1 and 140 characters.`);
            } else {
                this.errorMessages.push(`Error at title: ${form.errors().title}`);
            }
        }
        form.errors().lines.forEach((lineError, index) => {
            if(lineError) {
                if(lineError === "The New line field is required.") {
                    this.errorMessages.push(`Line ${index} can't be empty.`);
                } else if(lineError === "The New line field must be between 1 and 140.") {
                    this.errorMessages.push(`Line ${index} must be between 1 and 140 characters.`);
                } else {
                    this.errorMessages.push(`Error at line ${index}: ${lineError}`);
                }
            }
        });
        form.invalidate('There were errors with your submission.');
    }
}

export const createListFormWithInitialState = (values, onSuccessCallback) =>
    new ListForm({ fields, values, labels, placeholders, rules}, { plugins }, onSuccessCallback);

export const createEmptyListForm = (onSuccessCallback) =>
    createListFormWithInitialState({ lines: [''] }, onSuccessCallback);<|endoftext|>


<commit_before>//This server is here, because we need to go up a directory from the test site for some resources.
var connect = require('connect');
connect.createServer(
    connect.static(__dirname)
).listen(3000);<commit_msg>Add logging to the test server.<commit_after>//This server is here, because we need to go up a directory from the test site for some resources.
var connect = require('connect'), http = require('http');

var app = connect()
    .use(connect.logger('short'))
    .use(connect.static(__dirname));

http.createServer(app).listen(3000);
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const help = `
Usage: checkmydeps [options] [path]
    path  The path of the target node module to check. Uses current directory if
          no path is provided.

Options:
    --hide-up-to-date  Prevents the display of up-to-date dependencies.
    --github-token     Defines the GitHub token to use to access private github
                       repositories. The token must have "repo" capability (check
                       your GitHub settings, section "Personal access tokens").
    -h, --help         Shows this description.`;

// -----------------------------------------------------------------------------
// PROGRAM
// -----------------------------------------------------------------------------

const minimist    = require('minimist');
const semver      = require('semver');
const suspend     = require('suspend');
const checkmydeps = require('../lib/checkmydeps');
const utils       = require('../lib/utils');
const $$          = suspend.resume;

const args         = minimist(process.argv.slice(2));
const modulePath   = args._[0] || '.';
const hideUpToDate = args['hide-up-to-date'];
const githubToken  = args['github-token'] || process.env.GITHUB_TOKEN;
const showHelp     = args.h || args.help;

if (showHelp) {
  console.log(help.trim());
  process.exit(0);
  return;
}

suspend.run(function* () {

  yield* checkForUpdate();

  const result = yield checkmydeps(modulePath, { githubToken }, $$());
  const report = createReport(result);
  console.log(report);

}, err => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
});

// -----------------------------------------------------------------------------
// REPORT CREATION
// -----------------------------------------------------------------------------

function createReport(deps) {
  let report = '';

  if (deps.ok.length && !hideUpToDate) {
    report += '\nUP-TO-DATE\n';
    report += '--------------------------------------------------------------------------------\n';

    for (const { name, found, needs, type } of deps.ok) {
      let needs2 = needs;
      if (type === 'github') { needs2 += ' (on github)'; }

      report += `${name}|needs ${needs2}|found ${found}\n`;
    }
  }

  if (deps.nok.length) {
    report += '\nOUTDATED\n';
    report += '--------------------------------------------------------------------------------\n';

    for (const { name, found, needs, type } of deps.nok) {
      let needs2 = needs;
      if (type === 'github') { needs2 += ' (on github)'; }

      report += `${name}|needs ${needs2}|found ${found}\n`;
    }
  } else {
    report += '\nAll dependencies are up-to-date!';
  }

  return formatTable(report.trim());
}

function formatTable(text) {
  const lines       = text.split('\n');
  let maxLenghtCol1 = 0;
  let maxLenghtCol2 = 0;

  for (const line of lines) {
    const idxSeparator1 = line.indexOf('|');
    if (idxSeparator1 === -1) { continue; }
    maxLenghtCol1 = Math.max(maxLenghtCol1, idxSeparator1);

    const idxSeparator2 = line.indexOf('|', idxSeparator1 + 1);
    if (idxSeparator2 === -1) { continue; }
    maxLenghtCol2 = Math.max(maxLenghtCol2, idxSeparator2 - idxSeparator1 - 1);
  }

  for (let i = 0; i < lines.length; ++i) {
    const parts = lines[i].split('|');
    if (parts.length !== 3) { continue; }

    const filler1 = new Array(maxLenghtCol1 - parts[0].length + 1).join(' ');
    const filler2 = new Array(maxLenghtCol2 - parts[1].length + 1).join(' ');

    lines[i] = parts[0] + filler1 + ' | ' + parts[1] + filler2 + ' | ' + parts[2];
  }

  return lines.join('\n');
}

// -----------------------------------------------------------------------------
// CHECK FOR UPDATE
// -----------------------------------------------------------------------------

function* checkForUpdate() {
  const content        = yield utils.downloadGithubPackage('AurelienRibon/node-checkmydeps', null, $$());
  const latestVersion  = content.version;
  const currentVersion = require('../package.json').version;

  if (semver.gt(latestVersion, currentVersion)) {
    const tty        = process.stdout.isTTY;
    const colorStart = tty ? '\u001b[31;1m' : '';
    const colorEnd   = tty ? '\u001b[0m' : '';

    const msg = `${colorStart}Version ${latestVersion} is available, current is ${currentVersion}, please update.${colorEnd}\n`;
    console.log(msg);
  }
}
<commit_msg>Move report table creation to a function<commit_after>#!/usr/bin/env node
'use strict';

const help = `
Usage: checkmydeps [options] [path]
    path  The path of the target node module to check. Uses current directory if
          no path is provided.

Options:
    --hide-up-to-date  Prevents the display of up-to-date dependencies.
    --github-token     Defines the GitHub token to use to access private github
                       repositories. The token must have "repo" capability (check
                       your GitHub settings, section "Personal access tokens").
    -h, --help         Shows this description.`;

// -----------------------------------------------------------------------------
// PROGRAM
// -----------------------------------------------------------------------------

const minimist    = require('minimist');
const semver      = require('semver');
const suspend     = require('suspend');
const checkmydeps = require('../lib/checkmydeps');
const utils       = require('../lib/utils');
const $$          = suspend.resume;

const args         = minimist(process.argv.slice(2));
const modulePath   = args._[0] || '.';
const hideUpToDate = args['hide-up-to-date'];
const githubToken  = args['github-token'] || process.env.GITHUB_TOKEN;
const showHelp     = args.h || args.help;

if (showHelp) {
  console.log(help.trim());
  process.exit(0);
  return;
}

suspend.run(function* () {

  yield* checkForUpdate();

  const result = yield checkmydeps(modulePath, { githubToken }, $$());
  const report = createReport(result);
  console.log(report);

}, err => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
});

// -----------------------------------------------------------------------------
// REPORT CREATION
// -----------------------------------------------------------------------------

function createReport(result) {
  let report = '';

  if (result.ok.length && !hideUpToDate) {
    report += createTable(result.ok, 'UP-TO-DATE');
  }

  if (result.nok.length) {
    report += createTable(result.nok, 'OUTDATED');
  } else {
    report += '\nAll dependencies are up-to-date!';
  }

  return formatTable(report.trim());
}

function createTable(deps, title) {
  let table = `\n${title}\n--------------------------------------------------------------------------------\n`;

  for (const { name, found, needs, type } of deps) {
    let needs2 = needs;
    if (type === 'github') { needs2 += ' (on github)'; }

    table += `${name}|needs ${needs2}|found ${found}\n`;
  }

  return table;
}

function formatTable(text) {
  const lines       = text.split('\n');
  let maxLenghtCol1 = 0;
  let maxLenghtCol2 = 0;

  for (const line of lines) {
    const idxSeparator1 = line.indexOf('|');
    if (idxSeparator1 === -1) { continue; }
    maxLenghtCol1 = Math.max(maxLenghtCol1, idxSeparator1);

    const idxSeparator2 = line.indexOf('|', idxSeparator1 + 1);
    if (idxSeparator2 === -1) { continue; }
    maxLenghtCol2 = Math.max(maxLenghtCol2, idxSeparator2 - idxSeparator1 - 1);
  }

  for (let i = 0; i < lines.length; ++i) {
    const parts = lines[i].split('|');
    if (parts.length !== 3) { continue; }

    const filler1 = new Array(maxLenghtCol1 - parts[0].length + 1).join(' ');
    const filler2 = new Array(maxLenghtCol2 - parts[1].length + 1).join(' ');

    lines[i] = parts[0] + filler1 + ' | ' + parts[1] + filler2 + ' | ' + parts[2];
  }

  return lines.join('\n');
}

// -----------------------------------------------------------------------------
// CHECK FOR UPDATE
// -----------------------------------------------------------------------------

function* checkForUpdate() {
  const content        = yield utils.downloadGithubPackage('AurelienRibon/node-checkmydeps', null, $$());
  const latestVersion  = content.version;
  const currentVersion = require('../package.json').version;

  if (semver.gt(latestVersion, currentVersion)) {
    const tty        = process.stdout.isTTY;
    const colorStart = tty ? '\u001b[31;1m' : '';
    const colorEnd   = tty ? '\u001b[0m' : '';

    const msg = `${colorStart}Version ${latestVersion} is available, current is ${currentVersion}, please update.${colorEnd}\n`;
    console.log(msg);
  }
}
<|endoftext|>


<commit_before>/* eslint spaced-comment: 0 */
/* eslint no-redeclare: 0 */
/* eslint no-undef: 0 */
/* eslint no-unused-vars: 0 */

const assert = require('chai').assert;

/// title: Tokenize a string with escaping
/// type: rosetta-code

/// categories:
/// strings
/// text processing

/// difficulty: 4

/// description:
///

///
Write a function or program that can split a string at each non-escaped occurrence of a separator character.

It should accept three input parameters:

///

The string

///
The separator character

///
The escape character

///

///
It should output a list of strings.

///

///
Rules for splitting:

///

The fields that were separated by the separators, become the elements of the output list.

///
Empty fields should be preserved, even at the start and end.

///

///
Rules for escaping:

///

"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.

///
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).

///
Each occurrences of the escape character that was used to escape something, should not become part of the output.

///

Demonstrate that your function satisfies the following test-case:

///
{| class="wikitable"

///
|-

///
! Input

///
! Output

///
|-

///
| style="vertical-align:top" |

///
{| style="border-collapse:collapse; border:none" border="0"

///
|-

///
| style="border:none; text-align:right" | string:

///
| style="border:none" |
one^|uno||three^^^^|four^^^|^cuatro|

///
|-

///
| style="border:none; text-align:right" | separator character:

///
| style="border:none" |
|

///
|-

///
| style="border:none; text-align:right" | escape character:

///
| style="border:none" |
^

///
|}

///
|

///
{| style="border-collapse:collapse; border:none" border="0"

///
|-

///
| style="border:none" |
one|uno

///
|-

///
| style="border:none" |

///
|-

///
| style="border:none" |
three^^

///
|-

///
| style="border:none" |
four^|cuatro

///
|-

///
| style="border:none" |

///
|}

///
|}

///
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)

///

///

Tokenize a string

///
Brace expansion

====

///

<lang AppleScript>-- tokenize :: String -> Character -> Character -> [String]

///
on tokenize(str, chrDelim, chrEsc)

script charParse

///
-- Record: {esc:Bool, token:String, tokens:[String]}

///
-- charParse :: Record -> Character -> Record

///
on lambda(a, x)

///
set blnEsc to esc of a

///
set blnEscChar to ((not blnEsc) and (x = chrEsc))

if ((not blnEsc) and (x = chrDelim)) then

///
set strToken to ""

///
set lstTokens to (tokens of a) & token of a

///
else

///
set strToken to (token of a) & cond(blnEscChar, "", x)

///
set lstTokens to tokens of (a)

///
end if

{esc:blnEscChar, token:strToken, tokens:lstTokens}

///
end lambda

///
end script

set recParse to foldl(charParse, ¬

///
{esc:false, token:"", tokens:[]}, splitOn("", str))

tokens of recParse & token of recParse

///
end tokenize

///

-- TEST

///
on run

script numberedLine

///
on lambda(a, s)

///
set iLine to lineNum of a

///
{lineNum:iLine + 1, report:report of a & iLine & ":" & tab & s & linefeed}

///
end lambda

///
end script

report of foldl(numberedLine, {lineNum:1, report:""}, ¬

///
tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^"))

///
end run

///

-- GENERIC FUNCTIONS

-- foldl :: (a -> b -> a) -> a -> [b] -> a

///
on foldl(f, startValue, xs)

///
tell mReturn(f)

///
set v to startValue

///
set lng to length of xs

///
repeat with i from 1 to lng

///
set v to lambda(v, item i of xs, i, xs)

///
end repeat

///
return v

///
end tell

///
end foldl

-- Lift 2nd class handler function into 1st class script wrapper

///
-- mReturn :: Handler -> Script

///
on mReturn(f)

///
if class of f is script then

///
f

///
else

///
script

///
property lambda : f

///
end script

///
end if

///
end mReturn

-- splitOn :: Text -> Text -> [Text]

///
on splitOn(strDelim, strMain)

///
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}

///
set xs to text items of strMain

///
set my text item delimiters to dlm

///
return xs

///
end splitOn

-- cond :: Bool -> a -> a -> a

///
on cond(bool, f, g)

///
if bool then

///
f

///
else

///
g

///
end if

///
end cond</lang>

///

1:    one|uno
/// 2:
/// 3:    three^^
/// 4:    four^|cuatro
/// 5:
///

/// challengeSeed:
function tokenize(str, esc, sep) {
  return true;
}

/// solutions:
// tokenize :: String -> Character -> Character -> [String]
function tokenize(str, charDelim, charEsc) {
  const dctParse = str.split('')
    .reduce((a, x) => {
      const blnEsc = a.esc;
      const blnBreak = !blnEsc && x === charDelim;
      const blnEscChar = !blnEsc && x === charEsc;

      return {
        esc: blnEscChar,
        token: blnBreak ? '' : (
          a.token + (blnEscChar ? '' : x)
        ),
        list: a.list.concat(blnBreak ? a.token : [])
      };
    }, {
      esc: false,
      token: '',
      list: []
    });

  return dctParse.list.concat(
    dctParse.token
  );
}

/// tail:
const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|';
const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', ''];

// TODO add more tests
const testStr2 = 'a@&bcd&ef&&@@hi';
const res2 = ['a&bcd', 'ef', '', '@hi'];

/// tests:
assert(typeof tokenize === 'function', 'message: tokenize is a function.');
assert(typeof tokenize('a', 'b', 'c') === 'object', 'message: tokenize should return an array.');
assert.deepEqual(tokenize(testStr1, '|', '^'), res1, "message: tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')  should return ['one|uno', '', 'three^^', 'four^|cuatro', '']");
assert.deepEqual(tokenize(testStr2, '&', '@'), res2, "message: tokenize('a@&bcd&ef&&@@hi', '&', '@') should return ['a&bcd', 'ef', '', '@hi']");
/// id: 594faaab4e2a8626833e9c3d
<commit_msg>Cleaned up the HTML formatting.<commit_after>/* eslint spaced-comment: 0 */
/* eslint no-redeclare: 0 */
/* eslint no-undef: 0 */
/* eslint no-unused-vars: 0 */

const assert = require('chai').assert;

/// title: Tokenize a string with escaping
/// type: rosetta-code

/// categories:
/// strings
/// text processing

/// difficulty: 4

/// description:
///

///

/// Write a function or program that can split a string at each non-escaped occurrence of a separator character.
///

///

///

/// It should accept three input parameters:
///

///

///
The string

///
The separator character

///
The escape character

///

///

///
It should output a list of strings.

///

///
Rules for splitting:

///

///
The fields that were separated by the separators, become the elements of the output list.

///
Empty fields should be preserved, even at the start and end.

///

///

///
Rules for escaping:

///

///
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.

///
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).

///
Each occurrences of the escape character that was used to escape something, should not become part of the output.

///

///

///
Demonstrate that your function satisfies the following test-case:
///   Given string
one^|uno||three^^^^|four^^^|^cuatro|
 and using
///
|
 as a separator and
^
 as escape character, your
///   function should output the following array:
///

///

///

///

///   ['one|uno', '', 'three^^', 'four^|quatro', '']
///

///

///

/// challengeSeed:
function tokenize(str, esc, sep) {
  return true;
}

/// solutions:
// tokenize :: String -> Character -> Character -> [String]
function tokenize(str, charDelim, charEsc) {
  const dctParse = str.split('')
    .reduce((a, x) => {
      const blnEsc = a.esc;
      const blnBreak = !blnEsc && x === charDelim;
      const blnEscChar = !blnEsc && x === charEsc;

      return {
        esc: blnEscChar,
        token: blnBreak ? '' : (
          a.token + (blnEscChar ? '' : x)
        ),
        list: a.list.concat(blnBreak ? a.token : [])
      };
    }, {
      esc: false,
      token: '',
      list: []
    });

  return dctParse.list.concat(
    dctParse.token
  );
}

/// tail:
const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|';
const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', ''];

// TODO add more tests
const testStr2 = 'a@&bcd&ef&&@@hi';
const res2 = ['a&bcd', 'ef', '', '@hi'];

/// tests:
assert(typeof tokenize === 'function', 'message: tokenize is a function.');
assert(typeof tokenize('a', 'b', 'c') === 'object', 'message: tokenize should return an array.');
assert.deepEqual(tokenize(testStr1, '|', '^'), res1, "message: tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')  should return ['one|uno', '', 'three^^', 'four^|cuatro', '']");
assert.deepEqual(tokenize(testStr2, '&', '@'), res2, "message: tokenize('a@&bcd&ef&&@@hi', '&', '@') should return ['a&bcd', 'ef', '', '@hi']");
/// id: 594faaab4e2a8626833e9c3d
<|endoftext|>


<commit_before>'use strict'

class API {
  static createQueryFromRequest (request) {
    let limit = parseInt(request.limit) || 25
    delete request.limit

    let offset = parseInt(request.offset) || 0
    delete request.offset

    let order = parseInt(request.order) || 'createdAt'
    delete request.order
    let direction = request.direction || 'ASC'
    delete request.direction

    if (request.data) {
      let dataQuery = request.data
      delete request.data

      request.data = {
        $contains: JSON.parse(dataQuery)
      }
    }

    let query = {
      where: request,
      limit: limit,
      offset: offset,
      order: [
        [order, direction]
      ]
    }

    return query
  }
}

module.exports = API<commit_msg>Fix nick search missing from new standardised search function<commit_after>'use strict'

class API {
  static createQueryFromRequest (request) {
    let limit = parseInt(request.limit) || 25
    delete request.limit

    let offset = parseInt(request.offset) || 0
    delete request.offset

    let order = parseInt(request.order) || 'createdAt'
    delete request.order
    let direction = request.direction || 'ASC'
    delete request.direction

    if (request.data) {
      let dataQuery = request.data
      delete request.data

      request.data = {
        $contains: JSON.parse(dataQuery)
      }
    }

    if (query.nicknames) {
      query.nicknames = { $contains: [query.nicknames] }
    }

    let query = {
      where: request,
      limit: limit,
      offset: offset,
      order: [
        [order, direction]
      ]
    }

    return query
  }
}

module.exports = API
<|endoftext|>


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

'use strict';

process.env.DEBUG = 'actions-on-google:*';
const { DialogflowApp } = require('actions-on-google');
const functions = require('firebase-functions');

// Dialogflow Actions
const TRANSACTION_CHECK_NO_PAYMENT = 'transaction.check.no.payment';
const TRANSACTION_CHECK_ACTION_PAYMENT = 'transaction.check.action';
const TRANSACTION_CHECK_GOOGLE_PAYMENT = 'transaction.check.google';
const TRANSACTION_CHECK_COMPLETE = 'transaction.check.complete';
const DELIVERY_ADDRESS = 'delivery.address';
const DELIVERY_ADDRESS_COMPLETE = 'delivery.address.complete';
const TRANSACTION_DECISION_ACTION_PAYMENT = 'transaction.decision.action';
const TRANSACTION_DECISION_COMPLETE = 'transaction.decision.complete';

const MILLISECONDS_TO_SECONDS_QUOTIENT = 1000;

exports.transactions = functions.https.onRequest((request, response) => {
  const app = new DialogflowApp({ request, response });
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));

  function transactionCheckNoPayment (app) {
    app.askForTransactionRequirements();
  }

  function transactionCheckActionPayment (app) {
    app.askForTransactionRequirements({
      type: app.Transactions.PaymentType.PAYMENT_CARD,
      displayName: 'VISA-1234',
      deliveryAddressRequired: false
    });
  }

  function transactionCheckGooglePayment (app) {
    app.askForTransactionRequirements({
      // These will be provided by payment processor, like Stripe, Braintree, or
      // Vantiv
      tokenizationParameters: {},
      cardNetworks: [
        app.Transactions.CardNetwork.VISA,
        app.Transactions.CardNetwork.AMEX
      ],
      prepaidCardDisallowed: false,
      deliveryAddressRequired: false
    });
  }

  function transactionCheckComplete (app) {
    if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) {
      // Normally take the user through cart building flow
      app.ask('Looks like you\'re good to go! Try saying "Get Delivery Address".');
    } else {
      app.tell('Transaction failed.');
    }
  }

  function deliveryAddress (app) {
    app.askForDeliveryAddress('To know where to send the order');
  }

  function deliveryAddressComplete (app) {
    if (app.getDeliveryAddress()) {
      console.log('DELIVERY ADDRESS: ' +
        app.getDeliveryAddress().postalAddress.addressLines[0]);
      app.data.deliveryAddress = app.getDeliveryAddress();
      app.ask('Great, got your address! Now say "confirm transaction".');
    } else {
      app.tell('Transaction failed.');
    }
  }

  function transactionDecision (app) {
    const order = app.buildOrder('<UNIQUE_ORDER_ID>')
      .setCart(app.buildCart().setMerchant('book_store_1', 'Book Store')
        .addLineItems([
          app.buildLineItem('memoirs_1', 'My Memoirs')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 3, 990000000)
            .setQuantity(1)
            .addSublines('Note from the author')
            .setType(app.Transactions.LineItemType.REGULAR),
          app.buildLineItem('memoirs_2', 'Memoirs of a person')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 5, 990000000)
            .setQuantity(1)
            .addSublines('Special introduction by author')
            .setType(app.Transactions.LineItemType.REGULAR),
          app.buildLineItem('memoirs_3', 'Their memoirs')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 15, 750000000)
            .setQuantity(1)
            .setType(app.Transactions.LineItemType.REGULAR)
            .addSublines(
              app.buildLineItem('memoirs_epilogue', 'Special memoir epilogue')
                .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 3, 990000000)
                .setQuantity(1)
                .setType(app.Transactions.LineItemType.REGULAR)
            ),
          app.buildLineItem('memoirs_4', 'Our memoirs')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 6, 490000000)
            .setQuantity(1)
            .setType(app.Transactions.LineItemType.REGULAR)
        ]).setNotes('The Memoir collection'))
      .addOtherItems([
        app.buildLineItem('subtotal', 'Subtotal')
          .setType(app.Transactions.LineItemType.SUBTOTAL)
          .setPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 36, 210000000),
        app.buildLineItem('tax', 'Tax')
          .setType(app.Transactions.LineItemType.TAX)
          .setPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 2, 780000000)
      ])
      .setTotalPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 38, 990000000);

    if (app.data.deliveryAddress) {
      order.addLocation(app.Transactions.OrderLocationType.DELIVERY, app.data.deliveryAddress);
    }

    // To test payment w/ sample, uncheck the 'Testing in Sandbox Mode' box in the
    // Actions console simulator
    app.askForTransactionDecision(order, {
      type: app.Transactions.PaymentType.PAYMENT_CARD,
      displayName: 'VISA-1234',
      deliveryAddressRequired: true
    });

    /*
      // If using Google provided payment instrument instead
      app.askForTransactionDecision(order, {
        // These will be provided by payment processor, like Stripe,
        // Braintree, or Vantiv
        tokenizationParameters: {},
        cardNetworks: [
          app.Transactions.CardNetwork.VISA,
          app.Transactions.CardNetwork.AMEX
        ],
        prepaidCardDisallowed: false,
        deliveryAddressRequired: false
      });
    */
  }

  function transactionDecisionComplete (app) {
    if (app.getTransactionDecision() &&
      app.getTransactionDecision().userDecision ===
        app.Transactions.TransactionUserDecision.ACCEPTED) {
      const finalOrderId = app.getTransactionDecision().order.finalOrder.id;

      // Confirm order and make any charges in order processing backend
      // If using Google provided payment instrument:
      // const paymentDisplayName = app.getTransactionDecision().order.paymentInfo.displayName;

      app.tell(app.buildRichResponse().addOrderUpdate(
        app.buildOrderUpdate(finalOrderId, false)
          .setOrderState(app.Transactions.OrderState.CREATED, 'Order created')
          .setUpdateTime(Math.floor(Date.now() / MILLISECONDS_TO_SECONDS_QUOTIENT))
          .setInfo(app.Transactions.OrderStateInfo.RECEIPT, {
            confirmedActionOrderId: '<UNIQUE_ORDER_ID>'
          })
          // Replace the URL with your own customer service page
          .addOrderManagementAction(app.Transactions.ActionType.CUSTOMER_SERVICE,
            'Customer Service', 'http://example.com/customer-service'))
        .addSimpleResponse('Transaction completed! You\'re all set!'));
    } else if (app.getTransactionDecision() &&
      app.getTransactionDecision().userDecision ===
        app.Transactions.ConfirmationDecision.DELIVERY_ADDRESS_UPDATED) {
      return deliveryAddress(app);
    } else {
      app.tell('Transaction failed.');
    }
  }

  const actionMap = new Map();
  actionMap.set(TRANSACTION_CHECK_NO_PAYMENT, transactionCheckNoPayment);
  actionMap.set(TRANSACTION_CHECK_ACTION_PAYMENT, transactionCheckActionPayment);
  actionMap.set(TRANSACTION_CHECK_GOOGLE_PAYMENT, transactionCheckGooglePayment);
  actionMap.set(TRANSACTION_CHECK_COMPLETE, transactionCheckComplete);
  actionMap.set(DELIVERY_ADDRESS, deliveryAddress);
  actionMap.set(DELIVERY_ADDRESS_COMPLETE, deliveryAddressComplete);
  actionMap.set(TRANSACTION_DECISION_ACTION_PAYMENT, transactionDecision);
  actionMap.set(TRANSACTION_DECISION_COMPLETE, transactionDecisionComplete);

  app.handleRequest(actionMap);
});
<commit_msg>Reverse buildLineItem() method args.<commit_after>// Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

process.env.DEBUG = 'actions-on-google:*';
const { DialogflowApp } = require('actions-on-google');
const functions = require('firebase-functions');

// Dialogflow Actions
const TRANSACTION_CHECK_NO_PAYMENT = 'transaction.check.no.payment';
const TRANSACTION_CHECK_ACTION_PAYMENT = 'transaction.check.action';
const TRANSACTION_CHECK_GOOGLE_PAYMENT = 'transaction.check.google';
const TRANSACTION_CHECK_COMPLETE = 'transaction.check.complete';
const DELIVERY_ADDRESS = 'delivery.address';
const DELIVERY_ADDRESS_COMPLETE = 'delivery.address.complete';
const TRANSACTION_DECISION_ACTION_PAYMENT = 'transaction.decision.action';
const TRANSACTION_DECISION_COMPLETE = 'transaction.decision.complete';

const MILLISECONDS_TO_SECONDS_QUOTIENT = 1000;

exports.transactions = functions.https.onRequest((request, response) => {
  const app = new DialogflowApp({ request, response });
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));

  function transactionCheckNoPayment (app) {
    app.askForTransactionRequirements();
  }

  function transactionCheckActionPayment (app) {
    app.askForTransactionRequirements({
      type: app.Transactions.PaymentType.PAYMENT_CARD,
      displayName: 'VISA-1234',
      deliveryAddressRequired: false
    });
  }

  function transactionCheckGooglePayment (app) {
    app.askForTransactionRequirements({
      // These will be provided by payment processor, like Stripe, Braintree, or
      // Vantiv
      tokenizationParameters: {},
      cardNetworks: [
        app.Transactions.CardNetwork.VISA,
        app.Transactions.CardNetwork.AMEX
      ],
      prepaidCardDisallowed: false,
      deliveryAddressRequired: false
    });
  }

  function transactionCheckComplete (app) {
    if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) {
      // Normally take the user through cart building flow
      app.ask('Looks like you\'re good to go! Try saying "Get Delivery Address".');
    } else {
      app.tell('Transaction failed.');
    }
  }

  function deliveryAddress (app) {
    app.askForDeliveryAddress('To know where to send the order');
  }

  function deliveryAddressComplete (app) {
    if (app.getDeliveryAddress()) {
      console.log('DELIVERY ADDRESS: ' +
        app.getDeliveryAddress().postalAddress.addressLines[0]);
      app.data.deliveryAddress = app.getDeliveryAddress();
      app.ask('Great, got your address! Now say "confirm transaction".');
    } else {
      app.tell('Transaction failed.');
    }
  }

  function transactionDecision (app) {
    const order = app.buildOrder('<UNIQUE_ORDER_ID>')
      .setCart(app.buildCart().setMerchant('book_store_1', 'Book Store')
        .addLineItems([
          app.buildLineItem('My Memoirs', 'memoirs_1')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 3, 990000000)
            .setQuantity(1)
            .addSublines('Note from the author')
            .setType(app.Transactions.LineItemType.REGULAR),
          app.buildLineItem('Memoirs of a person', 'memoirs_2')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 5, 990000000)
            .setQuantity(1)
            .addSublines('Special introduction by author')
            .setType(app.Transactions.LineItemType.REGULAR),
          app.buildLineItem('Their memoirs', 'memoirs_3')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 15, 750000000)
            .setQuantity(1)
            .setType(app.Transactions.LineItemType.REGULAR)
            .addSublines(
              app.buildLineItem('Special memoir epilogue', 'memoirs_epilogue')
                .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 3, 990000000)
                .setQuantity(1)
                .setType(app.Transactions.LineItemType.REGULAR)
            ),
          app.buildLineItem('Our memoirs', 'memoirs_4')
            .setPrice(app.Transactions.PriceType.ACTUAL, 'USD', 6, 490000000)
            .setQuantity(1)
            .setType(app.Transactions.LineItemType.REGULAR)
        ]).setNotes('The Memoir collection'))
      .addOtherItems([
        app.buildLineItem('Subtotal', 'subtotal')
          .setType(app.Transactions.LineItemType.SUBTOTAL)
          .setPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 36, 210000000),
        app.buildLineItem('Tax', 'tax')
          .setType(app.Transactions.LineItemType.TAX)
          .setPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 2, 780000000)
      ])
      .setTotalPrice(app.Transactions.PriceType.ESTIMATE, 'USD', 38, 990000000);

    if (app.data.deliveryAddress) {
      order.addLocation(app.Transactions.OrderLocationType.DELIVERY, app.data.deliveryAddress);
    }

    // To test payment w/ sample, uncheck the 'Testing in Sandbox Mode' box in the
    // Actions console simulator
    app.askForTransactionDecision(order, {
      type: app.Transactions.PaymentType.PAYMENT_CARD,
      displayName: 'VISA-1234',
      deliveryAddressRequired: true
    });

    /*
      // If using Google provided payment instrument instead
      app.askForTransactionDecision(order, {
        // These will be provided by payment processor, like Stripe,
        // Braintree, or Vantiv
        tokenizationParameters: {},
        cardNetworks: [
          app.Transactions.CardNetwork.VISA,
          app.Transactions.CardNetwork.AMEX
        ],
        prepaidCardDisallowed: false,
        deliveryAddressRequired: false
      });
    */
  }

  function transactionDecisionComplete (app) {
    if (app.getTransactionDecision() &&
      app.getTransactionDecision().userDecision ===
        app.Transactions.TransactionUserDecision.ACCEPTED) {
      const finalOrderId = app.getTransactionDecision().order.finalOrder.id;

      // Confirm order and make any charges in order processing backend
      // If using Google provided payment instrument:
      // const paymentDisplayName = app.getTransactionDecision().order.paymentInfo.displayName;

      app.tell(app.buildRichResponse().addOrderUpdate(
        app.buildOrderUpdate(finalOrderId, false)
          .setOrderState(app.Transactions.OrderState.CREATED, 'Order created')
          .setUpdateTime(Math.floor(Date.now() / MILLISECONDS_TO_SECONDS_QUOTIENT))
          .setInfo(app.Transactions.OrderStateInfo.RECEIPT, {
            confirmedActionOrderId: '<UNIQUE_ORDER_ID>'
          })
          // Replace the URL with your own customer service page
          .addOrderManagementAction(app.Transactions.ActionType.CUSTOMER_SERVICE,
            'Customer Service', 'http://example.com/customer-service'))
        .addSimpleResponse('Transaction completed! You\'re all set!'));
    } else if (app.getTransactionDecision() &&
      app.getTransactionDecision().userDecision ===
        app.Transactions.ConfirmationDecision.DELIVERY_ADDRESS_UPDATED) {
      return deliveryAddress(app);
    } else {
      app.tell('Transaction failed.');
    }
  }

  const actionMap = new Map();
  actionMap.set(TRANSACTION_CHECK_NO_PAYMENT, transactionCheckNoPayment);
  actionMap.set(TRANSACTION_CHECK_ACTION_PAYMENT, transactionCheckActionPayment);
  actionMap.set(TRANSACTION_CHECK_GOOGLE_PAYMENT, transactionCheckGooglePayment);
  actionMap.set(TRANSACTION_CHECK_COMPLETE, transactionCheckComplete);
  actionMap.set(DELIVERY_ADDRESS, deliveryAddress);
  actionMap.set(DELIVERY_ADDRESS_COMPLETE, deliveryAddressComplete);
  actionMap.set(TRANSACTION_DECISION_ACTION_PAYMENT, transactionDecision);
  actionMap.set(TRANSACTION_DECISION_COMPLETE, transactionDecisionComplete);

  app.handleRequest(actionMap);
});
<|endoftext|>


<commit_before>// ==UserScript==
// @author      Robert Slifka (github @rslifka)
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepage    https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        Fate of All Fools
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @version     467
// ==/UserScript==
<commit_msg>AUTO-CREATED Release Artifact v468 c/o Travis<commit_after>// ==UserScript==
// @author      Robert Slifka (github @rslifka)
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepage    https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        Fate of All Fools
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @version     468
// ==/UserScript==
<|endoftext|>


<commit_before>/* globals jQuery, window, document */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false,
      "onSelected": false,
      "dynamicOptLabel": "Add a new option..."
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Does it allow to create new options dynamically?
        var dynamicOptions = $select.attr("data-dynamic-opts"),
            $dynamicInput = $();

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownClass);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly class=fakeinput>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");
        $ul.data("select", $select);

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);
          methods._addOption($ul, $this);

        });

        // If this select allows dynamic options add the widget
        if (dynamicOptions) {
          $dynamicInput = $("

");
          $dynamicInput.append("<input>");
          $dynamicInput.find("input").attr("placeholder", options.dynamicOptLabel);
          $ul.append($dynamicInput);
        }
        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
                $selected = $select.find(":selected").last();
            } else {
                $selected = $select.find("option, li").first();
            }

            methods._select($dropdown, $selected);
        } else {
            var selectors = [], val = $select.val()
            for (var i in val) {
              selectors.push('li[value=' + val[i] + ']')
            }
            if (selectors.length > 0) {
              methods._select($dropdown, $dropdown.find(selectors.join(',')));
            }
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        $ul.on("click", "li:not(.dropdownjs-add)", function(e) {
          methods._select($dropdown, $(this));
        });
        $ul.on("keydown", "li:not(.dropdownjs-add)", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").attr("tabindex", -1);
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32 && !$(e.target).is("input")) {
            methods._select($dropdown, $(this));
            return false;
          }
        });
        $ul.on("focus", "li:not(.dropdownjs-add)", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Add new options when the widget is used
        if (dynamicOptions && dynamicOptions.length) {
          $dynamicInput.on("keydown", function(e) {
            if(e.which !== 13) return;
            var $option = $("<option>"),
                val = $dynamicInput.find("input").val();
            $dynamicInput.find("input").val("");

            $option.attr("value", val);
            $option.text(val);
            $select.append($option);

          });
        }

        // Listen for new added options and update dropdown if needed
        $select.on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          methods._addOption($ul, $this);
          $ul.find("li").not(".dropdownjs-add").attr("tabindex", 0);

        });

        // Update dropdown when using val, need to use .val("value").trigger("change");
        $select.on("change", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            } else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          } else {
            methods._select($dropdown, $select.find(":selected"));
          }
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          $(".dropdownjs > ul > li").not(".dropdownjs-add").attr("tabindex", 0);

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        // Close every dropdown on click outside
        $(document).on("click", function(e) {

          // Don't close the multi dropdown if user is clicking inside it
          if (multi && $(e.target).parents(".dropdownjs").length) return;

          // Don't close the dropdown if user is clicking inside the dynamic-opts widget
          if ($(e.target).parents(".dropdownjs-add").length || $(e.target).is(".dropdownjs-add")) return;

          // Close opened dropdowns
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.is("select")) {
            $this = $this.find('select');
          }
          if ($this.is(options.autoinit)) {
            $this.each(function() {
              initElement($(this));
            });
          }
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {
      if ($target.is(".dropdownjs-add")) return;

      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input.fakeinput");
      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        $target.each(function() {
          var $selected = $select.find("[value=\"" + $(this).attr("value") + "\"]");
          $selected.prop("selected", $(this).hasClass("selected"));
        });
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        // Unselect options except the one that will be selected
        if ($target.is("li")) {
          selectOptions.not($target).removeClass("selected");
        }
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text().trim());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

      // Call the callback
      if (this.options.onSelected) {
        this.options.onSelected($target.attr("value"));
      }
    },
    _addOption: function($ul, $this) {
      // Create the option
      var $option = $("

");

      // Style the option
      $option.addClass(this.options.optionClass);

      // If the option has some text then transfer it
      if ($this.text()) {
        $option.text($this.text());
      }
      // Otherwise set the empty label and set it as an empty option
      else {
        $option.html(" ");
      }
      // Set the value of the option
      $option.attr("value", $this.val());

      // Will user be able to remove this option?
      if ($ul.data("select").attr("data-dynamic-opts")) {
        $option.append("");
        $option.find(".close").on("click", function() {
          $option.remove();
          $this.remove();
        });
      }

      // Ss it selected?
      if ($this.prop("selected")) {
        $option.attr("selected", true);
        $option.addClass("selected");
      }

      // Append option to our dropdown
      if ($ul.find(".dropdownjs-add").length) {
        $ul.find(".dropdownjs-add").before($option);
      } else {
        $ul.append($option);
      }
    }
  };

  $.fn.dropdown = function(params) {
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

}));
<commit_msg>Watch removed items from 'select'<commit_after>/* globals jQuery, window, document */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false,
      "onSelected": false,
      "dynamicOptLabel": "Add a new option..."
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Does it allow to create new options dynamically?
        var dynamicOptions = $select.attr("data-dynamic-opts"),
            $dynamicInput = $();

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownClass);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly class=fakeinput>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");
        $ul.data("select", $select);

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);
          methods._addOption($ul, $this);

        });

        // If this select allows dynamic options add the widget
        if (dynamicOptions) {
          $dynamicInput = $("

");
          $dynamicInput.append("<input>");
          $dynamicInput.find("input").attr("placeholder", options.dynamicOptLabel);
          $ul.append($dynamicInput);
        }

        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
                $selected = $select.find(":selected").last();
            }
            else {
                $selected = $select.find("option, li").first();
               // $selected = $select.find("option").first();
            }
            methods._select($dropdown, $selected);
        } else {
            var selectors = [], val = $select.val()
            for (var i in val) {
              selectors.push('li[value=' + val[i] + ']')
            }
            if (selectors.length > 0) {
              methods._select($dropdown, $dropdown.find(selectors.join(',')));
            }
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        $ul.on("click", "li:not(.dropdownjs-add)", function(e) {
          methods._select($dropdown, $(this));
          // trigger change event, if declared on the original selector
          $select.change();
        });
        $ul.on("keydown", "li:not(.dropdownjs-add)", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").attr("tabindex", -1);
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32 && !$(e.target).is("input")) {
            methods._select($dropdown, $(this));
            return false;
          }
        });

        $ul.on("focus", "li:not(.dropdownjs-add)", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Add new options when the widget is used
        if (dynamicOptions && dynamicOptions.length) {
          $dynamicInput.on("keydown", function(e) {
            if(e.which !== 13) return;
            var $option = $("<option>"),
                val = $dynamicInput.find("input").val();
            $dynamicInput.find("input").val("");

            $option.attr("value", val);
            $option.text(val);
            $select.append($option);

          });
        }

        // Listen for new added options and update dropdown if needed
        $select.on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          methods._addOption($ul, $this);
          $ul.find("li").not(".dropdownjs-add").attr("tabindex", 0);

        });

        $select.on("DOMNodeRemoved", function(e) {
          var deletedValue = e.target.getAttribute('value');
          $ul.find("li[value='"+deletedValue+"']").remove();
        });

        // Update dropdown when using val, need to use .val("value").trigger("change");
        $select.on("change", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          } else {
            methods._select($dropdown, $select.find(":selected"));
          }
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          $(".dropdownjs > ul > li").not(".dropdownjs-add").attr("tabindex", 0);

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        // Close every dropdown on click outside
        $(document).on("click", function(e) {

          // Don't close the multi dropdown if user is clicking inside it
          if (multi && $(e.target).parents(".dropdownjs").length) return;

          // Don't close the dropdown if user is clicking inside the dynamic-opts widget
          if ($(e.target).parents(".dropdownjs-add").length || $(e.target).is(".dropdownjs-add")) return;

          // Close opened dropdowns
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.is("select")) {
            $this = $this.find('select');
          }
          if ($this.is(options.autoinit)) {
            $this.each(function() {
              initElement($(this));
            });
          }
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {
      if ($target.is(".dropdownjs-add")) return;

      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input.fakeinput");
      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        $target.each(function(){
          var $selected = $select.find("[value=\"" + $(this).attr("value") + "\"]");
          $selected.prop("selected", $(this).hasClass("selected"));
        });
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        // Unselect options except the one that will be selected
        if ($target.is("li")) {
            selectOptions.not($target).removeClass("selected");
        }
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text().trim());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

       // Call the callback
        if (this.options.onSelected) {
            this.options.onSelected($target.attr("value"));
        }

    },
    _removeOption: function ($ul, $this) {
      console.warn(arguments);
    },
    _addOption: function($ul, $this) {
      // Create the option
      var $option = $("

");

      // Style the option
      $option.addClass(this.options.optionClass);

      // If the option has some text then transfer it
      if ($this.text()) {
        $option.text($this.text());
      }
      // Otherwise set the empty label and set it as an empty option
      else {
        $option.html(" ");
      }
      // Set the value of the option
      $option.attr("value", $this.val());

      // Will user be able to remove this option?
      if ($ul.data("select").attr("data-dynamic-opts")) {
        $option.append("");
        $option.find(".close").on("click", function() {
          $option.remove();
          $this.remove();
        });
      }

      // Ss it selected?
      if ($this.prop("selected")) {
        $option.attr("selected", true);
        $option.addClass("selected");
      }

      // Append option to our dropdown
      if ($ul.find(".dropdownjs-add").length) {
        $ul.find(".dropdownjs-add").before($option);
      } else {
        $ul.append($option);
      }
    }
  };

  $.fn.dropdown = function(params) {
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

}));
<|endoftext|>


<commit_before>var models  = require('../models/index');

module.exports = function( app ) {

	app.get('/providers', function(req, res, next) {
		models.provider.findAll().then(function( providers) {
			res.json( providers );
		});
	});

	app.delete('/providers/:id', function(req, res, next) {
		models.provider.destroy({ where: { id: req.params.id } }).then(function () {
			res.json({ deleted: true });
		});
	});

	app.post('/providers/:id', function( req, res, next ) {

		var updateCreate = function( callback ) {
			models.provider
				.findOrCreate({ where: { id: req.body.id }, defaults: req.body })
				.spread( function( provider, created ) {
					var response = { created: created, model: provider.get({ plain: true }) };

					if ( !created ) {
						provider.name = req.body.name;
						provider.save().then(function() {
							callback( response );
						});
					}
					else {
						callback( response );
					}
			});
		}

		updateCreate(function( response ) {
			res.json( response );
		});
	});
}<commit_msg>Envio de coddigos HTTP<commit_after>var models  = require('../models/index');

module.exports = function( app ) {

	app.get('/providers', function(req, res, next) {
		models.provider.findAll().then(function( providers) {
			res.json( providers );
		});
	});

	app.delete('/providers/:id', function(req, res, next) {
		models.provider.destroy({ where: { id: req.params.id } }).then(function () {
			res.sendStatus(200);
		});
	});

	app.post('/providers/:id', function( req, res, next ) {

		var updateCreate = function( callback ) {
			models.provider
				.findOrCreate({ where: { id: req.body.id }, defaults: req.body })
				.spread( function( provider, created ) {
					var response = { created: created, model: provider.get({ plain: true }) };

					if ( !created ) {
						provider.name = req.body.name;
						provider.save().then(function() {
							callback( response );
						});
					}
					else {
						callback( response );
					}
			}).catch(function( err ) {
				callback( err )
			});
		}

		updateCreate(function( response ) {
			if (response.hasOwnProperty('model')) {
				res.sendStatus(500).json({ err: response.err[0].msg } );
			}
			else {
				res.sendStatus(200).json( response );
			}
		});
	});
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
/* More information about these options at jshint.com/docs/options */
/* exported reportBug */
'use strict';

function reportBug() {
  // Detect browser and version.
  var res = getBrowserNameAndVersion();
  var browserName = res.name;
  var browserVersion = res.version;
  console.log('Detected browser: ' + browserName + ' ' + browserVersion);

  var description = 'Browser: ' + browserName + ' ' + browserVersion +
      ' (' + navigator.platform + ')\n\n' +
      'Output from the troubleshooting page at http://test.webrtc.org:\n\n' +
      'Please replace this text with the copy+pasted output from test page!';

  // Labels for the bug to be filed.
  var osLabel = 'OS-';
  if (navigator.platform.indexOf('Win') !== -1) { osLabel += 'Windows'; }
  if (navigator.platform.indexOf('Mac') !== -1) { osLabel += 'Mac'; }
  if (navigator.platform.match('iPhone|iPad|iPod|iOS')) { osLabel += 'iOS'; }
  if (navigator.platform.indexOf('Linux') !== -1) { osLabel += 'Linux'; }
  if (navigator.platform.indexOf('Android') !== -1) { osLabel += 'Android'; }

  var labels = 'webrtc-troubleshooter,Cr-Blink-WebRTC,' + osLabel;
  var url = 'https://code.google.com/p/chromium/issues/entry?' +
      'comment=' + encodeURIComponent(description) +
      '&labels=' + encodeURIComponent(labels);
  console.log('Navigating to: ' + url);
  window.open(url);
}

/*
 * Detects the running browser name and version.
 *
 * @return {!Object.<string, string>} Object containing the browser name and
 *     version (mapped to the keys "name" and "version").
 */
function getBrowserNameAndVersion() {
  // Code inspired by http://goo.gl/9dZZqE with
  // added support of modern Internet Explorer versions (Trident).
  var agent = navigator.userAgent;
  var browserName = navigator.appName;
  var version = '' + parseFloat(navigator.appVersion);
  var offsetName, offsetVersion, ix;

  if ((offsetVersion = agent.indexOf('Chrome')) !== -1) {
    browserName = 'Chrome';
    version = agent.substring(offsetVersion + 7);
  } else if ((offsetVersion = agent.indexOf('MSIE')) !== -1) {
    browserName = 'Microsoft Internet Explorer'; // Older IE versions.
    version = agent.substring(offsetVersion + 5);
  } else if ((offsetVersion = agent.indexOf('Trident')) !== -1) {
    browserName = 'Microsoft Internet Explorer'; // Newer IE versions.
    version = agent.substring(offsetVersion + 8);
  } else if ((offsetVersion = agent.indexOf('Firefox')) !== -1) {
    browserName = 'Firefox';
  } else if ((offsetVersion = agent.indexOf('Safari')) !== -1) {
    browserName = 'Safari';
    version = agent.substring(offsetVersion + 7);
    if ((offsetVersion = agent.indexOf('Version')) !== -1) {
      version = agent.substring(offsetVersion + 8);
    }
  } else if ( (offsetName = agent.lastIndexOf(' ') + 1) <
              (offsetVersion = agent.lastIndexOf('/')) ) {
    // For other browsers 'name/version' is at the end of userAgent
    browserName = agent.substring(offsetName, offsetVersion);
    version = agent.substring(offsetVersion + 1);
    if (browserName.toLowerCase() === browserName.toUpperCase()) {
      browserName = navigator.appName;
    }
  } // Trim the version string at semicolon/space if present.
  if ((ix = version.indexOf(';')) !== -1) {
    version = version.substring(0, ix);
  }
  if ((ix = version.indexOf(' ')) !== -1) {
    version = version.substring(0, ix);
  }

  return { 'name': browserName, 'version': version };
}
<commit_msg>TestRTC: name variable properly.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
/* More information about these options at jshint.com/docs/options */
/* exported reportBug */
'use strict';

function reportBug() {
  // Detect browser and version.
  var result = getBrowserNameAndVersion();
  var browserName = result.name;
  var browserVersion = result.version;
  console.log('Detected browser: ' + browserName + ' ' + browserVersion);

  var description = 'Browser: ' + browserName + ' ' + browserVersion +
      ' (' + navigator.platform + ')\n\n' +
      'Output from the troubleshooting page at http://test.webrtc.org:\n\n' +
      'Please replace this text with the copy+pasted output from test page!';

  // Labels for the bug to be filed.
  var osLabel = 'OS-';
  if (navigator.platform.indexOf('Win') !== -1) { osLabel += 'Windows'; }
  if (navigator.platform.indexOf('Mac') !== -1) { osLabel += 'Mac'; }
  if (navigator.platform.match('iPhone|iPad|iPod|iOS')) { osLabel += 'iOS'; }
  if (navigator.platform.indexOf('Linux') !== -1) { osLabel += 'Linux'; }
  if (navigator.platform.indexOf('Android') !== -1) { osLabel += 'Android'; }

  var labels = 'webrtc-troubleshooter,Cr-Blink-WebRTC,' + osLabel;
  var url = 'https://code.google.com/p/chromium/issues/entry?' +
      'comment=' + encodeURIComponent(description) +
      '&labels=' + encodeURIComponent(labels);
  console.log('Navigating to: ' + url);
  window.open(url);
}

/*
 * Detects the running browser name and version.
 *
 * @return {!Object.<string, string>} Object containing the browser name and
 *     version (mapped to the keys "name" and "version").
 */
function getBrowserNameAndVersion() {
  // Code inspired by http://goo.gl/9dZZqE with
  // added support of modern Internet Explorer versions (Trident).
  var agent = navigator.userAgent;
  var browserName = navigator.appName;
  var version = '' + parseFloat(navigator.appVersion);
  var offsetName, offsetVersion, ix;

  if ((offsetVersion = agent.indexOf('Chrome')) !== -1) {
    browserName = 'Chrome';
    version = agent.substring(offsetVersion + 7);
  } else if ((offsetVersion = agent.indexOf('MSIE')) !== -1) {
    browserName = 'Microsoft Internet Explorer'; // Older IE versions.
    version = agent.substring(offsetVersion + 5);
  } else if ((offsetVersion = agent.indexOf('Trident')) !== -1) {
    browserName = 'Microsoft Internet Explorer'; // Newer IE versions.
    version = agent.substring(offsetVersion + 8);
  } else if ((offsetVersion = agent.indexOf('Firefox')) !== -1) {
    browserName = 'Firefox';
  } else if ((offsetVersion = agent.indexOf('Safari')) !== -1) {
    browserName = 'Safari';
    version = agent.substring(offsetVersion + 7);
    if ((offsetVersion = agent.indexOf('Version')) !== -1) {
      version = agent.substring(offsetVersion + 8);
    }
  } else if ( (offsetName = agent.lastIndexOf(' ') + 1) <
              (offsetVersion = agent.lastIndexOf('/')) ) {
    // For other browsers 'name/version' is at the end of userAgent
    browserName = agent.substring(offsetName, offsetVersion);
    version = agent.substring(offsetVersion + 1);
    if (browserName.toLowerCase() === browserName.toUpperCase()) {
      browserName = navigator.appName;
    }
  } // Trim the version string at semicolon/space if present.
  if ((ix = version.indexOf(';')) !== -1) {
    version = version.substring(0, ix);
  }
  if ((ix = version.indexOf(' ')) !== -1) {
    version = version.substring(0, ix);
  }

  return { 'name': browserName, 'version': version };
}
<|endoftext|>