<commit_before>var async		= require('async');
var url			= require('url');
var path		= require('path');
var pkg			= require(path.join(__dirname, './package.json'));
var fs			= require('fs');
var inquirer	= require('inquirer');
var program		= require('commander');
var request		= require('request');
var cheerio		= require('cheerio');
var webshot		= require('webshot');
var sluggin		= require('Sluggin').Sluggin;
var directory 	= './20160505/';
var sites		= require(directory + 'sites.js');

program
	.version( pkg.version )
	.parse( process.argv );

/**
 * cleanName( uri );
 * @uri: string | uri
 * return string
 */
var cleanName = function( uri ){

	return sluggin( url.parse(uri).href.replace('www.','').split('//')[1] );

}

/**
 * getScreenshot( sitename );
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * get and save a screenshot of each site
 *
 */
function getScreenshot( sitename, callback ){

	var webshotOptions = {
		encoding: 'binary',
		renderDelay: 1000
	};

	webshot(sitename, directory + cleanName( sitename ) + '.png', webshotOptions, function(err) {
		if (err) return callback(err);

		console.log('Getting screenshot: ' + sitename);
		callback(null, '📸  · ' + sitename + ' screenshot OK!');
	});

}

/**
 * getContent( sitename );
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * scrape title & description for each site
 *
 */
function getContent( sitename, callback ){

	var title = '';
	var description = '';

	request(sitename, function(error, response, html) {

		if (error || response.statusCode !== 200) return callback(error || new Error('Not found'));

		var $ = cheerio.load(html);

		title = $("title").text();
		description = $('meta[name="description"]').attr('content');

		console.log('Getting content: ' + sitename);
		callback(null, title + ' | ' +  description + ' | ' + sitename, sitename);

	});

}

/**
 * writeToFile( @params );
 * @content: string | content scraped
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * saves content to file for each site
 *
 */
function writeToFile( content, sitename, callback ) {

	fs.writeFile(directory + cleanName( sitename ) + '.md', content, function(err) {

		if (err) return callback(err);
		callback(null, '📂 · The file ' + cleanName( sitename ) + '.md was created!');

	});

}

/**
 * getContentAndWriteToFile( @params );
 *
 * @uri: string | uri
 * @callback: function | callback
 * return callback
 *
 */
function getContentAndWriteToFile( uri, callback ) {

	async.waterfall([

		async.apply(getContent, uri),
		writeToFile

	], callback);

}

/**
 * parseUrl( @params );
 *
 * @uri: string | uri
 * @callback: function | callback
 * return callback
 *
 */
function parseUrl( uri, callback ) {

	async.parallel([

		// take screenshot
		async.apply(getScreenshot, uri),
		// get content & save to file
		async.apply(getContentAndWriteToFile, uri)

	], callback);

}

/**
 * parseSites( @params );
 *
 * @sites: array | of site url's
 * @callback: function | callback
 * return callback
 *
 */
function parseSites( sites, callback ) {

	async.map(sites, parseUrl, callback);

}

/**
 * APPLY
 */
parseSites(sites, function( err, results ){

	if (err) return console.error(err);

	results.forEach(function(result) {
		result.forEach(function(log) {
			console.log(log);
		});
	});

	console.log('Everything OK');

});

<commit_msg>better markdown output<commit_after>var async			= require('async');
var url				= require('url');
var path			= require('path');
var pkg				= require(path.join(__dirname, './package.json'));
var fs				= require('fs');
var inquirer	= require('inquirer');
var program		= require('commander');
var request		= require('request');
var cheerio		= require('cheerio');
var webshot		= require('webshot');
var sluggin		= require('Sluggin').Sluggin;
var directory = './20160818/';
var sites			= require(directory + 'sites.js');

program
	.version( pkg.version )
	.parse( process.argv );

/**
 * cleanName( uri );
 * @uri: string | uri
 * return string
 */
var cleanName = function( uri ){

	return sluggin( url.parse(uri).href.replace('www.','').split('//')[1] );

}

/**
 * getScreenshot( sitename );
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * get and save a screenshot of each site
 *
 */
function getScreenshot( sitename, callback ){

	var webshotOptions = {
		encoding: 'binary',
		renderDelay: 1000
	};

	webshot(sitename, directory + cleanName( sitename ) + '.png', webshotOptions, function(err) {
		if (err) return callback(err);

		console.log('Getting screenshot: ' + sitename);
		callback(null, '📸  · ' + sitename + ' screenshot OK!');
	});

}

/**
 * getContent( sitename );
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * scrape title & description for each site
 *
 */
function getContent( sitename, callback ){

	var title = '';
	var description = '';
	var basicFormat = '';
	var fullFormat = '';

	request(sitename, function(error, response, html) {

		if (error || response.statusCode !== 200) return callback(error || new Error('Not found'));

		var $ = cheerio.load(html);

		title = $("title").text();
		description = $('meta[name="description"]').attr('content');
		basicFormat = 'Title: ' + title + '\n\nDescription: ' +  description + '\n\nURL: ' +  sitename + '\n\n';

		if (sitename.match('buscandriu')) {
			fullFormat = 'Buscandriu:
' + title + ' [link]
';
		} else {
			fullFormat = 'Full format: ' + title + ': ' +  description + ' [link]

';
		}

		callback(null, basicFormat + fullFormat, sitename);

	});

}

/**
 * writeToFile( @params );
 * @content: string | content scraped
 * @sitename: string | clean name of site
 * @callback: function | callback
 * return callback
 *
 * saves content to file for each site
 *
 */
function writeToFile( content, sitename, callback ) {

	fs.writeFile(directory + cleanName( sitename ) + '.md', content, function(err) {

		if (err) return callback(err);
		callback(null, '📂 · The file ' + cleanName( sitename ) + '.md was created!');

	});

}

/**
 * getContentAndWriteToFile( @params );
 *
 * @uri: string | uri
 * @callback: function | callback
 * return callback
 *
 */
function getContentAndWriteToFile( uri, callback ) {

	async.waterfall([

		async.apply(getContent, uri),
		writeToFile

	], callback);

}

/**
 * parseUrl( @params );
 *
 * @uri: string | uri
 * @callback: function | callback
 * return callback
 *
 */
function parseUrl( uri, callback ) {

	async.parallel([

		// take screenshot
		async.apply(getScreenshot, uri),
		// get content & save to file
		async.apply(getContentAndWriteToFile, uri)

	], callback);

}

/**
 * parseSites( @params );
 *
 * @sites: array | of site url's
 * @callback: function | callback
 * return callback
 *
 */
function parseSites( sites, callback ) {

	async.map(sites, parseUrl, callback);

}

/**
 * APPLY
 */
parseSites(sites, function( err, results ){

	if (err) return console.error(err);

	results.forEach(function(result) {
		result.forEach(function(log) {
			console.log(log);
		});
	});

	console.log('Everything OK');

});

<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-rickshaw',

  included: function included(app) {
    this._super.included(app);

    app.import(app.bowerDirectory + '/d3/d3.min.js');
    app.import(app.bowerDirectory + '/rickshaw/rickshaw.min.js');
    app.import(app.bowerDirectory + '/rickshaw/rickshaw.min.css');
  }
};
<commit_msg>rickshaw update<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-rickshaw',

  included: function included(app) {
    this._super.included(app);

    app.import(app.bowerDirectory + '/d3/d3.js');
    app.import(app.bowerDirectory + '/rickshaw/rickshaw.js');
    app.import(app.bowerDirectory + '/rickshaw/rickshaw.css');
  }
};
<|endoftext|>


<commit_before>var fs      = require('fs')
var path    = require('path')
var http    = require('http')
var zlib    = require('zlib')
var os      = require('os')

var request = require('request')
var mkdirp  = require('mkdirp')
var rimraf  = require('rimraf')
var tar     = require('tar')
var pull    = require('pull-stream')
var pt      = require('pull-traverse')

var registry = 'http://registry.npmjs.org'

function getUrl (name, ver) {
  return registry +"/" + name + "/-/" + name + "-" + ver + ".tgz"
}

function empty (obj) {
  for(var i in obj)
    return false
  return true
}

var preparePackage = exports.preparePackage =
function (pkg, cb) {
  if(!pkg.version)
    return cb(new Error(pkg.name + ' has no version'))

  var name = pkg.name
  var ver  = pkg.version
  var cache = path.join(process.env.HOME, '.npm', name, ver, 'package.tgz')
  var tmp = path.join(os.tmpdir(), ''+Date.now() + Math.random())

  fs.stat(cache, function (err) {

    var createStream = !err
    ? function (cb) { cb(null, fs.createReadStream(cache)) }
    : function (cb) {
      mkdirp(path.dirname(cache), function () {
        http.get(getUrl(name, ver), function (res) {
          res.pipe(fs.createWriteStream(cache))
          cb(null, res)
        })
      })
    }

    mkdirp(tmp, function (err) {
      if(err) return cb(err)
      createStream(function (err, stream) {
        var i = 1
        stream.on('error', next)
        stream.pipe(zlib.createGunzip())
        .pipe(tar.Extract({path: tmp}))
        .on('end', next)
        function next (err) {
          if(--i) return
          cb(err, tmp)
        }
      })
    })

  })
}

