<commit_before>var os = require('os')
  , fs = require('fs')
  , p = require('path')
  , exec = require('child_process').exec
  , spawn = require('child_process').spawn
  , helpers = require('./helpers')

var stats = {
  history: {},
  cpu: null, //used to store cpu informations
  proc: function(pid, options, done) {
    var self = this

    if(this.cpu !== null) {
      fs.readFile('/proc/uptime', 'utf8', function(err, uptime) {
        if(err)
          return done(err, null)

        if(uptime === undefined) {
          console.error("[pidusage] We couldn't find uptime from /proc/uptime")
          self.cpu.uptime = os.uptime()
        } else {
          self.cpu.uptime = uptime.split(' ')[0]
        }

        return self.proc_calc(pid, options, done)
      })
    } else {
      helpers.cpu(function(err, cpu) {
        if(err)
          return done(err, null)

        self.cpu = cpu
        return self.proc_calc(pid, options, done)
      })
    }
  },
  proc_calc: function(pid, options, done) {
    var history = this.history[pid] ? this.history[pid] : {}
    var cpu = this.cpu
    var self = this

    //Arguments to path.join must be strings
    fs.readFile(p.join('/proc', ''+pid, 'stat'), 'utf8', function(err, infos) {

      if(err)
        return done(err, null)

      //https://github.com/arunoda/node-usage/commit/a6ca74ecb8dd452c3c00ed2bde93294d7bb75aa8
      //preventing process space in name by removing values before last ) (pid (name) ...)
      var index = infos.lastIndexOf(')')
      infos = infos.substr(index + 2).split(' ')

      //according to http://man7.org/linux/man-pages/man5/proc.5.html (index 0 based - 2)
      //In kernels before Linux 2.6, start was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
      var stat = {
          utime: parseFloat(infos[11]),
          stime: parseFloat(infos[12]),
          cutime: parseFloat(infos[13]),
          cstime: parseFloat(infos[14]),
          start: parseFloat(infos[19]) / cpu.clock_tick,
          rss: parseFloat(infos[21])
      }

      //http://stackoverflow.com/questions/16726779/total-cpu-usage-of-an-application-from-proc-pid-stat/16736599#16736599

      var childrens = options.childrens ? stat.cutime + stat.cstime : 0

      var total = stat.stime - (history.stime || 0) + stat.utime - (history.utime || 0) + childrens

      total = total / cpu.clock_tick

      //time elapsed between calls
      var seconds = history.uptime !== undefined ? cpu.uptime - history.uptime : stat.start - cpu.uptime
      seconds = Math.abs(seconds)
      seconds = seconds === 0 ? 0.1 : seconds //we sure can't divide through 0

      self.history[pid] = stat
      self.history[pid].seconds = seconds
      self.history[pid].uptime = cpu.uptime

      return done(null, {
        cpu: (total / seconds) * 100,
        memory: stat.rss * cpu.pagesize
      })
    })
  },
  /**
   * Get pid informations through ps command
   * @param  {int}   pid
   * @return  {Function} done (err, stat)
   * on os x skip headers with pcpu=,rss=
   * on linux it could be --no-header
   * on solaris 11 can't figure out a way to do this properly so...
   */
  ps: function(pid, options, done) {

    var cmd = 'ps -o pcpu,rss -p '

    if(os.platform() == 'aix')
      cmd = 'ps -o pcpu,rssize -p ' //this one could work on other platforms

    exec(cmd + pid, function(err, stdout, stderr) {
      if(err)
        return done(err, null)

      stdout = stdout.split(os.EOL)[1]
      stdout = stdout.replace(/^\s+/, '').replace(/\s\s+/g, ' ').split(' ')

      return done(null, {
        cpu: parseFloat(stdout[0].replace(',', '.')),
        memory: parseFloat(stdout[1]) * 1024
      })
    })
  },
  /**
   * This is really in a beta stage
   */
  win: function(pid, options, done) {
    // The code is tested under:
    // Windows 7 Ultimate/Enterprise SP1 64bit
    // Windows 8.1 Enterprise SP1 64bit
    // Windows 10 Professonal 64bit
    // Windows Server 2008 R2 64bit
    // Windows Server 2012 R2 64bit

    // Ref:
    // https://msdn.microsoft.com/en-us/library/aa394277(v=vs.85).aspx

    var args = 'path Win32_PerfFormattedData_PerfProc_Process WHERE IDProcess=' + pid + ' get PercentProcessorTime, WorkingSet'
    var wmic = spawn('wmic', args.split(' '), {detached: true})
    var stdout = ''
    var stderr = ''

    wmic.stdout.on('data', function(d) {
     stdout += d.toString()
    })

    wmic.stderr.on('data', function(d) {
      stderr += d.toString()
    })

    wmic.on('close', function(code) {
      stdout = stdout.trim()

      if(!stdout)
        return done(new Error(pid + ' does not exist'), null)

      stderr = stderr.trim()

      if (!!code && stderr) {
        return done(new Error(stderr), null)
      }

      // The new line in Windows is '\r\r\n'
      var lines = stdout.split(/\r?\r\n/)
      // We might need the titles someday.
      //var titles = lines[0].trim().split( / +/ )
      var values = lines[1].trim().split(/ +/)
      var cpuPercent = parseFloat(values[0])
      var memUsage   = parseFloat(values[1])

      if(isNaN(cpuPercent) || isNaN(memUsage)) {
        return done(new Error('Invalid cpu or memory occupation'), null)
      }

      return done(null, {cpu : cpuPercent, memory : memUsage})
    })
  }
}

module.exports = stats;
<commit_msg>fix #24<commit_after>var os = require('os')
  , fs = require('fs')
  , p = require('path')
  , exec = require('child_process').exec
  , spawn = require('child_process').spawn
  , helpers = require('./helpers')

var stats = {
  history: {},
  cpu: null, //used to store cpu informations
  proc: function(pid, options, done) {
    var self = this

    if(this.cpu !== null) {
      fs.readFile('/proc/uptime', 'utf8', function(err, uptime) {
        if(err)
          return done(err, null)

        if(uptime === undefined) {
          console.error("[pidusage] We couldn't find uptime from /proc/uptime")
          self.cpu.uptime = os.uptime()
        } else {
          self.cpu.uptime = uptime.split(' ')[0]
        }

        return self.proc_calc(pid, options, done)
      })
    } else {
      helpers.cpu(function(err, cpu) {
        if(err)
          return done(err, null)

        self.cpu = cpu
        return self.proc_calc(pid, options, done)
      })
    }
  },
  proc_calc: function(pid, options, done) {
    var history = this.history[pid] ? this.history[pid] : {}
    var cpu = this.cpu
    var self = this

    //Arguments to path.join must be strings
    fs.readFile(p.join('/proc', ''+pid, 'stat'), 'utf8', function(err, infos) {

      if(err)
        return done(err, null)

      //https://github.com/arunoda/node-usage/commit/a6ca74ecb8dd452c3c00ed2bde93294d7bb75aa8
      //preventing process space in name by removing values before last ) (pid (name) ...)
      var index = infos.lastIndexOf(')')
      infos = infos.substr(index + 2).split(' ')

      //according to http://man7.org/linux/man-pages/man5/proc.5.html (index 0 based - 2)
      //In kernels before Linux 2.6, start was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
      var stat = {
          utime: parseFloat(infos[11]),
          stime: parseFloat(infos[12]),
          cutime: parseFloat(infos[13]),
          cstime: parseFloat(infos[14]),
          start: parseFloat(infos[19]) / cpu.clock_tick,
          rss: parseFloat(infos[21])
      }

      //http://stackoverflow.com/questions/16726779/total-cpu-usage-of-an-application-from-proc-pid-stat/16736599#16736599

      var childrens = options.childrens ? stat.cutime + stat.cstime : 0

      var total = stat.stime - (history.stime || 0) + stat.utime - (history.utime || 0) + childrens

      total = total / cpu.clock_tick

      //time elapsed between calls
      var seconds = history.uptime !== undefined ? cpu.uptime - history.uptime : stat.start - cpu.uptime
      seconds = Math.abs(seconds)
      seconds = seconds === 0 ? 0.1 : seconds //we sure can't divide through 0

      self.history[pid] = stat
      self.history[pid].seconds = seconds
      self.history[pid].uptime = cpu.uptime

      return done(null, {
        cpu: (total / seconds) * 100,
        memory: stat.rss * cpu.pagesize
      })
    })
  },
  /**
   * Get pid informations through ps command
   * @param  {int}   pid
   * @return  {Function} done (err, stat)
   * on os x skip headers with pcpu=,rss=
   * on linux it could be --no-header
   * on solaris 11 can't figure out a way to do this properly so...
   */
  ps: function(pid, options, done) {

    var cmd = 'ps -o pcpu,rss -p '

    if(os.platform() == 'aix')
      cmd = 'ps -o pcpu,rssize -p ' //this one could work on other platforms

    exec(cmd + pid, function(err, stdout, stderr) {
      if(err)
        return done(err, null)

      stdout = stdout.split(os.EOL)[1]
      stdout = stdout.replace(/^\s+/, '').replace(/\s\s+/g, ' ').split(' ')

      return done(null, {
        cpu: parseFloat(stdout[0].replace(',', '.')),
        memory: parseFloat(stdout[1]) * 1024
      })
    })
  },
  /**
   * This is really in a beta stage
   */
  win: function(pid, options, done) {
    // The code is tested under:
    // Windows 7 Ultimate/Enterprise SP1 64bit
    // Windows 8.1 Enterprise SP1 64bit
    // Windows 10 Professonal 64bit
    // Windows Server 2008 R2 64bit
    // Windows Server 2012 R2 64bit

    // Ref:
    // https://msdn.microsoft.com/en-us/library/aa394277(v=vs.85).aspx

    var args = 'path Win32_PerfFormattedData_PerfProc_Process WHERE IDProcess=' + pid + ' get PercentProcessorTime, WorkingSet'
    var wmic = spawn('wmic', args.split(' '), {detached: true})
    var stdout = ''
    var stderr = ''

    wmic.stdout.on('data', function(d) {
     stdout += d.toString()
    })

    wmic.stderr.on('data', function(d) {
      stderr += d.toString()
    })

    wmic.on('error', function(err) {
      console.error('[pidusage] Command "wmic ' + args + '" failed with error %s', err)
    })

    wmic.on('close', function(code) {
      stdout = stdout.trim()

      if(!stdout)
        return done(new Error(pid + ' does not exist'), null)

      stderr = stderr.trim()

      if (!!code && stderr) {
        return done(new Error(stderr), null)
      }

      // The new line in Windows is '\r\r\n'
      var lines = stdout.split(/\r?\r\n/)
      // We might need the titles someday.
      //var titles = lines[0].trim().split( / +/ )
      var values = lines[1].trim().split(/ +/)
      var cpuPercent = parseFloat(values[0])
      var memUsage   = parseFloat(values[1])

      if(isNaN(cpuPercent) || isNaN(memUsage)) {
        return done(new Error('Invalid cpu or memory occupation'), null)
      }

      return done(null, {cpu : cpuPercent, memory : memUsage})
    })
  }
}

