<commit_before>// Load modules

var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.defaults = {
    maxByteSize: 100 * 1024 * 1024          // 100MB
};

// Provides a named reference for memory debugging
internals.MemoryCacheSegment = function MemoryCacheSegment() {
};

internals.MemoryCacheEntry = function MemoryCacheEntry(key, value, ttl) {

    // stringify() to prevent value from changing while in the cache
    var stringifiedValue = JSON.stringify(value);

    this.item = stringifiedValue;
    this.stored = Date.now();
    this.ttl = ttl;

    // Approximate cache entry size without value: 144 bytes
    this.byteSize = 144 + Buffer.byteLength(stringifiedValue) + Buffer.byteLength(key.segment) + Buffer.byteLength(key.id);

    this.timeoutId = null;
};

exports = module.exports = internals.Connection = function (options) {

    Hoek.assert(this.constructor === internals.Connection, 'Memory cache client must be instantiated using new');
    Hoek.assert(!options || options.maxByteSize === undefined || options.maxByteSize >= 0, 'Invalid cache maxByteSize value');

    this.settings = Hoek.applyToDefaults(internals.defaults, options || {});
    this.cache = null;
};

internals.Connection.prototype.start = function (callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        this.cache = {};
        this.byteSize = 0;
    }

    return callback();
};

internals.Connection.prototype.stop = function () {

    this.cache = null;
    this.byteSize = 0;
    return;
};

internals.Connection.prototype.isReady = function () {

    return (!!this.cache);
};

internals.Connection.prototype.validateSegmentName = function (name) {

    if (!name) {
        return new Error('Empty string');
    }

    if (name.indexOf('\0') !== -1) {
        return new Error('Includes null character');
    }

    return null;
};

internals.Connection.prototype.get = function (key, callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    var segment = this.cache[key.segment];
    if (!segment) {
        return callback(null, null);
    }

    var envelope = segment[key.id];
    if (!envelope) {
        return callback(null, null);
    }

    var value = null;
    try {
        value = JSON.parse(envelope.item);
    }
    catch (err) {
        return callback(new Error('Bad value content'));
    }

    var result = {
        item: value,
        stored: envelope.stored,
        ttl: envelope.ttl
    };

    return callback(null, result);
};

internals.Connection.prototype.set = function (key, value, ttl, callback) {

    var self = this;

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    if (ttl > 2147483647) {                                                         // Math.pow(2, 31)
        return callback(new Error('Invalid ttl (greater than 2147483647)'));
    }

    var envelope = null;
    try {
        envelope = new internals.MemoryCacheEntry(key, value, ttl);
    } catch (err) {
        return callback(err);
    }

    this.cache[key.segment] = this.cache[key.segment] || new internals.MemoryCacheSegment();
    var segment = this.cache[key.segment];

    var cachedItem = segment[key.id];
    if (cachedItem &&
        cachedItem.timeoutId) {

        clearTimeout(cachedItem.timeoutId);
        self.byteSize -= cachedItem.byteSize;                   // If the item existed, decrement the byteSize as the value could be different
    }

    if (this.settings.maxByteSize) {
        if (self.byteSize + envelope.byteSize > this.settings.maxByteSize) {
            return callback(new Error('Cache size limit reached'));
        }
    }

    var timeoutId = setTimeout(function () {

        self.drop(key, function () { });
    }, ttl);

    envelope.timeoutId = timeoutId;

    segment[key.id] = envelope;
    return callback(null);
};

internals.Connection.prototype.drop = function (key, callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    var segment = this.cache[key.segment];
    if (segment) {
        var item = segment[key.id];

        if (item) {
            this.byteSize -= item.byteSize;
        }

        delete segment[key.id];
    }

    return callback();
};
<commit_msg>Add MemoryCache root object named class<commit_after>// Load modules

var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.defaults = {
    maxByteSize: 100 * 1024 * 1024          // 100MB
};

// Provides a named reference for memory debugging
internals.MemoryCacheSegment = function MemoryCacheSegment() {
};

internals.MemoryCacheEntry = function MemoryCacheEntry(key, value, ttl) {

    // stringify() to prevent value from changing while in the cache
    var stringifiedValue = JSON.stringify(value);

    this.item = stringifiedValue;
    this.stored = Date.now();
    this.ttl = ttl;

    // Approximate cache entry size without value: 144 bytes
    this.byteSize = 144 + Buffer.byteLength(stringifiedValue) + Buffer.byteLength(key.segment) + Buffer.byteLength(key.id);

    this.timeoutId = null;
};

exports = module.exports = internals.Connection = function MemoryCache(options) {

    Hoek.assert(this.constructor === internals.Connection, 'Memory cache client must be instantiated using new');
    Hoek.assert(!options || options.maxByteSize === undefined || options.maxByteSize >= 0, 'Invalid cache maxByteSize value');

    this.settings = Hoek.applyToDefaults(internals.defaults, options || {});
    this.cache = null;
};

internals.Connection.prototype.start = function (callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        this.cache = {};
        this.byteSize = 0;
    }

    return callback();
};

internals.Connection.prototype.stop = function () {

    this.cache = null;
    this.byteSize = 0;
    return;
};

internals.Connection.prototype.isReady = function () {

    return (!!this.cache);
};

internals.Connection.prototype.validateSegmentName = function (name) {

    if (!name) {
        return new Error('Empty string');
    }

    if (name.indexOf('\0') !== -1) {
        return new Error('Includes null character');
    }

    return null;
};

internals.Connection.prototype.get = function (key, callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    var segment = this.cache[key.segment];
    if (!segment) {
        return callback(null, null);
    }

    var envelope = segment[key.id];
    if (!envelope) {
        return callback(null, null);
    }

    var value = null;
    try {
        value = JSON.parse(envelope.item);
    }
    catch (err) {
        return callback(new Error('Bad value content'));
    }

    var result = {
        item: value,
        stored: envelope.stored,
        ttl: envelope.ttl
    };

    return callback(null, result);
};

internals.Connection.prototype.set = function (key, value, ttl, callback) {

    var self = this;

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    if (ttl > 2147483647) {                                                         // Math.pow(2, 31)
        return callback(new Error('Invalid ttl (greater than 2147483647)'));
    }

    var envelope = null;
    try {
        envelope = new internals.MemoryCacheEntry(key, value, ttl);
    } catch (err) {
        return callback(err);
    }

    this.cache[key.segment] = this.cache[key.segment] || new internals.MemoryCacheSegment();
    var segment = this.cache[key.segment];

    var cachedItem = segment[key.id];
    if (cachedItem &&
        cachedItem.timeoutId) {

        clearTimeout(cachedItem.timeoutId);
        self.byteSize -= cachedItem.byteSize;                   // If the item existed, decrement the byteSize as the value could be different
    }

    if (this.settings.maxByteSize) {
        if (self.byteSize + envelope.byteSize > this.settings.maxByteSize) {
            return callback(new Error('Cache size limit reached'));
        }
    }

    var timeoutId = setTimeout(function () {

        self.drop(key, function () { });
    }, ttl);

    envelope.timeoutId = timeoutId;

    segment[key.id] = envelope;
    return callback(null);
};

internals.Connection.prototype.drop = function (key, callback) {

    callback = Hoek.nextTick(callback);

    if (!this.cache) {
        return callback(new Error('Connection not started'));
    }

    var segment = this.cache[key.segment];
    if (segment) {
        var item = segment[key.id];

        if (item) {
            this.byteSize -= item.byteSize;
        }

        delete segment[key.id];
    }

    return callback();
};
<|endoftext|>


<commit_before>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>works<commit_after>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "http://formspree.io/Stephen.Pino@utexas.edu",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>


<commit_before>'use strict';

//var moment = require('moment');

var fs = require('fs');

var length_remaining = 0
var section_0 = {};

var section_1 = {};

var section_2 = {};
var section_3 = {};
var section_4 = {};
var section_5 = {};
var section_6 = {};
var section_7 = {};
var section_8 = {};

var readSection0 = function(buf) {
  var section = {};

  section['discipline'] = buf.readUInt8(45);
  section['edition'] = buf.readUInt8(46);
  section['total_length'] = (buf.readUInt32BE(47) << 8) + buf.readUInt32BE(51);
  return section;
};