var installTree = exports.installTree =
function (tree, opts, cb) {
  if(!cb)
    cb = opts, opts = {}

  tree.path = path.join(opts.path || process.cwd(), 'node_modules')

  pull(
    pt.widthFirst(tree, function (pkg) {
      return pull(
        pull.values(pkg.dependencies),
        pull.map(function (_pkg) {
          _pkg.path = path.join(pkg.path, pkg.name, 'node_modules')
          return _pkg
        })
      )
    }),
    //unpack every file, so that it can be moved into place.
    //optimization: if a module has no deps,
    //just link it.
    pull.asyncMap(function (pkg, cb) {
      preparePackage(pkg, function (err, data) {
        pkg.tmp = data
        cb(err, pkg)
      })
    }, 64),
    pull.asyncMap(function (pkg, cb) {
      if(!pkg.tmp)
        return cb(new Error('no path for:'+ pkg.name))

      var source = path.join(pkg.tmp, 'package')
      var dest   = path.join(pkg.path, pkg.name)
      mkdirp(pkg.path, function () {
        fs.lstat(dest, function (err) {
          if(!err) return cb()
          fs.rename(source, dest, function (err) {
            console.error(pkg.name + '@' + pkg.version, '->', pkg.path)
            cb(err)
          })
        })
      })
    }),
    pull.drain(null, cb)
  )

}

exports = module.exports = installTree

exports.commands = function (db, config) {
  db.commands.install = function (config, cb) {
    db.resolve(config._[0], {greedy: config.greedy}, function (err, tree) {
      if(err) return cb(err)
      installTree(tree, {path: config.installPath}, cb)
    })
  }
}

exports.db = function () {}

<commit_msg>use new npmd cli api<commit_after>var fs      = require('fs')
var path    = require('path')
var http    = require('http')
var zlib    = require('zlib')
var os      = require('os')

var request = require('request')
var mkdirp  = require('mkdirp')
var rimraf  = require('rimraf')
var tar     = require('tar')
var pull    = require('pull-stream')
var pt      = require('pull-traverse')

var registry = 'http://registry.npmjs.org'

function getUrl (name, ver) {
  return registry +"/" + name + "/-/" + name + "-" + ver + ".tgz"
}

function empty (obj) {
  for(var i in obj)
    return false
  return true
}

var preparePackage = exports.preparePackage =
function (pkg, cb) {
  if(!pkg.version)
    return cb(new Error(pkg.name + ' has no version'))

  var name = pkg.name
  var ver  = pkg.version
  var cache = path.join(process.env.HOME, '.npm', name, ver, 'package.tgz')
  var tmp = path.join(os.tmpdir(), ''+Date.now() + Math.random())

  fs.stat(cache, function (err) {

    var createStream = !err
    ? function (cb) { cb(null, fs.createReadStream(cache)) }
    : function (cb) {
      mkdirp(path.dirname(cache), function () {
        http.get(getUrl(name, ver), function (res) {
          res.pipe(fs.createWriteStream(cache))
          cb(null, res)
        })
      })
    }

    mkdirp(tmp, function (err) {
      if(err) return cb(err)
      createStream(function (err, stream) {
        var i = 1
        stream.on('error', next)
        stream.pipe(zlib.createGunzip())
        .pipe(tar.Extract({path: tmp}))
        .on('end', next)
        function next (err) {
          if(--i) return
          cb(err, tmp)
        }
      })
    })

  })
}

var installTree = exports.installTree =
function (tree, opts, cb) {
  if(!cb)
    cb = opts, opts = {}

  tree.path = path.join(opts.path || process.cwd(), 'node_modules')

  pull(
    pt.widthFirst(tree, function (pkg) {
      return pull(
        pull.values(pkg.dependencies),
        pull.map(function (_pkg) {
          _pkg.path = path.join(pkg.path, pkg.name, 'node_modules')
          return _pkg
        })
      )
    }),
    //unpack every file, so that it can be moved into place.
    //optimization: if a module has no deps,
    //just link it.
    pull.asyncMap(function (pkg, cb) {
      preparePackage(pkg, function (err, data) {
        pkg.tmp = data
        cb(err, pkg)
      })
    }, 64),
    pull.asyncMap(function (pkg, cb) {
      if(!pkg.tmp)
        return cb(new Error('no path for:'+ pkg.name))

      var source = path.join(pkg.tmp, 'package')
      var dest   = path.join(pkg.path, pkg.name)
      mkdirp(pkg.path, function () {
        fs.lstat(dest, function (err) {
          if(!err) return cb()
          fs.rename(source, dest, function (err) {
            console.error(pkg.name + '@' + pkg.version, '->', pkg.path)
            cb(err)
          })
        })
      })
    }),
    pull.drain(null, cb)
  )

}

exports = module.exports = installTree

