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

var fs = require('fs');

var dirname = __dirname.split('/');
dirname.pop();
dirname = dirname.join('/');
dirname += '/lib/';

var dirs = [];

try { dirs = fs.readdirSync(dirname); }catch(e) {}

dirs.forEach(function (op) {
  if (op.charAt(0) === '.') return;
  var from = dirname + op;
  var to = from.replace('/lib/', '/');
  fs.renameSync(from, to);
});

<commit_msg>debug install errors<commit_after>#!/usr/bin/env node
'use strict';

var fs = require('fs');

var dirname = __dirname.split('/');
dirname.pop();
dirname = dirname.join('/');
dirname += '/lib/';

var dirs = [];

try { dirs = fs.readdirSync(dirname); }catch(e) {}

dirs.forEach(function (op) {
  if (op.charAt(0) === '.') return;
  var from = dirname + op;
  var to = from.replace('/lib/', '/');
  console.log('op:', op, 'from:', from, 'to:', to);
  fs.renameSync(from, to);
});

<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';
var log              =  require('npmlog')
  , resolveGitRemote =  require('resolve-git-remote')
  , getConfig        =  require('../lib/get-config')
  , updatePackage    =  require('../lib/update-package')
  , createHook       =  require('../lib/create-testling-hook')
  , testHook         =  require('../lib/test-testling-hook')
  ;

var task = (function () {
  var arg = process.argv[2];
  if (!arg) return 'hook';

  arg = arg.toLowerCase();
  if (arg === 'test' || arg === 'badge') return arg;

  log.error('testlingify', 'unknown task: ' + arg);
  process.exit(1);
})();

if (task === 'hook') {
  log.info('testlingify', 'Adding testling config to your package and creating testling hook on your github repository');
}
if (task === 'test') {
  log.info('testlingify', 'Testing testling hook on your github repository');
}

resolveGitRemote(function (err, remote) {
  if (err) {
    log.error('testlingify', err);
    log.error('testlingify', 'Sorry, testingify has to be executed from inside a git repository');
    process.exit(1);
  }
  gotRemote(remote);
});

function gotRemote(remote) {
  var ownerRepo = remote.split('/')
    , owner = ownerRepo[0]
    , repo = ownerRepo[1]
    ;

  if (task === 'badge')
    return console.log(
      '[![testling badge](https://ci.testling.com/' + owner + '/' + repo + '.png)]' +
      '(https://ci.testling.com/' + owner + '/' + repo + ')'
    );

  getConfig(function (err, config) {
    if (err) {
      log.error('testlingify', err);
      process.exit(1);
    }
    checkConfig(config);
    gotRemoteAndConfig(config, owner, repo);
  });
}

function gotRemoteAndConfig(config, owner, repo) {
  if (config.github.username !== owner)
    log.warn('testlingify', 'github username found in config: "%s", does not match username of repository: "%s"', config.github.username, owner);

  if (task === 'hook')
    return updatePackage(config, createTestlingHook.bind(null, config, owner, repo));
  if (task === 'test')
    return testTestlingHook(config, owner, repo);

  log.error('testlingify', 'Unkown task: %s. Try "testlingify" or "testlignify test" or "testlingify badge"', task);
}

function createTestlingHook(config, owner, repo) {
  var gh = config.github;
  createHook(gh.username, gh.password, owner, repo, function (err, hook) {
    if (err) {
      log.error('testlingify', 'Encountered error when testling hook for %s/%s as %s', owner, repo, config.github.username);
      return log.error('testlingify', err);
    }

    return hook.created
      ? log.info('testlingify', 'Successfully created testling hook for %s/%s as %s', owner, repo, config.github.username)
      : log.warn('testlingify', 'Did not create testling hook for %s/%s as %s because it already exists', owner, repo, config.github.username);
  });
}

function testTestlingHook(config, owner, repo) {
  var gh = config.github;
  testHook(gh.username, gh.password, owner, repo, function (err, hook) {
    if (err) return log.error('testlingify', err.message);
    if (hook.sent) return log.info('testlingify', hook.message);
    log.warn('testlingify', 'Although no error occurred, a post to your testling hook could not be properly sent');
  });
}

function checkConfig(config) {
  function tellToEditAndExit(problem) {
    log.error('testlingify', problem);
    log.error('testlingify', 'Please edit the testlingify config at %s to correct this.', config.location);
    process.exit(1);
  }

  var github = config.github;
  if (!github) tellToEditAndExit('No github config found!');
  if (!github.username || github.username.length === 0) tellToEditAndExit('github username missing!');
  if (!github.password || github.password.length === 0) tellToEditAndExit('github password missing!');
  if (!config.testling) tellToEditAndExit('testling config missing!');
}
<commit_msg>Print documentation for -h or --help<commit_after>#!/usr/bin/env node

'use strict';
var log              =  require('npmlog')
  , resolveGitRemote =  require('resolve-git-remote')
  , getConfig        =  require('../lib/get-config')
  , updatePackage    =  require('../lib/update-package')
  , createHook       =  require('../lib/create-testling-hook')
  , testHook         =  require('../lib/test-testling-hook')
  ;

var task = (function () {
  var arg = process.argv[2];
  if (!arg) return 'hook';

  arg = arg.toLowerCase();
  if (arg === 'test' || arg === 'badge') return arg;

  if (arg === "-h" || arg === "--help") {
    return console.log("usage:\n" +
      "run testlingify to add hooks.\n" +
      "run testlingify test to test the hook")
  }

  log.error('testlingify', 'unknown task: ' + arg);
  process.exit(1);
})();

if (task === 'hook') {
  log.info('testlingify', 'Adding testling config to your package and creating testling hook on your github repository');
}
if (task === 'test') {
  log.info('testlingify', 'Testing testling hook on your github repository');
}

resolveGitRemote(function (err, remote) {
  if (err) {
    log.error('testlingify', err);
    log.error('testlingify', 'Sorry, testingify has to be executed from inside a git repository');
    process.exit(1);
  }
  gotRemote(remote);
});

function gotRemote(remote) {
  var ownerRepo = remote.split('/')
    , owner = ownerRepo[0]
    , repo = ownerRepo[1]
    ;

  if (task === 'badge')
    return console.log(
      '[![testling badge](https://ci.testling.com/' + owner + '/' + repo + '.png)]' +
      '(https://ci.testling.com/' + owner + '/' + repo + ')'
    );

  getConfig(function (err, config) {
    if (err) {
      log.error('testlingify', err);
      process.exit(1);
    }
    checkConfig(config);
    gotRemoteAndConfig(config, owner, repo);
  });
}

function gotRemoteAndConfig(config, owner, repo) {
  if (config.github.username !== owner)
    log.warn('testlingify', 'github username found in config: "%s", does not match username of repository: "%s"', config.github.username, owner);

  if (task === 'hook')
    return updatePackage(config, createTestlingHook.bind(null, config, owner, repo));
  if (task === 'test')
    return testTestlingHook(config, owner, repo);

  log.error('testlingify', 'Unkown task: %s. Try "testlingify" or "testlignify test" or "testlingify badge"', task);
}

function createTestlingHook(config, owner, repo) {
  var gh = config.github;
  createHook(gh.username, gh.password, owner, repo, function (err, hook) {
    if (err) {
      log.error('testlingify', 'Encountered error when testling hook for %s/%s as %s', owner, repo, config.github.username);
      return log.error('testlingify', err);
    }

    return hook.created
      ? log.info('testlingify', 'Successfully created testling hook for %s/%s as %s', owner, repo, config.github.username)
      : log.warn('testlingify', 'Did not create testling hook for %s/%s as %s because it already exists', owner, repo, config.github.username);
  });
}

function testTestlingHook(config, owner, repo) {
  var gh = config.github;
  testHook(gh.username, gh.password, owner, repo, function (err, hook) {
    if (err) return log.error('testlingify', err.message);
    if (hook.sent) return log.info('testlingify', hook.message);
    log.warn('testlingify', 'Although no error occurred, a post to your testling hook could not be properly sent');
  });
}