var readSection1 = function(buf) {
  var section = {};

  section['length'] = buf.readUInt32BE(55);
  section['id'] = buf.readUInt8(59);
  section['origin_center'] = buf.readUInt16BE(60);
  section['origin_subcenter'] = buf.readUInt16BE(62);
  section['master_version'] = buf.readUInt8(64);
  section['local_version'] = buf.readUInt8(65);
  section['time_significance'] = buf.readUInt8(66);
  var year = buf.readUInt16BE(67);
  var month = buf.readUInt8(69) - 1; //month appears to be zero based
  var day = buf.readUInt8(70);
  var hour = buf.readUInt8(71);
  var minute = buf.readUInt8(72);
  var second = buf.readUInt8(73);
  section['timestamp'] = new Date(year, month, day, hour, minute, second);
  section['production_status'] = buf.readUInt8(74);
  section['data_type'] = buf.readUInt8(75);

  return section;
};

var readSection2 = function(buf) {
  var section = {};

  section['length'] = buf.readUInt32BE(76);
  section['id'] = buf.readUInt8(80);
  section['data'] = buf.slice(81, 81+section.length-1);

  return section;
};

var readSection3 = function(buf) {
  var section = {};

  return section;
};

var readSection4 = function(buf) {
  var section = {};

  return section;
};

var readSection5 = function(buf) {
  var section = {};

  return section;
};

var readSection6 = function(buf) {
  var section = {};

  return section;
};

var readSection7 = function(buf) {
  var section = {};

  return section;
};

module.exports.parse = function (filename) {
  var buf = fs.readFileSync(filename);

  section_0 = readSection0(buf);
  length_remaining = section_0.total_length - 16;
  console.log('section 0: ');
  console.log(section_0);

  section_1 = readSection1(buf);
  length_remaining -= section_1.length;
  console.log('section 1: ');
  console.log(section_1);

  section_2 = readSection2(buf);
  length_remaining -= section_2.length;
  console.log('section 2: ');
  console.log(section_2);

//  for (var i = 37; i < 60; i++) {
//    console.log(i+': '+contents[i]);
//  }

  return 'test';
}

var test = 'test';
<commit_msg>adding section 2<commit_after>'use strict';

//var moment = require('moment');

var fs = require('fs');

var length_remaining = 0
var section_0 = {};

var section_1 = {};

var section_2 = {};
var section_3 = {};
var section_4 = {};
var section_5 = {};
var section_6 = {};
var section_7 = {};
var section_8 = {};

var readSection0 = function(buf) {
  var section = {};

  section['discipline'] = buf.readUInt8(45);
  section['edition'] = buf.readUInt8(46);
  section['total_length'] = (buf.readUInt32BE(47) << 8) + buf.readUInt32BE(51);
  return section;
};

var readSection1 = function(buf) {
  var section = {};

  section['length'] = buf.readUInt32BE(55);
  section['id'] = buf.readUInt8(59);
  section['origin_center'] = buf.readUInt16BE(60);
  section['origin_subcenter'] = buf.readUInt16BE(62);
  section['master_version'] = buf.readUInt8(64);
  section['local_version'] = buf.readUInt8(65);
  section['time_significance'] = buf.readUInt8(66);
  var year = buf.readUInt16BE(67);
  var month = buf.readUInt8(69) - 1; //month appears to be zero based
  var day = buf.readUInt8(70);
  var hour = buf.readUInt8(71);
  var minute = buf.readUInt8(72);
  var second = buf.readUInt8(73);
  section['timestamp'] = new Date(year, month, day, hour, minute, second);
  section['production_status'] = buf.readUInt8(74);
  section['data_type'] = buf.readUInt8(75);

  return section;
};

var readSection2 = function(buf) {
  var section = {};

  section['length'] = buf.readUInt32BE(76);
  section['id'] = buf.readUInt8(80);
  section['data'] = buf.slice(81, 81+section.length-1).toString();

  return section;
};

var readSection3 = function(buf) {
  var section = {};

  return section;
};

var readSection4 = function(buf) {
  var section = {};

  return section;
};

var readSection5 = function(buf) {
  var section = {};

  return section;
};

var readSection6 = function(buf) {
  var section = {};

  return section;
};

var readSection7 = function(buf) {
  var section = {};

  return section;
};

module.exports.parse = function (filename) {
  var buf = fs.readFileSync(filename);

  section_0 = readSection0(buf);
  length_remaining = section_0.total_length - 16;
  console.log('section 0: ');
  console.log(section_0);

  section_1 = readSection1(buf);
  length_remaining -= section_1.length;
  console.log('section 1: ');
  console.log(section_1);

  section_2 = readSection2(buf);
  length_remaining -= section_2.length;
  console.log('section 2: ');
  console.log(section_2);

//  for (var i = 37; i < 60; i++) {
//    console.log(i+': '+contents[i]);
//  }

  return 'test';
}

var test = 'test';
<|endoftext|>


<commit_before>import { need, system } from 'pkg-cache';
import assert from 'assert';
import { log } from './log.js';
import minimist from 'minimist';
import packer from './packer.js';
import path from 'path';
import { plusx } from './chmod.js';
import producer from './producer.js';
import reporter from './reporter.js';
import walker from './walker.js';
import { writeFile } from 'fs-promise';

const { hostArch, hostPlatform, knownArchs,
  knownPlatforms, toFancyArch, toFancyPlatform } = system;
const hostNodeRange = 'v' + process.version[1];

function parse (items) {
  // v6-osx-x64,v6-linux-x64
  if (!items) return [];
  const targets = [];
  for (const item of items.split(',')) {
    const target = {
      nodeRange: hostNodeRange,
      platform: hostPlatform,
      arch: hostArch
    };
    for (const token of item.split('-')) {
      if (!token) continue;
      const p = toFancyPlatform(token);
      if (knownPlatforms.indexOf(p) >= 0) {
        target.platform = p;
        continue;
      }
      const a = toFancyArch(token);
      if (knownArchs.indexOf(a) >= 0) {
        target.arch = a;
        continue;
      }
      target.nodeRange = token;
    }
    targets.push(target);
  }
  return targets;
}

function humanize (target) {
  const { nodeRange, platform, arch } = target;
  return `${nodeRange}-${platform}-${arch}`;
}

function fabricatorForTarget (target) {
  const { nodeRange } = target;
  return { nodeRange, platform: hostPlatform, arch: hostArch };
}

export async function exec (argv2) {
  const argv = minimist(argv2, {
    string: [ 'c', 'config', 'l', 'loglevel', 'o',
      'output', 't', 'target', 'targets' ]
  });

  const loglevel = argv.l || argv.loglevel;

  if (loglevel) {
    if (!reporter.isCorrectLevel(loglevel)) {
      throw new Error('Incorrect loglevel: ' + loglevel);
    }
    reporter.level = loglevel;
  }

  if (argv._.length > 1) {
    throw new Error('Not more than one input file/directory is expected');
  }
  if (!argv._.length) {
    throw new Error('At least one input file/directory is expected');
  }

  const input = path.resolve(argv._[0]);
  let targets = parse(argv.t || argv.target || argv.targets);

  if (!targets.length) {
    targets = parse('-'); // will produce all default values
    assert(targets.length === 1);
    log.warn(`Targets not specified. Assuming ${humanize(targets[0])}`);
  }

  for (const target of targets) {
    target.binaryPath = await need(target);
    const f = target.fabricator = fabricatorForTarget(target);
    f.binaryPath = await need(f);
    if (f.platform !== 'win') {
      await plusx(f.binaryPath);
    }
  }

  let output = argv.o || argv.output;
  if (!output) output = 'project'; // TODO from package.json.name?

  if (targets.length === 1) {
    targets[0].output = output;
  } else {
    for (const target of targets) {
      let file = `${output}-${humanize(target)}`;
      if (target.platform === 'win') file += '.exe';
      target.output = file;
    }
  }

  let config = argv.c || argv.config;
  if (config) config = path.resolve(config);
  const records = await walker({ cli: { config, input } });

  // TODO memory consuming! when streams?
  const stripes = {};

  for (const target of targets) {
    const slash = target.platform === 'win' ? '\\' : '/';
    target.slash = slash;
    if (!stripes[slash]) {
      stripes[slash] = await packer({ records, slash });
    }
  }

  for (const target of targets) {
    const buffer = await producer({
      stripe: stripes[target.slash],
      fabricatorName: target.fabricator.binaryPath,
      houseName: target.binaryPath
    });
    await writeFile(target.output, buffer);
    if (target.platform !== 'win') {
      await plusx(target.output);
    }
  }
}
<commit_msg>'linux,osx,win' if no targets specified<commit_after>import { need, system } from 'pkg-cache';
import assert from 'assert';
import { log } from './log.js';
import minimist from 'minimist';
import packer from './packer.js';
import path from 'path';
import { plusx } from './chmod.js';
import producer from './producer.js';
import reporter from './reporter.js';
import walker from './walker.js';
import { writeFile } from 'fs-promise';