exports.commands = function (db, config) {
  db.cli.push(function (db, config, cb) {
    var args = config._.slice()
    if('install' !== args.shift()) return
    db.resolve(args, {greedy: config.greedy}, function (err, tree) {
      if(err) return cb(err)
      installTree(tree, {path: config.installPath}, cb)
    })
  }
}

exports.db = function () {}

<|endoftext|>


<commit_before>'use strict'
const Promise = require('bluebird')
const EventEmitter = require('events');
const Utils = require('./utils')
const Catbox = require('catbox')
const CatboxMemory = require('catbox-memory')

let externals = {}

class flowEmitter extends EventEmitter { }

const INITIAL_STATE = 0

const client = new Catbox.Client(CatboxMemory)

module.exports.new = () => {
  return new Promise((resolve, reject) => {
    client.start((err) => {
      if (err) {
        reject(err)
      }

      externals.Instance = (function () {

        function Instance(model, emitter, middlewares) {
          /*this.flow = flow
          this.id = id*/
          this.model = model
          this.actualState = this.model.states[INITIAL_STATE]
          this.middlewares = []
          this.internalEmitter = emitter
          this.middlewares = middlewares
        }

        Instance.prototype.searchNextState = function (stateName) {
          return new Promise((resolve, reject) => {
            this.model.states.forEach((state) => {
              if (state.name === stateName) {
                return resolve(state)
              }
            })
            return reject(new Error('No default state found'))
          })
        }

        Instance.prototype.validateTransition = function (transitionName) {
          return new Promise((resolve, reject) => {
            if (this.actualState.transitions) {
              this.actualState.transitions.forEach((transition) => {
                if (Utils.matchRule(transition.name, transitionName) || Utils.matchRegExp(transition.name, transitionName)) {
                  return resolve(transition)
                }
              })
              return reject(new Error('No se pudo encontrar el estado en las transiciones'))
            } else {
              return reject(new Error('No se pudo encontrar el estado en las transiciones'))
            }
          })
        }

        Instance.prototype.getState = function (data) {
          return new Promise((resolve, reject) => {
            if (data && data.action) {
              this.validateTransition(data.action).then((transition) => {
                this.searchNextState(transition.to).then((nextState) => {
                  if (transition.use) {
                    this.middlewares[transition.use](this.actualState, (data) => {
                      this.actualState = nextState
                      return resolve(this.actualState)
                    })
                  } else {
                    this.actualState = nextState
                    if (this.actualState.onEnter) {
                      if (this.actualState.onEnter.emit) {
                        this.internalEmitter.emit(this.actualState.onEnter.emit, this.actualState.onEnter.data)
                      }
                    }
                    return resolve(this.actualState)
                  }
                })
              }).catch((err) => {
                this.searchNextState('default').then((nextState) => {
                  this.actualState = nextState
                  if (this.actualState.onEnter) {
                    if (this.actualState.onEnter.emit) {
                      this.internalEmitter.emit(this.actualState.onEnter.emit, this.actualState.onEnter.data)
                    }
                  }
                  return resolve(this.actualState)
                }).catch((err) => {
                  return resolve({ template: err })
                })
              })
            } else {
              return resolve(this.actualState)
            }
          })
        }

        return Instance
      })()

      externals.Flow = (function () {

        function Flow(name, model) {
          this.name = name
          this.model = model
          this.instances = []
          this.middlewares = []
          this.internalEmitter = new flowEmitter();
        }

        Flow.prototype.newInstance = function (id) {
          //this.instances[id] = new externals.Instance(this.model, this.internalEmitter, this.middlewares)
          //return this.instances[id]
          return new Promise((resolve, reject) => {
            var newInstance = new externals.Instance(this.model, this.internalEmitter, this.middlewares)
            client.set(id, newInstance, this.model.ttl, (err) => {
              if (err) {
                reject(err)
              }
              resolve(newInstance)
            })
          })
        }

        Flow.prototype.addInstance = function (instance) {
          //this.instance[instance.id] = instance
          //return this.instances[instance.id]
          return new Promise((resolve, reject) => {
            client.set(instance.id, instance, this.model.ttl, (err) => {
              if (err) {
                reject(err)
              }
              resolve(instance)
            })
          })
        }

        Flow.prototype.getInstance = function (id) {
          //return this.instances[id]
          return new Promise((resolve, reject) => {
            client.get(id, (err, cached) => {
              if (err || !cached) {
                this.newInstance(id).then((newInstance) => {
                  resolve(newInstance)
                }).catch((err) => {
                  reject(err)
                })
              } else {
                resolve(cached.item)
              }
            })
          })
        }

        Flow.prototype.on = function (eventName, eventFunction) {
          this.internalEmitter.on(eventName, eventFunction)
        }

        Flow.prototype.register = function (name, fn) {
          this.middlewares[name] = fn
        }

        return Flow

      })()

      resolve(externals)

    })
  })
}<commit_msg>[UPDATE] Change logic from instance to flow<commit_after>'use strict'
const Promise = require('bluebird')
const EventEmitter = require('events');
const Utils = require('./utils')
const Catbox = require('catbox')
const CatboxMemory = require('catbox-memory')

let externals = {}

class flowEmitter extends EventEmitter { }

const INITIAL_STATE = 0

const client = new Catbox.Client(CatboxMemory)

module.exports.new = () => {
  return new Promise((resolve, reject) => {
    client.start((err) => {
      if (err) {
        reject(err)
      }

      externals.Instance = (function () {

        function Instance(id, emitter, middlewares) {
          this.id = id
          this.actualState = this.model.states[INITIAL_STATE]
          this.middlewares = []
          this.internalEmitter = emitter
          this.middlewares = middlewares
        }

        return Instance
      })()

      externals.Flow = (function () {

        function Flow(name, model) {
          this.name = name
          this.model = model
          this.instances = []
          this.middlewares = []
          this.internalEmitter = new flowEmitter();
        }

        Flow.prototype.newInstance = function (id) {
          console.log('CREANDO NUEVA INSTANCIA')
          return new Promise((resolve, reject) => {
            var newInstance = new externals.Instance(id, this.internalEmitter, this.middlewares)
            client.set(id, newInstance, this.model.ttl, (err) => {
              if (err) {
                reject(err)
              }
              resolve(newInstance)
            })
          })
        }

        Flow.prototype.addInstance = function (instance) {
          return new Promise((resolve, reject) => {
            client.set(instance.id, instance, this.model.ttl, (err) => {
              if (err) {
                reject(err)
              }
              resolve(instance)
            })
          })
        }

        Flow.prototype.getInstance = function (id) {
          return new Promise((resolve, reject) => {
            client.get(id, (err, cached) => {
              if (err || !cached) {
                this.newInstance(id).then((newInstance) => {
                  resolve(newInstance)
                }).catch((err) => {
                  reject(err)
                })
              } else {
                console.log('INSTANCIA ENCONTRADA')
                resolve(cached.item)
              }
            })
          })
        }

        Flow.prototype.searchNextState = function (stateName) {
          return new Promise((resolve, reject) => {
            this.model.states.forEach((state) => {
              if (state.name === stateName) {
                return resolve(state)
              }
            })
            return reject(new Error('No default state found'))
          })
        }

        Flow.prototype.validateTransition = function (instance, transitionName) {
          return new Promise((resolve, reject) => {
            if (instance.actualState.transitions) {
              instance.actualState.transitions.forEach((transition) => {
                if (Utils.matchRule(transition.name, transitionName) || Utils.matchRegExp(transition.name, transitionName)) {
                  return resolve(transition)
                }
              })
              return reject(new Error('No se pudo encontrar el estado en las transiciones'))
            } else {
              return reject(new Error('No se pudo encontrar el estado en las transiciones'))
            }
          })
        }

        Flow.prototype.getState = function (instance, data) {
          return new Promise((resolve, reject) => {
            if (data && data.action) {
              this.validateTransition(instance, data.action).then((transition) => {
                this.searchNextState(transition.to).then((nextState) => {
                  if (transition.use) {
                    instance.middlewares[transition.use](instance.actualState, (data) => {
                      instance.actualState = nextState

                      client.set(instance.id, instance, this.model.ttl, (err) => {
                        if (err) {
                          reject(err)
                        }
                        if (instance.actualState.onEnter) {
                          if (instance.actualState.onEnter.emit) {
                            instance.internalEmitter.emit(instance.actualState.onEnter.emit, instance.actualState.onEnter.data)
                          }
                        }
                        resolve(instance.actualState)
                      })
                    })
                  } else {
                    instance.actualState = nextState
                    client.set(instance.id, instance, this.model.ttl, (err) => {
                      console.log('EL NUEVO ESTADO ' + JSON.stringify(instance))
                      if (err) {
                        reject(err)
                      }
                      if (instance.actualState.onEnter) {
                        if (instance.actualState.onEnter.emit) {
                          instance.internalEmitter.emit(instance.actualState.onEnter.emit, instance.actualState.onEnter.data)
                        }
                      }
                      resolve(instance.actualState)
                    })

                  }
                })
              }).catch((err) => {
                this.searchNextState('default').then((nextState) => {
                  instance.actualState = nextState
                  client.set(instance.id, instance, this.model.ttl, (err) => {
                    if (err) {
                      reject(err)
                    }
                    if (instance.actualState.onEnter) {
                      if (instance.actualState.onEnter.emit) {
                        instance.internalEmitter.emit(instance.actualState.onEnter.emit, instance.actualState.onEnter.data)
                      }
                    }
                    resolve(instance.actualState)
                  })
                }).catch((err) => {
                  return resolve({ template: err })
                })
              })
            } else {
              return resolve(instance.actualState)
            }
          })
        }

        Flow.prototype.on = function (eventName, eventFunction) {
          this.internalEmitter.on(eventName, eventFunction)
        }

        Flow.prototype.register = function (name, fn) {
          this.middlewares[name] = fn
        }

        return Flow

      })()

      resolve(externals)

    })
  })
}<|endoftext|>


<commit_before>const querystring = require('querystring');
const url = require('url');

const uuid = require('uuid');
const rp = require('request-promise');
const redirect = require('micro-redirect');

const provider = 'github';

const microAuthGithub = ({ clientId, clientSecret, callbackUrl, path = '/auth/github', scope = 'user' }) => {

  const getRedirectUrl = (state) => {
    return `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${callbackUrl}&scope=${scope}&state=${state}`;
  };

  const states = [];
  return fn => async (req, res, ...args) => {

    const { pathname, query } = url.parse(req.url);

    if (pathname === path) {
      try {
        const state = uuid.v4();
        const redirectUrl = getRedirectUrl(state);
        states.push(state);
        return redirect(res, 302, redirectUrl);
      } catch (err) {
        args.push({ err, provider });
        return fn(req, res, ...args);
      }
    }

    const callbackPath = url.parse(callbackUrl).pathname;
    if (pathname === callbackPath) {
      try {
        const { state, code } = querystring.parse(query);

        if (!states.includes(state)) {
          const err = new Error('Invalid state');
          return fn(req, res, { err, provider });
        }

        states.splice(states.indexOf(state), 1);

        const response = await rp({
          method: 'POST',
          url: 'https://github.com/login/oauth/access_token',
          json: true,
          body: {
            // eslint-disable-next-line camelcase
            client_id: clientId,
            // eslint-disable-next-line camelcase
            client_secret: clientSecret,
            code
          }
        });

        if (response.error) {
          args.push({ err: response.error, provider });
          return fn(req, res, ...args);
        }

        const accessToken = response.access_token;
        const user = await rp({
          method: 'GET',
          url: 'https://api.github.com/user',
          headers: {
            'Authorization': `token ${accessToken}`,
            'User-Agent': 'Microauth-Github'
          },
          json: true
        });

        const result = {
          provider,
          accessToken,
          info: user
        };

        args.push({ result });
        return fn(req, res, ...args);
      } catch (err) {
        args.push({ err, provider });
        return fn(req, res, ...args);
      }
    }

    return fn(req, res, ...args);
  };
};

module.exports = microAuthGithub;
<commit_msg>fix invalid error passing<commit_after>const querystring = require('querystring');
const url = require('url');

const uuid = require('uuid');
const rp = require('request-promise');
const redirect = require('micro-redirect');

const provider = 'github';

const microAuthGithub = ({ clientId, clientSecret, callbackUrl, path = '/auth/github', scope = 'user' }) => {

  const getRedirectUrl = (state) => {
    return `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${callbackUrl}&scope=${scope}&state=${state}`;
  };

  const states = [];
  return fn => async (req, res, ...args) => {

    const { pathname, query } = url.parse(req.url);

    if (pathname === path) {
      try {
        const state = uuid.v4();
        const redirectUrl = getRedirectUrl(state);
        states.push(state);
        return redirect(res, 302, redirectUrl);
      } catch (err) {
        args.push({ err, provider });
        return fn(req, res, ...args);
      }
    }

    const callbackPath = url.parse(callbackUrl).pathname;
    if (pathname === callbackPath) {
      try {
        const { state, code } = querystring.parse(query);

        if (!states.includes(state)) {
          const err = new Error('Invalid state');
          args.push({ err, provider });
          return fn(req, res, ...args);
        }

        states.splice(states.indexOf(state), 1);

        const response = await rp({
          method: 'POST',
          url: 'https://github.com/login/oauth/access_token',
          json: true,
          body: {
            // eslint-disable-next-line camelcase
            client_id: clientId,
            // eslint-disable-next-line camelcase
            client_secret: clientSecret,
            code
          }
        });

        if (response.error) {
          args.push({ err: response.error, provider });
          return fn(req, res, ...args);
        }

        const accessToken = response.access_token;
        const user = await rp({
          method: 'GET',
          url: 'https://api.github.com/user',
          headers: {
            'Authorization': `token ${accessToken}`,
            'User-Agent': 'Microauth-Github'
          },
          json: true
        });

        const result = {
          provider,
          accessToken,
          info: user
        };

        args.push({ result });
        return fn(req, res, ...args);
      } catch (err) {
        args.push({ err, provider });
        return fn(req, res, ...args);
      }
    }

    return fn(req, res, ...args);
  };
};

module.exports = microAuthGithub;
<|endoftext|>


<commit_before>"format cjs";

var wrap = require('word-wrap');

// This can be any kind of SystemJS compatible module.
// We use Commonjs here, but ES6 or AMD would do just
// fine.
module.exports = {

  // When a user runs `git cz`, prompter will
  // be executed. We pass you cz, which currently
  // is just an instance of inquirer.js. Using
  // this you can ask questions and get answers.
  //
  // The commit callback should be executed when
  // you're ready to send back a commit template
  // to git.
  //
  // By default, we'll de-indent your commit
  // template and will keep empty lines.
  prompter: function(cz, commit) {
    console.log('\nLine 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.\n');

    // Let's ask some questions of the user
    // so that we can populate our commit
    // template.
    //
    // See inquirer.js docs for specifics.
    // You can also opt to use another input
    // collection library if you prefer.
    cz.prompt([
      {
        type: 'list',
        name: 'type',
        message: 'Select the type of change that you\'re committing:',
        choices: [
        {
          name: 'feat:     A new feature',
          value: 'feat'
        }, {
          name: 'fix:      A bug fix',
          value: 'fix'
        }, {
          name: 'docs:     Documentation only changes',
          value: 'docs'
        }, {
          name: 'style:    Changes that do not affect the meaning of the code\n            (white-space, formatting, missing semi-colons, etc)',
          value: 'style'
        }, {
          name: 'refactor: A code change that neither fixes a bug or adds a feature',
          value: 'refactor'
        }, {
          name: 'perf:     A code change that improves performance',
          value: 'perf'
        }, {
          name: 'test:     Adding missing tests',
          value: 'test'
        }, {
          name: 'chore:    Changes to the build process or auxiliary tools\n            and libraries such as documentation generation',
          value: 'chore'
        }]
      }, {
        type: 'input',
        name: 'scope',
        message: 'Denote the scope of this change ($location, $browser, $compile, etc.):\n'
      }, {
        type: 'input',
        name: 'subject',
        message: 'Write a short, imperative tense description of the change:\n'
      }, {
        type: 'input',
        name: 'body',
        message: 'Provide a longer description of the change:\n'
      }, {
        type: 'input',
        name: 'footer',
        message: 'List any breaking changes or issues closed by this change:\n'
      }
    ]).then(function(answers) {

      var maxLineWidth = 100;

      var wrapOptions = {
        trim: true,
        newline: '\n',
        indent:'',
        width: maxLineWidth
      };

      // parentheses are only needed when a scope is present
      var scope = answers.scope.trim();
      scope = scope ? '(' + answers.scope.trim() + ')' : '';

      // Hard limit this line
      var head = (answers.type + scope + ': ' + answers.subject.trim()).slice(0, maxLineWidth);

      // Wrap these lines at 100 characters
      var body = wrap(answers.body, wrapOptions);
      var footer = wrap(answers.footer, wrapOptions);

      commit(head + '\n\n' + body + '\n\n' + footer);
    });
  }
}
<commit_msg>update submit template<commit_after>"format cjs";

var wrap = require('word-wrap');

// This can be any kind of SystemJS compatible module.
// We use Commonjs here, but ES6 or AMD would do just
// fine.
module.exports = {

  // When a user runs `git cz`, prompter will
  // be executed. We pass you cz, which currently
  // is just an instance of inquirer.js. Using
  // this you can ask questions and get answers.
  //
  // The commit callback should be executed when
  // you're ready to send back a commit template
  // to git.
  //
  // By default, we'll de-indent your commit
  // template and will keep empty lines.
  prompter: function(cz, commit) {
    console.log('\nLine 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.\n');

    // Let's ask some questions of the user
    // so that we can populate our commit
    // template.
    //
    // See inquirer.js docs for specifics.
    // You can also opt to use another input
    // collection library if you prefer.
    cz.prompt([
      {
        type: 'list',
        name: 'type',
        message: 'Select the type of change that you\'re committing:',
        choices: [
        {
          name: 'story:      故事卡',
          value: 'story'
        }, {
          name: 'bug:      bug fix',
          value: 'bug'
        }, {
          name: 'commit:      普通提交',
          value: 'commit'
          }]
      }, {
        type: 'input',
        name: 'scope',
        message: 'Jira Issue ID(s) 或者 输入一个普通提交信息 (required):\n',
        validate: function(input) {
          if (!input) {
            return '必须输入一个Jira Issue ID(s) 或者 输入一个普通提交信息';
          } else {
            return true;
          }
        }
      }, {
        type: 'input',
        name: 'subject',
        message: '对Jira Issue ID(s)的一个简单描述(小于100字):\n'
      }, {
        type: 'input',
        name: 'body',
        message: '详细描述(如果有):\n'
      }
    ]).then(function(answers) {

      var maxLineWidth = 100;

      var wrapOptions = {
        trim: true,
        newline: '\n',
        indent:'',
        width: maxLineWidth
      };

      // parentheses are only needed when a scope is present
      var scope = answers.scope.trim();
      scope = scope ? '[' + answers.scope.trim() + ']' : '';

      // Hard limit this line
      var head = (answers.type + scope + ': ' + answers.subject.trim()).slice(0, maxLineWidth);

      // Wrap these lines at 100 characters
      var body = answers.body.trim();
      body = body ? '详细描述: \n' + answers.body.trim() : ''
      var body = wrap(body, wrapOptions);

      commit(head + '\n' + body);
    });
  }
}
<|endoftext|>


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

var fs = require('fs'),
    path = require('path'),
    parse = require('url').parse,
    http = require('http'),
    spawn = require('child_process').spawn,
    rootpath = path.resolve(process.argv[2] || '.'),
    port = parseInt(process.argv[3]) || process.env.PORT || 4567,
    tmpl = fs.readFileSync(require.resolve('./template.html'), 'utf8'),
    hookpath = require.resolve('./hooks/post-receive'),
    hookVersion = parseHookVersion(hookpath),
    guiVersion = require('./package.json').version,
    ansiRe = new RegExp('\033\\[(\\d+)m', 'g'),
    statusChars = ['✓', '✗', '—'];

function esc(str) {
  return str.replace(new RegExp("'", "g", '"'));
}

function fdate(d) {
  return d.toDateString() + ' ' + d.toLocaleTimeString();
}

function colorize(text) {
  var count = 0;
  return text.replace(ansiRe, function(_, code) {
    var res;
    if (code === '0') {
      res = new Array(count+1).join('');
      count = 0;
    } else {
      res = '';
      count++;
    }
    return res;
  })+new Array(count+1).join('');
};

function logExec(cmd, callback) {
  console.log('Execting shell command:', cmd);
  var child = spawn("sh", ["-c", cmd]);
  child.on('close', function(code) {
    var err = code !== 0
      ? new Error("logExec: shell exited with non-zero: " + code)
      : null;
    if (err) console.error(err)
    if (callback) callback(err)
  })
}

function copyHook(to, runner, match, callback) {
  var eto = esc(to), er = esc(runner), em = esc(match);
  logExec("cp '"+esc(hookpath)+"' '"+eto+"/hooks/post-receive' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.runner '"+er+"' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.match '"+em+"'",
  callback);
}

function invokeHook(to, before, after, ref, callback) {
  var eref = esc(ref);
  logExec("cd '"+esc(to)+"' && git fetch origin '"+eref+":"+eref+"' && "+
    "echo '"+esc(before+" "+after+" "+ref)+"' | hooks/post-receive",
  callback);
}

function parseHookVersion(hookpath) {
  var m;
  if (!fs.existsSync(hookpath)) return;
  m = fs.readFileSync(hookpath, 'utf8').match(/TINCIV=([\d.]+)/);
  return m !== null ? m[1] : false;
}

function template(model) {
  var html = tmpl, i;
  for (i in model) html = html.split('{{'+i+'}}').join(model[i]);
  return html;
}

function logToHtml(log) {
  return '

' +
    statusChars[log.status] + ' ' + log.ref +
    ' '+ fdate(log.ctime) + ' ' + log.rev +
    '
' + '
' +
    colorize(log.log.replace(/\r?\n/g, '
')) + '

';
}

function parseLog(log) {
  var refm;
  if (!log.log) {
    log.log = fs.readFileSync(log.path, 'utf8').trim();
    log.ref = (refm = /# ref refs\/(?:heads|tags)\/(.*)/.exec(log.log), refm ? refm[1] : '');
    log.exitcode = log.log.slice(log.log.lastIndexOf('\n')+1).split(' ').slice(-1)[0];
    log.status = /^\d+$/.test(log.exitcode) ? (log.exitcode==='0' ? 0 : 1) : 2;
  }
  return log;
}

function logs(tincipath) {
  var res = {logs:[], dict:{}};
  if (fs.existsSync(tincipath)) {
    res.logs = fs.readdirSync(tincipath).filter(function(file){
      return file.slice(-4) === '.log';
    }).map(function(file) {
      var filepath = path.join(tincipath, file),
          rev = path.basename(file, '.log');
      return res.dict[rev] = {
        path: filepath,
        rev: rev,
        ctime: fs.statSync(filepath).ctime
      };
    }).sort(function(a, b){ return a.ctime - b.ctime; });
  }
  return res;
}

http.createServer(function(req, res) {
  var url = parse(req.url, true),
      pathname = path.resolve(rootpath, './'+url.pathname),
      format = url.query.format || 'html',
      model = {}, data = '?', logs_, ls, dict,
      page, reponame, tincipath, hookv;
  if (pathname.indexOf(rootpath) === 0 && fs.existsSync(pathname)) {
    reponame = path.basename(pathname, '.git');
    if (fs.existsSync(path.join(pathname, 'hooks'))) {
      if ('invoke' in url.query) {
        req.on('data', function(chunk) { data += chunk; })
        .on('end', function() {
          var gitinfo;
          try {
            gitinfo = JSON.parse(parse(data, true).query.payload);
            invokeHook(pathname, gitinfo.before, gitinfo.after, gitinfo.ref);
            res.writeHead(200);
          } catch (ex) {
            res.writeHead(500);
            console.log('Error on invoke call: '+ex.message);
          }
          res.end();
        });
        return;
      }
      hookv = parseHookVersion(path.resolve(pathname, 'hooks', 'post-receive'));
      model = {
          title: reponame,
          status: 2,
          logs: [],
          guiVersion: guiVersion,
          hookVersion: hookVersion,
          installedVersion: hookv
      };
      if ('update' in url.query) {
        if (url.query.runner) {
          copyHook(
            pathname,
            url.query.runner,
            url.query.match||'master',
            function () {
              res.writeHead(302, { 'Location': url.pathname });
              res.end();
            }
          );
          return;
        } else {
          if (hookv != null) model.overwrite = 'show';
          model.config = 'show';
        }
      } else if (hookv) {
        tincipath = path.join(pathname, '.tinci');
        logs_ = logs(tincipath);
        ls = logs_.logs;
        dict = logs_.dict;
        if (ls.length) model.status = parseLog(ls[ls.length-1]).status;
        model.logs = (function(){
          if (url.query.log) {
            return [dict[url.query.log]];
          } else {
            page = (url.query.page || Math.max(0,ls.length-10)+',').split(',');
            return ls.slice(
              page[0],
              page[1] === ''
                ? undefined
                : parseInt(page[0])+(parseInt(page[1])||10)
            );
          }
        })().map(function(log) { return parseLog(log); }).reverse();
      } else {
        res.writeHead(302, { 'Location': url.pathname+'?update' });
        res.end();
        return;
      }
      if (format === 'html') {
        model.status = statusChars[model.status];
        model.logs = model.logs.map(function(log) {
          return log ? logToHtml(log) : '';
        }).join('');
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(template(model));
      } else if (url.query.log && format === 'text') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(model.logs[0].log);
      } else {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(model));
      }
    } else {
      res.writeHead(500);
      res.end("Directory not a bare git repo?");
    }
  } else {
    res.writeHead(404);
    res.end("Directory not found.");
  }
}).listen(port);

console.log('tinci vision at http://localhost:'+port);
<commit_msg>Fix crash on requesting non-existing log<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    parse = require('url').parse,
    http = require('http'),
    spawn = require('child_process').spawn,
    rootpath = path.resolve(process.argv[2] || '.'),
    port = parseInt(process.argv[3]) || process.env.PORT || 4567,
    tmpl = fs.readFileSync(require.resolve('./template.html'), 'utf8'),
    hookpath = require.resolve('./hooks/post-receive'),
    hookVersion = parseHookVersion(hookpath),
    guiVersion = require('./package.json').version,
    ansiRe = new RegExp('\033\\[(\\d+)m', 'g'),
    statusChars = ['✓', '✗', '—'];

function esc(str) {
  return str.replace(new RegExp("'", "g", '"'));
}

function fdate(d) {
  return d.toDateString() + ' ' + d.toLocaleTimeString();
}

function colorize(text) {
  var count = 0;
  return text.replace(ansiRe, function(_, code) {
    var res;
    if (code === '0') {
      res = new Array(count+1).join('');
      count = 0;
    } else {
      res = '';
      count++;
    }
    return res;
  })+new Array(count+1).join('');
};

function logExec(cmd, callback) {
  console.log('Execting shell command:', cmd);
  var child = spawn("sh", ["-c", cmd]);
  child.on('close', function(code) {
    var err = code !== 0
      ? new Error("logExec: shell exited with non-zero: " + code)
      : null;
    if (err) console.error(err)
    if (callback) callback(err)
  })
}

function copyHook(to, runner, match, callback) {
  var eto = esc(to), er = esc(runner), em = esc(match);
  logExec("cp '"+esc(hookpath)+"' '"+eto+"/hooks/post-receive' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.runner '"+er+"' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.match '"+em+"'",
  callback);
}

function invokeHook(to, before, after, ref, callback) {
  var eref = esc(ref);
  logExec("cd '"+esc(to)+"' && git fetch origin '"+eref+":"+eref+"' && "+
    "echo '"+esc(before+" "+after+" "+ref)+"' | hooks/post-receive",
  callback);
}

function parseHookVersion(hookpath) {
  var m;
  if (!fs.existsSync(hookpath)) return;
  m = fs.readFileSync(hookpath, 'utf8').match(/TINCIV=([\d.]+)/);
  return m !== null ? m[1] : false;
}

function template(model) {
  var html = tmpl, i;
  for (i in model) html = html.split('{{'+i+'}}').join(model[i]);
  return html;
}

function logToHtml(log) {
  return '

' +
    statusChars[log.status] + ' ' + log.ref +
    ' '+ fdate(log.ctime) + ' ' + log.rev +
    '
' + '
' +
    colorize(log.log.replace(/\r?\n/g, '
')) + '

';
}

function parseLog(log) {
  var refm;
  if (!log.log) {
    log.log = fs.readFileSync(log.path, 'utf8').trim();
    log.ref = (refm = /# ref refs\/(?:heads|tags)\/(.*)/.exec(log.log), refm ? refm[1] : '');
    log.exitcode = log.log.slice(log.log.lastIndexOf('\n')+1).split(' ').slice(-1)[0];
    log.status = /^\d+$/.test(log.exitcode) ? (log.exitcode==='0' ? 0 : 1) : 2;
  }
  return log;
}

function logs(tincipath) {
  var res = {logs:[], dict:{}};
  if (fs.existsSync(tincipath)) {
    res.logs = fs.readdirSync(tincipath).filter(function(file){
      return file.slice(-4) === '.log';
    }).map(function(file) {
      var filepath = path.join(tincipath, file),
          rev = path.basename(file, '.log');
      return res.dict[rev] = {
        path: filepath,
        rev: rev,
        ctime: fs.statSync(filepath).ctime
      };
    }).sort(function(a, b){ return a.ctime - b.ctime; });
  }
  return res;
}

http.createServer(function(req, res) {
  var url = parse(req.url, true),
      pathname = path.resolve(rootpath, './'+url.pathname),
      format = url.query.format || 'html',
      model = {}, data = '?', logs_, ls, dict,
      page, reponame, tincipath, hookv;
  if (pathname.indexOf(rootpath) === 0 && fs.existsSync(pathname)) {
    reponame = path.basename(pathname, '.git');
    if (fs.existsSync(path.join(pathname, 'hooks'))) {
      if ('invoke' in url.query) {
        req.on('data', function(chunk) { data += chunk; })
        .on('end', function() {
          var gitinfo;
          try {
            gitinfo = JSON.parse(parse(data, true).query.payload);
            invokeHook(pathname, gitinfo.before, gitinfo.after, gitinfo.ref);
            res.writeHead(200);
          } catch (ex) {
            res.writeHead(500);
            console.log('Error on invoke call: '+ex.message);
          }
          res.end();
        });
        return;
      }
      hookv = parseHookVersion(path.resolve(pathname, 'hooks', 'post-receive'));
      model = {
          title: reponame,
          status: 2,
          logs: [],
          guiVersion: guiVersion,
          hookVersion: hookVersion,
          installedVersion: hookv
      };
      if ('update' in url.query) {
        if (url.query.runner) {
          copyHook(
            pathname,
            url.query.runner,
            url.query.match||'master',
            function () {
              res.writeHead(302, { 'Location': url.pathname });
              res.end();
            }
          );
          return;
        } else {
          if (hookv != null) model.overwrite = 'show';
          model.config = 'show';
        }
      } else if (hookv) {
        tincipath = path.join(pathname, '.tinci');
        logs_ = logs(tincipath);
        ls = logs_.logs;
        dict = logs_.dict;
        if (ls.length) model.status = parseLog(ls[ls.length-1]).status;
        model.logs = (function(){
          if (url.query.log) {
            var log = dict[url.query.log];
            return log ? [log] : [];
          } else {
            page = (url.query.page || Math.max(0,ls.length-10)+',').split(',');
            return ls.slice(
              page[0],
              page[1] === ''
                ? undefined
                : parseInt(page[0])+(parseInt(page[1])||10)
            );
          }
        })().map(function(log) { return parseLog(log); }).reverse();
      } else {
        res.writeHead(302, { 'Location': url.pathname+'?update' });
        res.end();
        return;
      }
      if (format === 'html') {
        model.status = statusChars[model.status];
        model.logs = model.logs.map(function(log) {
          return log ? logToHtml(log) : '';
        }).join('');
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(template(model));
      } else if (url.query.log && format === 'text') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(model.logs[0].log);
      } else {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(model));
      }
    } else {
      res.writeHead(500);
      res.end("Directory not a bare git repo?");
    }
  } else {
    res.writeHead(404);
    res.end("Directory not found.");
  }
}).listen(port);

console.log('tinci vision at http://localhost:'+port);
<|endoftext|>


<commit_before>// Mise en place des en tetes
const discord = require('discord.js')
const client = new discord.Client()
const setting = require('./module/teste.json')
// On start le bot
client.on('ready', () => {
  client.user.setGame('+inv | +help | +stats' + client.guilds.size + ' serveurs', 'https://www.twitch.tv/the_commentary', 0)
  console.log('-------------------------------------')
  console.log('    [!] ComaBot connecté [!]')
  console.log('-------------------------------------')
  console.log('le prefix est: ' + setting.prefix)
})

/* Partie Ping */
const ping = require('./module/ping.js')
ping(client)

/* Partie Liste 2 */
const liste2 = require('./module/liste_2.js')
liste2(client)

/* Partie Musique */
const music = require('./discord.js-music-v11')
music(client)

/* Partie Liste 1 */
const message1 = require('./module/liste_1.js')
message1(client)

/* Partie Help */
const help = require('./module/help.js')
help(client)

/* Partie Admini 1 */
const Admini1 = require('./module/admini1.js')
Admini1(client)

var dt = process.env.TOKEN || process.argv[2]

if (!dt) {
  console.log('')
}

client.login(dt)
<commit_msg>Added Files<commit_after>// Mise en place des en tetes
const discord = require('discord.js')
const client = new discord.Client()
const setting = require('./module/teste.json')
// On start le bot
client.on('ready', () => {
  client.user.setGame('+inv | +help | +stats | On ' + client.guilds.size + ' servers', 'https://www.twitch.tv/the_commentary', 0)
  console.log('-------------------------------------')
  console.log('    [!] ComaBot connecté [!]')
  console.log('-------------------------------------')
  console.log('le prefix est: ' + setting.prefix)
})

/* Partie Ping */
const ping = require('./module/ping.js')
ping(client)

/* Partie Liste 2 */
const liste2 = require('./module/liste_2.js')
liste2(client)

/* Partie Musique */
const music = require('./discord.js-music-v11')
music(client)

/* Partie Liste 1 */
const message1 = require('./module/liste_1.js')
message1(client)

/* Partie Help */
const help = require('./module/help.js')
help(client)

/* Partie Admini 1 */
const Admini1 = require('./module/admini1.js')
Admini1(client)

var dt = process.env.TOKEN || process.argv[2]

if (!dt) {
  console.log('')
}

client.login(dt)
<|endoftext|>


<commit_before>'use strict';

const util = require('util');

const Node = exports.Node = require('./lib/node');

exports.createNode = function (a, b, c) {

    return new Node(a, b, c);
};

const Bridge = exports.Bridge = require('./lib/bridge');

exports.createBridge = function (a, b) {
    return new Bridge(a, b);
};

exports.Node = Node;
exports.Bridge = Bridge;
<commit_msg>Export default port in index;<commit_after>'use strict';

const util = require('util');

exports.DEFAULT_PORT = 8221;

const Node = exports.Node = require('./lib/node');

exports.createNode = function (a, b, c) {

    return new Node(a, b, c);
};

const Bridge = exports.Bridge = require('./lib/bridge');

exports.createBridge = function (a, b) {
    return new Bridge(a, b);
};

exports.Node = Node;
exports.Bridge = Bridge;
<|endoftext|>


<commit_before>/**
 * Download tool for Unicode CLDR JSON data
 *
 * Copyright 2013 Rafael Xavier de Souza
 * Released under the MIT license
 * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT
 */

"use strict";

var assert = require("assert");
var AvailableLocales = require("./lib/available_locales");
var download = require("./lib/download");
var isUrl = require("./lib/util").isUrl;
var progress = require("./lib/progress");
var Q = require("q");
var readJSON = require("./lib/util").readJSON;
var State = require("./lib/state");
var unpack = require("./lib/unpack");

Q.longStackSupport = true;

function alwaysArray(arrayOrSomething) {
  return Array.isArray(arrayOrSomething) ?
    arrayOrSomething :
    arrayOrSomething ? [arrayOrSomething] : [];
}

/**
 * fn( srcUrl, destPath [, options], callback )
 */
module.exports = function(srcUrl, destPath, options, callback) {
  var error, state;

  if (callback === undefined && typeof options === "function") {
    callback = options;
    options = {};
  }

  assert(typeof srcUrl === "string", "must include srcUrl (e.g., " +
    "\"http://www.unicode.org/Public/cldr/26/json.zip\")");

  assert(typeof destPath === "string", "must include destPath (e.g., " +
    "\"./cldr\")");

  assert(typeof options === "object", "invalid options");

  assert(typeof callback === "function", "must include callback function");

  Q.try(function() {

    // Is srcUrl a config file?
    if (!isUrl(srcUrl) && (/.json$/i).test(srcUrl)) {
      // Read its URL.
      options.srcUrlKey = options.srcUrlKey || "core";
      srcUrl = readJSON(srcUrl)[options.srcUrlKey];
    }

    // Is it already installed?
    state = new State(srcUrl, destPath);
    if (!options.force && state.isInstalled()) {
      error = new Error("Already downloaded and unpacked, quitting... Use " +
        "`options.force = true` to override.");
      error.code = "E_ALREADY_INSTALLED";
      throw error;
    }

  // Download
  }).then(function() {
    var srcUrls = alwaysArray(srcUrl);
    return Q.all(srcUrls.map(function(srcUrl) {
      return download({
        url: srcUrl
      });
    })).progress(progress(srcUrls.length));

  // Unpack
  }).then(unpack({
    path: destPath

  // Generate available locales.
  })).then(function() {
    try {
      new AvailableLocales(destPath).write();
    } catch(error) {
      error.message = "Error generating available locales. " + error.message;
      throw error;
    }

  // Save installation state.
  }).then(function() {
    try {
      state.write();
    } catch(error) {
      error.message = "Error saving installation state. " + error.message;
      throw error;
    }

  // Done
  }).catch(callback).done(function() {
    callback();
  });
};
<commit_msg>Fix srcUrl assertion to accept either a string or an Array<commit_after>/**
 * Download tool for Unicode CLDR JSON data
 *
 * Copyright 2013 Rafael Xavier de Souza
 * Released under the MIT license
 * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT
 */

"use strict";

var assert = require("assert");
var AvailableLocales = require("./lib/available_locales");
var download = require("./lib/download");
var isUrl = require("./lib/util").isUrl;
var progress = require("./lib/progress");
var Q = require("q");
var readJSON = require("./lib/util").readJSON;
var State = require("./lib/state");
var unpack = require("./lib/unpack");

Q.longStackSupport = true;

function alwaysArray(arrayOrSomething) {
  return Array.isArray(arrayOrSomething) ?
    arrayOrSomething :
    arrayOrSomething ? [arrayOrSomething] : [];
}

/**
 * fn( srcUrl, destPath [, options], callback )
 */
module.exports = function(srcUrl, destPath, options, callback) {
  var error, state;

  if (callback === undefined && typeof options === "function") {
    callback = options;
    options = {};
  }

  assert(typeof srcUrl === "string" || Array.isArray(srcUrl), "must include" +
    "srcUrl (e.g., \"http://www.unicode.org/Public/cldr/26/json.zip\")");

  assert(typeof destPath === "string", "must include destPath (e.g., " +
    "\"./cldr\")");

  assert(typeof options === "object", "invalid options");

  assert(typeof callback === "function", "must include callback function");

  Q.try(function() {

    // Is srcUrl a config file?
    if (!isUrl(srcUrl) && (/.json$/i).test(srcUrl)) {
      // Read its URL.
      options.srcUrlKey = options.srcUrlKey || "core";
      srcUrl = readJSON(srcUrl)[options.srcUrlKey];
    }

    // Is it already installed?
    state = new State(srcUrl, destPath);
    if (!options.force && state.isInstalled()) {
      error = new Error("Already downloaded and unpacked, quitting... Use " +
        "`options.force = true` to override.");
      error.code = "E_ALREADY_INSTALLED";
      throw error;
    }

  // Download
  }).then(function() {
    var srcUrls = alwaysArray(srcUrl);
    return Q.all(srcUrls.map(function(srcUrl) {
      return download({
        url: srcUrl
      });
    })).progress(progress(srcUrls.length));

  // Unpack
  }).then(unpack({
    path: destPath

  // Generate available locales.
  })).then(function() {
    try {
      new AvailableLocales(destPath).write();
    } catch(error) {
      error.message = "Error generating available locales. " + error.message;
      throw error;
    }

  // Save installation state.
  }).then(function() {
    try {
      state.write();
    } catch(error) {
      error.message = "Error saving installation state. " + error.message;
      throw error;
    }

  // Done
  }).catch(callback).done(function() {
    callback();
  });
};
<|endoftext|>


<commit_before>
var gl;

var somethingVertexPositionBuffer;
var somethingVertexColorBuffer;
var somethingVertexIndexBuffer;

var shaderProgram;

var mvMatrix = mat4.create();
var pMatrix = mat4.create();

var vertices = [];
var colors = [];
var indices = [];

var numBlocks = 5;
var secondNumBlocks = 25;

var moving = [];
for (var i = 0; i < numBlocks; i++) {
  var somethingMove = [];
  for (var l = 0; l < secondNumBlocks; l++) {
    somethingMove.push({
      one: {isMoving: false, isMovingUp: false, current: 0},
      two: {isMoving: false, isMovingUp: false, current: 0},
      three: {isMoving: false, isMovingUp: false, current: 0},
      four: {isMoving: false, isMovingUp: false, current: 0},
    })
  }
  moving.push(somethingMove);
}

function degToRad(deg) {
  return deg * (Math.PI / 180);
}

function radToDeg(rad) {
  return rad * (180 / Math.PI);
}

function generateVertices() {

  var currentX = -1;
  var currentY = 1;
  var currentIndex = 0;

  var changeColor = false;

  for (var i = 0; i < numBlocks; i++) {

    for (var l = 0; l < secondNumBlocks; l++) {

      var tempVertices = [
        currentX, currentY, 0.0,
        currentX + 2, currentY, 0.0,
        currentX + 2, currentY - 2, 0.0,
        currentX, currentY - 2, 0.0
      ];

      var tempColors = [];
      var somethingColor = [];

      if (!changeColor) {
        somethingColor = [0.0, 0.0, 0.0, 1.0];
        changeColor = true;
      }
      else {
        somethingColor = [0.5, 0.5, 0.5, 1.0];
        changeColor = false;
      }

      while (tempColors.length < 4 * 4) {
        tempColors = tempColors.concat(somethingColor);
      }

      var tempIndices = [
        currentIndex, currentIndex + 1, currentIndex + 2,
        currentIndex + 2, currentIndex + 3, currentIndex
      ];

      vertices = vertices.concat(tempVertices);
      colors = colors.concat(tempColors);
      indices = indices.concat(tempIndices);

      currentX += 2;
      currentIndex += 4;

    }

    currentX = -1;
    currentY += 2;

  }

}

function startMove() {
  setInterval(function () {
    move();
  }, 100);
  setInterval(function () {
    setMove();
  }, 100);
}

function setMove() {

  var randomOne = Math.floor(Math.random() * numBlocks);
  var randomTwo = Math.floor(Math.random() * secondNumBlocks);
  var randomIndex = Math.floor(Math.random() * 4);

  var moveBlock = moving[randomOne][randomTwo];
  var index;

  if (randomIndex === 0) {
    index = moveBlock.one;
  }
  if (randomIndex === 1) {
    index = moveBlock.two;
  }
  if (randomIndex === 2) {
    index = moveBlock.three;
  }
  if (randomIndex === 3) {
    index = moveBlock.four;
  }

  if (!index.isMoving) {
    index.isMoving = true;
    index.isMovingUp = true;
  }

}

function move() {

  for (var i = 0; i < moving.length; i++) {
    for (var l = 0; l < moving[i].length; l++) {
      ['one', 'two', 'three', 'four'].forEach(function (e) {

        var block = moving[i][l][e];

        if (block.isMoving) {

          if (block.isMovingUp) {
            block.current = block.current + 0.1;
            if (block.current > 1) {
              block.isMovingUp = false;
            }
          }
          else {
            block.current = block.current - 0.1;
            if (block.current < 0) {
              block.current = 0;
              block.isMoving = false;
            }
          }

          var temp = (l * (4 * 3)) + (i * (secondNumBlocks * (4 * 3)))
          var indice = 0;

          if (e === 'one') {
            indice = temp + 2;
          }
          if (e === 'two') {
            indice = temp + 5;
          }
          if (e === 'three') {
            indice = temp + 8;
          }
          if (e === 'four') {
            indice = temp + 11;
          }

          vertices[indice] = block.current;

        }

      });
    }
  }

  initBuffers();
  drawScene();

}

function setMatrixUniforms() {
  gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
  gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

function initGL(canvas) {

  try {
    gl = canvas.getContext('experimental-webgl');
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
  }

  if (!gl) {
    console.log('could not initialise webgl');
  }

}

function getShader(gl, id) {

  var shaderScript = document.getElementById(id);
  if (!shaderScript) {
    return null;
  }

  var str = '';
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType == 3) {
      str += k.textContent;
    }
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type == 'x-shader/x-fragment') {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  }
  else if (shaderScript.type == 'x-shader/x-vertex') {
    shader = gl.createShader(gl.VERTEX_SHADER);
  }
  else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    console.log(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initShaders() {

  var fragmentShader = getShader(gl, 'shader-fs');
  var vertexShader = getShader(gl, 'shader-vs');

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    console.log('could not initialize shaders');
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, 'aVertexColor');
  gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, 'uPMatrix');
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, 'uMVMatrix');

}

function initBuffers() {

  somethingVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexPositionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  somethingVertexPositionBuffer.itemSize = 3;
  somethingVertexPositionBuffer.numItems = 4 * (numBlocks * secondNumBlocks);

  somethingVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexColorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
  somethingVertexColorBuffer.itemSize = 4;
  somethingVertexColorBuffer.numItems = 3 * (numBlocks * secondNumBlocks);

  somethingVertexIndexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, somethingVertexIndexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  somethingVertexIndexBuffer.itemSize = 1;
  somethingVertexIndexBuffer.numItems = 6 * (numBlocks * secondNumBlocks);

}

function drawScene() {

  gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);

  mat4.identity(mvMatrix);
  mat4.translate(mvMatrix, [-35.0, -17.0, -45]);
  mat4.rotateX(mvMatrix, degToRad(-45));

  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, somethingVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, somethingVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, somethingVertexIndexBuffer);
  setMatrixUniforms();
  gl.drawElements(gl.TRIANGLES, somethingVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

}

