<commit_before>/*!
 * ood
 * Copyright(c) 2015-2016 Anatol Sommer <anatol@anatol.at>
 * MIT Licensed
 */

'use strict';

var app=require('commander'), zygon=require('zygon'),
  util=require('./util'), argv=process.argv, api;

require('colors');

process.on('uncaughtException', function(err) {
  var stack;
  if (err.code==='EACCES') {
    console.log('You do not have the permission to run this command!'.bold.red);
    console.log('Use sudo or consult: https://oodjs.com/docs/security');
    process.exit();
  } else {
    if (err.stack && err.stack.match) {
      stack=err.stack.match(/(.*)\n([\w\W]*)/);
      console.error('Error: '.bold.red+stack[1]+'\n'+stack[2].grey);
    } else {
      console.error('Fatal error!'.bold.red);
    }
  }
});

api=require('./api-client');

app.command('init <app>')
  .description('Initialise a new app')
  .option('-s, --script <script>', 'Script file (default: app.js)')
  .option('-d, --cwd <dir>', 'Set different working directory')
  .action(function(appName, opts) {
    var config={};
    config.cwd=opts.cwd || process.cwd();
    config.script=opts.script;
    request('init', {app:appName, config:config}, function(res) {
      if (res.success) {
        app.parse([null, null, 'status', appName]);
      } else {
        console.error(res.error || 'Error!'.bold.red);
      }
    });
  })
  .on('--help', examples([
    'ood init testapp',
    'ood init example.com'
  ]));

app.command('start <app>')
  .description('Start an app')
  .action(function(appName) {
    request('start', {app:appName}, function() {
      setTimeout(function() {
        app.parse([null, null, 'status', appName]);
      }, 1200);
    });
  })
  .on('--help', examples([
    'ood start testapp',
    'ood start example.com'
  ]));

app.command('stop <app>')
  .description('Stop a running app')
  .action(function(appName) {
    request('stop', {app:appName}, function() {
      app.parse([null, null, 'status', appName]);
    });
  })
  .on('--help', examples([
    'ood stop testapp',
    'ood stop example.com'
  ]));

app.command('restart <app>')
  .description('Restart a running app')
  .action(function(appName) {
    request('restart', {app:appName}, function() {
      app.parse([null, null, 'status', appName]);
    });
  })
  .on('--help', examples([
    'ood restart testapp',
    'ood restart example.com'
  ]));

app.command('scale <app> <instances>')
  .description('Kill or fork new worker instances')
  .action(function(appName, instances) {
    request('scale', {app:appName, instances:instances});
  })
  .on('--help', examples([
    'ood scale testapp 4',
    'ood scale example.com 12'
  ]));

/* TODO
app.command('redirect <host> [target]')
  .description('Set http redirect for a hostname')
  .option('-d, --delete', 'Deletes a redirect')
  .action(function(host, target, opts) {
    var args;
    if (!opts) {
      opts=target;
      target=null;
    }
    // TODO
  })
  .on('--help', examples([
    'ood redirect www.example.org http://example.org',
    'ood redirect example.com https://example.com',
    'ood redirect www.example.com https://example.com',
    'ood redirect --delete example.com',
    'ood redirect -d example.org'
  ]));
*/

app.command('status')
  .description('Show status of all apps');

app.command('status [app]')
  .description('Shows status of a running app')
  .action(function(appName, opts) {
    if (!opts) {
      opts=appName;
      appName=null;
    }
    request('status', {app:appName}, function(res) {
      var tbl=zygon([
        {name:'App name', size:20, color:function(val, row) {
          return row[4] ? 'blue' : 'silver';
        }},
        {name:'PID', size:6, align:'right'},
        {name:'Worker', size:6, align:'right'},
        {name:'State', size:9, color:function(val, row) {
          return {
            online:'cyan',
            listening:'green',
            ok:'green',
            fatal:'red',
            stopped:'grey'
          }[row[3].toLowerCase()];
        }},
        {name:'Uptime', size:13, align:'right', format:uptimeHuman},
        {name:'CPU', size:7, align:'right', format:function(p) {
          return p.toFixed(2)+'%';
        }},
        {name:'RAM', size:9, align:'right', format:function(b) {
          return (b/1048576).toFixed(2)+' MB';
        }}
      ]);

      tbl.printHead();

      Object.keys(res.status).forEach(function(appName) {
        var app=res.status[appName];
        if (app==='stopped') {
          tbl.printRow([appName, '', '', 'stopped']);
        } else {
          tbl.printRow([
            appName,
            app.master.pid,
            'MASTER',
            app.master.state,
            app.master.startTime,
            app.master.cpu,
            app.master.ram
          ]);
          app.workers.forEach(function(worker) {
            tbl.printRow([
              '',
              worker.pid,
              '#'+worker.workerId,
              worker.state,
              worker.startTime,
              worker.cpu,
              worker.ram
            ]);
          });
        }
      });

      tbl.end();
    });
  })
  .on('--help', examples([
    'ood status',
    'ood status testapp',
    'ood status example.com'
  ]));

app.command('config')
  .description('Modify or show config')
  .option('-a, --app <app>', 'Get or set app configuration')
  .option('-g, --get [key]', 'Get configuration value')
  .option('-s, --set <key> <value>', 'Set configuration value')
  .option('-d, --delete <key>', 'Delete configuration value')
  .action(function(val, opts) {
    var change;
    if (!opts) {
      opts=val;
      val=null;
    }
    change={app:opts.app};
    if (opts.delete) {
      change.delete=opts.delete;
    } else if (opts.get) {
      change.get=(opts.get===true ? '' : opts.get);
    } else if (opts.set) {
      change.set=opts.set;
      change.value=val;
    }
    request('config', change, function(res) {
      var val;
      if (!res.success) {
        return console.error(res.error || 'Error!'.bold.red);
      }
      if (opts.get) {
        val=JSON.stringify(res.value, null, 2).replace(/\n/g, '\n  ');
        console.log('\n  '+(opts.get===true ? '' : opts.get+' = ')+val+'\n');
      }
    });
  })
  .on('--help', examples([
    'ood config --get',
    'ood config --get httpPort',
    'ood config --set httpsPort 443',
    'ood config --get --app example.com',
    'ood config -a example.com --get port',
    'ood config -a testapp -s cwd /home/test/testapp',
    'ood config -a testapp -s env.NODE_ENV development',
    'ood config -a testapp --delete env'
  ]));

app.command('log')
  .description('Read log files')
  .action(function() {
    var tbl=zygon([
      {name:'Time', key:'time', size:8, color:'grey', format:function(time) {
        return time.substr(11, 8);
      }},
      {name:'Type', key:'type', size:5, color:logColor},
      {name:'App', key:'app', size:15, color:logColor},
      {name:'Message', key:'msg', size:Infinity}
    ]);
    tbl.printHead();
    util.logReader('/var/log/ood.log', function(log) {
      var info=[];
      Object.keys(log).forEach(function(key) {
        var val;
        if (!~['time', 'type', 'app', 'msg'].indexOf(key)) {
          val=log[key];
          if (typeof val==='object') {
            val=JSON.stringify(val);
          } else if (typeof val==='string') {
            val=val.replace(/\n/g, '\n  ');
          }
          info.push((key+': '+val).grey);
        }
      });
      log.msg=log.msg ? log.msg.bold[logColor(null, log)] : '';
      log.msg=log.msg ? log.msg+'\n'+zygon.cellPadding('', 36) : '';
      log.msg=(log.msg+info.join(', ')).trim();
      tbl.printRow(log);
    });
  });

app.command('install')
  .description('Install and start system service')
  .action(function() {
    require('../install');
  });

app.command('help [command]')
  .description('Show help')
  .action(function(cmd, opts) {
    if (opts) {
      help(cmd);
    } else {
      app.help();
    }
  }).on('--help', examples([
    'ood help init',
    'ood help start',
    'ood help redirect',
    'ood help status',
    'ood help config'
  ]));

app.helpInformation=function() {
  return [
    '\n  Usage: '+this._name+' '+'[command]',
    this.commandHelp().replace('Commands:\n', 'Commands:'.bold),
    ''
  ].join('\n');
};

app.Command.prototype.missingArgument=function(name) {
  process.stdout.write('\n  Error: missing required argument "'+name+'"\n');
  help(this._name);
};

app.Command.prototype.optionMissingArgument=function(option) {
  process.stdout.write('\n  Error: missing required argument "'+option.flags+'"\n');
  help(this._name);
};

app.Command.prototype.unknownOption = function(flag) {
  process.stdout.write('\n  Error: unknown option "'+flag+'"\n');
  help(this._name);
};

app.on('--help', examples([
  'ood help status',
  'ood help config',
  'ood start testapp',
  'ood stop example.com',
//  'ood redirect www.example.org http://example.org',
//  'ood redirect --delete www.example.org',
  'ood status',
  'ood config --get',
  'ood config --get httpPort',
  'ood config --set httpsPort 443',
  'ood config --get --app example.com',
  'ood config -a example.com -g port',
  'ood config -a testapp -s cwd /home/test/testapp',
]));

colorOutput();
app.parse(argv);

if (!app.args.length) {
  app.help();
}

function help(cmd) {
  app.parse([null, null, cmd, '--help']);
}

function examples(lines, title) {
  return function() {
    console.log('  '+(title || 'Examples')+':');
    console.log('    '+lines.join('\n    ')+'\n');
  };
}

function colorOutput() {
  var w=process.stdout.write;
  process.stdout.write=function(data, enc, cb) {
    data=data.toString();
    data=data.replace('  Usage:','  Usage:'.bold);
    data=data.replace('  Options:\n\n','  Options:\n'.bold);
    data=data.replace('  Examples:','  Examples:'.bold);
    data=data.replace('  Error:','  Error:'.bold.red);
    w.call(process.stdout, data, enc, cb);
  };
}