const { hostArch, hostPlatform, knownArchs,
  knownPlatforms, toFancyArch, toFancyPlatform } = system;
const hostNodeRange = 'v' + process.version[1];

function parse (items) {
  // v6-osx-x64,v6-linux-x64
  if (!items) return [];
  const targets = [];
  for (const item of items.split(',')) {
    const target = {
      nodeRange: hostNodeRange,
      platform: hostPlatform,
      arch: hostArch
    };
    for (const token of item.split('-')) {
      if (!token) continue;
      const p = toFancyPlatform(token);
      if (knownPlatforms.indexOf(p) >= 0) {
        target.platform = p;
        continue;
      }
      const a = toFancyArch(token);
      if (knownArchs.indexOf(a) >= 0) {
        target.arch = a;
        continue;
      }
      target.nodeRange = token;
    }
    targets.push(target);
  }
  return targets;
}

function humanize (target) {
  const { nodeRange, platform, arch } = target;
  return `${nodeRange}-${platform}-${arch}`;
}

function fabricatorForTarget (target) {
  const { nodeRange } = target;
  return { nodeRange, platform: hostPlatform, arch: hostArch };
}

export async function exec (argv2) {

  const argv = minimist(argv2, {
    string: [ 'c', 'config', 'l', 'loglevel', 'o',
      'output', 't', 'target', 'targets' ]
  });

  const loglevel = argv.l || argv.loglevel;

  if (loglevel) {
    if (!reporter.isCorrectLevel(loglevel)) {
      throw new Error('Incorrect loglevel: ' + loglevel);
    }
    reporter.level = loglevel;
  }

  if (argv._.length > 1) {
    throw new Error('Not more than one input file/directory is expected');
  }
  if (!argv._.length) {
    throw new Error('At least one input file/directory is expected');
  }

  const input = path.resolve(argv._[0]);
  let targets = parse(argv.t || argv.target || argv.targets);

  if (!targets.length) {
    targets = parse('linux,osx,win');
    log.warn(`Targets not specified. Assuming ${targets.map(humanize).join(', ')}`);
  }

  for (const target of targets) {
    target.binaryPath = await need(target);
    const f = target.fabricator = fabricatorForTarget(target);
    f.binaryPath = await need(f);
    if (f.platform !== 'win') {
      await plusx(f.binaryPath);
    }
  }

  let output = argv.o || argv.output;
  if (!output) output = 'project'; // TODO from package.json.name?

  if (targets.length === 1) {
    targets[0].output = output;
  } else {
    for (const target of targets) {
      let file = `${output}-${humanize(target)}`;
      if (target.platform === 'win') file += '.exe';
      target.output = file;
    }
  }

  let config = argv.c || argv.config;
  if (config) config = path.resolve(config);
  const records = await walker({ cli: { config, input } });

  // TODO memory consuming! when streams?
  const stripes = {};

  for (const target of targets) {
    const slash = target.platform === 'win' ? '\\' : '/';
    target.slash = slash;
    if (!stripes[slash]) {
      stripes[slash] = await packer({ records, slash });
    }
  }

  for (const target of targets) {
    const buffer = await producer({
      stripe: stripes[target.slash],
      fabricatorName: target.fabricator.binaryPath,
      houseName: target.binaryPath
    });
    await writeFile(target.output, buffer);
    if (target.platform !== 'win') {
      await plusx(target.output);
    }
  }

}
<|endoftext|>


<commit_before>// CDMX - HOME
// @package  : cdmx
// @location : /js
// @file     : controller.js
// @author   : Gobierno fácil <howdy@gobiernofacil.com>
// @url      : http://gobiernofacil.com

define(function(require){

  //
  // L O A D   T H E   A S S E T S   A N D   L I B R A R I E S
  // --------------------------------------------------------------------------------
  //
  var Backbone       = require('backbone'),
      d3             = require("d3"),
      ScrollMagic    = require("ScrollMagic"),
      TweenLite      = require("TweenLite"),
      SplitText      = require("splitText"),
      TweenMax       = require("TweenMax"),
      xxx            = require("ScrollMagic.animation.gsap"),
      ScrollToPlugin = require("ScrollToPlugin"),
      TimelineMax    = require("TimelineMax"),
  //
  // D E F I N E   T H E   S E T U P   V A R I A B L E S
  // --------------------------------------------------------------------------------
  //

  //
  // C A C H E   T H E   C O M M O N   E L E M E N T S
  // --------------------------------------------------------------------------------
  //

  // STEPS
  Planning = document.querySelector(".slide.e-1.planeacion"),
  Bidding  = document.querySelector(".slide.e-2.licitacion"),
  Award    = document.querySelector(".slide.e-2.adjudicacion"),
  Contract = document.querySelector(".slide.e-2.contrato"),
  Implementation = document.querySelector(".slide.e-2.implementacion"),

  // POSIBILITIES
  Viz    = document.querySelector("#tools-visualize"),
  Api    = document.querySelector("#tools-api"),
  Social = document.querySelector("#tools-social");

  //
  // I N I T I A L I Z E   T H E   B A C K B O N E   " C O N T R O L L E R "
  // --------------------------------------------------------------------------------
  //

  var controller =  Backbone.View.extend({
    events : {
      // NAVIGATION
      "click .cta" : "move_to_second",
      "click #goto-step1" : "move_to_first",
      "click #goto-step2" : "move_to_second",
      "click #goto-step3" : "move_to_third",
      "click #goto-step4" : "move_to_fourth",

      // STANDAR
      "click #link_nav_planeacion"     : "show_planning",
      "click #link_nav_licitacion"     : "show_bidding",
      "click #link_nav_adjudicacion"   : "show_award",
      "click #link_nav_contratacion"   : "show_contract",
      "click #link_nav_implementacion" : "show_implementation",

      // POSIBILITIES
      "click #tools-visualize-btn" : "show_viz",
      "click #tools-api-btn"       : "show_api",
      "click #tools-social-btn"    : "show_social"
    },

    el : "body",

    //
    // S E T U P   S C E N E S
    // --------------------------------------------------------------------------------
    //

    initialize : function(){
      this.hide_stuff();
      this.set_animation_controller();
    },

    set_animation_controller : function(){
      this.animation = new ScrollMagic.Controller();
      this.set_first_scene();
      this.set_second_scene();
      this.set_third_scene();
      this.set_fourth_scene();
    },

    hide_stuff : function(){
      Bidding.style.display = "none";
      Award.style.display = "none";
      Contract.style.display = "none";
      Implementation.style.display = "none";
      Api.style.display = "none";
      Social.style.display = "none";
    },

    set_first_scene : function(){
      this.scene1 = new ScrollMagic.Scene({
        triggerElement : ".participacion",
        //duration : 400
      })
      //.setTween(tl)
      //.setPin(".participacion")
      .addTo(this.animation);
    },

    set_second_scene : function(){
      this.scene2 = new ScrollMagic.Scene({
        triggerElement : ".etapas .container",
        duration : 400,
        offset : -70
      })
      //.setTween(tl)
      //.setPin(".etapas")
      .addTo(this.animation);
    },

    set_third_scene : function(){
      this.scene3 = new ScrollMagic.Scene({
        triggerElement : ".win",
        duration : 400
      })
      //.setTween(tl)
      //.setPin(".win")
      .addTo(this.animation);
    },

    set_fourth_scene : function(){
      this.scene4 = new ScrollMagic.Scene({
        triggerElement : ".tools",
        duration : 400
      })
      //.setTween(tl)
      //.setPin(".tools")
      .addTo(this.animation);
    },

    //
    // G E N E R A L   T R A N S I T I O N S
    // --------------------------------------------------------------------------------
    //

    move_to_first : function(e){
      e.preventDefault();
      var y = this.scene1.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
    },

    move_to_second : function(e){
      e.preventDefault();
      var y = this.scene2.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
    },

    move_to_third : function(e){
      e.preventDefault();
      var y = this.scene3.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
    },

    move_to_fourth : function(e){
      e.preventDefault();
      var y = this.scene4.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
    },

    //
    // L O C A L   T R A N S I T I O N S
    // --------------------------------------------------------------------------------
    //

    show_planning : function(e){
      e.preventDefault();
      Planning.style.display       = "block";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
    },

    show_bidding : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "block";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
    },

    show_award : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "block";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
    },

    show_contract : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "block";
      Implementation.style.display = "none";
    },

    show_implementation : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "block";
    },

    show_viz : function(e){
      e.preventDefault();
      Viz.style.display    = "block";
      Api.style.display    = "none";
      Social.style.display = "none";
    },

    show_api : function(e){
      e.preventDefault();
      Viz.style.display    = "none";
      Api.style.display    = "block";
      Social.style.display = "none";
    },

    show_social : function(e){
      e.preventDefault();
      Viz.style.display    = "none";
      Api.style.display    = "none";
      Social.style.display = "block";
    }

    /*

    setupScroll : function(){
      var servidor = new TimelineMax({repeat:-1});
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 5, x:2, y:2, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 0, x:0, y:0, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: -5, x:-2, y:2, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 0, x:0, y:0, transformOrigin:"50% 50%"}));

      var mySplit = new SplitText("#mini-description-a", {type: "chars, lines, words"}),
          chars   = mySplit.chars,
          tl      = new TimelineMax();
          tl.staggerFrom(chars, 0.8, {opacity:0, scale:0, y:80, rotationX:180, transformOrigin:"0% 50% -50",  ease:Back.easeOut}, 0.005, "+=0");

      $("#mini-description-a").css({
        perspective:400,
        opacity : 1
      });

      var animation = new ScrollMagic.Controller(),
          scene1    = new ScrollMagic.Scene({
            triggerElement : ".etapas",
            duration : 400
          })
          .setTween(tl)
          //.setPin(".etapas")
          .addTo(animation),
          scene2    = new ScrollMagic.Scene({
            triggerElement : ".win",
            duration : 400
          }).setPin(".win").addTo(animation),
          scene3    = new ScrollMagic.Scene({
            triggerElement : ".tools",
            duration : 400
          }).setPin(".tools").addTo(animation);
    },
    */
  });

  //
  // R E T U R N   T H E   B A C K B O N E   " C O N T R O L L E R "
  // --------------------------------------------------------------------------------
  //
  return controller;
});<commit_msg>add and remove class js<commit_after>// CDMX - HOME
// @package  : cdmx
// @location : /js
// @file     : controller.js
// @author   : Gobierno fácil <howdy@gobiernofacil.com>
// @url      : http://gobiernofacil.com