function webGLStart() {

  var canvas = document.getElementById('canvas');

  generateVertices();

  initGL(canvas);
  initShaders();
  initBuffers();

  gl.clearColor(1.0, 1.0, 1.0, 1.0);
  gl.enable(gl.DEPTH_TEST);

  drawScene();
  //startMove();

}
<commit_msg>add multiple index move<commit_after>
var gl;

var somethingVertexPositionBuffer;
var somethingVertexColorBuffer;
var somethingVertexIndexBuffer;

var shaderProgram;

var mvMatrix = mat4.create();
var pMatrix = mat4.create();

var vertices = [];
var colors = [];
var indices = [];

var numBlocks = 5;
var secondNumBlocks = 25;

var moving = [];
for (var i = 0; i < numBlocks; i++) {
  var somethingMove = [];
  for (var l = 0; l < secondNumBlocks; l++) {
    somethingMove.push({
      one: {isMoving: false, isMovingUp: false, current: 0},
      two: {isMoving: false, isMovingUp: false, current: 0},
      three: {isMoving: false, isMovingUp: false, current: 0},
      four: {isMoving: false, isMovingUp: false, current: 0},
    })
  }
  moving.push(somethingMove);
}

function degToRad(deg) {
  return deg * (Math.PI / 180);
}

function radToDeg(rad) {
  return rad * (180 / Math.PI);
}