function request(cmd, params, cb) {
  params=params || {};
  api(cmd, params, function(err, res) {
    if (err) {
      return console.error('Could not connect to server!'.red+' ('+err.message+')');
    }
    if (~['start', 'stop', 'restart', 'scale'].indexOf(cmd)) {
      if (res.error || !res.success) {
        console.log('\n  '+(res.error || 'Unknown error').red.bold+'\n');
      } else {
        console.log('\n  Command successfully sent!\n'.green.bold);
      }
    }
    if (typeof cb==='function') {
      cb(res);
    }
  });
}

function uptimeHuman(time) {
  var ms=Date.now()-time, s=Math.floor(ms/1000), m, h, d;
  m=Math.floor(s/60);
  s=s % 60;
  h=Math.floor(m/60);
  m=m % 60;
  d=Math.floor(h/24);
  h=h % 24;
  s=s<10 ? '0'+s : s;
  m=m<10 ? '0'+m : m;
  h=h<10 ? '0'+h : h;
  return (d+'d ')[d>0 ? 'reset' : 'grey']+h+':'+m+':'+s;
}

function logColor(val, row) {
  return {ERROR:'red', INFO:'blue', DEBUG:'grey'}[row.type];
}
<commit_msg>added --alias option for init<commit_after>/*!
 * ood
 * Copyright(c) 2015-2016 Anatol Sommer <anatol@anatol.at>
 * MIT Licensed
 */

'use strict';

var app=require('commander'), zygon=require('zygon'),
  util=require('./util'), argv=process.argv, api;

require('colors');

process.on('uncaughtException', function(err) {
  var stack;
  if (err.code==='EACCES') {
    console.log('You do not have the permission to run this command!'.bold.red);
    console.log('Use sudo or consult: https://oodjs.com/docs/security');
    process.exit();
  } else {
    if (err.stack && err.stack.match) {
      stack=err.stack.match(/(.*)\n([\w\W]*)/);
      console.error('Error: '.bold.red+stack[1]+'\n'+stack[2].grey);
    } else {
      console.error('Fatal error!'.bold.red);
    }
  }
});

api=require('./api-client');

app.command('init <app>')
  .description('Initialise a new app')
  .option('-s, --script <script>', 'Script file (default: app.js)')
  .option('-d, --cwd <dir>', 'Set different working directory')
  .option('-a, --alias <domains>', 'Comma seperated list of alias host names')
  .action(function(appName, opts) {
    var config={};
    config.script=opts.script;
    config.cwd=opts.cwd || process.cwd();
    config.alias=opts.alias || '';
    request('init', {app:appName, config:config}, function(res) {
      if (res.success) {
        app.parse([null, null, 'status', appName]);
      } else {
        console.error(res.error || 'Error!'.bold.red);
      }
    });
  })
  .on('--help', examples([
    'ood init testapp',
    'ood init example.com'
  ]));

app.command('start <app>')
  .description('Start an app')
  .action(function(appName) {
    request('start', {app:appName}, function() {
      setTimeout(function() {
        app.parse([null, null, 'status', appName]);
      }, 1200);
    });
  })
  .on('--help', examples([
    'ood start testapp',
    'ood start example.com'
  ]));

app.command('stop <app>')
  .description('Stop a running app')
  .action(function(appName) {
    request('stop', {app:appName}, function() {
      app.parse([null, null, 'status', appName]);
    });
  })
  .on('--help', examples([
    'ood stop testapp',
    'ood stop example.com'
  ]));

app.command('restart <app>')
  .description('Restart a running app')
  .action(function(appName) {
    request('restart', {app:appName}, function() {
      app.parse([null, null, 'status', appName]);
    });
  })
  .on('--help', examples([
    'ood restart testapp',
    'ood restart example.com'
  ]));

app.command('scale <app> <instances>')
  .description('Kill or fork new worker instances')
  .action(function(appName, instances) {
    request('scale', {app:appName, instances:instances});
  })
  .on('--help', examples([
    'ood scale testapp 4',
    'ood scale example.com 12'
  ]));

/* TODO
app.command('redirect <host> [target]')
  .description('Set http redirect for a hostname')
  .option('-d, --delete', 'Deletes a redirect')
  .action(function(host, target, opts) {
    var args;
    if (!opts) {
      opts=target;
      target=null;
    }
    // TODO
  })
  .on('--help', examples([
    'ood redirect www.example.org http://example.org',
    'ood redirect example.com https://example.com',
    'ood redirect www.example.com https://example.com',
    'ood redirect --delete example.com',
    'ood redirect -d example.org'
  ]));
*/

app.command('status')
  .description('Show status of all apps');

app.command('status [app]')
  .description('Shows status of a running app')
  .action(function(appName, opts) {
    if (!opts) {
      opts=appName;
      appName=null;
    }
    request('status', {app:appName}, function(res) {
      var tbl=zygon([
        {name:'App name', size:20, color:function(val, row) {
          return row[4] ? 'blue' : 'silver';
        }},
        {name:'PID', size:6, align:'right'},
        {name:'Worker', size:6, align:'right'},
        {name:'State', size:9, color:function(val, row) {
          return {
            online:'cyan',
            listening:'green',
            ok:'green',
            fatal:'red',
            stopped:'grey'
          }[row[3].toLowerCase()];
        }},
        {name:'Uptime', size:13, align:'right', format:uptimeHuman},
        {name:'CPU', size:7, align:'right', format:function(p) {
          return p.toFixed(2)+'%';
        }},
        {name:'RAM', size:9, align:'right', format:function(b) {
          return (b/1048576).toFixed(2)+' MB';
        }}
      ]);

      tbl.printHead();

      Object.keys(res.status).forEach(function(appName) {
        var app=res.status[appName];
        if (app==='stopped') {
          tbl.printRow([appName, '', '', 'stopped']);
        } else {
          tbl.printRow([
            appName,
            app.master.pid,
            'MASTER',
            app.master.state,
            app.master.startTime,
            app.master.cpu,
            app.master.ram
          ]);
          app.workers.forEach(function(worker) {
            tbl.printRow([
              '',
              worker.pid,
              '#'+worker.workerId,
              worker.state,
              worker.startTime,
              worker.cpu,
              worker.ram
            ]);
          });
        }
      });

      tbl.end();
    });
  })
  .on('--help', examples([
    'ood status',
    'ood status testapp',
    'ood status example.com'
  ]));

app.command('config')
  .description('Modify or show config')
  .option('-a, --app <app>', 'Get or set app configuration')
  .option('-g, --get [key]', 'Get configuration value')
  .option('-s, --set <key> <value>', 'Set configuration value')
  .option('-d, --delete <key>', 'Delete configuration value')
  .action(function(val, opts) {
    var change;
    if (!opts) {
      opts=val;
      val=null;
    }
    change={app:opts.app};
    if (opts.delete) {
      change.delete=opts.delete;
    } else if (opts.get) {
      change.get=(opts.get===true ? '' : opts.get);
    } else if (opts.set) {
      change.set=opts.set;
      change.value=val;
    }
    request('config', change, function(res) {
      var val;
      if (!res.success) {
        return console.error(res.error || 'Error!'.bold.red);
      }
      if (opts.get) {
        val=JSON.stringify(res.value, null, 2).replace(/\n/g, '\n  ');
        console.log('\n  '+(opts.get===true ? '' : opts.get+' = ')+val+'\n');
      }
    });
  })
  .on('--help', examples([
    'ood config --get',
    'ood config --get httpPort',
    'ood config --set httpsPort 443',
    'ood config --get --app example.com',
    'ood config -a example.com --get port',
    'ood config -a testapp -s cwd /home/test/testapp',
    'ood config -a testapp -s env.NODE_ENV development',
    'ood config -a testapp --delete env'
  ]));

app.command('log')
  .description('Read log files')
  .action(function() {
    var tbl=zygon([
      {name:'Time', key:'time', size:8, color:'grey', format:function(time) {
        return time.substr(11, 8);
      }},
      {name:'Type', key:'type', size:5, color:logColor},
      {name:'App', key:'app', size:15, color:logColor},
      {name:'Message', key:'msg', size:Infinity}
    ]);
    tbl.printHead();
    util.logReader('/var/log/ood.log', function(log) {
      var info=[];
      Object.keys(log).forEach(function(key) {
        var val;
        if (!~['time', 'type', 'app', 'msg'].indexOf(key)) {
          val=log[key];
          if (typeof val==='object') {
            val=JSON.stringify(val);
          } else if (typeof val==='string') {
            val=val.replace(/\n/g, '\n  ');
          }
          info.push((key+': '+val).grey);
        }
      });
      log.msg=log.msg ? log.msg.bold[logColor(null, log)] : '';
      log.msg=log.msg ? log.msg+'\n'+zygon.cellPadding('', 36) : '';
      log.msg=(log.msg+info.join(', ')).trim();
      tbl.printRow(log);
    });
  });

app.command('install')
  .description('Install and start system service')
  .action(function() {
    require('../install');
  });

app.command('help [command]')
  .description('Show help')
  .action(function(cmd, opts) {
    if (opts) {
      help(cmd);
    } else {
      app.help();
    }
  }).on('--help', examples([
    'ood help init',
    'ood help start',
    'ood help redirect',
    'ood help status',
    'ood help config'
  ]));

app.helpInformation=function() {
  return [
    '\n  Usage: '+this._name+' '+'[command]',
    this.commandHelp().replace('Commands:\n', 'Commands:'.bold),
    ''
  ].join('\n');
};