function checkConfig(config) {
  function tellToEditAndExit(problem) {
    log.error('testlingify', problem);
    log.error('testlingify', 'Please edit the testlingify config at %s to correct this.', config.location);
    process.exit(1);
  }

  var github = config.github;
  if (!github) tellToEditAndExit('No github config found!');
  if (!github.username || github.username.length === 0) tellToEditAndExit('github username missing!');
  if (!github.password || github.password.length === 0) tellToEditAndExit('github password missing!');
  if (!config.testling) tellToEditAndExit('testling config missing!');
}
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";

    var slice = require("base/slice");
    var assert = require("base/assert");
    var trim = require("base/trim");
    var hasOwnProperty = require("base/hasOwnProperty");

    var DEVICE_PIXEL_RATIO = window.devicePixelRatio;

    var validator = {
        map: function (set) {
            return function (value) {
                value = trim(value);
                assert(hasOwnProperty(set, value), "unknow key \"" + value + "\"");
                return set[value];
            };
        },
        oneOf: function ( /*list*/ ) {
            var list = slice(arguments);
            return function (value) {
                value = trim(value);
                assert(list.indexOf(value) > -1, "value mast be one of " + list.join());
                return value;
            };
        },

        string: function (value) {
            return String(value);
        },

        font: function (value) {
            return String(value);
        },

        px: function (value) {
            var regResult = /^(\-?\d+(?:\.\d+)?)(?:px)?$/.match(value); //TODO: 目前阶段为了容错，暂时仍支持不加px单位，后续考虑不允许不写单位
            assert(!!regResult, "value must be number, unit must be px");
            return parseFloat(regResult[1]);
        },

        number: function (value) {
            assert(!isNaN(value) && isFinite(value), "must be number");
            value = parseFloat(value);
            return value;
        },

        boolean: function (value) {
            if (value !== true && value !== false) {
                value = trim(String(value)).toLowerCase();
                value = value === "true" ? true : value === "false" ? false : assert(false, "must be boolean");
            }
            return value;
        },

        color: (function () {
            var NAMEED_COLORS = {
                "transparent": "#00000000",
                "black": "#ff000000",
                "silver": "#ffc0c0c0",
                "gray": "#ff808080",
                "white": "#ffffffff",
                "maroon": "#ff800000",
                "red": "#ffff0000",
                "purple": "#ff800080",
                "fuchsia": "#ffff00ff",
                "green": "#ff008000",
                "lime": "#ff00ff00",
                "olive": "#ff808000",
                "yellow": "#ffffff00",
                "navy": "#ff000080",
                "blue": "#ff0000ff",
                "teal": "#ff008080",
                "aqua": "#ff00ffff",
                "orange": "#ffffa500"
            };
            var REG_HEX_RGB = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/;
            var REG_HEX_RRGGBB = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/;
            var REG_RGB = /^rgb\s*\(\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*\)$/;
            var REG_RGBA = /^rgba\s*\(\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*\)$/;
            //^[1-9]/d*/./d*|0/./d*[1-9]/d*$

            function getHexValue(value, maxValue) {
                value = Math.round(value * 0xFF / maxValue);
                return value < 0x10 ? "0" + value.toString(16) : value.toString(16);
            }

            return function (value) {

                value = trim(value).toLowerCase();

                if (hasOwnProperty(NAMEED_COLORS, value)) {
                    return NAMEED_COLORS[value];
                }
                if (REG_HEX_RGB.test(value)) {
                    return "#ff" +
                        RegExp.$1 + RegExp.$1 +
                        RegExp.$2 + RegExp.$2 +
                        RegExp.$3 + RegExp.$3;
                }
                if (REG_HEX_RRGGBB.test(value)) {
                    return "#ff" +
                        RegExp.$1 +
                        RegExp.$2 +
                        RegExp.$3;
                }
                if (REG_RGB.test(value)) {
                    return "#ff" +
                        getHexValue(parseFloat(RegExp.$1), 0xFF) + // r
                        getHexValue(parseFloat(RegExp.$2), 0xFF) + // g
                        getHexValue(parseFloat(RegExp.$3), 0xFF); // b
                }
                if (REG_RGBA.test(value)) {
                    return "#" +
                        getHexValue(parseFloat(RegExp.$4), 1) + // a
                        getHexValue(parseFloat(RegExp.$1), 0xFF) + // r
                        getHexValue(parseFloat(RegExp.$2), 0xFF) + // g
                        getHexValue(parseFloat(RegExp.$3), 0xFF); // b
                }
                assert(false, "unknow color: \"" + value + "\"");
            };
        })()

    };

    module.exports = validator;

});
<commit_msg>bug fix: reg.match -> reg.exec<commit_after>define(function (require, exports, module) {
    "use strict";

    var slice = require("base/slice");
    var assert = require("base/assert");
    var trim = require("base/trim");
    var hasOwnProperty = require("base/hasOwnProperty");

    var DEVICE_PIXEL_RATIO = window.devicePixelRatio;

    var validator = {
        map: function (set) {
            return function (value) {
                value = trim(value);
                assert(hasOwnProperty(set, value), "unknow key \"" + value + "\"");
                return set[value];
            };
        },
        oneOf: function ( /*list*/ ) {
            var list = slice(arguments);
            return function (value) {
                value = trim(value);
                assert(list.indexOf(value) > -1, "value mast be one of " + list.join());
                return value;
            };
        },

        string: function (value) {
            return String(value);
        },

        font: function (value) {
            return String(value);
        },

        px: function (value) {
            var regResult = /^(\-?\d+(?:\.\d+)?)(?:px)?$/.exec(value); //TODO: 目前阶段为了容错，暂时仍支持不加px单位，后续考虑不允许不写单位
            assert(!!regResult, "value must be number, unit must be px");
            return parseFloat(regResult[1]);
        },

        number: function (value) {
            assert(!isNaN(value) && isFinite(value), "must be number");
            value = parseFloat(value);
            return value;
        },

        boolean: function (value) {
            if (value !== true && value !== false) {
                value = trim(String(value)).toLowerCase();
                value = value === "true" ? true : value === "false" ? false : assert(false, "must be boolean");
            }
            return value;
        },

        color: (function () {
            var NAMEED_COLORS = {
                "transparent": "#00000000",
                "black": "#ff000000",
                "silver": "#ffc0c0c0",
                "gray": "#ff808080",
                "white": "#ffffffff",
                "maroon": "#ff800000",
                "red": "#ffff0000",
                "purple": "#ff800080",
                "fuchsia": "#ffff00ff",
                "green": "#ff008000",
                "lime": "#ff00ff00",
                "olive": "#ff808000",
                "yellow": "#ffffff00",
                "navy": "#ff000080",
                "blue": "#ff0000ff",
                "teal": "#ff008080",
                "aqua": "#ff00ffff",
                "orange": "#ffffa500"
            };
            var REG_HEX_RGB = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/;
            var REG_HEX_RRGGBB = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/;
            var REG_RGB = /^rgb\s*\(\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*\)$/;
            var REG_RGBA = /^rgba\s*\(\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*,\s*(\d+|\d*\.\d+)\s*\)$/;
            //^[1-9]/d*/./d*|0/./d*[1-9]/d*$

            function getHexValue(value, maxValue) {
                value = Math.round(value * 0xFF / maxValue);
                return value < 0x10 ? "0" + value.toString(16) : value.toString(16);
            }

            return function (value) {

                value = trim(value).toLowerCase();

                if (hasOwnProperty(NAMEED_COLORS, value)) {
                    return NAMEED_COLORS[value];
                }
                if (REG_HEX_RGB.test(value)) {
                    return "#ff" +
                        RegExp.$1 + RegExp.$1 +
                        RegExp.$2 + RegExp.$2 +
                        RegExp.$3 + RegExp.$3;
                }
                if (REG_HEX_RRGGBB.test(value)) {
                    return "#ff" +
                        RegExp.$1 +
                        RegExp.$2 +
                        RegExp.$3;
                }
                if (REG_RGB.test(value)) {
                    return "#ff" +
                        getHexValue(parseFloat(RegExp.$1), 0xFF) + // r
                        getHexValue(parseFloat(RegExp.$2), 0xFF) + // g
                        getHexValue(parseFloat(RegExp.$3), 0xFF); // b
                }
                if (REG_RGBA.test(value)) {
                    return "#" +
                        getHexValue(parseFloat(RegExp.$4), 1) + // a
                        getHexValue(parseFloat(RegExp.$1), 0xFF) + // r
                        getHexValue(parseFloat(RegExp.$2), 0xFF) + // g
                        getHexValue(parseFloat(RegExp.$3), 0xFF); // b
                }
                assert(false, "unknow color: \"" + value + "\"");
            };
        })()

    };

    module.exports = validator;

});
<|endoftext|>


<commit_before>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<commit_msg>Add Military Branch and Rank to Flight Export.<commit_after>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<|endoftext|>


<commit_before>// Given an input string, determine whether any anagram of the string is a palindrome

function isPalindrome(str){
  var len = str.length;
  for(var i = 0; i < len/2; i++){
    if (str[i]!== str[len -1 -i])
       return false;
  }
  return true;
}

function isPalindrome(str) {
    var revStr = "";
    for (var i = str.length - 1; i >= 0; i--) {
        revStr += str[i];
    }
    if (str === revStr) {
      return true
    }
    else {
      return false
    }
}

//  palindrome, considering only alphanumeric characters and ignoring cases.
var isPalindrome = function(str) {
  var s = str.toUpperCase().replace(/[\W_]+/g,"");
  var len = s.length;
  for(var i = 0; i < len/2; i++){
    if (s[i]!== s[len -1 -i])
       return false;
  }
  return true;
};
<commit_msg>add solution<commit_after>// Given an input string, determine whether any anagram of the string is a palindrome

function isPalindrome(str){
  var len = str.length;
  for(var i = 0; i < len/2; i++){
    if (str[i]!== str[len -1 -i])
       return false;
  }
  return true;
}

function isPalindrome(str) {
    var revStr = "";
    for (var i = str.length - 1; i >= 0; i--) {
        revStr += str[i];
    }
    if (str === revStr) {
      return true
    }
    else {
      return false
    }
}

//  palindrome, considering only alphanumeric characters and ignoring cases.
var isPalindrome = function(str) {
  var s = str.toUpperCase().replace(/[\W_]+/g,"");
  var len = s.length;
  for(var i = 0; i < len/2; i++){
    if (s[i]!== s[len -1 -i])
       return false;
  }
  return true;
};

var isPalindrome = function(str) {
  var s = str.toUpperCase().replace(/[\W_]+/g,"");
  var len = s.length;
  var counter = 0;
      for(var i = len - 1; i > len/2; i--){
          if (s[i]!== s[counter])
               return false;
          counter++;
       }
  return true;
};
<|endoftext|>


<commit_before><commit_msg>minor<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {

    // jQuery cycle plugin usage
    $('.slideshow').cycle({
        fx:     'scrollRight',
        speed: 300,
        timeout: 4000,
    });
});
<commit_msg>tweak slideshow animation<commit_after>$(document).ready(function() {

    // jQuery cycle plugin usage
    $('.slideshow').cycle({
        fx:     'fade',
        speed: 1000,
        timeout: 6000,
    });
});
<|endoftext|>


<commit_before>require('vigour-scratch/index.less')
require('./style.less')

var Element = require('../../lib/element')
var app = new Element({
  node: document.body
})

Element.prototype.inject(
  require('vigour-js/lib/operator/add'),
  require('../../lib/events/down'),
  require('../../lib/events/move')
)