function generateVertices() {

  var currentX = -1;
  var currentY = 1;
  var currentIndex = 0;

  var changeColor = false;

  for (var i = 0; i < numBlocks; i++) {

    for (var l = 0; l < secondNumBlocks; l++) {

      var tempVertices = [
        currentX, currentY, 0.0,
        currentX + 2, currentY, 0.0,
        currentX + 2, currentY - 2, 0.0,
        currentX, currentY - 2, 0.0
      ];

      var tempColors = [];
      var somethingColor = [];

      if (!changeColor) {
        somethingColor = [0.0, 0.0, 0.0, 1.0];
        changeColor = true;
      }
      else {
        somethingColor = [0.5, 0.5, 0.5, 1.0];
        changeColor = false;
      }

      while (tempColors.length < 4 * 4) {
        tempColors = tempColors.concat(somethingColor);
      }

      var tempIndices = [
        currentIndex, currentIndex + 1, currentIndex + 2,
        currentIndex + 2, currentIndex + 3, currentIndex
      ];

      vertices = vertices.concat(tempVertices);
      colors = colors.concat(tempColors);
      indices = indices.concat(tempIndices);

      currentX += 2;
      currentIndex += 4;

    }

    currentX = -1;
    currentY += 2;

  }

}

function startMove() {
  setInterval(function () {
    move();
  }, 100);
  setInterval(function () {
    setMove();
  }, 100);
}