app.Command.prototype.missingArgument=function(name) {
  process.stdout.write('\n  Error: missing required argument "'+name+'"\n');
  help(this._name);
};

app.Command.prototype.optionMissingArgument=function(option) {
  process.stdout.write('\n  Error: missing required argument "'+option.flags+'"\n');
  help(this._name);
};

app.Command.prototype.unknownOption = function(flag) {
  process.stdout.write('\n  Error: unknown option "'+flag+'"\n');
  help(this._name);
};

app.on('--help', examples([
  'ood help init',
  'ood help config',
  'ood init example.com --alias www.example.com',
  'ood start example.com',
  'ood stop testapp',
//  'ood redirect www.example.org http://example.org',
//  'ood redirect --delete www.example.org',
  'ood status',
  'ood config --get',
  'ood config --get httpPort',
  'ood config --set httpsPort 443',
  'ood config --get --app example.com',
  'ood config -ga example.com',
  'ood config -a example.com -g port',
  'ood config -a testapp -s cwd /home/test/testapp',
]));

colorOutput();
app.parse(argv);

if (!app.args.length) {
  app.help();
}

function help(cmd) {
  app.parse([null, null, cmd, '--help']);
}

function examples(lines, title) {
  return function() {
    console.log('  '+(title || 'Examples')+':');
    console.log('    '+lines.join('\n    ')+'\n');
  };
}

function colorOutput() {
  var w=process.stdout.write;
  process.stdout.write=function(data, enc, cb) {
    data=data.toString();
    data=data.replace('  Usage:','  Usage:'.bold);
    data=data.replace('  Options:\n\n','  Options:\n'.bold);
    data=data.replace('  Examples:','  Examples:'.bold);
    data=data.replace('  Error:','  Error:'.bold.red);
    w.call(process.stdout, data, enc, cb);
  };
}

function request(cmd, params, cb) {
  params=params || {};
  api(cmd, params, function(err, res) {
    if (err) {
      return console.error('Could not connect to server!'.red+' ('+err.message+')');
    }
    if (~['start', 'stop', 'restart', 'scale'].indexOf(cmd)) {
      if (res.error || !res.success) {
        console.log('\n  '+(res.error || 'Unknown error').red.bold+'\n');
      } else {
        console.log('\n  Command successfully sent!\n'.green.bold);
      }
    }
    if (typeof cb==='function') {
      cb(res);
    }
  });
}

function uptimeHuman(time) {
  var ms=Date.now()-time, s=Math.floor(ms/1000), m, h, d;
  m=Math.floor(s/60);
  s=s % 60;
  h=Math.floor(m/60);
  m=m % 60;
  d=Math.floor(h/24);
  h=h % 24;
  s=s<10 ? '0'+s : s;
  m=m<10 ? '0'+m : m;
  h=h<10 ? '0'+h : h;
  return (d+'d ')[d>0 ? 'reset' : 'grey']+h+':'+m+':'+s;
}

function logColor(val, row) {
  return {ERROR:'red', INFO:'blue', DEBUG:'grey'}[row.type];
}
<|endoftext|>


<commit_before>
'use strict';

var utils = require('../utils');
var onFileProgress = utils.onFileProgress;
var handleFileUpload = require('../handlefileupload').handleFileUpload;
var initSocket = require('../socket').initSocket;
var showError = require('./showerror').showError;
var effects = require('./effects');

var LOOKUP_TABLE = {
  'en-US_BroadbandModel': ['sample1.wav', 'sample2.wav'],
  'en-US_NarrowbandModel': ['sample1.wav', 'sample2.wav'],
  'es-ES_BroadbandModel': ['Es_ES_spk24_16khz.wav', 'Es_ES_spk19_16khz.wav'],
  'es-ES_NarrowbandModel': ['Es_ES_spk24_8khz.wav', 'Es_ES_spk19_8khz.wav'],
  'ja-JP_BroadbandModel': ['sample-Ja_JP-wide1.wav', 'sample-JA_JP-wide2.wav'],
  'ja-JP_NarrowbandModel': ['sample-Ja_JP-narrow1.wav', 'sample-JA_JP-narrow2.wav']
};

var playSample = (function() {

  var running = false;

  return function(token, imageTag, iconName, url, callback) {

    var currentlyDisplaying = JSON.parse(localStorage.getItem('currentlyDisplaying'));

    if (currentlyDisplaying && running) {
      console.log('HARD SOCKET STOP');
      $.publish('hardsocketstop');
      localStorage.setItem('currentlyDisplaying', false);
      running = false;
      return;
    }

    if (currentlyDisplaying) {
      showError('Currently another file is playing, please stop the file or wait until it finishes');
      return;
    }

    $.publish('clearscreen');

    localStorage.setItem('currentlyDisplaying', true);
    running = true;

    var timer = setInterval(effects.toggleImage, 750, imageTag, iconName);

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
      var blob = xhr.response;
      var currentModel = localStorage.getItem('currentModel') || 'en-US_BroadbandModel';
      var reader = new FileReader();
      var blobToText = new Blob([blob]).slice(0, 4);
      reader.readAsText(blobToText);
      reader.onload = function() {
        var contentType = reader.result === 'fLaC' ? 'audio/flac' : 'audio/wav';
        console.log('Uploading file', reader.result);
        var mediaSourceURL = URL.createObjectURL(blob);
        var audio = new Audio();
        audio.src = mediaSourceURL;
        audio.play();
        handleFileUpload(token, currentModel, blob, contentType, function(socket) {
          var parseOptions = {
            file: blob
          };
          onFileProgress(parseOptions,
            // On data chunk
            function(chunk) {
              socket.send(chunk);
            },
            // On file read error
            function(evt) {
              console.log('Error reading file: ', evt.message);
              showError(evt.message);
            },
            // On load end
            function() {
              socket.send(JSON.stringify({'action': 'stop'}));
            });
        },
        // On connection end
          function(evt) {
            effects.stopToggleImage(timer, imageTag, iconName);
            localStorage.getItem('currentlyDisplaying', false);
          }
        );
      };
    };
    xhr.send();
  };
})();

exports.initPlaySample = function(ctx) {

  var currentModel = localStorage.getItem('currentModel') || 'en-US_BroadbandModel';

  console.log('current model', currentModel);

  (function() {
    var el = $('.play-sample-1');
    var iconName = 'play';
    var imageTag = el.find('img');
    el.click( function(evt) {
      currentModel = localStorage.getItem('currentModel') || currentModel;
      var fileName = 'audio/' + LOOKUP_TABLE[currentModel][0];
      playSample(ctx.token, imageTag, iconName, fileName, function(result) {
        console.log('Play sample result', result);
      });
    });
  })(ctx, LOOKUP_TABLE, currentModel);

  (function() {
    var fileName = 'audio/' + LOOKUP_TABLE[currentModel][1];
    var el = $('.play-sample-2');
    var iconName = 'play';
    var imageTag = el.find('img');
    el.click( function(evt) {
      currentModel = localStorage.getItem('currentModel') || currentModel;
      var fileName = 'audio/' + LOOKUP_TABLE[currentModel][1];
      playSample(ctx.token, imageTag, iconName, fileName, function(result) {
        console.log('Play sample result', result);
      });
    });
  })(ctx, LOOKUP_TABLE, currentModel);

};

<commit_msg>Add new samples to lookup table<commit_after>
'use strict';

var utils = require('../utils');
var onFileProgress = utils.onFileProgress;
var handleFileUpload = require('../handlefileupload').handleFileUpload;
var initSocket = require('../socket').initSocket;
var showError = require('./showerror').showError;
var effects = require('./effects');

var LOOKUP_TABLE = {
  'en-US_BroadbandModel': ['Us_English_Broadband_Sample_1.wav', 'Us_English_Broadband_Sample_2.wav'],
  'en-US_NarrowbandModel': ['Us_English_Narrowband_Sample_1.wav', 'Us_English_Narrowband_Sample_2.wav'],
  'es-ES_BroadbandModel': ['Es_ES_spk24_16khz.wav', 'Es_ES_spk19_16khz.wav'],
  'es-ES_NarrowbandModel': ['Es_ES_spk24_8khz.wav', 'Es_ES_spk19_8khz.wav'],
  'ja-JP_BroadbandModel': ['sample-Ja_JP-wide1.wav', 'sample-JA_JP-wide2.wav'],
  'ja-JP_NarrowbandModel': ['sample-Ja_JP-narrow1.wav', 'sample-JA_JP-narrow2.wav']
};

var playSample = (function() {

  var running = false;

  return function(token, imageTag, iconName, url, callback) {

    var currentlyDisplaying = JSON.parse(localStorage.getItem('currentlyDisplaying'));

    if (currentlyDisplaying && running) {
      console.log('HARD SOCKET STOP');
      $.publish('hardsocketstop');
      localStorage.setItem('currentlyDisplaying', false);
      running = false;
      return;
    }

    if (currentlyDisplaying) {
      showError('Currently another file is playing, please stop the file or wait until it finishes');
      return;
    }

    $.publish('clearscreen');

    localStorage.setItem('currentlyDisplaying', true);
    running = true;

    var timer = setInterval(effects.toggleImage, 750, imageTag, iconName);

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
      var blob = xhr.response;
      var currentModel = localStorage.getItem('currentModel') || 'en-US_BroadbandModel';
      var reader = new FileReader();
      var blobToText = new Blob([blob]).slice(0, 4);
      reader.readAsText(blobToText);
      reader.onload = function() {
        var contentType = reader.result === 'fLaC' ? 'audio/flac' : 'audio/wav';
        console.log('Uploading file', reader.result);
        var mediaSourceURL = URL.createObjectURL(blob);
        var audio = new Audio();
        audio.src = mediaSourceURL;
        audio.play();
        handleFileUpload(token, currentModel, blob, contentType, function(socket) {
          var parseOptions = {
            file: blob
          };
          onFileProgress(parseOptions,
            // On data chunk
            function(chunk) {
              socket.send(chunk);
            },
            // On file read error
            function(evt) {
              console.log('Error reading file: ', evt.message);
              showError(evt.message);
            },
            // On load end
            function() {
              socket.send(JSON.stringify({'action': 'stop'}));
            });
        },
        // On connection end
          function(evt) {
            effects.stopToggleImage(timer, imageTag, iconName);
            localStorage.getItem('currentlyDisplaying', false);
          }
        );
      };
    };
    xhr.send();
  };
})();