var Property = require('../../lib/property')
Property.prototype.inject(require('../../lib/animation'))

var mouse = new Property({
  x: 0,
  y: 0
})

var thing = new Element({
  inject: [
    require('../../lib/property/size'),
    require('../../lib/property/transform')
  ],
  width: 20,
  height: 20
})

thing.node.style.position = 'absolute'

var Img = new Element({
  background: {
    inject: require('../../lib/property/background/position')
  }
}).Constructor

var holder = new Element({})

for (var i = 0; i < 100; i++) {
  var t = new thing.Constructor({
    define: {
      i: i
    },
    y: {
      val: mouse.y,
      add: function () {
        return Math.sin(this.parent.i / 10 + mouse.y.val / 20) * (mouse.y.val)
      },
      animation: {
        duration: 200
      }
    },
    scale: i * 0.01 + 1,
    x: {
      val: mouse.x,
      add: function () {
        return Math.cos(this.parent.i / 20 + mouse.x.val / 200) * 300 + 150
      },
      animation: {
        duration: i / 5
      }
    }
  })
  holder.setKey(i, t)
}

app.set({
  holder: holder,
  on: {
    move: function (e, event) {
      mouse.x.val = e.pageX
      mouse.y.val = e.pageY
    },
    down: function (e, event) {
      mouse.x.val = e.pageX
      mouse.y.val = e.pageY
    }
  }
})
<commit_msg>playing with add operator<commit_after>require('vigour-scratch/index.less')
require('./style.less')

var Element = require('../../lib/element')
var app = new Element({
  node: document.body
})

Element.prototype.inject(
  require('../../lib/events/down'),
  require('../../lib/events/move')
)

var Observable = require('vigour-js/lib/observable')
Observable.prototype.inject(
  // require('vigour-js/lib/operator/add')
)

var Property = require('../../lib/property')
Property.prototype.inject(
  require('../../lib/animation')
)

var mouse = new Property({
  x: 0,
  y: 0
})

var thing = new Element({
  inject: [
    require('../../lib/property/size'),
    require('../../lib/property/transform'),

    // add operator
    require('vigour-js/lib/operator/add')
  ],
  width: 20,
  height: 20
})

thing.node.style.position = 'absolute'

var Img = new Element({
  background: {
    inject: require('../../lib/property/background/position')
  }
}).Constructor

var holder = new Element({})

for (var i = 0; i < 100; i++) {
  var t = new thing.Constructor({
    define: {
      i: i
    },
    y: {
      val: mouse.y,
      add: function () {
        return Math.sin(this.parent.i / 10 + mouse.y.val / 20) * (mouse.y.val)
      },
      animation: {
        duration: 200
      }
    },
    scale: i * 0.01 + 1,
    x: {
      val: mouse.x,
      add: function () {
        return Math.cos(this.parent.i / 20 + mouse.x.val / 200) * 300 + 150
      },
      animation: {
        duration: i / 5
      }
    }
  })
  holder.setKey(i, t)
}

app.set({
  holder: holder,
  on: {
    move: function (e, event) {
      mouse.x.val = e.pageX
      mouse.y.val = e.pageY
    },
    down: function (e, event) {
      mouse.x.val = e.pageX
      mouse.y.val = e.pageY
    }
  }
})
<|endoftext|>


<commit_before>import React from 'react';

import {SharedElementTransitionGroup} from '../../src/index.js';
import Page1 from './Page1';
import Page2 from './Page2';

class Example extends React.Component {
    state = {
        switch: true,
    };

    toggle = () => {
        this.setState((prevState) => ({
            switch: !prevState.switch,
        }));
    };

    render() {
        return (

                <button onClick={this.toggle}>Click Me</button>
                <SharedElementTransitionGroup>
                    {this.state.switch && <Page1 />}
                    {!this.state.switch && <Page2 />}
                </SharedElementTransitionGroup>

        );
    }
}

export default Example;
<commit_msg>Change imported file name<commit_after>import React from 'react';

import {SharedElementTransitionGroup} from '../../src/index.tsx';
import Page1 from './Page1';
import Page2 from './Page2';

class Example extends React.Component {
    state = {
        switch: true,
    };

    toggle = () => {
        this.setState((prevState) => ({
            switch: !prevState.switch,
        }));
    };

    render() {
        return (

                <button onClick={this.toggle}>Click Me</button>
                <SharedElementTransitionGroup>
                    {this.state.switch && <Page1 />}
                    {!this.state.switch && <Page2 />}
                </SharedElementTransitionGroup>

        );
    }
}

export default Example;
<|endoftext|>


<commit_before>"Use Strict";
var test = "Mine";

for (var i = 0; i < 10; i++) {
    test += i;
}
alert(test);
function FirstFactorial(num) {
    "Use Strict";
    // code goes here
    var mysum = 1;
    for (var i = 1; i < num + 1; i++) {
        mysum = mysum * i;
    }
    //Return
    return mysum;

}

function LongestWord(sen) {

    // Use RegExp to make sure its a valid word A-Z
    var epathern = /^[a-zA-Z]+$/;
    var maxWord = "";
    //split the string into array
    sen = sen.split(" ");
    for (var i = 0; i < sen.length; i++) {
        if (epathern.test(sen[i])) {
            //check if its the highest
            if (maxWord.length < sen[i].length) {
                maxWord = sen[i];
            }
        }
    }
    if (maxWord === "") {
        maxWord = "No valid Word";
    }
    return maxWord;
}<commit_msg>Added LetterChanges<commit_after>"Use Strict";
var test = "Mine";

for (var i = 0; i < 10; i++) {
    test += i;
}
alert(test);
function FirstFactorial(num) {
    "Use Strict";
    // code goes here
    var mysum = 1;
    for (var i = 1; i < num + 1; i++) {
        mysum = mysum * i;
    }
    //Return
    return mysum;

}

function LongestWord(sen) {

    // Use RegExp to make sure its a valid word A-Z
    var epathern = /^[a-zA-Z]+$/;
    var maxWord = "";
    //split the string into array
    sen = sen.split(" ");
    for (var i = 0; i < sen.length; i++) {
        if (epathern.test(sen[i])) {
            //check if its the highest
            if (maxWord.length < sen[i].length) {
                maxWord = sen[i];
            }
        }
    }
    if (maxWord === "") {
        maxWord = "No valid Word";
    }
    return maxWord;
}

function LetterChanges(str) {

    var newstr = "";
    var word = "";
    var validletter = /^[a-zA-Z]+$/;

    for (var i = 0; i < str.length; i++) { //Get all the letters
        if (!validletter.test(str[i])) { //check for valid letters
            newstr = str[i];             //takes care of numbers and spaces and special char
        } else if (str[i] === 'z' || str[i] === 'Z') { //converts z to a (both cases)
            newstr = String.fromCharCode(str[i].charCodeAt(0));
        } else {
            newstr = String.fromCharCode(str[i].charCodeAt(0) + 1); //do other letters
        }
        //Do vowels
        if (newstr === 'a' || newstr === 'e' || newstr === 'o' || newstr === 'u') {
            newstr = newstr.toUpperCase();
        }
        word = word + newstr; //all to the entire string
    }

    return word;

}<|endoftext|>


<commit_before><commit_msg>Fix syntax error<commit_after><|endoftext|>


<commit_before>var SelectTree = (function () {

    var my = {};

    my.initTree = function (config) {

        jQuery(config.selector).jstree({
            "core": {
                "initially_load": config.path.expanded,
                "initially_open": config.path.preloaded
            },
            "plugins": [ "themes", "types", "ui", "json_data"],
            "json_data": {
                "ajax": {
                    url:    Routing.generate('symfony_cmf_phpcr_browser_children'),
                    data:   function (node) {
                        if(node == -1) {
                            return { 'root' : config.rootNode };
                        } else {
                            return { 'root' : jQuery(node).attr('id') };
                        }
                    }
                }
            },
            "types": {
                "max_depth":        -2,
                "max_children":     -2,
                "valid_children":  [ "folder" ],
                "types": {
                    "default": {
                        "valid_children": "none",
                        "icon": {
                            "image": config.icon.document
                        }
                    },
                    "folder": {
                        "valid_children": [ "default", "folder" ],
                        "icon": {
                            "image": config.icon.folder
                        }
                    }
                }
            },
        })
        .bind("select_node.jstree", function (event, data) {
            jQuery(config.output).val(data.rslt.obj.attr("id"));
        })
        .bind("move_node.jstree", function (event, data) {
            var dropped = data.rslt.o;
            var target = data.rslt.r;

            $.post(
                Routing.generate('symfony_cmf_phpcr_browser_move'),
                { "dropped": dropped.attr("id"), "target": target.attr("id") },
                function (data) {
                    dropped.attr("id", data);
                }
            );
        })
        .delegate("a", "click", function (event, data) { event.preventDefault(); });
    };

    return my;

}());
<commit_msg>removing code related to move ndoes in select tree setup<commit_after>var SelectTree = (function () {

    var my = {};

    my.initTree = function (config) {

        jQuery(config.selector).jstree({
            "core": {
                "initially_load": config.path.expanded,
                "initially_open": config.path.preloaded
            },
            "plugins": [ "themes", "types", "ui", "json_data"],
            "json_data": {
                "ajax": {
                    url:    Routing.generate('symfony_cmf_phpcr_browser_children'),
                    data:   function (node) {
                        if(node == -1) {
                            return { 'root' : config.rootNode };
                        } else {
                            return { 'root' : jQuery(node).attr('id') };
                        }
                    }
                }
            },
            "types": {
                "max_depth":        -2,
                "max_children":     -2,
                "valid_children":  [ "folder" ],
                "types": {
                    "default": {
                        "valid_children": "none",
                        "icon": {
                            "image": config.icon.document
                        }
                    },
                    "folder": {
                        "valid_children": [ "default", "folder" ],
                        "icon": {
                            "image": config.icon.folder
                        }
                    }
                }
            },
        })
        .bind("select_node.jstree", function (event, data) {
            jQuery(config.output).val(data.rslt.obj.attr("id"));
        })
        .delegate("a", "click", function (event, data) { event.preventDefault(); });
    };

    return my;

}());
<|endoftext|>