define(function(require){

  //
  // L O A D   T H E   A S S E T S   A N D   L I B R A R I E S
  // --------------------------------------------------------------------------------
  //
  var Backbone       = require('backbone'),
      d3             = require("d3"),
      ScrollMagic    = require("ScrollMagic"),
      TweenLite      = require("TweenLite"),
      SplitText      = require("splitText"),
      TweenMax       = require("TweenMax"),
      xxx            = require("ScrollMagic.animation.gsap"),
      ScrollToPlugin = require("ScrollToPlugin"),
      TimelineMax    = require("TimelineMax"),
  //
  // D E F I N E   T H E   S E T U P   V A R I A B L E S
  // --------------------------------------------------------------------------------
  //

  //
  // C A C H E   T H E   C O M M O N   E L E M E N T S
  // --------------------------------------------------------------------------------
  //

  // STEPS
  Planning = document.querySelector(".slide.e-1.planeacion"),
  Bidding  = document.querySelector(".slide.e-2.licitacion"),
  Award    = document.querySelector(".slide.e-2.adjudicacion"),
  Contract = document.querySelector(".slide.e-2.contrato"),
  Implementation = document.querySelector(".slide.e-2.implementacion"),

  // POSIBILITIES
  Viz    = document.querySelector("#tools-visualize"),
  Api    = document.querySelector("#tools-api"),
  Social = document.querySelector("#tools-social");

  //
  // I N I T I A L I Z E   T H E   B A C K B O N E   " C O N T R O L L E R "
  // --------------------------------------------------------------------------------
  //

  var controller =  Backbone.View.extend({
    events : {
      // NAVIGATION
      "click .cta" : "move_to_second",
      "click #goto-step1" : "move_to_first",
      "click #goto-step2" : "move_to_second",
      "click #goto-step3" : "move_to_third",
      "click #goto-step4" : "move_to_fourth",

      // STANDAR
      "click #link_nav_planeacion"     : "show_planning",
      "click #link_nav_licitacion"     : "show_bidding",
      "click #link_nav_adjudicacion"   : "show_award",
      "click #link_nav_contratacion"   : "show_contract",
      "click #link_nav_implementacion" : "show_implementation",

      // POSIBILITIES
      "click #tools-visualize-btn" : "show_viz",
      "click #tools-api-btn"       : "show_api",
      "click #tools-social-btn"    : "show_social"
    },

    el : "body",

    //
    // S E T U P   S C E N E S
    // --------------------------------------------------------------------------------
    //

    initialize : function(){
      this.hide_stuff();
      this.set_animation_controller();
    },

    set_animation_controller : function(){
      this.animation = new ScrollMagic.Controller();
      this.set_first_scene();
      this.set_second_scene();
      this.set_third_scene();
      this.set_fourth_scene();
    },

    hide_stuff : function(){
      Bidding.style.display = "none";
      Award.style.display = "none";
      Contract.style.display = "none";
      Implementation.style.display = "none";
      Api.style.display = "none";
      Social.style.display = "none";
    },

    set_first_scene : function(){
      this.scene1 = new ScrollMagic.Scene({
        triggerElement : ".participacion",
        //duration : 400
      })
      //.setTween(tl)
      //.setPin(".participacion")
      .addTo(this.animation);
    },

    set_second_scene : function(){
      this.scene2 = new ScrollMagic.Scene({
        triggerElement : ".etapas .container",
        duration : 400,
        offset : -100
      })
      //.setTween(tl)
      //.setPin(".etapas")
      .addTo(this.animation);
    },

    set_third_scene : function(){
      this.scene3 = new ScrollMagic.Scene({
        triggerElement : ".win",
        duration : 400,
        offset : 30
      })
      //.setTween(tl)
      //.setPin(".win")
      .addTo(this.animation);
    },

    set_fourth_scene : function(){
      this.scene4 = new ScrollMagic.Scene({
        triggerElement : ".tools",
        duration : 400,
        offset : 20
      })
      //.setTween(tl)
      //.setPin(".tools")
      .addTo(this.animation);
    },

    //
    // G E N E R A L   T R A N S I T I O N S
    // --------------------------------------------------------------------------------
    //

    move_to_first : function(e){
      e.preventDefault();
      var y = this.scene1.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
      $("#menu_scroll a").removeClass("current");
      $("#goto-step1").addClass("current");
    },

    move_to_second : function(e){
      e.preventDefault();
      var y = this.scene2.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
      $("#menu_scroll a").removeClass("current");
      $("#goto-step2").addClass("current");
    },

    move_to_third : function(e){
      e.preventDefault();
      var y = this.scene3.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
      $("#menu_scroll a").removeClass("current");
      $("#goto-step3").addClass("current");
    },

    move_to_fourth : function(e){
      e.preventDefault();
      var y = this.scene4.triggerPosition();
      TweenMax.to(window, 1, {scrollTo:{y: y}, ease:Power2.easeOut});
      $("#menu_scroll a").removeClass("current");
      $("#goto-step4").addClass("current");
    },

    //
    // L O C A L   T R A N S I T I O N S
    // --------------------------------------------------------------------------------
    //

    show_planning : function(e){
      e.preventDefault();
      Planning.style.display       = "block";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
      $("a.nav_stage").removeClass("current");
      $("#link_nav_planeacion").addClass("current");
    },

    show_bidding : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "block";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
      $("a.nav_stage").removeClass("current");
      $("#link_nav_licitacion").addClass("current");
    },

    show_award : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "block";
      Contract.style.display       = "none";
      Implementation.style.display = "none";
      $("a.nav_stage").removeClass("current");
      $("#link_nav_adjudicacion").addClass("current");
    },

    show_contract : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "block";
      Implementation.style.display = "none";
      $("a.nav_stage").removeClass("current");
      $("#link_nav_contratacion").addClass("current");
    },

    show_implementation : function(e){
      e.preventDefault();
      Planning.style.display       = "none";
      Bidding.style.display        = "none";
      Award.style.display          = "none";
      Contract.style.display       = "none";
      Implementation.style.display = "block";
      $("a.nav_stage").removeClass("current");
      $("#link_nav_implementacion").addClass("current");
    },

    show_viz : function(e){
      e.preventDefault();
      Viz.style.display    = "block";
      Api.style.display    = "none";
      Social.style.display = "none";
      $(".tools li a").removeClass("current");
      $("#tools-visualize-btn").addClass("current");
    },

    show_api : function(e){
      e.preventDefault();
      Viz.style.display    = "none";
      Api.style.display    = "block";
      Social.style.display = "none";
      $(".tools li a").removeClass("current");
      $("#tools-api-btn").addClass("current");
    },

    show_social : function(e){
      e.preventDefault();
      Viz.style.display    = "none";
      Api.style.display    = "none";
      Social.style.display = "block";
      $(".tools li a").removeClass("current");
      $("#tools-social-btn").addClass("current");
    }

    /*

    setupScroll : function(){
      var servidor = new TimelineMax({repeat:-1});
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 5, x:2, y:2, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 0, x:0, y:0, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: -5, x:-2, y:2, transformOrigin:"50% 50%"}));
      servidor.add(TweenMax.to(document.getElementById("cabeza_servidor"), .8, {rotation: 0, x:0, y:0, transformOrigin:"50% 50%"}));

      var mySplit = new SplitText("#mini-description-a", {type: "chars, lines, words"}),
          chars   = mySplit.chars,
          tl      = new TimelineMax();
          tl.staggerFrom(chars, 0.8, {opacity:0, scale:0, y:80, rotationX:180, transformOrigin:"0% 50% -50",  ease:Back.easeOut}, 0.005, "+=0");

      $("#mini-description-a").css({
        perspective:400,
        opacity : 1
      });

      var animation = new ScrollMagic.Controller(),
          scene1    = new ScrollMagic.Scene({
            triggerElement : ".etapas",
            duration : 400
          })
          .setTween(tl)
          //.setPin(".etapas")
          .addTo(animation),
          scene2    = new ScrollMagic.Scene({
            triggerElement : ".win",
            duration : 400
          }).setPin(".win").addTo(animation),
          scene3    = new ScrollMagic.Scene({
            triggerElement : ".tools",
            duration : 400
          }).setPin(".tools").addTo(animation);
    },
    */
  });

  //
  // R E T U R N   T H E   B A C K B O N E   " C O N T R O L L E R "
  // --------------------------------------------------------------------------------
  //
  return controller;
});<|endoftext|>