exports.initPlaySample = function(ctx) {

  var currentModel = localStorage.getItem('currentModel') || 'en-US_BroadbandModel';

  console.log('current model', currentModel);

  (function() {
    var el = $('.play-sample-1');
    var iconName = 'play';
    var imageTag = el.find('img');
    el.click( function(evt) {
      currentModel = localStorage.getItem('currentModel') || currentModel;
      var fileName = 'audio/' + LOOKUP_TABLE[currentModel][0];
      playSample(ctx.token, imageTag, iconName, fileName, function(result) {
        console.log('Play sample result', result);
      });
    });
  })(ctx, LOOKUP_TABLE, currentModel);

  (function() {
    var fileName = 'audio/' + LOOKUP_TABLE[currentModel][1];
    var el = $('.play-sample-2');
    var iconName = 'play';
    var imageTag = el.find('img');
    el.click( function(evt) {
      currentModel = localStorage.getItem('currentModel') || currentModel;
      var fileName = 'audio/' + LOOKUP_TABLE[currentModel][1];
      playSample(ctx.token, imageTag, iconName, fileName, function(result) {
        console.log('Play sample result', result);
      });
    });
  })(ctx, LOOKUP_TABLE, currentModel);

};

<|endoftext|>


<commit_before>var program = require('commander'),
    Q = require('q'),
    winston = require('winston'),
    inquirer = require('inquirer'),
    _ = require('underscore'),
    Table = require('cli-table'),
    pg2json = require('..'),
    connection = require('../lib/connection'),
    tables = require('../lib/tables'),
    columns = require('../lib/columns'),
    relations = require('../lib/relations'),
    me = module.exports;

me.start = function(argv) {
    me.setup();
    program.parse(argv);
    me.run();
};

me.setup = function() {
    program
        .description('reads the schema of a db and creates a json-schema')
        .option('-c, --config [value]', 'db-config file')
        .option('-o, --output [value]', 'output filename')
        .option('-l, --delimiter [value]', 'template delimiter')
        .option('-s, --silent', 'no console output')
        .option('-f, --force', 'create folders if not existing')
        .option('-d, --dry-run', 'don\'t create files')
        .option('-D, --debug', 'print error object')
        .option('-T, --trace', 'print stacktrace')
        .version('0.0.1');
    winston.cli();
};

me.run = function() {
    if (program.silent) {
        winston.clear();
    }

    if (program.config) {
        connection.connect(program.config)
            .then(tables.get)
            .then(listTables)
            .fail(onFail);
    } else {
        program.help();
    }
};

function listTables(tables) {
    var tablesChoices = _.map(tables, function(table) {
        return table.table_name;
    });
    inquirer.prompt([{
        type: 'checkbox',
        name: 'tables',
        message: 'Select a table',
        choices: tablesChoices
    }], function(choices) {
        var promises = [];
        _.each(choices.tables, function(table) {
            winston.data('Table: ' + table);
            promises.push(columns.get(table).then(listColumns));
            promises.push(relations.get(table).then(listRelations));
        });
        Q.allSettled(promises)
            .then(finished)
            .catch (onFail);
    });
}

function listColumns(columns) {
    var table = new Table({
        head: ['Name', 'Type']
    });
    winston.info('columns:');
    _.each(columns, function(column, key) {
        table.push(
            [column.column_name, column.data_type]
        );
    });
    console.log(table.toString());
}

function listRelations(relations) {
    var table = new Table({
        head: ['Foreign Key', 'Referenced Table', 'Referenced Column']
    });
    winston.info('relations:');
    _.each(relations, function(relation) {
        table.push(
            [relation.fk_column_name, relation.referenced_table_name, relation.referenced_column_name]
        );
    });
    console.log(table.toString());
}

function finished(path) {
    if (path) {
        winston.info('File writen to: ', path);
    }
    winston.info('Successfull!');
    if (program.dryRun) {
        winston.warn('THIS WAS A DRY RUN');
        winston.warn('nothing has been writen');
    }
    process.kill();
}

function onFail(error) {
    winston.error('Message: ' + error.message);
    if (program.debug) {
        winston.data(error);
    }
    if (program.trace) {
        console.trace();
    }
    process.kill();
}
<commit_msg>ui refinments<commit_after>var program = require('commander'),
    Q = require('q'),
    winston = require('winston'),
    inquirer = require('inquirer'),
    _ = require('underscore'),
    Table = require('cli-table'),
    pg2json = require('..'),
    connection = require('../lib/connection'),
    tables = require('../lib/tables'),
    columns = require('../lib/columns'),
    relations = require('../lib/relations'),
    me = module.exports;

me.start = function(argv) {
    me.setup();
    program.parse(argv);
    me.run();
};

me.setup = function() {
    program
        .description('reads the schema of a db and creates a json-schema')
        .option('-c, --config [value]', 'db-config file')
        .option('-o, --output [value]', 'output filename')
        .option('-l, --delimiter [value]', 'template delimiter')
        .option('-s, --silent', 'no console output')
        .option('-f, --force', 'create folders if not existing')
        .option('-d, --dry-run', 'don\'t create files')
        .option('-D, --debug', 'print error object')
        .option('-T, --trace', 'print stacktrace')
        .version('0.0.1');
    winston.cli();
};

me.run = function() {
    if (program.silent) {
        winston.clear();
    }

    if (program.config) {
        connection.connect(program.config)
            .then(tables.get)
            .then(listTables)
            .fail(onFail);
    } else {
        program.help();
    }
};

function listTables(tables) {
    var tablesChoices = _.map(tables, function(table) {
        return table.table_name;
    });
    inquirer.prompt([{
        type: 'checkbox',
        name: 'tables',
        message: 'Select a table',
        choices: tablesChoices
    }], function(choices) {
        var promises = [];
        _.each(choices.tables, function(table) {
            winston.data('Table: ' + table);
            promises.push(columns.get(table)
                .then(function(columns){
                    listColumns(table, columns);
                }));
            promises.push(relations.get(table)
                .then(function(relations){
                    listRelations(table, relations);
                }));
        });
        Q.allSettled(promises)
            .then(finished)
            .catch (onFail);
    });
}

function listColumns(tableName, columns) {
    var table = new Table({
        head: ['Name', 'Type']
    });
    _.each(columns, function(column, key) {
        table.push(
            [column.column_name, column.data_type]
        );
    });
    if (table.length > 0){
        winston.info(tableName + ' columns');
        console.log(table.toString());
    }
}

function listRelations(tableName, relations) {
    var table = new Table({
        head: ['Foreign Key', 'Referenced Table', 'Referenced Column']
    });
    _.each(relations, function(relation) {
        table.push(
            [relation.fk_column_name, relation.referenced_table_name, relation.referenced_column_name]
        );
    });
    if (table.length > 0){
        winston.info(tableName + ' relations');
        console.log(table.toString());
    }
}

function finished(path) {
    if (path) {
        winston.info('File writen to: ', path);
    }
    winston.info('Successfull!');
    if (program.dryRun) {
        winston.warn('THIS WAS A DRY RUN');
        winston.warn('nothing has been writen');
    }
    process.kill();
}