<commit_before>/*
*	HEPIPE-JANUS 0.1
*	Meetecho Janus Event API to HEP/EEP Utility
*	Copyright 2016 QXIP BV (http://qxip.net)
*/

var version = 0.1
console.log("HEPIPE-JANUS v"+version+" (http://sipcapture.org)");
console.log("Press CTRL-C to Exit...");

/* Requires */

var http = require('http');
var HEPjs = require('hep-js');
var dgram = require('dgram');
var socket = dgram.createSocket("udp4");

var dirty = require('dirty');
var db = dirty(); // omit filename for no persistence

	/* Default Config */

	var _config_ = {
			HEP_SERVER: '127.0.0.1',
			HEP_PORT: 9060,
			HEP_PASS: 'multipass',
			HEP_ID: 2222,
			API_SERVER: '127.0.0.1',
			API_PORT: 7777
	};

var debug = false;
var report_rtcp = false; // Media to RTCP
var log = true; // SIP + Session

var exit = false;
var stats = {rcvd: 0, parsed: 0, hepsent: 0, err: 0, heperr: 0 };

/* Command Options */

if(process.argv.indexOf("-d") != -1){ debug = true; }
if(process.argv.indexOf("-s") != -1){ _config_.HEP_SERVER = process.argv[process.argv.indexOf("-s") + 1]; }
if(process.argv.indexOf("-p") != -1){ _config_.HEP_PORT = process.argv[process.argv.indexOf("-p") + 1]; }
if(process.argv.indexOf("-es") != -1){ _config_.API_SERVER = process.argv[process.argv.indexOf("-es") + 1]; }
if(process.argv.indexOf("-ep") != -1){ _config_.API_PORT = process.argv[process.argv.indexOf("-ep") + 1]; }

/* UDP Socket Handler */

var getSocket = function (type) {
    if (undefined === socket) {
        socket = dgram.createSocket(type);
        socket.on('error', socketErrorHandler);
        /**
         * Handles socket's 'close' event,
         * recover socket in case of unplanned closing.
         */
        var socketCloseHandler = function () {
            if (socketUsers > 0) {
                socket = undefined;
                --socketUsers;
                getSocket(type);
            }
        };
        socket.on('close', socketCloseHandler);
    }
    return socket;
}

var socket = dgram.createSocket("udp4");
    socket = getSocket('udp4');

/* HEP Handler */

var sendHEP3 = function(msg,rcinfo){
	if (rcinfo && msg) {
		try {
			if (debug) console.log('Sending HEP3 Packet to '+_config_.HEP_SERVER+':'+_config_.HEP_PORT+'...');
			if (! typeof msg === 'string' || ! msg instanceof String) msg = JSON.stringify(msg);
			var hep_message = HEPjs.encapsulate(msg.toString(),rcinfo);
			stats.parsed++;
			if (hep_message && hep_message.length) {
				socket.send(hep_message, 0, hep_message.length, _config_.HEP_PORT, _config_.HEP_SERVER, function(err) {
					stats.hepsent++;
				});
			} else { console.log('HEP Parsing error!'); stats.heperr++; }
		}
		catch (e) {
			console.log('HEP3 Error sending!');
			console.log(e);
			stats.heperr++;
		}
	}
}

var preHep = function(message) {

	var rcinfo = message.rcinfo;
	var msg = message.payload;
	if (rcinfo.correlation_id == null || ! rcinfo.correlation_id.length ) return;
	if (debug) console.log(msg);
	stats.rcvd++;

	var hrTime = process.hrtime();
	var datenow = new Date().getTime();
	rcinfo.time_sec = Math.floor( datenow / 1000);
	rcinfo.time_usec = datenow - (rcinfo.time_sec*1000);

	if (debug) console.log(rcinfo);
	sendHEP3(msg,rcinfo);
};

/* JANUS Event Handler */

function processJanusEvent(e) {
      // Parse Event
      e = JSON.parse(e);
      // do stuff
      if (debug) console.log('Janus Session-ID: ' + e.session_id);
      if (debug) console.log('Janus Event Type: ' + e.type);

      // No CID no Party! Check handle_id to Call-ID association, Skip if none available
	if (db) {
			if (db.get(e.handle_id)) {
				if (debug) console.log('FOUND HANDLE ID!', db.get(e.handle_id).cid);
				var xcid = db.get(e.handle_id).cid;
			}

   	} else { var xcid = e.handle_id; }

	/* EVENT LOGGER */
	if (log) {

	    // Log Events to HEP Message
	    if(e.type == 64) {

		// Save association Handle-ID > SIP Call-ID
		if(e.event.data['call-id']) {
		    db.set(e.handle_id, {cid: e.event.data['call-id']}, function() {
		       if (debug) console.log('Session Correlation ' + e.handle_id + ' = ' + e.event.data['call-id']);
   		    });
		    xcid = e.event.data['call-id'];
	        }

		var ip = '127.0.0.1';

		if(e.event.data['sip']) {
		// Send as SIP type

			var payload = e.event.data['sip'];

			// Format HEP Header
			var message = {

				rcinfo: {
	                          type: 'HEP',
	                          version: 3,
	                          payload_type: 'SIP',
	                          captureId: _config_.HEP_ID,
	                          capturePass: _config_.HEP_PASS,
	                          ip_family: 2,
	                          protocol: 17,
	                          proto_type: 1,
	                          srcIp: ip,
	                          dstIp: ip,
	                          srcPort: 0,
	                          dstPort: 0,
	                          correlation_id: xcid ? xcid : e.handle_id
	                  	},
			        payload: payload
			};

			// Prepare for shipping!
			preHep(message);

		} else {
		// Send as Log type
	 	        var payload = e.timestamp + ': ';
		        payload += JSON.stringify(e.event);

			// Format HEP Header
			var message = {

				rcinfo: {
	                          type: 'HEP',
	                          version: 3,
	                          payload_type: 'JSON',
	                          captureId: _config_.HEP_ID,
	                          capturePass: _config_.HEP_PASS,
	                          ip_family: 2,
	                          protocol: 17,
	                          proto_type: 100,
	                          srcIp: ip,
	                          dstIp: ip,
	                          srcPort: 0,
	                          dstPort: 0,
	                          correlation_id: xcid ? xcid : e.handle_id
	                  	},
			        payload: payload
			};

			// Prepare for shipping!
			preHep(message);

		}

	  }
      }
}

/* HTTP API Receiver */

http.createServer(function (req, res) {
    var body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        // console.log(body);
	processJanusEvent(body);
        res.writeHead(200);
        res.end();
    });
}).listen(_config_.API_PORT);

/* Exit */

process.on('SIGINT', function() {
    console.log();
    console.log('Stats:',stats);
    if (exit) {
    	console.log("Exiting...");
        process.exit();
    } else {
    	console.log("Press CTRL-C within 2 seconds to Exit...");
        exit = true;
	setTimeout(function () {
    	  // console.log("Continuing...");
	  exit = false;
	}, 2000)
    }
});
<commit_msg>hepipe-janus.js: returns when correlation_id is a number<commit_after>/*
*	HEPIPE-JANUS 0.1
*	Meetecho Janus Event API to HEP/EEP Utility
*	Copyright 2016 QXIP BV (http://qxip.net)
*/

var version = 0.1
console.log("HEPIPE-JANUS v"+version+" (http://sipcapture.org)");
console.log("Press CTRL-C to Exit...");

/* Requires */

var http = require('http');
var HEPjs = require('hep-js');
var dgram = require('dgram');
var socket = dgram.createSocket("udp4");

var dirty = require('dirty');
var db = dirty(); // omit filename for no persistence

	/* Default Config */

	var _config_ = {
			HEP_SERVER: '127.0.0.1',
			HEP_PORT: 9060,
			HEP_PASS: 'multipass',
			HEP_ID: 2222,
			API_SERVER: '127.0.0.1',
			API_PORT: 7777
	};

var debug = false;
var report_rtcp = false; // Media to RTCP
var log = true; // SIP + Session

var exit = false;
var stats = {rcvd: 0, parsed: 0, hepsent: 0, err: 0, heperr: 0 };

/* Command Options */

if(process.argv.indexOf("-d") != -1){ debug = true; }
if(process.argv.indexOf("-s") != -1){ _config_.HEP_SERVER = process.argv[process.argv.indexOf("-s") + 1]; }
if(process.argv.indexOf("-p") != -1){ _config_.HEP_PORT = process.argv[process.argv.indexOf("-p") + 1]; }
if(process.argv.indexOf("-es") != -1){ _config_.API_SERVER = process.argv[process.argv.indexOf("-es") + 1]; }
if(process.argv.indexOf("-ep") != -1){ _config_.API_PORT = process.argv[process.argv.indexOf("-ep") + 1]; }

/* UDP Socket Handler */

var getSocket = function (type) {
    if (undefined === socket) {
        socket = dgram.createSocket(type);
        socket.on('error', socketErrorHandler);
        /**
         * Handles socket's 'close' event,
         * recover socket in case of unplanned closing.
         */
        var socketCloseHandler = function () {
            if (socketUsers > 0) {
                socket = undefined;
                --socketUsers;
                getSocket(type);
            }
        };
        socket.on('close', socketCloseHandler);
    }
    return socket;
}

var socket = dgram.createSocket("udp4");
    socket = getSocket('udp4');

/* HEP Handler */