<commit_before>require(["xpop/croquis/DrawData",
		"xpop/croquis/Drawer",
		"xpop/croquis/tabletapi",
		"xpop/croquis/color/RGBColor",
		"xpop/croquis/paintingtool/Brush"],
	function (DrawData, Drawer, tabletapi, RGBColor, Brush)
	{
		var layers = document.getElementById("layers");
		var canvas = document.createElement("canvas");
		canvas.width = 500;
		canvas.height = 500;
		layers.appendChild(canvas);
		var context = canvas.getContext("2d");
		context.fillStyle = "#FFFFFF";
		context.fillRect(0, 0, canvas.width, canvas.height);

		var drawer = new Drawer;
		drawer.setDrawInterval(5);

		var brush = new Brush(context);
		brush.setSize(30);
		brush.setInterval(0);
		brush.setColor(new RGBColor(0.5, 0.5, 1, 1));

		var brushSizeSlider = document.getElementById("brushSizeSlider");
		brushSizeSlider.value = brush.getSize();
		brushSizeSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushSizeSlider.addEventListener("change", function(){
			drawer.addDrawData(new DrawData(brush, brush.setSize, [brushSizeSlider.value]));
		});

		var brushColorRSlider = document.getElementById("brushColorRSlider");
		brushColorRSlider.value = brush.getColor().getR()*0xFF;
		brushColorRSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorRSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColorRSlider.value/0xFF,
				brushColor.getG(),
				brushColor.getB(),
				brushColor.getA())]));
		});

		var brushColorGSlider = document.getElementById("brushColorGSlider");
		brushColorGSlider.value = brush.getColor().getG()*0xFF;
		brushColorGSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorGSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColor.getR(),
				brushColorGSlider.value/255,
				brushColor.getB(),
				brushColor.getA())]));
		});

		var brushColorBSlider = document.getElementById("brushColorBSlider");
		brushColorBSlider.value = brush.getColor().getB()*0xFF;
		brushColorBSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorBSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColor.getR(),
				brushColor.getG(),
				brushColorBSlider.value/0xFF,
				brushColor.getA())]));
		});

		document.body.addEventListener("mousedown", onMouseDown);
		document.addEventListener("mouseup", onMouseUp);
		function onMouseDown(e)
		{
			drawer.addDrawData(new DrawData(brush, brush.down, [e.clientX, e.clientY, tabletapi.pressure()]));
			document.body.addEventListener("mousemove", onMouseMove);
		}
		function onMouseMove(e)
		{
			drawer.addDrawData(new DrawData(brush, brush.move, [e.clientX, e.clientY, tabletapi.pressure()]));
		}
		function onMouseUp(e)
		{
			document.body.removeEventListener("mousemove", onMouseMove);
		}
	}
);<commit_msg>background checkers pattern<commit_after>require(["xpop/croquis/DrawData",
		"xpop/croquis/Drawer",
		"xpop/croquis/tabletapi",
		"xpop/croquis/color/RGBColor",
		"xpop/croquis/paintingtool/Brush"],
	function (DrawData, Drawer, tabletapi, RGBColor, Brush)
	{
		var layers = document.getElementById("layers");
		var background = document.createElement("div");
		layers.appendChild(background);
		var backgroundImage = document.createElement("canvas");
		backgroundImage.width = backgroundImage.height = 20;
		var backgroundImageContext = backgroundImage.getContext("2d");
		backgroundImageContext.fillStyle = "#FFFFFF";
		backgroundImageContext.fillRect(0, 0, 20, 20);
		backgroundImageContext.fillStyle = "#CCCCCC";
		backgroundImageContext.fillRect(0, 0, 10, 10);
		backgroundImageContext.fillRect(10, 10, 20, 20);
		background.style.backgroundImage = "url(" + backgroundImage.toDataURL() + ")";
		background.style.width = "500px";
		background.style.height = "500px";
		var canvas = document.createElement("canvas");
		canvas.width = 500;
		canvas.height = 500;
		layers.appendChild(canvas);
		canvas.style.marginTop = "-500px";
		canvas.style.position = "absolute";
		var context = canvas.getContext("2d");
		context.fillStyle = "#FFFFFF";
		context.fillRect(0, 0, canvas.width, canvas.height);

		var drawer = new Drawer;
		drawer.setDrawInterval(5);

		var brush = new Brush(context);
		brush.setKnockout(true);
		brush.setSize(30);
		brush.setInterval(0);
		brush.setColor(new RGBColor(0.5, 0.5, 1, 1));

		var brushSizeSlider = document.getElementById("brushSizeSlider");
		brushSizeSlider.value = brush.getSize();
		brushSizeSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushSizeSlider.addEventListener("change", function(){
			drawer.addDrawData(new DrawData(brush, brush.setSize, [brushSizeSlider.value]));
		});

		var brushColorRSlider = document.getElementById("brushColorRSlider");
		brushColorRSlider.value = brush.getColor().getR()*0xFF;
		brushColorRSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorRSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColorRSlider.value/0xFF,
				brushColor.getG(),
				brushColor.getB(),
				brushColor.getA())]));
		});

		var brushColorGSlider = document.getElementById("brushColorGSlider");
		brushColorGSlider.value = brush.getColor().getG()*0xFF;
		brushColorGSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorGSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColor.getR(),
				brushColorGSlider.value/255,
				brushColor.getB(),
				brushColor.getA())]));
		});

		var brushColorBSlider = document.getElementById("brushColorBSlider");
		brushColorBSlider.value = brush.getColor().getB()*0xFF;
		brushColorBSlider.addEventListener("mousedown", function(e){
			e.stopPropagation();
		});
		brushColorBSlider.addEventListener("change", function(){
			var brushColor = brush.getColor();
			drawer.addDrawData(new DrawData(brush, brush.setColor, [new RGBColor(
				brushColor.getR(),
				brushColor.getG(),
				brushColorBSlider.value/0xFF,
				brushColor.getA())]));
		});

		document.body.addEventListener("mousedown", onMouseDown);
		document.addEventListener("mouseup", onMouseUp);
		function onMouseDown(e)
		{
			drawer.addDrawData(new DrawData(brush, brush.down, [e.clientX, e.clientY, tabletapi.pressure()]));
			document.body.addEventListener("mousemove", onMouseMove);
		}
		function onMouseMove(e)
		{
			drawer.addDrawData(new DrawData(brush, brush.move, [e.clientX, e.clientY, tabletapi.pressure()]));
		}
		function onMouseUp(e)
		{
			document.body.removeEventListener("mousemove", onMouseMove);
		}
	}
);<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var libpath = process.env.TEST_COV ? '../lib-cov/' : '../lib/';
var detector = require(libpath + 'detector');