module.exports = stats;
<|endoftext|>


<commit_before>import EventEmitter from 'events';
import { ipcRenderer } from 'electron';

const store = new EventEmitter();

let files = JSON.parse(localStorage.getItem("files")) || [];

store.emit('change');

let idCounter = localStorage.getItem("idCounter") || 0;

store.all = () => files.concat([]);

store.add = ({fileName, content, active}) => {
  let id = ++idCounter;
  localStorage.setItem("idCounter", idCounter);
  files = files.concat({ fileName, content, active: active || false, markdown: false, id: id});
  store.emit('change', files);
};

store.remove = (id) => {
  files = files.filter(file => file.id !== id );
  store.emit('change', files);
};

store.updateFileName = (newFileName, id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, {fileName: newFileName});
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.select = (id) => {
  files = files.map(file => {
    if (file.id === id) {
      return Object.assign({}, file, { active: true });
    }
    return Object.assign({}, file, { active: false});
  });

  store.emit('change', files);
};

store.deselect = () => {
  files = files.map(file => Object.assign({}, file, { active: false }));
  store.emit('change', files);
};

store.saveContent = (id, updatedContent) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { content: updatedContent});
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.saveActiveFile = () => {
  let file = files.find(file => file.active);
  if (file) {
    store.saveContent(file.fileName, file.content);
  }
};

store.newFile = () => {
  store.saveActiveFile();
  store.deselect();
  let id = ++idCounter;
  localStorage.setItem("idCounter", idCounter);

  let newNote = { fileName: "New Note", content: "", active: true, id: id};
  files = files.concat(newNote);
  store.emit('change', files);
  return newNote;
};

store.addMarkdown = (id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { markdown: true });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.removeMarkdown = (id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { markdown: false });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.findActiveFile = () => {
  return files.find(file => file.active);
};