function onFail(error) {
    winston.error('Message: ' + error.message);
    if (program.debug) {
        winston.data(error);
    }
    if (program.trace) {
        console.trace();
    }
    process.kill();
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    //tutti gli eventi ajax che evvengono in plist sono nel formato pilst.on(evento,[selettore],function(...){...});
    var plist = $("#postlist");
    var loading = N.getLangData().LOADING;
    var lang = null; /* globale dato che la uso anche altrove */
    var load = false; //gestisce i caricamenti ed evita sovrapposizioni. Dichiarata qui che è il foglio che viene incluso di default ovunque e per primo
    plist.html('
'+loading+'...
');

    var fixHeights = function() {
        plist.find(".nerdz_message").each (function() {
            var el = $(this).find('div:first');
            // TODO: switch from attr('data-parsed') to data('parsed')
            if ((el.height() >= 200 || el.find ('.gistLoad').length > 0) && !el.attr('data-parsed'))
            {
                el.data ('real-height', el.height()).addClass ("compressed");
                var n = el.next();
                n.prepend ('
>> ' + N.getLangData().EXPAND + ' <<
'); // Spaces master race.
            }
            el.attr('data-parsed','1');
        });
    };

    var onRemoveHiddenPost = function() {
        var me = $(this), target = me.data ("target"), lv = localStorage.getItem ("hid").split ("|"), serialized = "";
        $("#" + target).slideToggle (function() {
            $(this).find (".img_frame > img").each (function() {
                $(this).css ("margin-top", (117 - $(this).height()) / 2);
            });
        });
        me.parent().remove();
        for (var zxcvbn in lv)
            if (lv[zxcvbn] != target)
                serialized += lv[zxcvbn] + "|";
        if (serialized != "")
            localStorage.setItem ("hid", serialized.slice (0, -1));
        else
        {
            localStorage.removeItem ("hid");
            $("#hp-cnt").remove();
            $("#hp-title").remove();
        }
    };

    var hideHidden = function() {
        var hidden = localStorage.getItem ("hid");
        if (hidden != null)
        {
            var pids = hidden.split ("|").sort().reverse(), len = pids.length;
            while (len--)
            {
                var post = plist.find ("#" + pids[len]);
                if (post.length)
                {
                    post.hide();
                    var pLink = window[pids[len].replace (/post/, "lnk")];
                    pids[len] = $(document.createElement("li"))
                        .append ($(document.createElement("a")).attr ("href", pLink).text (decodeURIComponent (pLink.substr (1))))
                        .append ($(document.createElement("a")).data ("target", pids[len]).css ("float", "right").html ("X").click (onRemoveHiddenPost));
                }
                else
                    pids.splice (len, 1);
            }
            if (pids.length)
            {
                if (!$("#hp-cnt").length)
                {
                    // create the hidden posts box
                    $(document.createElement("div")).addClass ("title").click (function() {
                        $("#hp-cnt").slideToggle();
                    }).html (N.getStaticData().lang.HIDDEN_POSTS).attr ("id", "hp-title").appendTo ("#right_col");
                    $(document.createElement("div")).hide().addClass ("box").attr ("id", "hp-cnt")
                        .append ($(document.createElement ("ul")).html (pids)).appendTo ("#right_col");
                }
                else
                    $("#hp-cnt ul").html (pids);
            }
        }
        fixHeights();
    };

    plist.on('click',".spoiler",function(){
      if($(this).data("parsed")) return;
      $.each($(this).find("img"),function(){
        m = (117-$(this).height())/2;
        if (m>1)
          $(this).css("margin-top", m)
      })
      $(this).data("parsed","1");
    });

    plist.on('click','.more',function() {
        var me = $(this), par = me.parent(), jenk = par.prev();
        if (me.data ('busy') == 'godyes') return;
        me.data ('busy', 'godyes');
        // obtain the real height of the post and do some hardcore animations
        //jenk.removeClass ("compressed"); var realHeight = jenk.height();
        jenk.animate ({ maxHeight: jenk.data ('real-height') }, 500, function() {
            jenk.removeClass ("compressed").css ("max-height", "none");
            me.slideUp ('slow', function() {
                me.remove();
            });
        });
    });

    plist.on('click',".hide",function() {
        var pid = $(this).data('postid');
        var hidden = localStorage.getItem('hid');
        if(hidden == null) {
            localStorage.setItem('hid',pid);
        }
        else
        {
            hidden += "|"+pid;
            localStorage.setItem('hid',hidden);
        }
        //auto lock
        var lock = $("#post"+pid).find('img.imgunlocked');
        if(lock.length)
        {
            lock.eq(0).click();
        }
        $("#"+pid).slideUp (hideHidden);
    });

    $("#profilePostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").show();
        $("#nerdzlist").hide();
        $(".selectlang").css('color','');
        localStorage.removeItem("autolang");
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','profile');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#projectPostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").hide();
        $("#projlist").hide();
        $(".projlang").css('color','');
        load = false;
        N.html.project.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','project');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#nerdzselect").on('click',function() {
        $("#nerdzlist").toggle();
    });

    $("#projselect").on('click',function() {
        $("#projlist").toggle();
    });

    $(".selectlang").on('click',function() {
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        localStorage.setItem("autolang",lang);
        $(".selectlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
            $("#fast_nerdz").show();
            N.html.profile.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','profile');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            if(lang == '*') {
                $("#fast_nerdz").show();
            }
            else {
                $("#fast_nerdz").hide();
            }

            load = false;
            N.html.profile.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('mode','language');
                plist.data('type','profile');
                hideHidden();
                load = true;
            });
        }
    });

    $(".projlang").on('click',function() {
        $("#fast_nerdz").hide();
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        $(".projlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
                N.html.project.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            N.html.project.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','language');
                hideHidden();
                load = true;
            });
        }
    });

    $("#stdfrm").on('submit',function(e) {
        e.preventDefault();
        $("#pmessage").html(loading+'...');
        N.json.profile.newPost({message: $("#frmtxt").val(), to: 0 },function(data) {
            if(data.status == 'ok') {
                $("#frmtxt").val('');
                load = false;
                if(lang == '*') {
                    N.html.profile.getByLangHomePostList(0,lang,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','language');
                        hideHidden();
                        load = true;
                    });
                }
                else if(lang == 'usersifollow') {
                    N.html.profile.getFollowedHomePostList(0,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','followed');
                        hideHidden();
                        load = true;
                    });
                }
                else {
                    $("#profilePostList").click();
                }
            }

            $("#pmessage").html(data.message);

            setTimeout(function() {
                        $("#pmessage").html('');
                        },5000);
        });
    });

    //default profile posts
    if(localStorage.getItem("autolang"))
    {
        $("#nerdzselect").click();
        var el = $("#nerdzlist").find("ul").find("[data-lang='"+localStorage.getItem("autolang")+"']");
        el.click();
        el.css('color','#2370B6');
    }
    else
    {
        plist.data('location','home');
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            hideHidden();
            plist.data('type','profile');
            plist.data('mode','std');
            load = true;
        });
    }

    /* Autoload vecchi post allo scrolldown */
        //questo serve per search, che avendo l'azione iniziale nel file default.js, non condivide la variabile load. Uso sessionStorage per ovviare
    var sl = 'searchLoad'; /*search label */
    sessionStorage.setItem(sl,"0");
    var tmpDivId = "scrtxt";
    var manageScrollResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            load = true;
            sessionStorage.setItem(sl, "0"); // se sono entrato qui, sicuramente non cerco
        }
    };

    var manageScrollSearchResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            sessionStorage.setItem(sl, "1");
            load = false; // se sono entrato qui, sicuramente stavo cercando
        }
    };

    $(window).scroll(function() {
        if($(this).scrollTop()+200 >= ( $(document).height() - $(this).height() ))
        {
            var num = 10; //TODO: numero di posts, parametro?
            var hpid = plist.find("div[id^='post']").last().data('hpid');
            var mode = plist.data('mode');
            var type = plist.data('type');
            var append = '
'+loading+'...
';

            if((load || ("1" == sessionStorage.getItem(sl))) && !$("#"+tmpDivId).length)
            {
                plist.append(append);
            }

            if(load)
            {
                load = false;
                if(mode == 'std') {
                    N.html[type].getHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'followed') {
                    N.html[type].getFollowedHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'language') {
                    N.html[type].getByLangHomePostListBeforeHpid(num,lang,hpid, manageScrollResponse);
                }
            }
            //a true ci va in default.js, dopo il primo search
            if(sessionStorage.getItem(sl) == "1")
            {
                sessionStorage.setItem(sl, "0");
                if(type == 'project' && mode == 'search')
                {
                    N.html.search.globalProjectPostsBeforeHpid(num,$("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
                else if(type == 'profile' && mode == 'search')
                {
                    N.html.search.globalProfilePostsBeforeHpid(num, $("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
            }
        }
    });
});
<commit_msg>Remove news of username change of a blacklisted user<commit_after>$(document).ready(function() {
    //tutti gli eventi ajax che evvengono in plist sono nel formato pilst.on(evento,[selettore],function(...){...});
    var plist = $("#postlist");
    var loading = N.getLangData().LOADING;
    var lang = null; /* globale dato che la uso anche altrove */
    var load = false; //gestisce i caricamenti ed evita sovrapposizioni. Dichiarata qui che è il foglio che viene incluso di default ovunque e per primo
    plist.html('
'+loading+'...
');

    var fixHeights = function() {
        plist.find(".nerdz_message").each (function() {
            var el = $(this).find('div:first');
            // TODO: switch from attr('data-parsed') to data('parsed')
            if ((el.height() >= 200 || el.find ('.gistLoad').length > 0) && !el.attr('data-parsed'))
            {
                el.data ('real-height', el.height()).addClass ("compressed");
                var n = el.next();
                n.prepend ('
>> ' + N.getLangData().EXPAND + ' <<
'); // Spaces master race.
            }
            el.attr('data-parsed','1');
        });
    };

    var onRemoveHiddenPost = function() {
        var me = $(this), target = me.data ("target"), lv = localStorage.getItem ("hid").split ("|"), serialized = "";
        $("#" + target).slideToggle (function() {
            $(this).find (".img_frame > img").each (function() {
                $(this).css ("margin-top", (117 - $(this).height()) / 2);
            });
        });
        me.parent().remove();
        for (var zxcvbn in lv)
            if (lv[zxcvbn] != target)
                serialized += lv[zxcvbn] + "|";
        if (serialized != "")
            localStorage.setItem ("hid", serialized.slice (0, -1));
        else
        {
            localStorage.removeItem ("hid");
            $("#hp-cnt").remove();
            $("#hp-title").remove();
        }
    };

    var hideHidden = function() {
        var hidden = localStorage.getItem ("hid");
        if (hidden != null)
        {
            var pids = hidden.split ("|").sort().reverse(), len = pids.length;
            while (len--)
            {
                var post = plist.find ("#" + pids[len]);
                if (post.length)
                {
                    post.hide();
                    var pLink = window[pids[len].replace (/post/, "lnk")];
                    pids[len] = $(document.createElement("li"))
                        .append ($(document.createElement("a")).attr ("href", pLink).text (decodeURIComponent (pLink.substr (1))))
                        .append ($(document.createElement("a")).data ("target", pids[len]).css ("float", "right").html ("X").click (onRemoveHiddenPost));
                }
                else
                    pids.splice (len, 1);
            }
            if (pids.length)
            {
                if (!$("#hp-cnt").length)
                {
                    // create the hidden posts box
                    $(document.createElement("div")).addClass ("title").click (function() {
                        $("#hp-cnt").slideToggle();
                    }).html (N.getStaticData().lang.HIDDEN_POSTS).attr ("id", "hp-title").appendTo ("#right_col");
                    $(document.createElement("div")).hide().addClass ("box").attr ("id", "hp-cnt")
                        .append ($(document.createElement ("ul")).html (pids)).appendTo ("#right_col");
                }
                else
                    $("#hp-cnt ul").html (pids);
            }
        }
        // Hide 'blacklisted user changed nickname'
        // We ALWAYS have windows.idios that is the blacklisted users array
        $("#postlist ").find(".news a:nth-last-child(3)").each(function() {
            if($.inArray($(this).html(), window.idiots) > -1) {
                $(this).parent().parent().hide();
            }
        });

        fixHeights();
    };

    plist.on('click',".spoiler",function(){
      if($(this).data("parsed")) return;
      $.each($(this).find("img"),function(){
        m = (117-$(this).height())/2;
        if (m>1)
          $(this).css("margin-top", m)
      })
      $(this).data("parsed","1");
    });

    plist.on('click','.more',function() {
        var me = $(this), par = me.parent(), jenk = par.prev();
        if (me.data ('busy') == 'godyes') return;
        me.data ('busy', 'godyes');
        // obtain the real height of the post and do some hardcore animations
        //jenk.removeClass ("compressed"); var realHeight = jenk.height();
        jenk.animate ({ maxHeight: jenk.data ('real-height') }, 500, function() {
            jenk.removeClass ("compressed").css ("max-height", "none");
            me.slideUp ('slow', function() {
                me.remove();
            });
        });
    });

    plist.on('click',".hide",function() {
        var pid = $(this).data('postid');
        var hidden = localStorage.getItem('hid');
        if(hidden == null) {
            localStorage.setItem('hid',pid);
        }
        else
        {
            hidden += "|"+pid;
            localStorage.setItem('hid',hidden);
        }
        //auto lock
        var lock = $("#post"+pid).find('img.imgunlocked');
        if(lock.length)
        {
            lock.eq(0).click();
        }
        $("#"+pid).slideUp (hideHidden);
    });

    $("#profilePostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").show();
        $("#nerdzlist").hide();
        $(".selectlang").css('color','');
        localStorage.removeItem("autolang");
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','profile');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#projectPostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").hide();
        $("#projlist").hide();
        $(".projlang").css('color','');
        load = false;
        N.html.project.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','project');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#nerdzselect").on('click',function() {
        $("#nerdzlist").toggle();
    });

    $("#projselect").on('click',function() {
        $("#projlist").toggle();
    });

    $(".selectlang").on('click',function() {
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        localStorage.setItem("autolang",lang);
        $(".selectlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
            $("#fast_nerdz").show();
            N.html.profile.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','profile');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            if(lang == '*') {
                $("#fast_nerdz").show();
            }
            else {
                $("#fast_nerdz").hide();
            }

            load = false;
            N.html.profile.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('mode','language');
                plist.data('type','profile');
                hideHidden();
                load = true;
            });
        }
    });

    $(".projlang").on('click',function() {
        $("#fast_nerdz").hide();
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        $(".projlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
                N.html.project.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            N.html.project.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','language');
                hideHidden();
                load = true;
            });
        }
    });

    $("#stdfrm").on('submit',function(e) {
        e.preventDefault();
        $("#pmessage").html(loading+'...');
        N.json.profile.newPost({message: $("#frmtxt").val(), to: 0 },function(data) {
            if(data.status == 'ok') {
                $("#frmtxt").val('');
                load = false;
                if(lang == '*') {
                    N.html.profile.getByLangHomePostList(0,lang,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','language');
                        hideHidden();
                        load = true;
                    });
                }
                else if(lang == 'usersifollow') {
                    N.html.profile.getFollowedHomePostList(0,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','followed');
                        hideHidden();
                        load = true;
                    });
                }
                else {
                    $("#profilePostList").click();
                }
            }

            $("#pmessage").html(data.message);

            setTimeout(function() {
                        $("#pmessage").html('');
                        },5000);
        });
    });

    //default profile posts
    if(localStorage.getItem("autolang"))
    {
        $("#nerdzselect").click();
        var el = $("#nerdzlist").find("ul").find("[data-lang='"+localStorage.getItem("autolang")+"']");
        el.click();
        el.css('color','#2370B6');
    }
    else
    {
        plist.data('location','home');
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            hideHidden();
            plist.data('type','profile');
            plist.data('mode','std');
            load = true;
        });
    }

    /* Autoload vecchi post allo scrolldown */
        //questo serve per search, che avendo l'azione iniziale nel file default.js, non condivide la variabile load. Uso sessionStorage per ovviare
    var sl = 'searchLoad'; /*search label */
    sessionStorage.setItem(sl,"0");
    var tmpDivId = "scrtxt";
    var manageScrollResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            load = true;
            sessionStorage.setItem(sl, "0"); // se sono entrato qui, sicuramente non cerco
        }
    };

    var manageScrollSearchResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            sessionStorage.setItem(sl, "1");
            load = false; // se sono entrato qui, sicuramente stavo cercando
        }
    };

    $(window).scroll(function() {
        if($(this).scrollTop()+200 >= ( $(document).height() - $(this).height() ))
        {
            var num = 10; //TODO: numero di posts, parametro?
            var hpid = plist.find("div[id^='post']").last().data('hpid');
            var mode = plist.data('mode');
            var type = plist.data('type');
            var append = '
'+loading+'...
';

            if((load || ("1" == sessionStorage.getItem(sl))) && !$("#"+tmpDivId).length)
            {
                plist.append(append);
            }

            if(load)
            {
                load = false;
                if(mode == 'std') {
                    N.html[type].getHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'followed') {
                    N.html[type].getFollowedHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'language') {
                    N.html[type].getByLangHomePostListBeforeHpid(num,lang,hpid, manageScrollResponse);
                }
            }
            //a true ci va in default.js, dopo il primo search
            if(sessionStorage.getItem(sl) == "1")
            {
                sessionStorage.setItem(sl, "0");
                if(type == 'project' && mode == 'search')
                {
                    N.html.search.globalProjectPostsBeforeHpid(num,$("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
                else if(type == 'profile' && mode == 'search')
                {
                    N.html.search.globalProfilePostsBeforeHpid(num, $("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
            }
        }
    });
});
<|endoftext|>


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

'use strict';

import pkg from '../package.json';
import log from './log';
import Xeon from './xeon';
import meow from 'meow';
import notifier from './notifier';

// notify if there are some updates
notifier(pkg);

const cli = meow(`
    Usage
      $ xeon -i ./index[.sh]

    Options
      --output -o Specify output file directory
      --watch -w  Watch for changes in required files and rebuild on the fly

    version: ${pkg.version}
  `,
  {
    alias: {
      i: 'input',
      o: 'output',
      w: 'watch',
      e: 'external'
    }
  }
);

const config = {
  entry: cli.flags.input,
  output: cli.flags.output,
  allowExternal: cli.flags.external
};

((config) => {
  if (!config.entry) return console.log('Entry file should be defined');
  const xeon = new Xeon(config);

  log(xeon);

  function processBundle() {
    xeon.buildDesGraph();
    xeon.resolveDepsGraph()
    xeon.writeBundle();
  }

  processBundle();

  if (cli.flags.watch) {
    xeon.watchDeps((file) => {
      processBundle();
    });
  }
})(config)
<commit_msg>added alias for --help<commit_after>#!/usr/bin/env node

'use strict';

import pkg from '../package.json';
import log from './log';
import Xeon from './xeon';
import meow from 'meow';
import notifier from './notifier';

// notify if there are some updates
notifier(pkg);

const cli = meow(`
    Usage
      $ xeon -i ./index[.sh]

    Options
      --output -o Specify output file directory
      --watch -w  Watch for changes in required files and rebuild on the fly

    version: ${pkg.version}
  `,
  {
    alias: {
      i: 'input',
      o: 'output',
      w: 'watch',
      e: 'external',
      h: 'help'
    }
  }
);

const config = {
  entry: cli.flags.input,
  output: cli.flags.output,
  allowExternal: cli.flags.external
};

((config) => {
  if (!config.entry) return console.log('Entry file should be defined');
  const xeon = new Xeon(config);

  log(xeon);

  function processBundle() {
    xeon.buildDesGraph();
    xeon.resolveDepsGraph()
    xeon.writeBundle();
  }

  processBundle();

  if (cli.flags.watch) {
    xeon.watchDeps((file) => {
      processBundle();
    });
  }
})(config)
<|endoftext|>


<commit_before>'use strict';

var cli = require('cli');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var util = require('util');

var _ = require('lodash');

var argv = require('./argv');
var base = require('./base');
var colors = require('cli-color-keywords')();
var junit = require('./junit');
var re = require('./re');

var Config = require('./config');
var File = require('./file');
var Formatter = require('./formatter');

var EventEmitter = require('drip').EnhancedEmitter;

var Logger = require('./logger');

var MAP_OMIT = {
	'$0': true,
	'_': true
};

var flags = _.reduce(
	argv,
	function(res, item, index) {
		if (index.length > 1 && !MAP_OMIT[index]) {
			index = _.camelCase(index);

			res[index] = item;
		}

		return res;
	},
	{}
);

var filterFileErrors = function(errors) {
	return _.reject(errors, ['type', 'ignored']);
};

class CLI extends EventEmitter {
	constructor(config) {
		super();

		config = config || {};

		this._configs = {};
		this._configFiles = {};

		this.flags = _.defaults(config.flags, flags);

		this._args = config.args || argv._;
		this._cwd = config.cwd || process.cwd();
		this._exec = config.exec || cli.exec.bind(cli);
		this.junit = config.junit || junit;
		this._log = config.log || console.log.bind(console);
		this._logger = config.logger || Logger;
		this._read = config.read || fs.readFileAsync.bind(fs);
		this._write = config.write || fs.writeFileAsync.bind(fs);
	}

	init() {
		var instance = this;

		this._config = new Config.Loader(
			{
				cwd: instance._cwd
			}
		);

		return this._loadConfigs().then(
			function(configs) {
				instance._configs = configs;

				return configs;
			}
		)
		.bind(instance)
		.then(instance._start);
	}

	afterFormat(results) {
		var instance = this;

		var series = [];

		if (instance.flags.inlineEdit) {
			series = results.reduce(
				function(prev, item, index) {
					if (item && !item.err && item.contents !== item.data) {
						prev.push(instance.writeFile(item.file, item.contents));
					}

					return prev;
				},
				series
			);
		}

		return Promise.all(series)
				.then(instance.onFinish.bind(instance))
				.catch(instance.logGeneralError.bind(instance));
	}

	checkMeta(results) {
		if (this._CHECK_META) {
			require(this._metaCheckerPath).check(
				{
					liferayModuleDir: this._liferayModuleDir
				}
			);
		}

		return results;
	}

	createReport(results) {
		if (this.flags.junit) {
			var junit = new this.junit(
				{
					flags: this.flags,
					logger: this._logger
				}
			);

			results = junit.generate().return(results);
		}

		return results;
	}

	formatFile(contents, file) {
		var formatter = Formatter.get(file, this._logger, this.flags);

		if (formatter) {
			formatter._config = this._configs[file];

			contents = this.processFileData(contents, formatter);

			this.isMetaCheckNeeded(file);
		}

		return contents;
	}

	hasModulesFile(fileDir) {
		return fs.existsSync(path.join(fileDir, 'modules.js'));
	}

	isMetaCheckNeeded(file) {
		if (!this._CHECK_META && this.flags.checkMetadata && path.extname(file) === '.js') {
			var fileDir = path.dirname(path.resolve(file));

			if (path.basename(fileDir) === 'liferay' && this.hasModulesFile(fileDir)) {
				this._CHECK_META = true;
				this._liferayModuleDir = fileDir;
			}
		}
	}

	logGeneralError(err) {
		var msg = util.format(colors.error('Something went wrong.\nDetails below:') + '\n%s', err.stack);

		this._log(msg);

		return msg;
	}

	logResults(out, file) {
		if (out) {
			this._log(out);
		}

		var verboseDetails = this._logger.verboseDetails[file];

		if (verboseDetails) {
			this._log(verboseDetails);
		}
	}

	onFinish(results) {
		if (this.flags.open) {
			this.openFiles(results);
		}

		return results;
	}

	onRead(contents, file) {
		return this.formatFile(contents, file);
	}

	onReadError(err, file) {
		var errMsg = File.handleFileReadError(err, file);

		if (errMsg) {
			this._log('');
			this._log(errMsg);
			this._log('');
		}

		return {
			contents: '',
			err: err,
			file: file
		};
	}

	openFiles(result) {
		var instance = this;

		var errorFiles = Object.keys(instance._logger.getErrors());

		if (errorFiles.length) {
			instance._exec(
				'git config --get user.editor',
				function(res) {
					instance._exec(
						'open -a "' + res[0] + '" "' + errorFiles.join('" "') + '"'
					);
				}
			);
		}
	}

	processFile(file) {
		return this._read(file, 'utf-8')
				.then(_.bindKeyRight(this, 'onRead', file))
				.error(_.bindKeyRight(this, 'onReadError', file));
	}

	processFileData(data, formatter) {
		var file = formatter.file;

		var contents = formatter.format(data);

		this.logResults(this.renderOutput(file), file);

		return {
			file: file,
			contents: contents,
			data: data
		};
	}

	renderOutput(file) {
		var flags = this.flags;

		var config = {
			showColumns: flags.showColumns
		};

		var out;

		if (flags.relative) {
			config.relative = process.env.GIT_PWD || this._cwd;
		}

		if (flags.filenames) {
			out = this._logger.renderFileNames(file, config);
		}
		else {
			config.showBanner = flags.quiet;
			config.showLintIds = flags.lintIds;

			if (flags.quiet) {
				this._logger.filterFileErrors(
					file,
					filterFileErrors
				);
			}

			out = this._logger.render(file, config);
		}

		return out;
	}

	writeFile(file, contents) {
		return this._write(file, contents)
				.then(_.bind(_.ary(util.format, 2), util, 'Wrote file: %s', file))
				.error(File.handleFileWriteError.bind(this, file))
				.then(_.unary(this._log).bind(this));
	}

	_loadConfigs() {
		var instance = this;

		return Promise.reduce(
			instance._args,
			function(prev, item, index) {
				var filePath = path.resolve(instance._cwd, path.dirname(item));

				var res;

				if (instance.flags.config) {
					res = instance._config.load(filePath);
				}
				else {
					var cfg = new Config({});

					cfg._paths.cwd = instance._cwd;

					res = Promise.resolve(cfg);
				}

				return res.then(
					function(config) {
						prev[item] = config;

						var obj = config._paths.obj;

						if (obj) {
							instance._configFiles[obj.filepath] = true;
						}

						return prev;
					}
				);
			},
			{}
		);
	}

	_notifyConfig() {
		if (this.flags.config && !this.flags.filenames) {
			var configFiles = _.keys(this._configFiles);

			var configSize = configFiles.length;

			if (configSize) {
				var msg;

				if (configSize === 1) {
					msg = `Using local config from ${configFiles[0]}`;
				}
				else if (this.flags.verbose) {
					msg = 'Using local config from: \n' + configFiles.join('\n');
				}
				else {
					msg = `Using local config from ${configSize} files. Pass -v to see all locations`;
				}

				msg += '\n';

				this._log(msg);
			}
		}
	}

	_start() {
		this.emit('init');

		this._notifyConfig();

		return Promise.all(this._args)
				.bind(this)
				.map(_.unary(this.processFile))
				.then(this.checkMeta)
				.then(this.createReport)
				.then(this.afterFormat);
	}
};

CLI.prototype._metaCheckerPath = './meta';

var cliInstance = new CLI();

cliInstance.CLI = CLI;

module.exports = cliInstance;<commit_msg>Switching to mapSeries so that the output is at least ordered predictably<commit_after>'use strict';

var cli = require('cli');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var util = require('util');

var _ = require('lodash');

var argv = require('./argv');
var base = require('./base');
var colors = require('cli-color-keywords')();
var junit = require('./junit');
var re = require('./re');

var Config = require('./config');
var File = require('./file');
var Formatter = require('./formatter');

var EventEmitter = require('drip').EnhancedEmitter;

var Logger = require('./logger');

var MAP_OMIT = {
	'$0': true,
	'_': true
};

var flags = _.reduce(
	argv,
	function(res, item, index) {
		if (index.length > 1 && !MAP_OMIT[index]) {
			index = _.camelCase(index);

			res[index] = item;
		}

		return res;
	},
	{}
);

var filterFileErrors = function(errors) {
	return _.reject(errors, ['type', 'ignored']);
};

class CLI extends EventEmitter {
	constructor(config) {
		super();

		config = config || {};

		this._configs = {};
		this._configFiles = {};

		this.flags = _.defaults(config.flags, flags);

		this._args = config.args || argv._;
		this._cwd = config.cwd || process.cwd();
		this._exec = config.exec || cli.exec.bind(cli);
		this.junit = config.junit || junit;
		this._log = config.log || console.log.bind(console);
		this._logger = config.logger || Logger;
		this._read = config.read || fs.readFileAsync.bind(fs);
		this._write = config.write || fs.writeFileAsync.bind(fs);
	}

	init() {
		var instance = this;

		this._config = new Config.Loader(
			{
				cwd: instance._cwd
			}
		);

		return this._loadConfigs().then(
			function(configs) {
				instance._configs = configs;

				return configs;
			}
		)
		.bind(instance)
		.then(instance._start);
	}

	afterFormat(results) {
		var instance = this;

		var series = [];

		if (instance.flags.inlineEdit) {
			series = results.reduce(
				function(prev, item, index) {
					if (item && !item.err && item.contents !== item.data) {
						prev.push(instance.writeFile(item.file, item.contents));
					}

					return prev;
				},
				series
			);
		}

		return Promise.all(series)
				.then(instance.onFinish.bind(instance))
				.catch(instance.logGeneralError.bind(instance));
	}

	checkMeta(results) {
		if (this._CHECK_META) {
			require(this._metaCheckerPath).check(
				{
					liferayModuleDir: this._liferayModuleDir
				}
			);
		}

		return results;
	}

	createReport(results) {
		if (this.flags.junit) {
			var junit = new this.junit(
				{
					flags: this.flags,
					logger: this._logger
				}
			);

			results = junit.generate().return(results);
		}

		return results;
	}

	formatFile(contents, file) {
		var formatter = Formatter.get(file, this._logger, this.flags);

		if (formatter) {
			formatter._config = this._configs[file];

			contents = this.processFileData(contents, formatter);

			this.isMetaCheckNeeded(file);
		}

		return contents;
	}

	hasModulesFile(fileDir) {
		return fs.existsSync(path.join(fileDir, 'modules.js'));
	}

	isMetaCheckNeeded(file) {
		if (!this._CHECK_META && this.flags.checkMetadata && path.extname(file) === '.js') {
			var fileDir = path.dirname(path.resolve(file));

			if (path.basename(fileDir) === 'liferay' && this.hasModulesFile(fileDir)) {
				this._CHECK_META = true;
				this._liferayModuleDir = fileDir;
			}
		}
	}

	logGeneralError(err) {
		var msg = util.format(colors.error('Something went wrong.\nDetails below:') + '\n%s', err.stack);

		this._log(msg);

		return msg;
	}

	logResults(out, file) {
		if (out) {
			this._log(out);
		}

		var verboseDetails = this._logger.verboseDetails[file];

		if (verboseDetails) {
			this._log(verboseDetails);
		}
	}

	onFinish(results) {
		if (this.flags.open) {
			this.openFiles(results);
		}

		return results;
	}

	onRead(contents, file) {
		return this.formatFile(contents, file);
	}

	onReadError(err, file) {
		var errMsg = File.handleFileReadError(err, file);

		if (errMsg) {
			this._log('');
			this._log(errMsg);
			this._log('');
		}

		return {
			contents: '',
			err: err,
			file: file
		};
	}

	openFiles(result) {
		var instance = this;

		var errorFiles = Object.keys(instance._logger.getErrors());

		if (errorFiles.length) {
			instance._exec(
				'git config --get user.editor',
				function(res) {
					instance._exec(
						'open -a "' + res[0] + '" "' + errorFiles.join('" "') + '"'
					);
				}
			);
		}
	}

	processFile(file) {
		return this._read(file, 'utf-8')
				.then(_.bindKeyRight(this, 'onRead', file))
				.error(_.bindKeyRight(this, 'onReadError', file));
	}

	processFileData(data, formatter) {
		var file = formatter.file;

		var contents = formatter.format(data);

		this.logResults(this.renderOutput(file), file);

		return {
			file: file,
			contents: contents,
			data: data
		};
	}

	renderOutput(file) {
		var flags = this.flags;

		var config = {
			showColumns: flags.showColumns
		};

		var out;

		if (flags.relative) {
			config.relative = process.env.GIT_PWD || this._cwd;
		}

		if (flags.filenames) {
			out = this._logger.renderFileNames(file, config);
		}
		else {
			config.showBanner = flags.quiet;
			config.showLintIds = flags.lintIds;

			if (flags.quiet) {
				this._logger.filterFileErrors(
					file,
					filterFileErrors
				);
			}

			out = this._logger.render(file, config);
		}

		return out;
	}

	writeFile(file, contents) {
		return this._write(file, contents)
				.then(_.bind(_.ary(util.format, 2), util, 'Wrote file: %s', file))
				.error(File.handleFileWriteError.bind(this, file))
				.then(_.unary(this._log).bind(this));
	}

	_loadConfigs() {
		var instance = this;

		return Promise.reduce(
			instance._args,
			function(prev, item, index) {
				var filePath = path.resolve(instance._cwd, path.dirname(item));

				var res;

				if (instance.flags.config) {
					res = instance._config.load(filePath);
				}
				else {
					var cfg = new Config({});

					cfg._paths.cwd = instance._cwd;

					res = Promise.resolve(cfg);
				}

				return res.then(
					function(config) {
						prev[item] = config;

						var obj = config._paths.obj;

						if (obj) {
							instance._configFiles[obj.filepath] = true;
						}

						return prev;
					}
				);
			},
			{}
		);
	}

	_notifyConfig() {
		if (this.flags.config && !this.flags.filenames) {
			var configFiles = _.keys(this._configFiles);

			var configSize = configFiles.length;

			if (configSize) {
				var msg;

				if (configSize === 1) {
					msg = `Using local config from ${configFiles[0]}`;
				}
				else if (this.flags.verbose) {
					msg = 'Using local config from: \n' + configFiles.join('\n');
				}
				else {
					msg = `Using local config from ${configSize} files. Pass -v to see all locations`;
				}

				msg += '\n';

				this._log(msg);
			}
		}
	}

	_start() {
		this.emit('init');

		this._notifyConfig();

		return Promise.all(this._args)
				.bind(this)
				.mapSeries(_.unary(this.processFile))
				.then(this.checkMeta)
				.then(this.createReport)
				.then(this.afterFormat);
	}
};

CLI.prototype._metaCheckerPath = './meta';

var cliInstance = new CLI();

cliInstance.CLI = CLI;

module.exports = cliInstance;<|endoftext|>


<commit_before>// Yerelleştirilmiş kullanıcı arayüzü.
var tr = {
	"off": "off",
	"on": "on",
	"syntax": "Sözdizimi-Vurgulaması",
	"lineno": "Satır-Numaraları",
	"reset": "Slaytı Resetle",
	"format": "Format Source Code",
	"kill": "Program'ı Öldür",
	"run": "Çalıştır",
	"toc": "İçerik Tablosu",
	"prev": "Geri",
	"next": "İleri",
	"waiting": "Sunucu bekleniyor...",
	"errcomm": "Sunucu iletişiminde hata.",
};
<commit_msg>Yenilendi<commit_after>// Yerelleştirilmiş kullanıcı arayüzü.
var tr = {
	"off": "off",
	"on": "on",
	"syntax": "Sözdizimi-Vurgulaması",
	"lineno": "Satır-Numaraları",
	"reset": "Slaytı Resetle",
	"format": "Kaynak Kodu Formatla",
	"kill": "Program'ı Öldür",
	"run": "Çalıştır",
	"toc": "İçerik Tablosu",
	"prev": "Geri",
	"next": "İleri",
	"waiting": "Sunucu bekleniyor...",
	"errcomm": "Sunucu iletişiminde hata.",
};
<|endoftext|>


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

var program = require('commander'),
    packageJSON = require('../package.json'),
    app = require('./index.js');

function parseArgs() {
    program
        .version(packageJSON.version)
        .usage('[options] <mpq> <listfile>')
        .option('-o, --dest <path>', 'the folder to extract files to (default: current directory)')
        .option('-f, --fullpath', 'preserve the full path heirarchy of the extracted files.')
        .option('-c, --lowercase', 'convert extracted file paths to lowercase.')
        .option('-v, --verbose', 'verbose output')
        .parse(process.argv);

    if (process.argv.length < 4) {
        console.error('Error: No listfile specified.');
        program.help();
    }
    if (process.argv.length < 3) {
        console.error('Error: No MPQ file specified.');
        program.help();
    }

    return {
        mpqPath: process.argv[2],
        listPath: process.argv[3],
        outPath: program.dest || './',
        useFullPath: program.fullpath || false,
        toLowercase: program.lowercase || false,
        verbose: program.verbose || false,
    };
}

var options = parseArgs();
app.extract(options);
<commit_msg>Fix error check ordering.<commit_after>#! /usr/bin/env node
'use strict';

var program = require('commander'),
    packageJSON = require('../package.json'),
    app = require('./index.js');

function parseArgs() {
    program
        .version(packageJSON.version)
        .usage('[options] <mpq> <listfile>')
        .option('-o, --dest <path>', 'the folder to extract files to (default: current directory)')
        .option('-f, --fullpath', 'preserve the full path heirarchy of the extracted files.')
        .option('-c, --lowercase', 'convert extracted file paths to lowercase.')
        .option('-v, --verbose', 'verbose output')
        .parse(process.argv);

    if (process.argv.length < 3) {
        console.error('Error: No MPQ file specified.');
        program.help();
    }
    if (process.argv.length < 4) {
        console.error('Error: No listfile specified.');
        program.help();
    }

    return {
        mpqPath: process.argv[2],
        listPath: process.argv[3],
        outPath: program.dest || './',
        useFullPath: program.fullpath || false,
        toLowercase: program.lowercase || false,
        verbose: program.verbose || false,
    };
}

var options = parseArgs();
app.extract(options);
<|endoftext|>


<commit_before>function like_add(post_id){
	$.post('classes/like_add.php', {post_id:post_id}, function(data) {
		like_get(post_id);
	}).done(function() {
		changeText(post_id);
	});
}

function like_get(post_id) {
	$.post('classes/like_get.php', {post_id:post_id}, function(data) {
		$('#post_'+post_id+'_likes').text(data);
	});
}

function changeText(post_id) {
    var element = document.getElementById('like_'+post_id);
    if (element.innerHTML != 'Unlike')
	{
    	element.innerHTML = 'Unlike';
		addName(post_id);
    }
    else
	{
        element.innerHTML = 'Like';
		removeName(post_id);
    }
}

function addName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("like") > -1) {
		element.innerHTML = "You, " + html;
	} else {
		element.innerHTML = "You like this.";
	}
}

function removeName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("You like this.") > -1) {
		element.innerHTML = "No one likes this.";
	} else {
		var i = html.indexOf("You")
		element.innerHTML = html.substring(i+5);
	}
}

<commit_msg>Woo Ajax<commit_after>function like_add(post_id){
	$.post('classes/like_add.php', {post_id:post_id}, function(data) {
		like_get(post_id);
	}).done(function() {
		changeText(post_id);
	});
}

function like_get(post_id) {
	$.post('classes/like_get.php', {post_id:post_id}, function(data) {
		$('#post_'+post_id+'_likes').text(data);
	});
}

function changeText(post_id) {
    var element = document.getElementById('like_'+post_id);
    if (element.innerHTML != 'Unlike')
	{
    	element.innerHTML = 'Unlike';
		addName(post_id);
    }
    else
	{
        element.innerHTML = 'Like';
		removeName(post_id);
    }
}

function addName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("likes") > -1) {
		element.innerHTML = "You, " + html;
	} else {
		element.innerHTML = "You like this.";
	}
}

function removeName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("You like this.") > -1) {
		element.innerHTML = "No one likes this.";
	} else {
		var i = html.indexOf("You")
		element.innerHTML = html.substring(i+5);
	}
}

<|endoftext|>