var handlers = {};
var types = ['png', 'gif', 'bmp', 'psd', 'jpg', 'webp'];

// load all available handlers
types.forEach(function (type) {
  handlers[type] = require(libpath + 'types/' + type);
});

/// Maximum buffer size, with a default of 4096 bytes.
var bufferSize = 4096;

function lookup (buffer) {
  // detect the file type.. don't rely on the extension
  var type = detector(buffer);
  // find an appropriate handler for this file type
  if (type in handlers) {
    return handlers[type](buffer);
  }
  // throw up, if we can't understand the file
  else {
    throw new TypeError('unsupported file type');
  }
}

/**
 * @params filepath - relative/absolute path of the image file
 * @params callback - optional function for async detection
 */
module.exports = function (filepath, callback) {

  // resolve the file path
  filepath = path.resolve(filepath);

  // create a buffer to read data in
  var buffer = new Buffer(bufferSize);

  if (typeof callback === 'function') {
    // open the file in read only mode
    fs.open(filepath, 'r', function (err, descriptor) {

      if (err) { return callback(err); }

      // read first buffer block from the file, asynchronously
      fs.read(descriptor, buffer, 0, bufferSize, 0, function (err) {
        if (err) { return callback(err); }

        // return the dimensions
        var dimensions = lookup(buffer);
        callback(null, dimensions);
      });
    });
  } else {
    // read first 1KB from the file, synchronously
    var descriptor = fs.openSync(filepath, 'r');
    fs.readSync(descriptor, buffer, 0, bufferSize, 0);

    // return the dimensions
    return lookup(buffer);
  }
};

// Export the lookup method for benchmarking
module.exports.lookup = lookup;
<commit_msg>webp isn't supported yet<commit_after>var fs = require('fs');
var path = require('path');

var libpath = process.env.TEST_COV ? '../lib-cov/' : '../lib/';
var detector = require(libpath + 'detector');

var handlers = {};
var types = ['png', 'gif', 'bmp', 'psd', 'jpg'];

// load all available handlers
types.forEach(function (type) {
  handlers[type] = require(libpath + 'types/' + type);
});

/// Maximum buffer size, with a default of 4096 bytes.
var bufferSize = 4096;

function lookup (buffer) {
  // detect the file type.. don't rely on the extension
  var type = detector(buffer);
  // find an appropriate handler for this file type
  if (type in handlers) {
    return handlers[type](buffer);
  }
  // throw up, if we can't understand the file
  else {
    throw new TypeError('unsupported file type');
  }
}

/**
 * @params filepath - relative/absolute path of the image file
 * @params callback - optional function for async detection
 */
module.exports = function (filepath, callback) {

  // resolve the file path
  filepath = path.resolve(filepath);

  // create a buffer to read data in
  var buffer = new Buffer(bufferSize);

  if (typeof callback === 'function') {
    // open the file in read only mode
    fs.open(filepath, 'r', function (err, descriptor) {

      if (err) { return callback(err); }

      // read first buffer block from the file, asynchronously
      fs.read(descriptor, buffer, 0, bufferSize, 0, function (err) {
        if (err) { return callback(err); }

        // return the dimensions
        var dimensions = lookup(buffer);
        callback(null, dimensions);
      });
    });
  } else {
    // read first 1KB from the file, synchronously
    var descriptor = fs.openSync(filepath, 'r');
    fs.readSync(descriptor, buffer, 0, bufferSize, 0);

    // return the dimensions
    return lookup(buffer);
  }
};

// Export the lookup method for benchmarking
module.exports.lookup = lookup;
<|endoftext|>