var sendHEP3 = function(msg,rcinfo){
	if (rcinfo && msg) {
		try {
			if (debug) console.log('Sending HEP3 Packet to '+_config_.HEP_SERVER+':'+_config_.HEP_PORT+'...');
			if (! typeof msg === 'string' || ! msg instanceof String) msg = JSON.stringify(msg);
			var hep_message = HEPjs.encapsulate(msg.toString(),rcinfo);
			stats.parsed++;
			if (hep_message && hep_message.length) {
				socket.send(hep_message, 0, hep_message.length, _config_.HEP_PORT, _config_.HEP_SERVER, function(err) {
					stats.hepsent++;
				});
			} else { console.log('HEP Parsing error!'); stats.heperr++; }
		}
		catch (e) {
			console.log('HEP3 Error sending!');
			console.log(e);
			stats.heperr++;
		}
	}
}

var preHep = function(message) {

	var rcinfo = message.rcinfo;
	var msg = message.payload;
	if (rcinfo.correlation_id == null || !(rcinfo.correlation_id.toString().length)) return;
	if (debug) console.log(msg);
	stats.rcvd++;

	var hrTime = process.hrtime();
	var datenow = new Date().getTime();
	rcinfo.time_sec = Math.floor( datenow / 1000);
	rcinfo.time_usec = datenow - (rcinfo.time_sec*1000);

	if (debug) console.log(rcinfo);
	sendHEP3(msg,rcinfo);
};

/* JANUS Event Handler */

function processJanusEvent(e) {
      // Parse Event
      e = JSON.parse(e);
      // do stuff
      if (debug) console.log('Janus Session-ID: ' + e.session_id);
      if (debug) console.log('Janus Event Type: ' + e.type);

      // No CID no Party! Check handle_id to Call-ID association, Skip if none available
	if (db) {
			if (db.get(e.handle_id)) {
				if (debug) console.log('FOUND HANDLE ID!', db.get(e.handle_id).cid);
				var xcid = db.get(e.handle_id).cid;
			}

   	} else { var xcid = e.handle_id; }

	/* EVENT LOGGER */
	if (log) {

	    // Log Events to HEP Message
	    if(e.type == 64) {

		// Save association Handle-ID > SIP Call-ID
		if(e.event.data['call-id']) {
		    db.set(e.handle_id, {cid: e.event.data['call-id']}, function() {
		       if (debug) console.log('Session Correlation ' + e.handle_id + ' = ' + e.event.data['call-id']);
   		    });
		    xcid = e.event.data['call-id'];
	        }

		var ip = '127.0.0.1';

		if(e.event.data['sip']) {
		// Send as SIP type

			var payload = e.event.data['sip'];

			// Format HEP Header
			var message = {

				rcinfo: {
	                          type: 'HEP',
	                          version: 3,
	                          payload_type: 'SIP',
	                          captureId: _config_.HEP_ID,
	                          capturePass: _config_.HEP_PASS,
	                          ip_family: 2,
	                          protocol: 17,
	                          proto_type: 1,
	                          srcIp: ip,
	                          dstIp: ip,
	                          srcPort: 0,
	                          dstPort: 0,
	                          correlation_id: xcid ? xcid : e.handle_id
	                  	},
			        payload: payload
			};

			// Prepare for shipping!
			preHep(message);

		} else {
		// Send as Log type
	 	        var payload = e.timestamp + ': ';
		        payload += JSON.stringify(e.event);

			// Format HEP Header
			var message = {

				rcinfo: {
	                          type: 'HEP',
	                          version: 3,
	                          payload_type: 'JSON',
	                          captureId: _config_.HEP_ID,
	                          capturePass: _config_.HEP_PASS,
	                          ip_family: 2,
	                          protocol: 17,
	                          proto_type: 100,
	                          srcIp: ip,
	                          dstIp: ip,
	                          srcPort: 0,
	                          dstPort: 0,
	                          correlation_id: xcid ? xcid : e.handle_id
	                  	},
			        payload: payload
			};

			// Prepare for shipping!
			preHep(message);

		}

	  }
      }
}

/* HTTP API Receiver */

http.createServer(function (req, res) {
    var body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        // console.log(body);
	processJanusEvent(body);
        res.writeHead(200);
        res.end();
    });
}).listen(_config_.API_PORT);

/* Exit */

process.on('SIGINT', function() {
    console.log();
    console.log('Stats:',stats);
    if (exit) {
    	console.log("Exiting...");
        process.exit();
    } else {
    	console.log("Press CTRL-C within 2 seconds to Exit...");
        exit = true;
	setTimeout(function () {
    	  // console.log("Continuing...");
	  exit = false;
	}, 2000)
    }
});
<|endoftext|>


<commit_before>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Input } from '../../libs/bootstrap/form';
import { getAffiliationName } from '../../libs/get_affiliation_name';
import { renderSelectedModeInheritance } from '../../libs/render_mode_inheritance';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import MomentLocaleUtils, { formatDate, parseDate } from 'react-day-picker/moment';

class CurationSnapshots extends Component {
    constructor(props) {
        super(props);
    }

    viewSnapshotSummary(snapshotId, type, e) {
        e.preventDefault(); e.stopPropagation();
        const snapshotUuid = snapshotId.slice(11, -1);
        if (type === 'classification') {
            window.open('/gene-disease-evidence-summary/?snapshot=' + snapshotUuid, '_blank');
        } else if (type === 'interpretation') {
            window.open('/variant-interpretation-summary/?snapshot=' + snapshotUuid, '_blank');
        }
    }

    /**
     * Method to display classification tag/label in the interpretation header
     * @param {string} status - The status of a given classification in an interpretation
     */
    renderClassificationStatusTag(status) {
        if (status === 'Provisioned') {
            return PROVISIONAL;
        } else if (status === 'Approved') {
            return APPROVED;
        }
    }

    renderProvisionalSnapshotStatusIcon(index) {
        if (index.toString() === "0") {
            return

;
        } else if (index.toString() === "1") {
            if (this.props.snapshots[0].approvalStatus === 'Approved') {
                return

;
            } else {
                return

;
            }
        } else {
            return

;
        }
    }

    renderProvisionalSnapshotViewSummaryBtn(index) {
        let buttonClass;
        if (index.toString() === "0") {
            buttonClass = 'btn-primary';
        } else if (index.toString() === "1") {
            if (this.props.snapshots[0].approvalStatus === 'Approved') {
                buttonClass = 'btn-primary';
            } else {
                buttonClass = 'btn-default';
            }
        } else {
            buttonClass = 'btn-default';
        }
        return buttonClass;
    }

    renderGdmProvisionalSnapshotApprovalLink(gdm, index) {
        let pathname = window.location.pathname;
        if (index.toString() === "0" && pathname.indexOf('provisional-curation') > -1) {
            return Approve this Saved Provisional;
        }
    }

    renderInterpretationProvisionalSnapshotApprovalLink(interpretation, index) {
        let pathname = window.location.pathname;
        if (index.toString() === "0" && pathname.indexOf('variant-central') > -1) {
            return <button type="button" className="btn btn-warning approve-provisional-link-item" role="button" onClick={this.props.approveProvisional}>Approve this Saved Provisional</button>;
        }
    }

    /**
     * Method to render snapshots in table rows
     * @param {object} snapshot - A saved copy of a provisioned/approved classification and its parent GDM/Interpretation
     */
    renderSnapshot(snapshot, shouldApproveClassification, classificationStatus, index) {
        const type = snapshot.resourceType;
        let buttonClass = index.toString() === "0" || index.toString() === "1" ? 'btn-primary' : 'btn-default';
        let resourceParent;
        if (snapshot.resourceType === 'classification' && snapshot.resourceParent.gdm) {
            resourceParent = snapshot.resourceParent.gdm;
        } else if (snapshot.resourceType === 'interpretation' && snapshot.resourceParent.interpretation) {
            resourceParent = snapshot.resourceParent.interpretation;
        }

        if (snapshot.approvalStatus === 'Provisioned') {
            return (

                                    {snapshot.resource && snapshot.resource.affiliation ?

ClinGen Affiliation:

{getAffiliationName(snapshot.resource.affiliation)}

                                        : null}

Provisional {snapshot.resourceType === 'classification'? 'Classification' : 'Interpretation'} entered by:

{snapshot.resource.provisionalSubmitter}

Date saved as Provisional:

{snapshot.resource.provisionalDate ? formatDate(snapshot.resource.provisionalDate, "YYYY MMM DD, h:mm a") : null}

                                        {this.renderClassificationStatusTag(snapshot.approvalStatus)}

Date reviewed:

{snapshot.resource.provisionalReviewDate ? formatDate(snapshot.resource.provisionalReviewDate, "YYYY MMM DD") : null}

{type === 'interpretation' ? 'Saved Pathogenicity:' : 'Saved Classification:'}

{snapshot.resource.alteredClassification ? {snapshot.resource.alteredClassification} (modified) : snapshot.resource.autoClassification}

Disease:

{resourceParent && resourceParent.disease && resourceParent.disease.term ? resourceParent.disease.term : 'None'}

Mode of Inheritance:

{renderSelectedModeInheritance(resourceParent)}

Additional comments:

{snapshot.resource.provisionalComment ? snapshot.resource.provisionalComment : null}

                                    {this.renderProvisionalSnapshotStatusIcon(index)}
                                    {resourceParent && resourceParent['@type'][0] === 'gdm' && classificationStatus !== 'Approved' ?
                                        this.renderGdmProvisionalSnapshotApprovalLink(resourceParent, index)
                                        : null}
                                    {resourceParent && resourceParent['@type'][0] === 'interpretation' && !shouldApproveClassification && classificationStatus !== 'Approved' ?
                                        this.renderInterpretationProvisionalSnapshotApprovalLink(resourceParent, index)
                                        : null}
                                    <Input type="button" inputClassName={this.renderProvisionalSnapshotViewSummaryBtn(index)} title="View Provisional Summary" clickHandler={this.viewSnapshotSummary.bind(this, snapshot['@id'], type)} />

            );
        } else if (snapshot.approvalStatus === 'Approved') {
            return (

                                    {snapshot.resource && snapshot.resource.affiliation ?

ClinGen Affiliation:

{getAffiliationName(snapshot.resource.affiliation)}

                                        : null}

Approved {snapshot.resourceType === 'classification'? 'Classification' : 'Interpretation'} entered by:

{snapshot.resource.approvalSubmitter}

                                    {snapshot.resource && snapshot.resource.classificationApprover ?

Approver:

{snapshot.resource.classificationApprover}

                                        : null}

Date saved as Approved:

{snapshot.resource.approvalDate ? formatDate(snapshot.resource.approvalDate, "YYYY MMM DD, h:mm a") : null}

                                        {this.renderClassificationStatusTag(snapshot.approvalStatus)}

Date approved:

{snapshot.resource.approvalReviewDate ? formatDate(snapshot.resource.approvalReviewDate, "YYYY MMM DD") : null}

{type === 'interpretation' ? 'Saved Pathogenicity:' : 'Saved Classification:'}

{snapshot.resource.alteredClassification ? {snapshot.resource.alteredClassification} (modified) : snapshot.resource.autoClassification}

Disease:

{resourceParent && resourceParent.disease && resourceParent.disease.term ? resourceParent.disease.term : 'None'}

Mode of Inheritance:

{renderSelectedModeInheritance(resourceParent)}

Additional comments:

{snapshot.resource.approvalComment ? snapshot.resource.approvalComment : null}

                                    {index.toString() === "0" || index.toString() === "1" ?

                                        :

                                    }
                                    <Input type="button" inputClassName={buttonClass} title="View Approved Summary" clickHandler={this.viewSnapshotSummary.bind(this, snapshot['@id'], type)} />

            );
        }
    }