function setMove() {

  var randomOne = Math.floor(Math.random() * numBlocks);
  var randomTwo = Math.floor(Math.random() * secondNumBlocks);
  var randomIndex = Math.floor(Math.random() * 4);

  var moveBlock = moving[randomOne][randomTwo];

  var index = 0;
  var indexTwo = 0;
  var indexThree = 0;
  var indexFour = 0;

  if (randomIndex === 0) {
    index = moveBlock.one;
    if (randomTwo - 1 > -1) {
      indexTwo = moving[randomOne][randomTwo - 1].two;
    }
    if ((randomTwo - 1 > -1) && (randomOne + 1 < numBlocks)) {
      indexThree = moving[randomOne + 1][randomTwo - 1].three;
    }
    if (randomOne + 1 < numBlocks) {
      indexFour = moving[randomOne + 1][randomTwo].four;
    }
  }

  if (randomIndex === 1) {
    index = moveBlock.two;
    if (randomTwo + 1 < secondNumBlocks) {
      indexTwo = moving[randomOne][randomTwo + 1].one;
    }
    if (randomTwo + 1 < secondNumBlocks && (randomOne + 1 < numBlocks)) {
      indexThree = moving[randomOne + 1][randomTwo + 1].four;
    }
    if (randomOne + 1 < numBlocks) {
      indexFour = moving[randomOne + 1][randomTwo].three;
    }
  }

  if (randomIndex === 2) {
    index = moveBlock.three;
    if (randomTwo + 1 < secondNumBlocks) {
      indexTwo = moving[randomOne][randomTwo + 1].four;
    }
    if ((randomTwo + 1 < secondNumBlocks) && (randomOne - 1 > -1)) {
      indexThree = moving[randomOne - 1][randomTwo + 1].one;
    }
    if (randomOne - 1 > -1) {
      indexFour = moving[randomOne - 1][randomTwo].two;
    }
  }

  if (randomIndex === 3) {
    index = moveBlock.four;
    if (randomTwo - 1 > -1) {
      indexTwo = moving[randomOne][randomTwo - 1].three;
    }
    if ((randomTwo - 1 > -1) && (randomOne - 1 > -1)) {
      indexThree = moving[randomOne - 1][randomTwo - 1].two;
    }
    if (randomOne - 1 > -1) {
      indexFour = moving[randomOne - 1][randomTwo].one;
    }
  }

  if (!index.isMoving) {
    index.isMoving = true;
    index.isMovingUp = true;
  }

  if (indexTwo) {
    if (!indexTwo.isMoving) {
      indexTwo.isMoving = true;
      indexTwo.isMovingUp = true;
    }
  }

  if (indexThree) {
    if (!indexThree.isMoving) {
      indexThree.isMoving = true;
      indexThree.isMovingUp = true;
    }
  }

  if (indexFour) {
    if (!indexFour.isMoving) {
      indexFour.isMoving = true;
      indexFour.isMovingUp = true;
    }
  }

}