<commit_before>define(["js/data/Entity", "js/core/List", "flow", "underscore"], function (Entity, List, flow, _) {

    var FETCHSTATE = {
        CREATED: 0,
        LOADING: 1,
        LOADED: 2,
        ERROR: -1
    };

    var STATE = {
        NEW: 0,
        CREATED: 1,
        DELETED: -1
    };

    var AUTO_GENERATE = {
        CREATION_DATE: "CREATION_DATE",
        UPDATED_DATE: "UPDATED_DATE"
    };

    var Model = Entity.inherit("js.data.Model", {

        ctor: function (attributes) {

            // stores the current fetch state
            this._fetch = {
                callbacks: [],
                state: FETCHSTATE.CREATED
            };

            this.callBase(attributes);
        },

        schema: {
            created: {
                type: Date,
                generated: true,
                key: AUTO_GENERATE.CREATION_DATE
            },
            updated: {
                type: Date,
                generated: true,
                key: AUTO_GENERATE.UPDATED_DATE
            }
        },

        $isDependentObject: false,

        /***
         *
         * persistent the model over the data-source in which it was created
         *
         * @param options
         * @param callback
         */
        save: function (options, callback) {

            // TODO: handle multiple access
            try {
                var status = this._status();

                if (status === STATE.NEW || status === STATE.CREATED) {
                    this.$context.$dataSource.saveModel(this, options, callback);
                } else {
                    throw "status '" + status + "' doesn't allow save";
                }
            } catch(e) {
                if (callback) {
                    callback(e);
                }
            }

        },
        /***
         *
         * @param options
         * @param callback
         */
        validateAndSave: function (options, callback) {
            var self = this;

            flow()
                .seq(function (cb) {
                    self.validate(options, cb);
                })
                .seq(function (cb) {
                    if (self.isValid()) {
                        self.save(options, cb)
                    } else {
                        cb("Model is not valid!");
                    }
                })
                .exec(function (err) {
                    callback(err, self);
                });
        },

        getCollection: function (key) {
            var schemaDefinition = this.schema[key];
            if (!schemaDefinition) {
                throw "Couldn't find '" + key + "' in schema";
            }
            var collection = this.get(key);
            if (!collection) {
                var context = this.getContextForChild(schemaDefinition.type.prototype.$modelFactory);
                if (context) {
                    collection = context.createCollection(schemaDefinition.type, null);
                    collection.$parent = this;
                    this.set(key, collection);
                } else {
                    throw "Couldn't determine context for " + key;
                }
            }
            return collection;

        },

        prepare: function (attributes, action) {
            attributes = this.callBase();

            if (action === "create") {
                // remove id
                delete(attributes.id);
            }

            return attributes;

        },

        /**
         * @param options
         * @param options.fetchSubModels
         * @param {Function} callback - function(err, model, options)
         */
        fetch: function (options, callback) {
            options = options || {};

            var self = this;

            if (this._fetch.state === FETCHSTATE.LOADING) {
                // currently fetching -> register callback
                this._fetch.callbacks.push(function (err, model) {
                    modelFetchedComplete(err, model, options, callback);
                });
            } else if (this._fetch.state == FETCHSTATE.LOADED) {
                // completed loaded -> execute
                modelFetchedComplete(null, this, options, callback);
            } else {
                // set state and start loading
                self._fetch.state = FETCHSTATE.LOADING;

                this.$context.$dataSource.loadModel(this, options, function (err, model) {
                    self._fetch.state = err ? FETCHSTATE.ERROR : FETCHSTATE.LOADED;

                    // execute callbacks
                    modelFetchedComplete.call(self, err, model, options, callback);

                    _.each(self._fetch.callbacks, function (cb) {
                        cb.call(self, err, model);
                    });

                });
            }
        },

        remove: function (options, callback) {
            // TODO: handle multiple access
            try {
                var status = this._status();
                var self = this;
                if (status === STATE.CREATED) {
                    this.$context.$dataSource.removeModel(this, options, function (err) {
                        if (!err) {
                            self.set('id', false);
                        }
                        callback && callback(err);
                    });
                } else {
                    throw new Error("status '" + status + "' doesn't allow delete");
                }
            } catch(e) {
                callback && callback(e);
            }
        },
        validateSubEntity: function (entity, callback) {
            if (entity instanceof Model) {
                // does nothing :)
                callback();
            } else {
                this.callBase();
            }
        },
        _status: function () {
            if (this.$.id === false) {
                return STATE.DELETED;
            } else {
                return this.$.id ? STATE.CREATED : STATE.NEW;
            }
        }.onChange('id'),

        isNew: function () {
            return this._status() === STATE.NEW;
        }.onChange('id')
    });

    function fetchSubModels(attributes, subModelTypes, delegates) {
        _.each(attributes, function (value, key) {
            if (value instanceof Model || value instanceof require('js/data/Collection')) {
                // check if the model is required
                var subModelTypeEntry = subModelTypes[key];

                if (subModelTypeEntry) {
                    // model required -> create delegate
                    subModelTypeEntry.found = true;

                    delegates.push(function (cb) {
                        value.fetch({
                            fetchSubModels: subModelTypeEntry.subModels
                        }, cb);
                    });
                }
            } else if (value instanceof Object) {
                // TODO: causes in some cases an unfinity loop
                // fetchSubModels(value, subModelTypes, delegates);
                console.log(value);
            }
        });
    }

    function modelFetchedComplete(err, model, options, originalCallback) {

        var callback = function (err, model) {
            if (originalCallback) {
                originalCallback(err, model, options)
            }
        };

        if (err) {
            callback(err, model);
        } else {

            var delegates = [];

            if (options.fetchSubModels && options.fetchSubModels.length > 0) {

                // for example fetch an article with ["currency", "product/design", "product/productType"]
                var subModels = Model.createSubModelLoadingChain(model, options.fetchSubModels);

                fetchSubModels(model.$, subModels, delegates);

                // check that all subResources where found
                var missingSubModels = _.filter(subModels, function (subModel) {
                    return !subModel.found;
                });

                if (missingSubModels.length > 0) {
                    // TODO load again with fullData=true if not laoded with fullData=false
                    this.log(["requested submodel missing", missingSubModels], "warn");

                    callback("requested submodel missing", model);
                    return;
                }
            }

            // execute all delegates in parallel and then execute callback
            flow()
                .par(delegates)
                .exec(function (err) {
                    callback(err, model);
                });
        }
    }

    Model.createSubModelLoadingChain = function (model, subModels) {
        var ret = {};

        _.each(subModels, function (item) {
            if (item) {
                var parts = item.split("/");
                var subModelKey = parts.shift(), subModelEntry = ret[subModelKey] || {};
                ret[subModelKey] = subModelEntry;
                subModelEntry.found = false;
                subModelEntry.type = subModelKey;
                subModelEntry.subModels = [] || subModelEntry.subModels;
                if (parts.length > 0) {
                    subModelEntry.subModels.push(parts.join("/"));
                }
            }
        });

        return ret;
    };

    Model.STATE = STATE;
    Model.FETCHSTATE = FETCHSTATE;
    Model.AUTO_GENERATE = AUTO_GENERATE;

    return Model;
});<commit_msg>fixed cloning of model references in a list, fixed handling of remove and create after success<commit_after>define(["js/data/Entity", "js/core/List", "flow", "underscore"], function (Entity, List, flow, _) {

    var FETCHSTATE = {
        CREATED: 0,
        LOADING: 1,
        LOADED: 2,
        ERROR: -1
    };

    var STATE = {
        NEW: 0,
        CREATED: 1,
        DELETED: -1
    };

    var AUTO_GENERATE = {
        CREATION_DATE: "CREATION_DATE",
        UPDATED_DATE: "UPDATED_DATE"
    };

    var Model = Entity.inherit("js.data.Model", {

        ctor: function (attributes) {

            // stores the current fetch state
            this._fetch = {
                callbacks: [],
                state: FETCHSTATE.CREATED
            };

            this.callBase(attributes);
        },

        schema: {
            created: {
                type: Date,
                generated: true,
                key: AUTO_GENERATE.CREATION_DATE
            },
            updated: {
                type: Date,
                generated: true,
                key: AUTO_GENERATE.UPDATED_DATE
            }
        },

        $isDependentObject: false,

        /***
         *
         * persistent the model over the data-source in which it was created
         *
         * @param options
         * @param callback
         */
        save: function (options, callback) {

            // TODO: handle multiple access
            try {
                var status = this._status();
                var self = this;
                if (status === STATE.NEW || status === STATE.CREATED) {
                    this.$context.$dataSource.saveModel(this, options, function(err){
                        if(!err){
                            if(status === STATE.NEW && self.$collection){
                                self.$collection.invalidatePageCache();
                            }
                        }
                        callback && callback(err, self, options);
                    });
                } else {
                    throw "status '" + status + "' doesn't allow save";
                }
            } catch(e) {
                if (callback) {
                    callback(e);
                }
            }

        },
        /***
         *
         * @param options
         * @param callback
         */
        validateAndSave: function (options, callback) {
            var self = this;

            flow()
                .seq(function (cb) {
                    self.validate(options, cb);
                })
                .seq(function (cb) {
                    if (self.isValid()) {
                        self.save(options, cb)
                    } else {
                        cb("Model is not valid!");
                    }
                })
                .exec(function (err) {
                    callback(err, self);
                });
        },

        getCollection: function (key) {
            var schemaDefinition = this.schema[key];
            if (!schemaDefinition) {
                throw "Couldn't find '" + key + "' in schema";
            }
            var collection = this.get(key);
            if (!collection) {
                var context = this.getContextForChild(schemaDefinition.type.prototype.$modelFactory);
                if (context) {
                    collection = context.createCollection(schemaDefinition.type, null);
                    collection.$parent = this;
                    this.set(key, collection);
                } else {
                    throw "Couldn't determine context for " + key;
                }
            }
            return collection;

        },

        prepare: function (attributes, action) {
            attributes = this.callBase();

            if (action === "create") {
                // remove id
                delete(attributes.id);
            }

            return attributes;

        },

        /**
         * @param options
         * @param options.fetchSubModels
         * @param {Function} callback - function(err, model, options)
         */
        fetch: function (options, callback) {
            options = options || {};

            var self = this;

            if (this._fetch.state === FETCHSTATE.LOADING) {
                // currently fetching -> register callback
                this._fetch.callbacks.push(function (err, model) {
                    modelFetchedComplete(err, model, options, callback);
                });
            } else if (this._fetch.state == FETCHSTATE.LOADED) {
                // completed loaded -> execute
                modelFetchedComplete(null, this, options, callback);
            } else {
                // set state and start loading
                self._fetch.state = FETCHSTATE.LOADING;

                this.$context.$dataSource.loadModel(this, options, function (err, model) {
                    self._fetch.state = err ? FETCHSTATE.ERROR : FETCHSTATE.LOADED;

                    // execute callbacks
                    modelFetchedComplete.call(self, err, model, options, callback);

                    _.each(self._fetch.callbacks, function (cb) {
                        cb.call(self, err, model);
                    });

                });
            }
        },

        remove: function (options, callback) {
            // TODO: handle multiple access
            try {
                var status = this._status();
                var self = this;
                if (status === STATE.CREATED) {
                    this.$context.$dataSource.removeModel(this, options, function (err) {
                        if (!err) {
                            self.set('id', false);
                            if(self.$collection){
                                self.$collection.remove(self);
                            }
                        }
                        callback && callback(err);
                    });
                } else {
                    throw new Error("status '" + status + "' doesn't allow delete");
                }
            } catch(e) {
                callback && callback(e);
            }
        },
        validateSubEntity: function (entity, callback) {
            if (entity instanceof Model) {
                // does nothing :)
                callback();
            } else {
                this.callBase();
            }
        },
        _status: function () {
            if (this.$.id === false) {
                return STATE.DELETED;
            } else {
                return this.$.id ? STATE.CREATED : STATE.NEW;
            }
        }.onChange('id'),

        _cloneAttribute: function(value, key){

            // don't clone a list of model references!
            if(value instanceof List){
                if(this.schema.hasOwnProperty(key)){
                    var type = this.schema[key].type;
                    if(type instanceof Array && type.length && type[0].classof && type[0].classof(Model)){
                        var list = new List();
                        list._$source = value;
                        list.add(value.$items);
                        return list;
                    }
                }
            }

            return this.callBase();
        },

        isNew: function () {
            return this._status() === STATE.NEW;
        }.onChange('id')
    });

    function fetchSubModels(attributes, subModelTypes, delegates) {
        _.each(attributes, function (value, key) {
            if (value instanceof Model || value instanceof require('js/data/Collection')) {
                // check if the model is required
                var subModelTypeEntry = subModelTypes[key];

                if (subModelTypeEntry) {
                    // model required -> create delegate
                    subModelTypeEntry.found = true;

                    delegates.push(function (cb) {
                        value.fetch({
                            fetchSubModels: subModelTypeEntry.subModels
                        }, cb);
                    });
                }
            } else if (value instanceof Object) {
                // TODO: causes in some cases an unfinity loop
                // fetchSubModels(value, subModelTypes, delegates);
                console.log(value);
            }
        });
    }

    function modelFetchedComplete(err, model, options, originalCallback) {

        var callback = function (err, model) {
            if (originalCallback) {
                originalCallback(err, model, options)
            }
        };

        if (err) {
            callback(err, model);
        } else {

            var delegates = [];

            if (options.fetchSubModels && options.fetchSubModels.length > 0) {

                // for example fetch an article with ["currency", "product/design", "product/productType"]
                var subModels = Model.createSubModelLoadingChain(model, options.fetchSubModels);

                fetchSubModels(model.$, subModels, delegates);

                // check that all subResources where found
                var missingSubModels = _.filter(subModels, function (subModel) {
                    return !subModel.found;
                });

                if (missingSubModels.length > 0) {
                    // TODO load again with fullData=true if not laoded with fullData=false
                    this.log(["requested submodel missing", missingSubModels], "warn");

                    callback("requested submodel missing", model);
                    return;
                }
            }

            // execute all delegates in parallel and then execute callback
            flow()
                .par(delegates)
                .exec(function (err) {
                    callback(err, model);
                });
        }
    }

    Model.createSubModelLoadingChain = function (model, subModels) {
        var ret = {};

        _.each(subModels, function (item) {
            if (item) {
                var parts = item.split("/");
                var subModelKey = parts.shift(), subModelEntry = ret[subModelKey] || {};
                ret[subModelKey] = subModelEntry;
                subModelEntry.found = false;
                subModelEntry.type = subModelKey;
                subModelEntry.subModels = [] || subModelEntry.subModels;
                if (parts.length > 0) {
                    subModelEntry.subModels.push(parts.join("/"));
                }
            }
        });

        return ret;
    };

    Model.STATE = STATE;
    Model.FETCHSTATE = FETCHSTATE;
    Model.AUTO_GENERATE = AUTO_GENERATE;

    return Model;
});<|endoftext|>