    render() {
        const { snapshots, shouldApproveClassification, classificationStatus } = this.props;

        return (

                    {snapshots.map((snapshot, i) => this.renderSnapshot(snapshot, shouldApproveClassification, classificationStatus, i))}

        );
    }
}

CurationSnapshots.propTypes = {
    snapshots: PropTypes.array,
    approveProvisional: PropTypes.func,
    shouldApproveClassification: PropTypes.bool,
    classificationStatus: PropTypes.string
};

export default CurationSnapshots;<commit_msg>Consolidating the method that handles the click event on the approve provisional button<commit_after>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Input } from '../../libs/bootstrap/form';
import { getAffiliationName } from '../../libs/get_affiliation_name';
import { renderSelectedModeInheritance } from '../../libs/render_mode_inheritance';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import MomentLocaleUtils, { formatDate, parseDate } from 'react-day-picker/moment';

class CurationSnapshots extends Component {
    constructor(props) {
        super(props);
    }

    viewSnapshotSummary(snapshotId, type, e) {
        e.preventDefault(); e.stopPropagation();
        const snapshotUuid = snapshotId.slice(11, -1);
        if (type === 'classification') {
            window.open('/gene-disease-evidence-summary/?snapshot=' + snapshotUuid, '_blank');
        } else if (type === 'interpretation') {
            window.open('/variant-interpretation-summary/?snapshot=' + snapshotUuid, '_blank');
        }
    }

    /**
     * Method to display classification tag/label in the interpretation header
     * @param {string} status - The status of a given classification in an interpretation
     */
    renderClassificationStatusTag(status) {
        if (status === 'Provisioned') {
            return PROVISIONAL;
        } else if (status === 'Approved') {
            return APPROVED;
        }
    }

    renderProvisionalSnapshotStatusIcon(index) {
        if (index.toString() === "0") {
            return

;
        } else if (index.toString() === "1") {
            if (this.props.snapshots[0].approvalStatus === 'Approved') {
                return

;
            } else {
                return

;
            }
        } else {
            return

;
        }
    }

    /**
     * Method to return different Bootstrap button class depending on the index param
     * The 'btn-default' button is changed to have gray background-color instead of white
     * @param {integer} index - The index of the object in the snapshots array
     */
    renderProvisionalSnapshotViewSummaryBtn(index) {
        let buttonClass;
        if (index.toString() === "0") {
            buttonClass = 'btn-primary';
        } else if (index.toString() === "1") {
            if (this.props.snapshots[0].approvalStatus === 'Approved') {
                buttonClass = 'btn-primary';
            } else {
                buttonClass = 'btn-default';
            }
        } else {
            buttonClass = 'btn-default';
        }
        return buttonClass;
    }

    /**
     * Method to render the button that allows users to approval the most recently saved provisional
     * @param {object} resourceParent - The parent object of the classification in a snapshot
     * @param {integer} index - The index of the object in the snapshots array
     */
    renderProvisionalSnapshotApprovalLink(resourceParent, index) {
        let pathname = window.location.pathname;
        if (index.toString() === "0") {
            if (pathname.indexOf('provisional-curation') > -1 && resourceParent['@type'][0] === 'gdm') {
                return (

                        Approve this Saved Provisional

                );
            } else {
                return (
                    <button type="button" className="btn btn-warning approve-provisional-link-item" role="button" onClick={this.props.approveProvisional}>
                        Approve this Saved Provisional
                    </button>
                );
            }
        }
    }

    /**
     * Method to render snapshots in table rows
     * @param {object} snapshot - A saved copy of a provisioned/approved classification and its parent GDM/Interpretation
     */
    renderSnapshot(snapshot, isApprovalActive, classificationStatus, index) {
        const type = snapshot.resourceType;
        let buttonClass = index.toString() === "0" || index.toString() === "1" ? 'btn-primary' : 'btn-default';
        let resourceParent;
        if (snapshot.resourceType === 'classification' && snapshot.resourceParent.gdm) {
            resourceParent = snapshot.resourceParent.gdm;
        } else if (snapshot.resourceType === 'interpretation' && snapshot.resourceParent.interpretation) {
            resourceParent = snapshot.resourceParent.interpretation;
        }

        if (snapshot.approvalStatus === 'Provisioned') {
            return (

                                    {snapshot.resource && snapshot.resource.affiliation ?

ClinGen Affiliation:

{getAffiliationName(snapshot.resource.affiliation)}

                                        : null}

Provisional {snapshot.resourceType === 'classification'? 'Classification' : 'Interpretation'} entered by:

{snapshot.resource.provisionalSubmitter}

Date saved as Provisional:

{snapshot.resource.provisionalDate ? formatDate(snapshot.resource.provisionalDate, "YYYY MMM DD, h:mm a") : null}

                                        {this.renderClassificationStatusTag(snapshot.approvalStatus)}

Date reviewed:

{snapshot.resource.provisionalReviewDate ? formatDate(snapshot.resource.provisionalReviewDate, "YYYY MMM DD") : null}

{type === 'interpretation' ? 'Saved Pathogenicity:' : 'Saved Classification:'}

{snapshot.resource.alteredClassification ? {snapshot.resource.alteredClassification} (modified) : snapshot.resource.autoClassification}

Disease:

{resourceParent && resourceParent.disease && resourceParent.disease.term ? resourceParent.disease.term : 'None'}

Mode of Inheritance:

{renderSelectedModeInheritance(resourceParent)}

Additional comments:

{snapshot.resource.provisionalComment ? snapshot.resource.provisionalComment : null}

                                    {this.renderProvisionalSnapshotStatusIcon(index)}
                                    {resourceParent && !isApprovalActive && classificationStatus !== 'Approved' ?
                                        this.renderProvisionalSnapshotApprovalLink(resourceParent, index)
                                        : null}
                                    <Input type="button" inputClassName={this.renderProvisionalSnapshotViewSummaryBtn(index)} title="View Provisional Summary"
                                        clickHandler={this.viewSnapshotSummary.bind(this, snapshot['@id'], type)} />

            );
        } else if (snapshot.approvalStatus === 'Approved') {
            return (

                                    {snapshot.resource && snapshot.resource.affiliation ?

ClinGen Affiliation:

{getAffiliationName(snapshot.resource.affiliation)}

                                        : null}

Approved {snapshot.resourceType === 'classification'? 'Classification' : 'Interpretation'} entered by:

{snapshot.resource.approvalSubmitter}

                                    {snapshot.resource && snapshot.resource.classificationApprover ?

Approver:

{snapshot.resource.classificationApprover}

                                        : null}

Date saved as Approved:

{snapshot.resource.approvalDate ? formatDate(snapshot.resource.approvalDate, "YYYY MMM DD, h:mm a") : null}

                                        {this.renderClassificationStatusTag(snapshot.approvalStatus)}

Date approved:

{snapshot.resource.approvalReviewDate ? formatDate(snapshot.resource.approvalReviewDate, "YYYY MMM DD") : null}

{type === 'interpretation' ? 'Saved Pathogenicity:' : 'Saved Classification:'}

{snapshot.resource.alteredClassification ? {snapshot.resource.alteredClassification} (modified) : snapshot.resource.autoClassification}

Disease:

{resourceParent && resourceParent.disease && resourceParent.disease.term ? resourceParent.disease.term : 'None'}

Mode of Inheritance:

{renderSelectedModeInheritance(resourceParent)}

Additional comments:

{snapshot.resource.approvalComment ? snapshot.resource.approvalComment : null}

                                    {index.toString() === "0" || index.toString() === "1" ?

                                        :

                                    }
                                    <Input type="button" inputClassName={buttonClass} title="View Approved Summary" clickHandler={this.viewSnapshotSummary.bind(this, snapshot['@id'], type)} />

            );
        }
    }

    render() {
        const { snapshots, isApprovalActive, classificationStatus } = this.props;

        return (

                    {snapshots.map((snapshot, i) => this.renderSnapshot(snapshot, isApprovalActive, classificationStatus, i))}

        );
    }
}