store.saveGist = (fileName, gistUrl) => {
  files = files.map((file) => {
    if (file.fileName === fileName) {
      return Object.assign({}, file, { gist: gistUrl });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

ipcRenderer.on('file-opened', (event, file) => {
  store.add(file);
});

ipcRenderer.on('file-saved', (event, fileName, id) => {
  store.updateFileName(fileName, id);
});

store.on('change', (event) => {
  let jsonFiles = JSON.stringify(files);
  localStorage.setItem("files", jsonFiles);
});

module.exports = store;
<commit_msg>new and open files added to top of file list<commit_after>import EventEmitter from 'events';
import { ipcRenderer } from 'electron';

const store = new EventEmitter();

let files = JSON.parse(localStorage.getItem("files")) || [];

store.emit('change');

let idCounter = localStorage.getItem("idCounter") || 0;

store.all = () => files.concat([]);

store.add = ({fileName, content, active}) => {
  let id = ++idCounter;
  localStorage.setItem("idCounter", idCounter);
  files.unshift({ fileName, content, active: active || false, markdown: false, id: id});
  files = Object.assign([], files);
  store.emit('change', files);
};

store.remove = (id) => {
  files = files.filter(file => file.id !== id );
  store.emit('change', files);
};

store.updateFileName = (newFileName, id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, {fileName: newFileName});
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.select = (id) => {
  files = files.map(file => {
    if (file.id === id) {
      return Object.assign({}, file, { active: true });
    }
    return Object.assign({}, file, { active: false});
  });

  store.emit('change', files);
};

store.deselect = () => {
  files = files.map(file => Object.assign({}, file, { active: false }));
  store.emit('change', files);
};

store.saveContent = (id, updatedContent) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { content: updatedContent});
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.saveActiveFile = () => {
  let file = files.find(file => file.active);
  if (file) {
    store.saveContent(file.fileName, file.content);
  }
};

store.newFile = () => {
  store.saveActiveFile();
  store.deselect();
  let id = ++idCounter;
  localStorage.setItem("idCounter", idCounter);
  let newNote = { fileName: "New Note", content: "", active: true, id: id};
  files.unshift(newNote);
  files = Object.assign([], files);
  store.emit('change', files);
  return newNote;
};

store.addMarkdown = (id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { markdown: true });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.removeMarkdown = (id) => {
  files = files.map((file) => {
    if (file.id === id) {
      return Object.assign({}, file, { markdown: false });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

store.findActiveFile = () => {
  return files.find(file => file.active);
};

store.saveGist = (fileName, gistUrl) => {
  files = files.map((file) => {
    if (file.fileName === fileName) {
      return Object.assign({}, file, { gist: gistUrl });
    }
    return Object.assign({}, file);
  });
  store.emit('change', files);
};

ipcRenderer.on('file-opened', (event, file) => {
  store.add(file);
});

ipcRenderer.on('file-saved', (event, fileName, id) => {
  store.updateFileName(fileName, id);
});

store.on('change', (event) => {
  let jsonFiles = JSON.stringify(files);
  localStorage.setItem("files", jsonFiles);
});

module.exports = store;
<|endoftext|>


<commit_before>var async = require('async');
var mongo = require('mongodb');

module.exports = Store;

function Store(entities, cache, metacache) {
    this.entities = entities;
    this.cache = cache;
    this.metacache = metacache;
    this.processors = {};
};

Store.prototype.processor = function(name, operation) {
    if (operation === undefined) {
        // Retrieve existing processor
        var processor = this.processors[name];
        if (processor === undefined) throw new Error('Unknown processor');
        return processor;
    } else {
        // Define new processor
        this.processors[name] = operation;
    }
};

Store.prototype.put = function(buffer, callback) {
    this.entities.put(buffer, callback);
};

Store.prototype.delete = function(id, callback) {
    var self = this;
    this.invalidate(id, function(err) {
        if (err) return callback(err);
        self.entities.delete(id, callback);
    });
};

Store.prototype.raw = function(id, callback) {
    this.entities.get(objectId(id), callback);
};

Store.prototype.get = function(id, processor, callback) {
    var self = this;
    var id = objectId(id);

    // Optional `processor` argument
    if (callback === undefined) {
        callback = processor;
        return this.raw(id, callback);
    }

    this.metacache.lookup(id, processor, function(err, cached) {
        if (err) return callback(err);
        if (cached) return self.cache.get(cached, callback);
        self.process(id, processor, callback);
    });
};

Store.prototype.process = function(id, processor, callback) {
    var self = this;
    var id = objectId(id);

    var funcs = [
        // Get raw entity
        function(callback) {
            self.raw(id, callback);
        },

        // Process the entity
        function(buffer, callback) {
            var operation = self.processor(processor);
            operation(buffer, callback);
        },

        // Cache the result
        function(result, callback) {
            self.cache.put(result, function(err, doc) {
                if (err) return callback(err);
                callback(null, result, doc._id);
            });
        },

        // Update the metacache
        function(result, cached, callback) {
            self.metacache.store(id, processor, cached, function(err) {
                if (err) return callback(err);
                callback(null, result);
            });
        }
    ];

    async.waterfall(funcs, callback);
};

Store.prototype.invalidate = function(id, callback) {
    var self = this;
    var id = objectId(id);

    var funcs = [
        // Lookup entire metacache entry
        function(callback) {
            self.metacache.lookup(id, callback);
        },

        // Delete all cached entities
        function(metacache, callback) {
            var funcs = [];

            for (var processor in metacache) {
                if (processor !== '_id') {
                    var cached = metacache[processor];
                    funcs.push(function(callback) {
                        self.cache.delete(cached, callback);
                    });
                }
            }

            async.parallel(funcs, callback);
        },

        // Delete metacache entry
        function(results, callback) {
            self.metacache.delete(id, callback);
        }
    ];

    async.waterfall(funcs, callback);
};

// Helpers
// ---------------

function objectId(id) {
    if (typeof id === 'string') id = new mongo.ObjectID(id);
    return id;
};<commit_msg>Pass options to Store.put<commit_after>var async = require('async');
var mongo = require('mongodb');

module.exports = Store;

function Store(entities, cache, metacache) {
    this.entities = entities;
    this.cache = cache;
    this.metacache = metacache;
    this.processors = {};
};

Store.prototype.processor = function(name, operation) {
    if (operation === undefined) {
        // Retrieve existing processor
        var processor = this.processors[name];
        if (processor === undefined) throw new Error('Unknown processor');
        return processor;
    } else {
        // Define new processor
        this.processors[name] = operation;
    }
};

Store.prototype.put = function(buffer, options, callback) {
    this.entities.put(buffer, options, callback);
};

Store.prototype.delete = function(id, callback) {
    var self = this;
    this.invalidate(id, function(err) {
        if (err) return callback(err);
        self.entities.delete(id, callback);
    });
};

Store.prototype.raw = function(id, callback) {
    this.entities.get(objectId(id), callback);
};

Store.prototype.get = function(id, processor, callback) {
    var self = this;
    var id = objectId(id);

    // Optional `processor` argument
    if (callback === undefined) {
        callback = processor;
        return this.raw(id, callback);
    }

    this.metacache.lookup(id, processor, function(err, cached) {
        if (err) return callback(err);
        if (cached) return self.cache.get(cached, callback);
        self.process(id, processor, callback);
    });
};

Store.prototype.process = function(id, processor, callback) {
    var self = this;
    var id = objectId(id);

    var funcs = [
        // Get raw entity
        function(callback) {
            self.raw(id, callback);
        },

        // Process the entity
        function(buffer, callback) {
            var operation = self.processor(processor);
            operation(buffer, callback);
        },

        // Cache the result
        function(result, callback) {
            self.cache.put(result, function(err, doc) {
                if (err) return callback(err);
                callback(null, result, doc._id);
            });
        },

        // Update the metacache
        function(result, cached, callback) {
            self.metacache.store(id, processor, cached, function(err) {
                if (err) return callback(err);
                callback(null, result);
            });
        }
    ];

    async.waterfall(funcs, callback);
};

Store.prototype.invalidate = function(id, callback) {
    var self = this;
    var id = objectId(id);

    var funcs = [
        // Lookup entire metacache entry
        function(callback) {
            self.metacache.lookup(id, callback);
        },

        // Delete all cached entities
        function(metacache, callback) {
            var funcs = [];

            for (var processor in metacache) {
                if (processor !== '_id') {
                    var cached = metacache[processor];
                    funcs.push(function(callback) {
                        self.cache.delete(cached, callback);
                    });
                }
            }

            async.parallel(funcs, callback);
        },

        // Delete metacache entry
        function(results, callback) {
            self.metacache.delete(id, callback);
        }
    ];

    async.waterfall(funcs, callback);
};

// Helpers
// ---------------

function objectId(id) {
    if (typeof id === 'string') id = new mongo.ObjectID(id);
    return id;
};<|endoftext|>


<commit_before>/*
 * Swipe 2.0
 *
 * Brad Birdsall
 * Copyright 2013, MIT License
 *
*/

function Swipe(container, options) {

  "use strict";

  // utilities
  var noop = function() {}; // simple no operation function
  var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

  // check browser capabilities
  var browser = {
    addEventListener: !!window.addEventListener,
    touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
    transitions: (function(temp) {
      var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
      for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
      return false;
    })(document.createElement('swipe'))
  };

  // quit if no root element
  if (!container) return;
  var element = container.children[0];
  var slides, slidePos, width, length;
  options = options || {};
  var index = parseInt(options.startSlide, 10) || 0;
  var speed = options.speed || 300;

  function setup() {

    // cache slides
    slides = element.children;
    length = slides.length;

    // create an array to store current positions of each slide
    slidePos = new Array(slides.length);

    // determine width of each slide
    width = container.getBoundingClientRect().width || container.offsetWidth;

    element.style.width = (slides.length * width) + 'px';

    // stack elements
    var pos = slides.length;
    while(pos--) {

      var slide = slides[pos];

      slide.style.width = width + 'px';
      slide.setAttribute('data-index', pos);

      if (browser.transitions) {
        slide.style.left = (pos * -width) + 'px';
        move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
      }

    }

    if (!browser.transitions) element.style.left = (index * -width) + 'px';

    container.style.visibility = 'visible';

  }

  function prev() {

    if (index) slide(index-1);

  }

  function next() {

    if (index < slides.length - 1) slide(index+1);

  }

  function circle(index) {

    // a simple positive modulo using slides.length
    return (slides.length + (index % slides.length)) % slides.length;

  }

  function slide(to, slideSpeed) {

    // do nothing if already on requested slide
    if (index == to) return;

    if (browser.transitions) {

      var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward

      var diff = Math.abs(index-to) - 1;

      // move all the slides between index and to in the right direction
      while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);

      to = circle(to);

      move(index, width * direction, slideSpeed || speed);
      move(to, 0, slideSpeed || speed);

    } else {

      to = circle(to);
      animate(index * -width, to * -width, slideSpeed || speed);
      //no fallback for a circular continuous if the browser does not accept transitions
    }

    index = to;
    offloadFn(options.callback && options.callback(index, slides[index]));
  }

  function move(index, dist, speed) {

    translate(index, dist, speed);
    slidePos[index] = dist;

  }

  function translate(index, dist, speed, direct) {
    var slide;
    if (direct){
      slide = direct;
    }
    else{
      slide = slides[index];
    }

    var style = slide && slide.style;

    if (!style) return;

    style.webkitTransitionDuration =
    style.MozTransitionDuration =
    style.msTransitionDuration =
    style.OTransitionDuration =
    style.transitionDuration = speed + 'ms';

    style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
    style.msTransform =
    style.MozTransform =
    style.OTransform = 'translateX(' + dist + 'px)';

  }

  function animate(from, to, speed) {

    // if not an animation, just reposition
    if (!speed) {

      element.style.left = to + 'px';
      return;

    }

    var start = +new Date;

    var timer = setInterval(function() {

      var timeElap = +new Date - start;

      if (timeElap > speed) {

        element.style.left = to + 'px';

        if (delay) begin();

        options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

        clearInterval(timer);
        return;

      }

      element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';

    }, 4);

  }

  // setup auto slideshow
  var delay = options.auto || 0;
  var interval;

  function begin() {

    interval = setTimeout(next, delay);

  }

  function stop() {

    delay = 0;
    clearTimeout(interval);

  }

  // setup initial vars
  var start = {};
  var delta = {};
  var isScrolling;

  // setup event capturing
  var events = {

    handleEvent: function(event) {

      switch (event.type) {
        case 'touchstart': this.start(event); break;
        case 'touchmove': this.move(event); break;
        case 'touchend': offloadFn(this.end(event)); break;
        case 'webkitTransitionEnd':
        case 'msTransitionEnd':
        case 'oTransitionEnd':
        case 'otransitionend':
        case 'transitionend': offloadFn(this.transitionEnd(event)); break;
        case 'resize': offloadFn(setup.call()); break;
      }

      if (options.stopPropagation) event.stopPropagation();

    },
    start: function(event) {

      var touches = event.touches[0];

      // measure start values
      start = {

        // get initial touch coords
        x: touches.pageX,
        y: touches.pageY,

        // store time to determine touch duration
        time: +new Date

      };

      // used for testing first move event
      isScrolling = undefined;

      // reset delta and end measurements
      delta = {};

      // attach touchmove and touchend listeners
      element.addEventListener('touchmove', this, false);
      element.addEventListener('touchend', this, false);

    },
    move: function(event) {

      // ensure swiping with one touch and not pinching
      if ( event.touches.length > 1 || event.scale && event.scale !== 1) return

      if (options.disableScroll) event.preventDefault();

      var touches = event.touches[0];

      // measure change in x and y
      delta = {
        x: touches.pageX - start.x,
        y: touches.pageY - start.y
      }

      // determine if scrolling test has run - one time test
      if ( typeof isScrolling == 'undefined') {
        isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
      }

      // if user is not trying to scroll vertically
      if (!isScrolling) {

        // prevent native scrolling
        event.preventDefault();

        // stop slideshow
        stop();

        // increase resistance if first or last slide

          delta.x =
            delta.x /
              ( (!index && delta.x > 0               // if first slide and sliding left
                || index == slides.length - 1        // or if last slide and sliding right
                && delta.x < 0                       // and if sliding at all
              ) ?
              ( Math.abs(delta.x) / width + 1 )      // determine resistance level
              : 1 );                                 // no resistance if false

          // translate 1:1
          translate(index-1, delta.x + slidePos[index-1], 0);
          translate(index, delta.x + slidePos[index], 0);
          translate(index+1, delta.x + slidePos[index+1], 0);

      }

    },
    end: function(event) {

      // measure duration
      var duration = +new Date - start.time;

      // determine if slide attempt triggers next/prev slide
      var isValidSlide =
            Number(duration) < 250               // if slide duration is less than 250ms
            && Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
            || Math.abs(delta.x) > width/2;      // or if slide amt is greater than half the width

      // determine if slide attempt is past start and end
      var isPastBounds =
            !index && delta.x > 0                            // if first slide and slide amt is greater than 0
            || index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

      // determine direction of swipe (true:right, false:left)
      var direction = delta.x < 0;

      // if not scrolling vertically
      if (!isScrolling) {

        if (isValidSlide && !isPastBounds) {

          if (direction) {

              move(index-1, -width, 0);

            move(index, slidePos[index]-width, speed);
            move(circle(index+1), slidePos[circle(index+1)]-width, speed);
            index = circle(index+1);

          } else {
              move(index+1, width, 0);

            move(index, slidePos[index]+width, speed);
            move(circle(index-1), slidePos[circle(index-1)]+width, speed);
            index = circle(index-1);

          }

          options.callback && options.callback(index, slides[index]);

        } else {

            move(index-1, -width, speed);
            move(index, 0, speed);
            move(index+1, width, speed);

        }

      }

      // kill touchmove and touchend event listeners until touchstart called again
      element.removeEventListener('touchmove', events, false)
      element.removeEventListener('touchend', events, false)

    },
    transitionEnd: function(event) {

      if (parseInt(event.target.getAttribute('data-index'), 10) == index) {

        if (delay) begin();

        options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

      }

    }

  }

  // trigger setup
  setup();

  // start auto slideshow if applicable
  if (delay) begin();

  // add event listeners
  if (browser.addEventListener) {

    // set touchstart event on element
    if (browser.touch) element.addEventListener('touchstart', events, false);

    if (browser.transitions) {
      element.addEventListener('webkitTransitionEnd', events, false);
      element.addEventListener('msTransitionEnd', events, false);
      element.addEventListener('oTransitionEnd', events, false);
      element.addEventListener('otransitionend', events, false);
      element.addEventListener('transitionend', events, false);
    }

    // set resize event on window
    window.addEventListener('resize', events, false);

  } else {

    window.onresize = function () { setup() }; // to play nice with old IE

  }

  // expose the Swipe API
  return {
    setup: function() {

      setup();

    },
    slide: function(to, speed) {

      // cancel slideshow
      stop();

      slide(to, speed);

    },
    prev: function() {

      // cancel slideshow
      stop();

      prev();

    },
    next: function() {

      // cancel slideshow
      stop();

      next();

    },
    getPos: function() {

      // return current index position
      return index;

    },
    getNumSlides: function() {

      // return total number of slides
      return length;
    },
    prepareForAddition: function(newElement) {

      // style an addition to the slides
      translate(null, width , 0, newElement);
      newElement.style.width = width + 'px';
      newElement.style.left = (length * -width) + 'px';

      element.style.width = (function(){
        var w = parseInt(element.style.width) / length;
        w *= (length + 1);
        return (w + 'px');
      }());
    }

  }

}

if ( window.jQuery || window.Zepto ) {
  (function($) {
    $.fn.Swipe = function(params) {
      return this.each(function() {
        $(this).data('Swipe', new Swipe($(this)[0], params));
      });
    }
  })( window.jQuery || window.Zepto )
}
<commit_msg>Remove auto-slideshow<commit_after>/*
 * Swipe 2.0
 *
 * Brad Birdsall
 * Copyright 2013, MIT License
 *
*/

function Swipe(container, options) {

  "use strict";

  // utilities
  var noop = function() {}; // simple no operation function
  var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

  // check browser capabilities
  var browser = {
    addEventListener: !!window.addEventListener,
    touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
    transitions: (function(temp) {
      var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
      for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
      return false;
    })(document.createElement('swipe'))
  };

  // quit if no root element
  if (!container) return;
  var element = container.children[0];
  var slides, slidePos, width, length;
  options = options || {};
  var index = parseInt(options.startSlide, 10) || 0;
  var speed = options.speed || 300;

  function setup() {

    // cache slides
    slides = element.children;
    length = slides.length;

    // create an array to store current positions of each slide
    slidePos = new Array(slides.length);

    // determine width of each slide
    width = container.getBoundingClientRect().width || container.offsetWidth;

    element.style.width = (slides.length * width) + 'px';

    // stack elements
    var pos = slides.length;
    while(pos--) {

      var slide = slides[pos];

      slide.style.width = width + 'px';
      slide.setAttribute('data-index', pos);

      if (browser.transitions) {
        slide.style.left = (pos * -width) + 'px';
        move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
      }

    }

    if (!browser.transitions) element.style.left = (index * -width) + 'px';

    container.style.visibility = 'visible';

  }

  function prev() {

    if (index) slide(index-1);

  }

  function next() {

    if (index < slides.length - 1) slide(index+1);

  }

  function circle(index) {

    // a simple positive modulo using slides.length
    return (slides.length + (index % slides.length)) % slides.length;

  }

  function slide(to, slideSpeed) {

    // do nothing if already on requested slide
    if (index == to) return;

    if (browser.transitions) {

      var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward

      var diff = Math.abs(index-to) - 1;

      // move all the slides between index and to in the right direction
      while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);

      to = circle(to);

      move(index, width * direction, slideSpeed || speed);
      move(to, 0, slideSpeed || speed);

    } else {

      to = circle(to);
      animate(index * -width, to * -width, slideSpeed || speed);
      //no fallback for a circular continuous if the browser does not accept transitions
    }

    index = to;
    offloadFn(options.callback && options.callback(index, slides[index]));
  }

  function move(index, dist, speed) {

    translate(index, dist, speed);
    slidePos[index] = dist;

  }

  function translate(index, dist, speed, direct) {
    var slide;
    if (direct){
      slide = direct;
    }
    else{
      slide = slides[index];
    }

    var style = slide && slide.style;

    if (!style) return;

    style.webkitTransitionDuration =
    style.MozTransitionDuration =
    style.msTransitionDuration =
    style.OTransitionDuration =
    style.transitionDuration = speed + 'ms';

    style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
    style.msTransform =
    style.MozTransform =
    style.OTransform = 'translateX(' + dist + 'px)';

  }

  function animate(from, to, speed) {

    // if not an animation, just reposition
    if (!speed) {

      element.style.left = to + 'px';
      return;

    }

    var start = +new Date;

    var timer = setInterval(function() {

      var timeElap = +new Date - start;

      if (timeElap > speed) {

        element.style.left = to + 'px';

        options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

        clearInterval(timer);
        return;

      }

      element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';

    }, 4);

  }

  // setup initial vars
  var start = {};
  var delta = {};
  var isScrolling;

  // setup event capturing
  var events = {

    handleEvent: function(event) {

      switch (event.type) {
        case 'touchstart': this.start(event); break;
        case 'touchmove': this.move(event); break;
        case 'touchend': offloadFn(this.end(event)); break;
        case 'webkitTransitionEnd':
        case 'msTransitionEnd':
        case 'oTransitionEnd':
        case 'otransitionend':
        case 'transitionend': offloadFn(this.transitionEnd(event)); break;
        case 'resize': offloadFn(setup.call()); break;
      }

      if (options.stopPropagation) event.stopPropagation();

    },
    start: function(event) {

      var touches = event.touches[0];

      // measure start values
      start = {

        // get initial touch coords
        x: touches.pageX,
        y: touches.pageY,

        // store time to determine touch duration
        time: +new Date

      };

      // used for testing first move event
      isScrolling = undefined;

      // reset delta and end measurements
      delta = {};

      // attach touchmove and touchend listeners
      element.addEventListener('touchmove', this, false);
      element.addEventListener('touchend', this, false);

    },
    move: function(event) {

      // ensure swiping with one touch and not pinching
      if ( event.touches.length > 1 || event.scale && event.scale !== 1) return

      if (options.disableScroll) event.preventDefault();

      var touches = event.touches[0];

      // measure change in x and y
      delta = {
        x: touches.pageX - start.x,
        y: touches.pageY - start.y
      }

      // determine if scrolling test has run - one time test
      if ( typeof isScrolling == 'undefined') {
        isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
      }

      // if user is not trying to scroll vertically
      if (!isScrolling) {

        // prevent native scrolling
        event.preventDefault();

        // increase resistance if first or last slide

          delta.x =
            delta.x /
              ( (!index && delta.x > 0               // if first slide and sliding left
                || index == slides.length - 1        // or if last slide and sliding right
                && delta.x < 0                       // and if sliding at all
              ) ?
              ( Math.abs(delta.x) / width + 1 )      // determine resistance level
              : 1 );                                 // no resistance if false

          // translate 1:1
          translate(index-1, delta.x + slidePos[index-1], 0);
          translate(index, delta.x + slidePos[index], 0);
          translate(index+1, delta.x + slidePos[index+1], 0);

      }

    },
    end: function(event) {

      // measure duration
      var duration = +new Date - start.time;

      // determine if slide attempt triggers next/prev slide
      var isValidSlide =
            Number(duration) < 250               // if slide duration is less than 250ms
            && Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
            || Math.abs(delta.x) > width/2;      // or if slide amt is greater than half the width

      // determine if slide attempt is past start and end
      var isPastBounds =
            !index && delta.x > 0                            // if first slide and slide amt is greater than 0
            || index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

      // determine direction of swipe (true:right, false:left)
      var direction = delta.x < 0;

      // if not scrolling vertically
      if (!isScrolling) {

        if (isValidSlide && !isPastBounds) {

          if (direction) {

              move(index-1, -width, 0);

            move(index, slidePos[index]-width, speed);
            move(circle(index+1), slidePos[circle(index+1)]-width, speed);
            index = circle(index+1);

          } else {
              move(index+1, width, 0);

            move(index, slidePos[index]+width, speed);
            move(circle(index-1), slidePos[circle(index-1)]+width, speed);
            index = circle(index-1);

          }

          options.callback && options.callback(index, slides[index]);

        } else {

            move(index-1, -width, speed);
            move(index, 0, speed);
            move(index+1, width, speed);

        }

      }

      // kill touchmove and touchend event listeners until touchstart called again
      element.removeEventListener('touchmove', events, false)
      element.removeEventListener('touchend', events, false)

    },
    transitionEnd: function(event) {

      if (parseInt(event.target.getAttribute('data-index'), 10) == index) {

        options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

      }

    }

  }

  // trigger setup
  setup();

  // add event listeners
  if (browser.addEventListener) {

    // set touchstart event on element
    if (browser.touch) element.addEventListener('touchstart', events, false);

    if (browser.transitions) {
      element.addEventListener('webkitTransitionEnd', events, false);
      element.addEventListener('msTransitionEnd', events, false);
      element.addEventListener('oTransitionEnd', events, false);
      element.addEventListener('otransitionend', events, false);
      element.addEventListener('transitionend', events, false);
    }

    // set resize event on window
    window.addEventListener('resize', events, false);

  } else {

    window.onresize = function () { setup() }; // to play nice with old IE

  }

  // expose the Swipe API
  return {
    setup: function() {

      setup();

    },
    slide: function(to, speed) {

      slide(to, speed);

    },
    prev: function() {

      prev();

    },
    next: function() {

      next();

    },
    getPos: function() {

      // return current index position
      return index;

    },
    getNumSlides: function() {

      // return total number of slides
      return length;
    },
    prepareForAddition: function(newElement) {

      // style an addition to the slides
      translate(null, width , 0, newElement);
      newElement.style.width = width + 'px';
      newElement.style.left = (length * -width) + 'px';

      element.style.width = (function(){
        var w = parseInt(element.style.width) / length;
        w *= (length + 1);
        return (w + 'px');
      }());
    }

  }

}

if ( window.jQuery || window.Zepto ) {
  (function($) {
    $.fn.Swipe = function(params) {
      return this.each(function() {
        $(this).data('Swipe', new Swipe($(this)[0], params));
      });
    }
  })( window.jQuery || window.Zepto )
}
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var lodash = require('lodash');

var Query = require(__dirname + '/node/query');
var Column = require(__dirname + '/column');
var TableNode = require(__dirname + '/node/table');
var JoinNode = require(__dirname + '/node/join');
var Joiner = require(__dirname + '/joiner');

var Table = function(config) {
  this._schema = config.schema;
  this._name = config.name;
  this._initialConfig = config;
  this.columns = [];
  this.table = this;
  if (!config.sql) {
    config.sql = require('./index');
  }
  this.sql = config.sql;
};

Table.define = function(config) {
  var table = new Table(config);
  // allow hash of columns as well as array
  if (config.columns && !util.isArray(config.columns)) {
    var cols = [];

    for (var key in config.columns) {
      if (config.columns.hasOwnProperty(key)) {
        var col = config.columns[key];
        col.name = key;
        cols.push(col);
      }
    }

    config.columns = cols;
  }

  for (var i = 0; i < config.columns.length; i++) {
    table.addColumn(config.columns[i]);
  }
  return table;
};

Table.prototype.createColumn = function(col) {
  if(!(col instanceof Column)) {
    if(typeof col === 'string') {
      col = { name: col };
    }

    col.table = this;
    col = new Column(col);
  }

  return col;
};

Table.prototype.addColumn = function(col, options) {
  col     = this.createColumn(col);
  options = lodash.extend({
    noisy: true
  }, options || {});

  if(this.hasColumn(col)) {
    if (options.noisy) {
      throw new Error('Table ' + this._name + ' already has column or property by the name of ' + col.name);
    } else {
      return this;
    }
  } else if(!!this[col.name] && (process.env.NODE_ENV !== 'test')) {
    console.log('Please notice that you have just defined the column "' + col.name + '". In order to access it, you need to use "table.getColumn(\'' + col.name + '\');"!');
  }
  this.columns.push(col);
  var property = col.property || col.name;
  this[property] = this[property] || col;
  return this;
};

Table.prototype.hasColumn = function(col) {
  col = this.createColumn(col);

  var cols = this.columns.filter(function(column) {
    return column.name === col.name;
  });

  return cols.length > 0;
};

Table.prototype.getColumn =
Table.prototype.get =
function(colName) {
  for(var i = 0; i < this.columns.length; i++) {
    var col = this.columns[i];
    if (col.name === colName) {
      return col;
    }
  }
  throw new Error('Table ' + this._name + ' does not have a column named ' + colName);
};

Table.prototype.getSchema = function() {
  return this._schema;
};

Table.prototype.getName = function() {
  return this._name;
};

Table.prototype.star = function() {
  return new Column({table: this, star: true});
};

Table.prototype.count = function(alias) {
  var name = this.alias || this._name,
    col = new Column({table: this, star: true});
  // ColumnNode
  return col.count(alias || name + '_count');
};

Table.prototype.select = function() {
  // create the query and pass it off
  var query = new Query(this);
  if (arguments.length === 0) {
    query.select.call(query, this.star());
  } else {
    query.select.apply(query, arguments);
  }
  return query;
};

Table.prototype.from = function() {
  var query = new Query(this);
  query.from.apply(query, arguments);
  return query;
};

Table.prototype.subQuery = function(alias) {
  // create the query and pass it off
  var query = new Query(this);
  query.type = 'SUBQUERY';
  query.alias = alias;
  return query;
};

Table.prototype.insert = function() {
  var query = new Query(this);
  query.insert.apply(query, arguments);
  return query;
};

Table.prototype.update = function() {
  var query = new Query(this);
  query.update.apply(query, arguments);
  return query;
};

Table.prototype['delete'] = function() {
  var query = new Query(this);
  query['delete'].apply(query, arguments);
  return query;
};

Table.prototype.create = function() {
  var query = new Query(this);
  query.create.apply(query, arguments);
  return query;
};

Table.prototype.drop = function() {
  var query = new Query(this);
  query.drop.apply(query, arguments);
  return query;
};

Table.prototype.alter = function() {
  var query = new Query(this);
  query.alter.apply(query, arguments);
  return query;
};

Table.prototype.toNode = function() {
  return new TableNode(this);
};

Table.prototype.join = function(other) {
  return new JoinNode('INNER', this.toNode(), other.toNode(), other);
};

Table.prototype.leftJoin = function(other) {
  return new JoinNode('LEFT', this.toNode(), other.toNode());
};

// auto-join tables based on column intropsection
Table.prototype.joinTo = function(other) {
  return Joiner.leftJoin(this, other);
};

Table.prototype.as = function(alias) {
  // TODO could this be cleaner?
  var t = Table.define(this._initialConfig);
  t.alias = alias;
  return t;
};

// called in shorthand when not calling select
Table.prototype.__defineGetter__("nodes", function() {
  return this.select(this.star()).nodes;
});

Table.prototype.where = function() {
  var query = new Query(this);
  query.where.apply(query, arguments);
  return query;
};

Table.prototype.and = function() {
  var query = new Query(this);
  query.where.apply(query, arguments);
  return query;
};

Table.prototype.or = function() {
  var query = new Query(this);
  query.or.apply(query, arguments);
  return query;
};

Table.prototype.indexes = function() {
  return new Query(this).indexes();
};

module.exports = Table;
<commit_msg>Add prototype to change schema name<commit_after>'use strict';

var util = require('util');
var lodash = require('lodash');

var Query = require(__dirname + '/node/query');
var Column = require(__dirname + '/column');
var TableNode = require(__dirname + '/node/table');
var JoinNode = require(__dirname + '/node/join');
var Joiner = require(__dirname + '/joiner');

var Table = function(config) {
  this._schema = config.schema;
  this._name = config.name;
  this._initialConfig = config;
  this.columns = [];
  this.table = this;
  if (!config.sql) {
    config.sql = require('./index');
  }
  this.sql = config.sql;
};

Table.define = function(config) {
  var table = new Table(config);
  // allow hash of columns as well as array
  if (config.columns && !util.isArray(config.columns)) {
    var cols = [];

    for (var key in config.columns) {
      if (config.columns.hasOwnProperty(key)) {
        var col = config.columns[key];
        col.name = key;
        cols.push(col);
      }
    }

    config.columns = cols;
  }

  for (var i = 0; i < config.columns.length; i++) {
    table.addColumn(config.columns[i]);
  }
  return table;
};

Table.prototype.createColumn = function(col) {
  if(!(col instanceof Column)) {
    if(typeof col === 'string') {
      col = { name: col };
    }

    col.table = this;
    col = new Column(col);
  }

  return col;
};

Table.prototype.addColumn = function(col, options) {
  col     = this.createColumn(col);
  options = lodash.extend({
    noisy: true
  }, options || {});

  if(this.hasColumn(col)) {
    if (options.noisy) {
      throw new Error('Table ' + this._name + ' already has column or property by the name of ' + col.name);
    } else {
      return this;
    }
  } else if(!!this[col.name] && (process.env.NODE_ENV !== 'test')) {
    console.log('Please notice that you have just defined the column "' + col.name + '". In order to access it, you need to use "table.getColumn(\'' + col.name + '\');"!');
  }
  this.columns.push(col);
  var property = col.property || col.name;
  this[property] = this[property] || col;
  return this;
};

Table.prototype.hasColumn = function(col) {
  col = this.createColumn(col);

  var cols = this.columns.filter(function(column) {
    return column.name === col.name;
  });

  return cols.length > 0;
};

Table.prototype.getColumn =
Table.prototype.get =
function(colName) {
  for(var i = 0; i < this.columns.length; i++) {
    var col = this.columns[i];
    if (col.name === colName) {
      return col;
    }
  }
  throw new Error('Table ' + this._name + ' does not have a column named ' + colName);
};

Table.prototype.getSchema = function() {
  return this._schema;
};

Table.prototype.setSchema = function(schema) {
  this._schema = schema;
};

Table.prototype.getName = function() {
  return this._name;
};

Table.prototype.star = function() {
  return new Column({table: this, star: true});
};

Table.prototype.count = function(alias) {
  var name = this.alias || this._name,
    col = new Column({table: this, star: true});
  // ColumnNode
  return col.count(alias || name + '_count');
};

Table.prototype.select = function() {
  // create the query and pass it off
  var query = new Query(this);
  if (arguments.length === 0) {
    query.select.call(query, this.star());
  } else {
    query.select.apply(query, arguments);
  }
  return query;
};

Table.prototype.from = function() {
  var query = new Query(this);
  query.from.apply(query, arguments);
  return query;
};

Table.prototype.subQuery = function(alias) {
  // create the query and pass it off
  var query = new Query(this);
  query.type = 'SUBQUERY';
  query.alias = alias;
  return query;
};

Table.prototype.insert = function() {
  var query = new Query(this);
  query.insert.apply(query, arguments);
  return query;
};

Table.prototype.update = function() {
  var query = new Query(this);
  query.update.apply(query, arguments);
  return query;
};

Table.prototype['delete'] = function() {
  var query = new Query(this);
  query['delete'].apply(query, arguments);
  return query;
};

Table.prototype.create = function() {
  var query = new Query(this);
  query.create.apply(query, arguments);
  return query;
};

Table.prototype.drop = function() {
  var query = new Query(this);
  query.drop.apply(query, arguments);
  return query;
};

Table.prototype.alter = function() {
  var query = new Query(this);
  query.alter.apply(query, arguments);
  return query;
};

Table.prototype.toNode = function() {
  return new TableNode(this);
};

Table.prototype.join = function(other) {
  return new JoinNode('INNER', this.toNode(), other.toNode(), other);
};

Table.prototype.leftJoin = function(other) {
  return new JoinNode('LEFT', this.toNode(), other.toNode());
};

// auto-join tables based on column intropsection
Table.prototype.joinTo = function(other) {
  return Joiner.leftJoin(this, other);
};

Table.prototype.as = function(alias) {
  // TODO could this be cleaner?
  var t = Table.define(this._initialConfig);
  t.alias = alias;
  return t;
};

// called in shorthand when not calling select
Table.prototype.__defineGetter__("nodes", function() {
  return this.select(this.star()).nodes;
});

Table.prototype.where = function() {
  var query = new Query(this);
  query.where.apply(query, arguments);
  return query;
};

Table.prototype.and = function() {
  var query = new Query(this);
  query.where.apply(query, arguments);
  return query;
};

Table.prototype.or = function() {
  var query = new Query(this);
  query.or.apply(query, arguments);
  return query;
};

Table.prototype.indexes = function() {
  return new Query(this).indexes();
};

module.exports = Table;
<|endoftext|>


<commit_before>(function (stylecow) {

	//Properties
	stylecow.tasks = [];
	stylecow.support = {
		explorer: false,
		firefox: false,
		chrome: false,
		safari: false,
		opera: false,
		android: false,
		ios: false
	};

	//Set temporary default browser support
	var defaultSupport;

	stylecow.forBrowsersLowerThan = function (support, callback) {
		var prevSupport = defaultSupport;

		defaultSupport = support;
		callback(stylecow);
		defaultSupport = prevSupport;

		return stylecow;
	};

	//Register new tasks
	stylecow.addTask = function (task) {
		task.forBrowsersLowerThan = task.forBrowsersLowerThan || defaultSupport;
		task.filter = task.filter || 'Root';
		task.position = task.position === 'before' ? 'before' : 'after';

		stylecow.tasks.push(task);

		return stylecow;
	};

	//Configure minimum browser support
	stylecow.minSupport = function (support) {
		stylecow.support = support;

		return stylecow;
	};

	//Run registered tasks
	stylecow.run = function (root) {
		var tasks = prepareTasks(stylecow.tasks, stylecow.support);

		executeRootTasks(root, tasks);
	};

})(require('./index'));

//filter and sort the tasks to improve performance
function prepareTasks (allTasks, support) {
	var tasks = {}, i;

	for (i = allTasks.length - 1; i >= 0; i--) {
		var task = allTasks[i];

		//browser compatibility
		if (!needFix(support, task.forBrowsersLowerThan)) {
			continue;
		}

		//Sort by position (after|before)
		tasks[task.position] = tasks[task.position] || {};

		//Sort by type
		if (typeof task.filter === 'string') {
			tasks[task.position][task.filter] = tasks[task.position][task.filter] || [];
			tasks[task.position][task.filter].push(task);
			continue;
		}

		if (typeof task.filter.type === 'string') {
			tasks[task.position][task.filter.type] = tasks[task.position][task.filter.type] || [];
			tasks[task.position][task.filter.type].push(task);
			continue;
		}

		if (typeof task.filter.type === Array) {
			task.filter.type.forEach(function (type) {
				tasks[task.position][type] = tasks[task.position][type] || [];
				tasks[task.position][type].push(task);
			});
			continue;
		}

		//Unknow type: use "_"
		tasks[task.position]._ = tasks[task.position]._ || [];
		tasks[task.position]._.push(task);
	}

	return tasks;
}

//check the browser support of a task
function needFix (minSupport, disablePlugin) {
	if (!disablePlugin || !minSupport) {
		return true;
	}

	for (var browser in disablePlugin) {
		if (minSupport[browser] === false) {
			continue;
		}

		if (disablePlugin[browser] === false || minSupport[browser] < disablePlugin[browser]) {
			return true;
		}
	}

	return false;
}

function executeRootTasks (element, tasks) {
	//mark as executed to don't execute it again
	element.data.executed = true;

	//execute tasks before its children
	if (tasks.hasOwnProperty('before')) {
		if (tasks.before.hasOwnProperty('Root')) {
			execRootTasks(element, tasks.before.Root);
		}

		if (tasks.before.hasOwnProperty('_')) {
			execRootTasks(element, tasks.before._);
		}
	}

	//execute the children tasks recursively
	if (element.length) {
		execChildrenTasks(element, tasks)
	}

	//execute tasks after its children
	if (tasks.hasOwnProperty('after')) {
		if (tasks.after.hasOwnProperty('Root')) {
			execRootTasks(element, tasks.after.Root);
		}

		if (tasks.after.hasOwnProperty('_')) {
			execRootTasks(element, tasks.after._);
		}
	}
}

function execRootTasks (element, tasks) {
	for (var i = tasks.length - 1; i >= 0; i--) {
		if (element.is(tasks[i].filter)) {
			tasks[i].fn(element);
		}
	}
}

function executeChildTasks (element, tasks) {
	//mark as executed to prevent execute it again
	element.data.executed = true;

	//was element removed?
	if (!element.parent) {
		return false;
	}

	//execute tasks before children
	if (tasks.hasOwnProperty('before')) {
		if (tasks.before.hasOwnProperty(element.type)) {
			if (!execChildTasks(element, tasks.before[element.type])) {
				return;
			}
		}

		if (tasks.before.hasOwnProperty('_')) {
			if (!execChildTasks(element, tasks.before._)) {
				return;
			}
		}
	}

	//execute the children tasks recursively
	if (element.length) {
		execChildrenTasks(element, tasks)
	}

	//execute tasks after children
	if (tasks.hasOwnProperty('after')) {
		if (tasks.after.hasOwnProperty(element.type)) {
			if (!execChildTasks(element, tasks.after[element.type])) {
				return;
			}
		}

		if (tasks.after.hasOwnProperty('_')) {
			if (!execChildTasks(element, tasks.after._)) {
				return;
			}
		}
	}
}

function execChildTasks (element, tasks) {
	for (var i = tasks.length - 1; i >= 0; i--) {
		if (element.is(tasks[i].filter)) {
			tasks[i].fn(element);

			//was element removed?
			if (!element.parent) {
				return false;
			}
		}
	}

	return true;
}

function execChildrenTasks (element, tasks) {
	var t, i, executed = true;

	while (executed) {
		executed = false;

		for (i = 0, t = element.length; i < t; i++) {
			if (element[i] && element[i].data.executed !== true) {
				executeChildTasks(element[i], tasks);
				executed = true;
			}
		}
	}
}
<commit_msg>reverted the way to execute tasks, because the new was buggy<commit_after>(function (stylecow) {

	//Properties
	stylecow.tasks = [];
	stylecow.support = {
		explorer: false,
		firefox: false,
		chrome: false,
		safari: false,
		opera: false,
		android: false,
		ios: false
	};

	//Set temporary default browser support
	var defaultSupport;

	stylecow.forBrowsersLowerThan = function (support, callback) {
		var prevSupport = defaultSupport;

		defaultSupport = support;
		callback(stylecow);
		defaultSupport = prevSupport;

		return stylecow;
	};

	//Register new tasks
	stylecow.addTask = function (task) {
		task.forBrowsersLowerThan = task.forBrowsersLowerThan || defaultSupport;
		task.filter = task.filter || 'Root';
		task.position = task.position === 'before' ? 'before' : 'after';

		stylecow.tasks.push(task);

		return stylecow;
	};

	//Configure minimum browser support
	stylecow.minSupport = function (support) {
		stylecow.support = support;

		return stylecow;
	};

	//Run registered tasks
	stylecow.run = function (root) {
		var tasks = prepareTasks(stylecow.tasks, stylecow.support);

		executeRootTasks(root, tasks);
	};

})(require('./index'));

//filter and sort the tasks to improve performance
function prepareTasks (allTasks, support) {
	var tasks = {}, i;

	for (i = allTasks.length - 1; i >= 0; i--) {
		var task = allTasks[i];

		//browser compatibility
		if (!needFix(support, task.forBrowsersLowerThan)) {
			continue;
		}

		//Sort by position (after|before)
		tasks[task.position] = tasks[task.position] || {};

		//Sort by type
		if (typeof task.filter === 'string') {
			tasks[task.position][task.filter] = tasks[task.position][task.filter] || [];
			tasks[task.position][task.filter].push(task);
			continue;
		}

		if (typeof task.filter.type === 'string') {
			tasks[task.position][task.filter.type] = tasks[task.position][task.filter.type] || [];
			tasks[task.position][task.filter.type].push(task);
			continue;
		}

		if (typeof task.filter.type === Array) {
			task.filter.type.forEach(function (type) {
				tasks[task.position][type] = tasks[task.position][type] || [];
				tasks[task.position][type].push(task);
			});
			continue;
		}

		//Unknow type: use "_"
		tasks[task.position]._ = tasks[task.position]._ || [];
		tasks[task.position]._.push(task);
	}

	return tasks;
}

//check the browser support of a task
function needFix (minSupport, disablePlugin) {
	if (!disablePlugin || !minSupport) {
		return true;
	}

	for (var browser in disablePlugin) {
		if (minSupport[browser] === false) {
			continue;
		}

		if (disablePlugin[browser] === false || minSupport[browser] < disablePlugin[browser]) {
			return true;
		}
	}

	return false;
}

function executeRootTasks (element, tasks) {
	//mark as executed to don't execute it again
	element.data.executed = true;

	//execute tasks before its children
	if (tasks.hasOwnProperty('before')) {
		if (tasks.before.hasOwnProperty('Root')) {
			execRootTasks(element, tasks.before.Root);
		}

		if (tasks.before.hasOwnProperty('_')) {
			execRootTasks(element, tasks.before._);
		}
	}

	//execute the children tasks recursively
	if (element.length) {
		execChildrenTasks(element, tasks)
	}

	//execute tasks after its children
	if (tasks.hasOwnProperty('after')) {
		if (tasks.after.hasOwnProperty('Root')) {
			execRootTasks(element, tasks.after.Root);
		}

		if (tasks.after.hasOwnProperty('_')) {
			execRootTasks(element, tasks.after._);
		}
	}
}

function execRootTasks (element, tasks) {
	for (var i = tasks.length - 1; i >= 0; i--) {
		if (element.is(tasks[i].filter)) {
			tasks[i].fn(element);
		}
	}
}

function executeChildTasks (element, tasks) {
	//mark as executed to prevent execute it again
	element.data.executed = true;

	//was element removed?
	if (!element.parent) {
		return false;
	}

	//execute tasks before children
	if (tasks.hasOwnProperty('before')) {
		if (tasks.before.hasOwnProperty(element.type)) {
			if (!execChildTasks(element, tasks.before[element.type])) {
				return;
			}
		}

		if (tasks.before.hasOwnProperty('_')) {
			if (!execChildTasks(element, tasks.before._)) {
				return;
			}
		}
	}

	//execute the children tasks recursively
	if (element.length) {
		execChildrenTasks(element, tasks)
	}

	//execute tasks after children
	if (tasks.hasOwnProperty('after')) {
		if (tasks.after.hasOwnProperty(element.type)) {
			if (!execChildTasks(element, tasks.after[element.type])) {
				return;
			}
		}

		if (tasks.after.hasOwnProperty('_')) {
			if (!execChildTasks(element, tasks.after._)) {
				return;
			}
		}
	}
}

function execChildTasks (element, tasks) {
	for (var i = tasks.length - 1; i >= 0; i--) {
		if (element.is(tasks[i].filter)) {
			tasks[i].fn(element);

			//was element removed?
			if (!element.parent) {
				return false;
			}
		}
	}

	return true;
}

function execChildrenTasks (element, tasks) {
	var k = 0;

	while (element[k] !== undefined) {
		if (element[k].data.executed) {
			++k;
			continue;
		}

		executeChildTasks(element[k], tasks);
		k = 0;
	}
}
<|endoftext|>


<commit_before>(function() {
    "use strict";

    var _ = require('underscore'),
        async = require('async'),
        path = require('path'),
        fs = require('fs'),
        wrench = require('wrench');

    _.mixin(require('./helpers'));

    // inserts a string into a file name, bounded by dots
    // e.g -
    // `fileSuffix('/home/a.txt', 'b') === '/home/a.b.txt'`
    function fileSuffix(fname, suff) {
        return path.join(path.dirname(fname), path.basename(fname, path.extname(fname)) + suff + path.extname(fname));
    }

    var tasks = {
        // read in `f.content` for all `f` in `this.files`
        read: function(done) {
            var t = this;
            _.each(this.files, function(f) {
                f.content = fs.readFileSync(f.src, 'utf8');
            });
            done();
        },
        // filter out `this.files`, based on regex, or function
        filter: function(regex, done) {
            this.files = _.filter(this.files, function(f) {
                return _.isFunction(regex) ? regex(f) : regex.test(f.src);
            });
            done();
        },
        // compress css and js `f.content`s, generate `.min` filenames for dest
        compress: function(options, done) {
            if(_.isFunction(options)) {
                done = options;
            }

            this.files = _.map(this.files, function(f) {
                return {
                    src: f.src,
                    content: path.extname(f.src) === '.js' ? _.compressjs(f.content) : (path.extname(f.src) === '.css' ? _.compresscss(f.content) : f.content),
                    dest: fileSuffix(f.dest, '.min')
                };
            });
            done();
        },
        // for all `f` in `this.files`, write `f.content` to `f.dest`
        write: function(files, done) {
            if(_.isFunction(files)) {
                done = files;
                files = this.files;
            }
            var t = this;
            _.each(files, function(f) {
                var dest = path.join(t.config.dest, f.dest);
                wrench.mkdirSyncRecursive(path.dirname(dest));
                fs.writeFileSync(dest, f.content);
            });
            done();
        },
        // takes a bunch of files, creates a meta hash with it, and writes it to `<target>.json`
        meta: function(files, target, done) {
            var meta = {},
                t = this;
            // YURRRGHHHH
            if(_.isFunction(target)) {
                done = target;
                target = files;
                files = this.files;
            } else if(_.isFunction(files)) {
                done = files;
                target = 'meta';
                files = this.files;
            }
            _.each(files, function(f) {
                meta[path.relative(t.config.src, f.src)] = f.dest;
            });
            t.write([{
                content: JSON.stringify(meta, null, '    '),
                dest: target + '.json'
            }], done);
        },
        // takes a bunch of files, generates hashed file names, writes to them
        hashify: function(done) {
            this.files = _.map(this.files, function(f) {
                return {
                    src: f.src,
                    content: f.content,
                    dest: fileSuffix(f.dest, '.' + _.hashify(f.content))
                };
            });
            done();
        },

        wait: function(time, done) {
            setTimeout(done, time);
        },

        log: function(msg, done) {
            console.log(msg);
            done();
        },

        concat: function(dest, done) {
            this.write([{
                content: _(this.files).pluck('content').join('\n'),
                dest: dest
            }], done);
        },

        templates: function(options, done) {
            var dest = 'templates.js'; // this has to be rewritten.
            // basic logic is so -
            // find the longest common starting substring in all files
            // excluding that bit, construct template name by stripping / and ., and replacing with - (or _)
            // write it to that common dir, unless passed in options
            // for now, just read all ejs templates
            // remember to add the new compiled templates into the .files arr?
            done();
        },

        analyze: function(options, done) {
            done();
        },
        yuianalyze: function(target, done) {
            if(_.isFunction(target)) {
                done = target;
                target = 'manifest.js';
            }
            _.map(this.files, function(f) {
                var analysis = _.yuianalyze(f.content);
                console.log(f.src, f.dest, analysis);
            });
            done();
        },

        cdnify: function(options, done) {
            // config options -
            // cdnbase
            done();
        },

        watch: function(onChange, done) {
            // setup handler on `this.files` that run everytime a file in the list changes
            done();
        },

        cmd: function(cmd, done) {
            // todo - pipe to std out/stderr
            require('child_process').exec(cmd, done);
        },

        clean: function(done) {
            // wipe out dest? what about versioned?
            if(this.config.src !== this.config.dest) {
                this.cmd('rm -rf ' + this.config.dest, done);
            } else {
                throw new Error('src is same as dest, aborting clean')
            }
        },
        // run jslint (csslint?)
        lint: function(done) {

        },
        // do nothing, and pass along execution
        noop: function() {
            var args = _.toArray(arguments);
            var done = _.isFunction(args[args.length - 1]) ? args[args.length - 1] : _.identity;
            // no op
            done();
        }
    };

    module.exports = tasks;

}).call(this);
<commit_msg>cmd tweak<commit_after>(function() {
    "use strict";

    var _ = require('underscore'),
        async = require('async'),
        path = require('path'),
        fs = require('fs'),
        wrench = require('wrench');

    _.mixin(require('./helpers'));

    // inserts a string into a file name, bounded by dots
    // e.g -
    // `fileSuffix('/home/a.txt', 'b') === '/home/a.b.txt'`

    function fileSuffix(fname, suff) {
        return path.join(path.dirname(fname), path.basename(fname, path.extname(fname)) + suff + path.extname(fname));
    }

    var tasks = {
        // read in `f.content` for all `f` in `this.files`
        read: function(done) {
            var t = this;
            _.each(this.files, function(f) {
                f.content = fs.readFileSync(f.src, 'utf8');
            });
            done();
        },
        // filter out `this.files`, based on regex, or function
        filter: function(regex, done) {
            this.files = _.filter(this.files, function(f) {
                return _.isFunction(regex) ? regex(f) : regex.test(f.src);
            });
            done();
        },
        // compress css and js `f.content`s, generate `.min` filenames for dest
        compress: function(options, done) {
            if(_.isFunction(options)) {
                done = options;
            }

            this.files = _.map(this.files, function(f) {
                return {
                    src: f.src,
                    content: path.extname(f.src) === '.js' ? _.compressjs(f.content) : (path.extname(f.src) === '.css' ? _.compresscss(f.content) : f.content),
                    dest: fileSuffix(f.dest, '.min')
                };
            });
            done();
        },
        // for all `f` in `this.files`, write `f.content` to `f.dest`
        write: function(files, done) {
            if(_.isFunction(files)) {
                done = files;
                files = this.files;
            }
            var t = this;
            _.each(files, function(f) {
                var dest = path.join(t.config.dest, f.dest);
                wrench.mkdirSyncRecursive(path.dirname(dest));
                fs.writeFileSync(dest, f.content);
            });
            done();
        },
        // takes a bunch of files, creates a meta hash with it, and writes it to `<target>.json`
        meta: function(files, target, done) {
            var meta = {},
                t = this;
            // YURRRGHHHH
            if(_.isFunction(target)) {
                done = target;
                target = files;
                files = this.files;
            } else if(_.isFunction(files)) {
                done = files;
                target = 'meta';
                files = this.files;
            }
            _.each(files, function(f) {
                meta[path.relative(t.config.src, f.src)] = f.dest;
            });
            t.write([{
                content: JSON.stringify(meta, null, '    '),
                dest: target + '.json'
            }], done);
        },
        // takes a bunch of files, generates hashed file names, writes to them
        hashify: function(done) {
            this.files = _.map(this.files, function(f) {
                return {
                    src: f.src,
                    content: f.content,
                    dest: fileSuffix(f.dest, '.' + _.hashify(f.content))
                };
            });
            done();
        },

        wait: function(time, done) {
            setTimeout(done, time);
        },

        log: function(msg, done) {
            console.log(msg);
            done();
        },

        concat: function(dest, done) {
            this.write([{
                content: _(this.files).pluck('content').join('\n'),
                dest: dest
            }], done);
        },

        templates: function(options, done) {
            var dest = 'templates.js'; // this has to be rewritten.
            // basic logic is so -
            // find the longest common starting substring in all files
            // excluding that bit, construct template name by stripping / and ., and replacing with - (or _)
            // write it to that common dir, unless passed in options
            // for now, just read all ejs templates
            // remember to add the new compiled templates into the .files arr?
            done();
        },

        analyze: function(options, done) {
            done();
        },
        yuianalyze: function(target, done) {
            if(_.isFunction(target)) {
                done = target;
                target = 'manifest.js';
            }
            _.map(this.files, function(f) {
                var analysis = _.yuianalyze(f.content);
                console.log(f.src, f.dest, analysis);
            });
            done();
        },
        // take a bunch of css files, and replace url() paths with cdn versions.
        cdnify: function(options, done) {
            // config options -
            // cdnbase
            done();
        },

        watch: function(onChange, done) {
            // setup handler on `this.files` that run everytime a file in the list changes
            done();
        },

        cmd: function(cmd, done) {
            // todo - pipe to std out/stderr
            var cp = require('child_process');
            var cmd = cp.exec(cmd, function(error, stdout, stderr) {
                if(error) {
                    console.log(error.stack);
                    console.log('Error code: ' + error.code);
                    console.log('Signal received: ' + error.signal);
                }
                stdout && console.log(':' + stdout);
                stderr && console.log('ERR: ' + stderr);
            });
            cmd.on('exit', function(code){
                // todo - error codes
                done();
            });
        },

        clean: function(done) {
            // wipe out dest? what about versioned?
            if(this.config.src !== this.config.dest) {
                this.cmd('rm -rf ' + this.config.dest, done);
            } else {
                throw new Error('src is same as dest, aborting clean')
            }
        },
        // run jslint (csslint?)
        lint: function(done) {

        },
        // do nothing, and pass along execution
        noop: function() {
            var args = _.toArray(arguments);
            var done = _.isFunction(args[args.length - 1]) ? args[args.length - 1] : _.identity;
            // no op
            done();
        }
    };

    module.exports = tasks;

}).call(this);<|endoftext|>