<commit_before>var PATH = require('path');

var U = require('express-bem/lib/util');

var MakePlatform = require('enb/lib/make');
var dropRequireCache = require('enb/lib/fs/drop-require-cache');

module.exports = {
    middleware: middleware,
    middlewares: [middleware]
};

function middleware(opts) {
    var that = this; // express-bem

    opts = opts || {};
    opts.env = opts.env || this.env;
    opts.root = PATH.resolve(opts.cdir || opts.root || this.projectRoot);
    opts.noLog = 'noLog' in opts ? opts.noLog :
        typeof opts.verbosity === 'boolean' ? !opts.verbosity :
        (opts.verbosity === 'error' && opts.verbosity !== 'debug');

    var makePlatform = new MakePlatform();

    return function (ctx, next) {
        var engine = this.engines.byExtension(this.ext);
        var relBundlePath = PATH.relative(opts.root, ctx.name);
        var bundleName = PATH.basename(ctx.name);
        var bemjsonName = PATH.join(relBundlePath, bundleName + '.bemjson.js');

        var targets = [];
        var targetExtensions = (engine.targetExtensions || [engine.extension]);
        if (targetExtensions.length) {
            // build only declared techs/exts
            targetExtensions.forEach(function (ext) {
                targets.push(PATH.join(relBundlePath, bundleName + ext));
            });

        } else {
            // can't build nothing
            next();
        }

        makePlatform.init(opts.root, opts.env).then(function () {
            if (opts.noLog) {
                makePlatform.getLogger().setEnabled(false);
            }
            makePlatform.loadCache();
            makePlatform.buildTargets(targets).always(function () {
                makePlatform.saveCache();
                makePlatform.destruct();
                next();
            });
        });

    };
}
<commit_msg>skip building nothing<commit_after>var PATH = require('path');

var U = require('express-bem/lib/util');

var MakePlatform = require('enb/lib/make');
var dropRequireCache = require('enb/lib/fs/drop-require-cache');

module.exports = {
    middleware: middleware,
    middlewares: [middleware]
};

function middleware(opts) {
    var that = this; // express-bem

    opts = opts || {};
    opts.env = opts.env || this.env;
    opts.root = PATH.resolve(opts.cdir || opts.root || this.projectRoot);
    opts.noLog = 'noLog' in opts ? opts.noLog :
        typeof opts.verbosity === 'boolean' ? !opts.verbosity :
        (opts.verbosity === 'error' && opts.verbosity !== 'debug');

    var makePlatform = new MakePlatform();

    return function (ctx, next) {
        var engine = this.engines.byExtension(this.ext);
        var relBundlePath = PATH.relative(opts.root, ctx.name);
        var bundleName = PATH.basename(ctx.name);
        var bemjsonName = PATH.join(relBundlePath, bundleName + '.bemjson.js');

        var targets = [];
        var targetExtensions = (engine.targetExtensions || [engine.extension]);
        if (!targetExtensions.length) {
            // can't build nothing
            next();
            return;
        }

        // build only declared techs/exts
        targetExtensions.forEach(function (ext) {
            targets.push(PATH.join(relBundlePath, bundleName + ext));
        });

        makePlatform.init(opts.root, opts.env).then(function () {
            if (opts.noLog) {
                makePlatform.getLogger().setEnabled(false);
            }
            makePlatform.loadCache();
            makePlatform.buildTargets(targets).always(function () {
                makePlatform.saveCache();
                makePlatform.destruct();
                next();
            });
        });

    };
}
<|endoftext|>