CurationSnapshots.propTypes = {
    snapshots: PropTypes.array,
    approveProvisional: PropTypes.func,
    isApprovalActive: PropTypes.string,
    classificationStatus: PropTypes.string
};

export default CurationSnapshots;<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global _*/
var GDP = GDP || {};

GDP.view = GDP.view || {};

GDP.view.ProcessView = GDP.util.BaseView.extend({

	algorithmConfigView : null,

	events : {
		"click .menu-dropdown-select-process" : "selectProcess"
	},

	render : function () {
		"use strict";
		this.$el.html(this.template(this.collection.models));
		this.algorithmConfigView = new GDP.view.AlgorithmConfigView({
			template : GDP.ADVANCED.templates.getTemplate('algorithm-config'),
			model : GDP.ADVANCED.Job
		});
		this.algorithmConfigView.processModelsCollection = this.collection;
		this.algorithmConfigView.$el = this.$("#container-process-configuration");
		return this;
	},

	/**
	 * Removes all other descriptions and only displays the algorithm description
	 * matching to name provided in parameter
	 *
	 * @param {String} algorithmName
	 * @returns {Object}
	 */
	displayAlgorithmDescription : function (algorithmName) {
		"use strict";

		if (!algorithmName) {
			return;
		}

		var $selectedDescription = $('#process-description-' + algorithmName);

		if ($selectedDescription.length === 0) {
			// Couldn't find a process description with that name
			return;
		}

		// Remove all descriptions and show only the selected algorithm description
		$('#container-process-description').children().not($selectedDescription).fadeOut(function () {
			$selectedDescription.fadeIn();
		});

		return $selectedDescription;
	},

	/**
	 * Hook for process selection from dropdown
	 * @param {JQuery event} evt
	 * @returns {undefined}
	 */
	selectProcess : function (evt) {
		"use strict";
		var targetId = evt.target.id;
		var algorithmName = _.last(targetId.split('-'));

		GDP.ADVANCED.Job.set('algorithmId', this.collection.getByName(algorithmName).get('id'));
		this.displayAlgorithmDescription(algorithmName);
		this.algorithmConfigView.render();
		this.algorithmConfigView.delegateEvents();
	}
});<commit_msg>Updating references.<commit_after>/*jslint browser: true*/
/*global _*/
var GDP = GDP || {};

GDP.view = GDP.view || {};

GDP.view.ProcessView = GDP.util.BaseView.extend({

	algorithmConfigView : null,

	events : {
		"click .menu-dropdown-select-process" : "selectProcess"
	},

	render : function () {
		"use strict";
		this.$el.html(this.template(this.collection.models));
		this.algorithmConfigView = new GDP.view.AlgorithmConfigView({
			template : GDP.ADVANCED.templates.getTemplate('algorithm-config'),
			model : GDP.ADVANCED.models.job
		});
		this.algorithmConfigView.processModelsCollection = this.collection;
		this.algorithmConfigView.$el = this.$("#container-process-configuration");
		return this;
	},

	/**
	 * Removes all other descriptions and only displays the algorithm description
	 * matching to name provided in parameter
	 *
	 * @param {String} algorithmName
	 * @returns {Object}
	 */
	displayAlgorithmDescription : function (algorithmName) {
		"use strict";

		if (!algorithmName) {
			return;
		}

		var $selectedDescription = $('#process-description-' + algorithmName);

		if ($selectedDescription.length === 0) {
			// Couldn't find a process description with that name
			return;
		}

		// Remove all descriptions and show only the selected algorithm description
		$('#container-process-description').children().not($selectedDescription).fadeOut(function () {
			$selectedDescription.fadeIn();
		});

		return $selectedDescription;
	},

	/**
	 * Hook for process selection from dropdown
	 * @param {JQuery event} evt
	 * @returns {undefined}
	 */
	selectProcess : function (evt) {
		"use strict";
		var targetId = evt.target.id;
		var algorithmName = _.last(targetId.split('-'));

		GDP.ADVANCED.model.job.set('algorithmId', this.collection.getByName(algorithmName).get('id'));
		this.displayAlgorithmDescription(algorithmName);
		this.algorithmConfigView.render();
		this.algorithmConfigView.delegateEvents();
	}
});<|endoftext|>


<commit_before>import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Link, useParams, Redirect } from "react-router-dom";
import { FormattedDate, FormattedNumber } from "react-intl";
import Types from "../item.types";
import { fetchItem, deleteItem, setAsActiveImage, deleteImage } from "../item.actions";
import { Label, Message, Icon, Divider, Grid, Image, Item, Button, Header, Card, Breadcrumb } from "semantic-ui-react";

export default function ItemDetail() {
    const { id } = useParams();
    const dispatch = useDispatch();
    const user = useSelector(state => state.userReducer.user);
    const item = useSelector(state => state.itemReducer.item);

    useEffect(() => {
        dispatch(fetchItem(id));
    }, []);

    const onDeleteItem = id => {
        if(confirm("Are you sure? All images associated with this item will be removed too.")) {
            dispatch(deleteItem(id)).then(function(result) {
                const { type } = result.action;

                if(type === Types.DELETE_ITEM_FULFILLED) {
                    <Redirect to="/items"/>
                }
            });
        }
    };

    const onDeleteImage = (itemId, fileId) => {
        if(confirm("Are you sure you want to delete this image?")) {
            dispatch(deleteImage(itemId, fileId));
        }
    }

    if(!item) {
        return (
            <Message icon warning>
                <Icon name="warning sign" size="large"/>
                <Message.Content>
                    <Message.Header>Warning!</Message.Header>
                    Item not found.
                </Message.Content>
            </Message>
        );
    }

    if(item.files && item.files.length) {
        item.activeImage = item.files.find(x => x.active === true);
    }

    const sections = [
        { key: "Items", content: "Items", href: "/items" },
        { key: "Category", content: `${item.category.name}`, href: `/items?categoryId=${item.category._id}` },
        { key: `${item.name}`, content: `${item.name}`, active: true }
    ];

    return (

            <Breadcrumb size="small" sections={sections}/>

            <Divider hidden/>

            <Grid>
                <Grid.Column width={10}>
                    { item.activeImage &&
                        <Image src={item.activeImage.secure_url} alt={item.name}/>
                    }
                    { item.files && item.files.length === 0 &&
                        <Message warning icon>
                        <Icon name="warning sign" size="large"/>
                            <Message.Content>
                                <Message.Header>Warning!</Message.Header>
                                No images are found for this item. <Link to={`/items/${item._id}/edit`}>Consider editing the item</Link>.
                            </Message.Content>
                        </Message>
                    }
                </Grid.Column>

                <Grid.Column width={6}>
                    <Item>
                        <Item.Content>
                            {item.name}
                            <Divider hidden/>

                            <Divider horizontal>Meta Informations</Divider>

                            <Item.Meta>

Category: <Link to={`/items?categoryId=${item.category._id}`}>{item.category.name}</Link>

Brand: <Link to={`/items?brandId=${item.brand._id}`}>{item.brand.name}</Link>

                                { item.price &&

Price: <FormattedNumber value={item.price} style="currency" currency="BDT"/>

                                }

Purchase Date: <FormattedDate value={item.purchaseDate} day="2-digit" month="long" year="numeric"/>

                            </Item.Meta>

                            <Divider horizontal>Description</Divider>

                            <Item.Description>
                                { item.description &&

                                }
                                { !item.description &&

Not available at the moment.

                                }
                            </Item.Description>
                        </Item.Content>
                    </Item>

                    { user && !user.isAdmin &&
                        <>
                            <Divider section/>

                            <Button color="blue" href={`/items/${item._id}/edit`}>
                                <Icon name="pencil"/> Edit
                            </Button>
                            <Button color="red"
                                onClick={() => onDeleteItem(id)}>
                                <Icon name="trash"/> Delete
                            </Button>
                        </>
                    }
                </Grid.Column>
            </Grid>

            { item.files && item.files.length > 0 &&

                    <Divider hidden/>

Manage images

                    <Divider section/>

                    <Card.Group>
                        { item.files.map((file) => {
                            return (
                                <Card key={file._id} raised>
                                    { file.active &&

                                            <Icon name="pin"/>

                                    }

                                    <Card.Content className="ui center aligned">
                                        <Image src={file.secure_url} size="small"/>
                                    </Card.Content>

                                    { user && !user.isAdmin &&
                                        <Card.Content extra>
                                             dispatch(setAsActiveImage(item._id, file._id))} disabled={file.active}>
                                                <Icon color="teal" name="checkmark"/>
                                                Set as active

                                                 onDeleteImage(item._id, file._id)}>
                                                    <Icon color="red" name="delete"/>
                                                    Discard

                                        </Card.Content>
                                    }
                                </Card>
                            );
                        })}
                    </Card.Group>

            }

    );
}
<commit_msg>Redirect to /items after deleting an item<commit_after>import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Link, useParams, useHistory } from "react-router-dom";
import { FormattedDate, FormattedNumber } from "react-intl";
import Types from "../item.types";
import { fetchItem, deleteItem, setAsActiveImage, deleteImage } from "../item.actions";
import { Label, Message, Icon, Divider, Grid, Image, Item, Button, Header, Card, Breadcrumb } from "semantic-ui-react";