function move() {

  for (var i = 0; i < moving.length; i++) {
    for (var l = 0; l < moving[i].length; l++) {
      ['one', 'two', 'three', 'four'].forEach(function (e) {

        var block = moving[i][l][e];

        if (block.isMoving) {

          if (block.isMovingUp) {
            block.current = block.current + 0.1;
            if (block.current > 1) {
              block.isMovingUp = false;
            }
          }
          else {
            block.current = block.current - 0.1;
            if (block.current < 0) {
              block.current = 0;
              block.isMoving = false;
            }
          }

          var temp = (l * (4 * 3)) + (i * (secondNumBlocks * (4 * 3)))
          var indice = 0;

          if (e === 'one') {
            indice = temp + 2;
          }
          if (e === 'two') {
            indice = temp + 5;
          }
          if (e === 'three') {
            indice = temp + 8;
          }
          if (e === 'four') {
            indice = temp + 11;
          }

          vertices[indice] = block.current;

        }

      });
    }
  }

  initBuffers();
  drawScene();

}

function setMatrixUniforms() {
  gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
  gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

function initGL(canvas) {

  try {
    gl = canvas.getContext('experimental-webgl');
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
  }

  if (!gl) {
    console.log('could not initialise webgl');
  }

}

function getShader(gl, id) {

  var shaderScript = document.getElementById(id);
  if (!shaderScript) {
    return null;
  }

  var str = '';
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType == 3) {
      str += k.textContent;
    }
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type == 'x-shader/x-fragment') {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  }
  else if (shaderScript.type == 'x-shader/x-vertex') {
    shader = gl.createShader(gl.VERTEX_SHADER);
  }
  else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    console.log(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initShaders() {

  var fragmentShader = getShader(gl, 'shader-fs');
  var vertexShader = getShader(gl, 'shader-vs');

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    console.log('could not initialize shaders');
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, 'aVertexColor');
  gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, 'uPMatrix');
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, 'uMVMatrix');

}