export default function ItemDetail() {
    const { id } = useParams();
    const history = useHistory();
    const dispatch = useDispatch();
    const user = useSelector(state => state.userReducer.user);
    const item = useSelector(state => state.itemReducer.item);

    useEffect(() => {
        dispatch(fetchItem(id));
    }, []);

    const onDeleteItem = id => {
        if(confirm("Are you sure? All images associated with this item will be removed too.")) {
            dispatch(deleteItem(id)).then(function(result) {
                const { type } = result.action;

                if(type === Types.DELETE_ITEM_FULFILLED) {
                    history.push("/items");
                }
            });
        }
    };

    const onDeleteImage = (itemId, fileId) => {
        if(confirm("Are you sure you want to delete this image?")) {
            dispatch(deleteImage(itemId, fileId));
        }
    }

    if(!item) {
        return (
            <Message icon warning>
                <Icon name="warning sign" size="large"/>
                <Message.Content>
                    <Message.Header>Warning!</Message.Header>
                    Item not found.
                </Message.Content>
            </Message>
        );
    }

    if(item.files && item.files.length) {
        item.activeImage = item.files.find(x => x.active === true);
    }

    const sections = [
        { key: "Items", content: "Items", href: "/items" },
        { key: "Category", content: `${item.category.name}`, href: `/items?categoryId=${item.category._id}` },
        { key: `${item.name}`, content: `${item.name}`, active: true }
    ];

    return (

            <Breadcrumb size="small" sections={sections}/>

            <Divider hidden/>

            <Grid>
                <Grid.Column width={10}>
                    { item.activeImage &&
                        <Image src={item.activeImage.secure_url} alt={item.name}/>
                    }
                    { item.files && item.files.length === 0 &&
                        <Message warning icon>
                        <Icon name="warning sign" size="large"/>
                            <Message.Content>
                                <Message.Header>Warning!</Message.Header>
                                No images are found for this item. <Link to={`/items/${item._id}/edit`}>Consider editing the item</Link>.
                            </Message.Content>
                        </Message>
                    }
                </Grid.Column>

                <Grid.Column width={6}>
                    <Item>
                        <Item.Content>
                            {item.name}
                            <Divider hidden/>

                            <Divider horizontal>Meta Informations</Divider>

                            <Item.Meta>

Category: <Link to={`/items?categoryId=${item.category._id}`}>{item.category.name}</Link>

Brand: <Link to={`/items?brandId=${item.brand._id}`}>{item.brand.name}</Link>

                                { item.price &&

Price: <FormattedNumber value={item.price} style="currency" currency="BDT"/>

                                }

Purchase Date: <FormattedDate value={item.purchaseDate} day="2-digit" month="long" year="numeric"/>

                            </Item.Meta>

                            <Divider horizontal>Description</Divider>

                            <Item.Description>
                                { item.description &&

                                }
                                { !item.description &&

Not available at the moment.

                                }
                            </Item.Description>
                        </Item.Content>
                    </Item>

                    { user && !user.isAdmin &&
                        <>
                            <Divider section/>

                            <Button color="blue" href={`/items/${item._id}/edit`}>
                                <Icon name="pencil"/> Edit
                            </Button>
                            <Button color="red"
                                onClick={() => onDeleteItem(id)}>
                                <Icon name="trash"/> Delete
                            </Button>
                        </>
                    }
                </Grid.Column>
            </Grid>

            { item.files && item.files.length > 0 &&

                    <Divider hidden/>

Manage images

                    <Divider section/>

                    <Card.Group>
                        { item.files.map((file) => {
                            return (
                                <Card key={file._id} raised>
                                    { file.active &&

                                            <Icon name="pin"/>

                                    }

                                    <Card.Content className="ui center aligned">
                                        <Image src={file.secure_url} size="small"/>
                                    </Card.Content>

                                    { user && !user.isAdmin &&
                                        <Card.Content extra>
                                             dispatch(setAsActiveImage(item._id, file._id))} disabled={file.active}>
                                                <Icon color="teal" name="checkmark"/>
                                                Set as active

                                                 onDeleteImage(item._id, file._id)}>
                                                    <Icon color="red" name="delete"/>
                                                    Discard

                                        </Card.Content>
                                    }
                                </Card>
                            );
                        })}
                    </Card.Group>

            }

    );
}
<|endoftext|>


<commit_before><commit_msg>Update main.js<commit_after><|endoftext|>


<commit_before>//Copied from http://stackoverflow.com/a/4256130/817277
String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

//inspired by http://ejohn.org/files/pretty.js
var prettyDate = function(utcDate) {
    var utcNow = getUTCDate(new Date());
    var diff = ((utcNow.getTime() - utcDate.getTime()) / 1000);
    var dayDiff = Math.floor(diff / 86400);

    if(dayDiff == 0) {
        if(diff < 60) {
            return "Just now";
        }
        else if(diff < 3600) {
            var minuteDiff = Math.floor(diff/60);
            return minuteDiff + " minute{0} ago".format(minuteDiff > 1 ? "s" : "");
        }
        else {
            var hoursDiff = Math.floor(diff/3600);
            return hoursDiff + " hour{0} ago".format(hoursDiff > 1 ? "s" : "");
        }
    }

    else if(dayDiff === 1) {
        return "Yesterday"
    }

    else if(dayDiff < 7) {
        return dayDiff + " days ago";
    }
    else {
        var weeksDiff = Math.floor(dayDiff);
        return weeksDiff + " week{0} ago".format(weeksDiff > 1 ? "s": "");
        return Math.floor(dayDiff / 7) + " weeks ago"
    }
};

//http://stackoverflow.com/a/6777470/817277
var getUTCDate = function(now) {
    now = now || new Date();
    var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    return now_utc;
};

var getHumanizedTimeDiff = function(localDate) {
    localDate = localDate || new Date();
    var utcDate = getUTCDate(localDate);
    return prettyDate(utcDate);
};

var getUniqueId = function() {

    var id = 0;
    var getId = function() {
        id += 1;
        return id;
    }
    return getId;
}();

var vectorReverse = function(v) {
    var r = _.map(v, function(i) {
        return -i;
    });
    return r;
};

var vectorAdd = function(a, b) {
    var lengthA = a.length;
    var lengthB = b.length;

    if(lengthA !== lengthB) {
        throw new Error("Vector lengths not equal. vectorAdd cannot be performed for ", a, b)
    }

    var result = new Array(lengthA);
    for(var i = 0; i < lengthA; i++) {
        result[i] = a[i] + b[i];
    }
    return result;
}

var vectorSubtract = function(a, b) {
    return vectorAdd(a, vectorReverse(b));
}

var vectorDotProduct = function(a, b) {

    var lengthA = a.length;
    var lengthB = b.length;

    if(lengthA !== lengthB) {
        throw new Error("Vector lengths not equal. vectorDotProduct cannot be performed", a, b);
    }

    var result = 0;
    for(var i = 0; i < lengthA; i++) {
        result += a[i]*b[i]
    }
    return result;
};

var vectorMultiplyByScalar = function(v, scale) {
    var length = v.length;
    var result = new Array(length);
    for(var i = 0 ; i < length; i++) {
        result[i] = v[i] * scale;
    }
    return result;
};<commit_msg>Migrated utils.js to module.exports (I don't know the technical name for this term). Maybe I should just say "Modularized Utils.js", yeah.<commit_after>//Copied from http://stackoverflow.com/a/4256130/817277
String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

//http://stackoverflow.com/a/6777470/817277
var getUTCDate = function(now) {
    now = now || new Date();
    var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    return now_utc;
};

var prettyDate = function(utcDate) {
    var utcNow = getUTCDate(new Date());
    var diff = ((utcNow.getTime() - utcDate.getTime()) / 1000);
    var dayDiff = Math.floor(diff / 86400);

    if(dayDiff == 0) {
        if(diff < 60) {
            return "Just now";
        }
        else if(diff < 3600) {
            var minuteDiff = Math.floor(diff/60);
            return minuteDiff + " minute{0} ago".format(minuteDiff > 1 ? "s" : "");
        }
        else {
            var hoursDiff = Math.floor(diff/3600);
            return hoursDiff + " hour{0} ago".format(hoursDiff > 1 ? "s" : "");
        }
    }

    else if(dayDiff === 1) {
        return "Yesterday"
    }

    else if(dayDiff < 7) {
        return dayDiff + " days ago";
    }
    else {
        var weeksDiff = Math.floor(dayDiff);
        return weeksDiff + " week{0} ago".format(weeksDiff > 1 ? "s": "");
        return Math.floor(dayDiff / 7) + " weeks ago"
    }
};

var getHumanizedTimeDiff = function(localDate) {
    localDate = localDate || new Date();
    var utcDate = getUTCDate(localDate);
    return prettyDate(utcDate);
};

var getUniqueId = function() {

    var id = 0;
    var getId = function() {
        id += 1;
        return id;
    }
    return getId;
}();

module.exports = {
    getUTCDate: getUTCDate,
    prettyDate: prettyDate,
    getHumanizedTimeDiff: getHumanizedTimeDiff,
    getUniqueId: getUniqueId
};

/*
var vectorReverse = function(v) {
    var r = _.map(v, function(i) {
        return -i;
    });
    return r;
};

var vectorAdd = function(a, b) {
    var lengthA = a.length;
    var lengthB = b.length;

    if(lengthA !== lengthB) {
        throw new Error("Vector lengths not equal. vectorAdd cannot be performed for ", a, b)
    }

    var result = new Array(lengthA);
    for(var i = 0; i < lengthA; i++) {
        result[i] = a[i] + b[i];
    }
    return result;
}

var vectorSubtract = function(a, b) {
    return vectorAdd(a, vectorReverse(b));
}

var vectorDotProduct = function(a, b) {

    var lengthA = a.length;
    var lengthB = b.length;

    if(lengthA !== lengthB) {
        throw new Error("Vector lengths not equal. vectorDotProduct cannot be performed", a, b);
    }

    var result = 0;
    for(var i = 0; i < lengthA; i++) {
        result += a[i]*b[i]
    }
    return result;
};

var vectorMultiplyByScalar = function(v, scale) {
    var length = v.length;
    var result = new Array(length);
    for(var i = 0 ; i < length; i++) {
        result[i] = v[i] * scale;
    }
    return result;
};
*/<|endoftext|>