function initBuffers() {

  somethingVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexPositionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  somethingVertexPositionBuffer.itemSize = 3;
  somethingVertexPositionBuffer.numItems = 4 * (numBlocks * secondNumBlocks);

  somethingVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexColorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
  somethingVertexColorBuffer.itemSize = 4;
  somethingVertexColorBuffer.numItems = 3 * (numBlocks * secondNumBlocks);

  somethingVertexIndexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, somethingVertexIndexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  somethingVertexIndexBuffer.itemSize = 1;
  somethingVertexIndexBuffer.numItems = 6 * (numBlocks * secondNumBlocks);

}

function drawScene() {

  gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);

  mat4.identity(mvMatrix);
  mat4.translate(mvMatrix, [-35.0, -17.0, -45]);
  mat4.rotateX(mvMatrix, degToRad(-45));

  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, somethingVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, somethingVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, somethingVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, somethingVertexIndexBuffer);
  setMatrixUniforms();
  gl.drawElements(gl.TRIANGLES, somethingVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

}

function webGLStart() {

  var canvas = document.getElementById('canvas');

  generateVertices();

  initGL(canvas);
  initShaders();
  initBuffers();

  gl.clearColor(1.0, 1.0, 1.0, 1.0);
  gl.enable(gl.DEPTH_TEST);

  drawScene();
  //startMove();

}
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var async = require('async');

var host = 'http://www.generalfil.es/';
var url = host + 'files-a/';
var options = '/?filter=_Video_';

var getFile = function(link, cb){
  request(host + link, function(err, response, body) {
    try {
      var finalLink = JSON.parse(body).link;
      cb(null, finalLink);
    } catch (e) {
      cb(new Error('Error on response parsing for ' + host+link));
    }
  });
};

var gf = function(title, cb) {
  var finalLinks = [];
  title = title.replace(/[^(\w)]+/gi, '-').toLowerCase();
  request(url+title+options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var links = body.match(/gf_ShowDownloadLink\([\w',?=\/&]+/gi);
      links = links.map(function(link){
        return link.split(',').pop().replace(/'/gi, '');
      });

      async.each(links, function(el, next) {
        getFile(el, function(err, result) {
          if (err) {
            next(err);
            return;
          }
          finalLinks.push(result);
          next();
        });
      }, function(err) {
        // Alles klar
        cb(err, finalLinks);
      });
    }
  });
};

gf('American Dad! S01E01', function(err, result) {
  console.log(err, result);
});

//GENERALFIL.ES
<commit_msg>:watermelon: export as module<commit_after>'use strict';

var request = require('request');
var async = require('async');

var host = 'http://www.generalfil.es/';
var url = host + 'files-a/';
var options = '/?filter=_Video_';

var getFile = function(link, cb){
  request(host + link, function(err, response, body) {
    try {
      var finalLink = JSON.parse(body).link;
      cb(null, finalLink);
    } catch (e) {
      cb(new Error('Error on response parsing for ' + host+link));
    }
  });
};

var gf = function(title, cb) {
  var finalLinks = [];
  title = title.replace(/[^(\w)]+/gi, '-').toLowerCase();
  request(url+title+options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var links = body.match(/gf_ShowDownloadLink\([\w',?=\/&]+/gi);
      links = links.map(function(link){
        return link.split(',').pop().replace(/'/gi, '');
      });

      async.each(links, function(el, next) {
        getFile(el, function(err, result) {
          if (err) {
            next(err);
            return;
          }
          finalLinks.push(result);
          next();
        });
      }, function(err) {
        // Alles klar
        cb(err, finalLinks);
      });
    }
  });
};

module.exports = gf;
<|endoftext|>


<commit_before>/*!
 * group-object <https://github.com/doowb/group-object>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

module.exports = function () {
  // do stuff
};
<commit_msg>implementation<commit_after>/*!
 * group-object <https://github.com/doowb/group-object>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

var set = require('upsert-value');
var forIn = require('for-in');

module.exports = groupBy;

/**
 * Create groupings from an object's keys and values.
 *
 * ```js
 * var groups = {};
 * function grouper (value, key, obj, setter) {
 *   return value.group;
 * }
 *
 * function setter (group, value, key, obj) {
 *   groups[group] = groups[group] || {};
 *   groups[group][key] = value;
 * }
 *
 * var obj = {
 *   a: { group: 'one', content: 'A'},
 *   b: { group: 'one', content: 'B'},
 *   c: { group: 'two', content: 'C'},
 *   d: { group: 'two', content: 'D'},
 *   e: { group: 'three', content: 'E'},
 *   f: { group: 'three', content: 'F'}
 * };
 *
 * groups = groupBy(obj, grouper, setter);
 * //=> {
 * //=>   one: {
 * //=>     a: { group: 'one', content: 'A'},
 * //=>     b: { group: 'one', content: 'B'}
 * //=>   },
 * //=>   two: {
 * //=>     c: { group: 'two', content: 'C'},
 * //=>     d: { group: 'two', content: 'D'}
 * //=>   },
 * //=>   three: {
 * //=>     e: { group: 'three', content: 'E'},
 * //=>     f: { group: 'three', content: 'F'}
 * //=>   }
 * //=> }
 * ```
 * @doc    api-[method]
 * @param  {[type]}     obj     [description]
 * @param  {[type]}     grouper [description]
 * @param  {[type]}     setter  [description]
 * @return {[type]}             [description]
 */
function groupBy (obj, grouper, setter) {
  var res = {};
  if (typeof grouper !== 'function') {
    grouper = function (value) {
      return value;
    };
  }
  if (typeof setter !== 'function') {
    setter = function (group, value, key) {
      if (typeof value === 'undefined') return;
      set(res, [group, key].join('.'), value);
    };
  }

  forIn(obj, function (value, key) {
    setter(grouper(value, key, obj, setter));
  });
  return res;
}
<|endoftext|>