<commit_before>var xray = require('x-ray');
var x = xray();

var signo;
var previsor = 'maya';
var duracao;
var duracaoTodos = [];
var signosTodos = [];
var previsorTodos = [];

function help() {
	//console.log('Utilização: node '+basename(process.argv[1])+' <signo> [diaria|semanal|semanal-amor|mensal|anual] [previsor]');
	console.log('Utilização: horos <signo> [diaria|semanal|semanal-amor|mensal|anual] [previsor]');
}

function basename(file) {
	if(file.lastIndexOf('/') !== -1) {
		return file.substring(file.lastIndexOf('/') + 1);
	}
	else if(file.lastIndexOf('\\') !== -1) {
		return file.substring(file.lastIndexOf('\\') + 1);
	} else {
		return file;
	}
}

function adicionarOutrosSignos(arraySignos) {
	var signosMatch = ['carneiro', 'cancer', 'balanca'];
	var signosAdicionar = ['aries', 'caranguejo', 'libra'];

	if(arraySignos.length === 0) return;

	for (var i = 0; i < signosMatch.length; i++) {
		var insertIndex = arraySignos.indexOf(signosMatch[i]);
		if(insertIndex !== -1) {
			arraySignos.splice(insertIndex, 0, signosAdicionar[i]);
		}
	}
}

switch(process.argv.length) {
	case 3:
		signo = process.argv[2].toLowerCase();
		if(signo === '-h' || signo === '--help') {
			help();
			return;
		}
		break;
	case 4:
		signo = process.argv[2].toLowerCase();
		duracao = process.argv[3].toLowerCase();
		break;
	case 5:
		signo = process.argv[2].toLowerCase();
		duracao = process.argv[3].toLowerCase();
		previsor = process.argv[4].toLowerCase();
		break;
	default:
		help();
		return;
	break;
}

switch(signo) {
	case 'caranguejo':
		signo = 'cancer';
	break;
	case 'aries':
		signo = 'carneiro';
	break;
	case 'libra':
		signo = 'balanca';
	break;
}

var http = require('http');

var options = {
    host: 'lifestyle.sapo.pt',
    port: 80,
    path: '/astral/previsoes/'+previsor+'?signo='+signo
};

var content = "";

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        HTML2Horoscopo(content);
    });
});

req.on('error', function(err) {
	console.error('Não foi possivel conectar. Provavelmente tem a ligacao em baixo.');
	return;
});

req.end();

function HTML2Horoscopo(string) {
	x(string, '#astrological_sign option', ['@value'])(function(err, data) {
		for (var i = 0; i < data.length; i++) {
			signosTodos.push(data[i]);
		}
		adicionarOutrosSignos(signosTodos);
		x(string, '#predictor option',
			[{
				value: '@value',
				selected: '@selected'
			}]
			)(function(err, data) {
			for (var i = 0; i < data.length; i++) {
				var obj = data[i];
				previsorTodos.push(obj.value);
				//if(obj.selected === 'selected') previsor = obj.value;
			}

			var getRealDataPromise = new Promise(function(resolve, reject) {
				if(signosTodos.length !== 0 && previsorTodos.length !== 0)  return resolve();
				var options2 = {
				    host: 'lifestyle.sapo.pt',
				    port: 80,
				    path: '/astral/previsoes/maya?signo=carneiro'
				};

				var content2 = "";

				var req2 = http.request(options2, function(res2) {
				    res2.setEncoding("utf8");
				    res2.on("data", function (chunk2) {
				        content2 += chunk2;
				    });

				    res2.on("end", function () {
				        x(content2, '#astrological_sign option', ['@value'])(function(err, data) {
							for (var i = 0; i < data.length; i++) {
								signosTodos.push(data[i]);
							}
							adicionarOutrosSignos(signosTodos);
							x(content2, '#predictor option',
								[{
									value: '@value',
									selected: '@selected'
								}]
								)(function(err, data) {
								for (var i = 0; i < data.length; i++) {
									var obj = data[i];
									previsorTodos.push(obj.value);
									//if(obj.selected === 'selected') previsor = obj.value;
								}
								/*x(content2, '.tabs-nav', ['a@href'])(function(err, data) {
									for (var i = 0; i < data.length; i++) {
										duracaoTodos.push(data[i].substring(data[i].indexOf('#') + 1));
									}*/

									if(signosTodos.length !== 0 && previsorTodos.length !== 0)  return resolve();
									else {
										var erroMsg = "Nao consegui encontrar";
										if(signosTodos.length === 0) {
											erroMsg += " os signos e";
										}
										if(previsorTodos.length === 0) {
											erroMsg += " os previsores e";
										}

										erroMsg = erroMsg.replace(/e$/, "");
										erroMsg += "existentes."
										return reject(new Error(erroMsg));
									}
								//});
							});
						});
				    });
				});

				req2.on('error', function(err) {
					console.error('Não foi possivel conectar. Tente outra vez.');
					return;
				});

				req2.end();
			});

			getRealDataPromise.catch(function(err) {
				console.error('Erro: '+err.message);
				return;
			});
			getRealDataPromise.then(function() {
				if(signosTodos.indexOf(signo) === -1) {
					var textoTodosSignos = signosTodos[0];
					for (var i = 1; i < signosTodos.length; i++) {
						textoTodosSignos += (i !== signosTodos.length - 1) ? (', '+signosTodos[i]) : (' ou '+signosTodos[i]);
					}
					console.error('Erro: Nao existe o signo "' + signo + '".\nEscolha '+textoTodosSignos+'.');
					return;
				}
				x(string, '.tabs-nav', ['a@href'])(function(err, data) { // isto e para ir buscar a duracaoTodos
					// a verificacao de previsor tem de vir antes da de duracao
					var textoTodosPrevisores = previsorTodos[0];
					for (var i = 1; i < previsorTodos.length; i++) {
						textoTodosPrevisores += (i !== previsorTodos.length - 1) ? (', '+previsorTodos[i]) : (' ou '+previsorTodos[i]);
					}
					if(previsorTodos.indexOf(previsor) === -1) {
						console.error('Erro: Nao existe o(a) previsor(a) "' + previsor + '".\nEscolha um de: '+textoTodosPrevisores+'.');
						return;
					}

					for (var i = 0; i < data.length; i++) {
						duracaoTodos.push(data[i].substring(data[i].lastIndexOf('#') + 1));
					}
					if(!duracao || duracao.length === 0 || duracao === '-') {
						duracao = duracaoTodos[0];
					} else {
						if(duracaoTodos.indexOf(duracao) === -1) { // duracao nao existe no array duracaoTodos
							console.error('Erro: ' + previsor + ' nao tem a opcao "' + duracao + '".\nEscolha "'+duracaoTodos.join('" ou "')+'".');
							return;
						}
					}

					x(string, '#'+duracao, ['p'])(function(err, data) {
						var output = "";
						for (var i = 0; i < data.length; i++) {
							output += (i !== data.length - 1) ? data[i] + '\n' : data[i];
						}
						output = output.replace(/<br\s*\/?>/mg,"\n");
						output = entities.decodeHTML(output);
						console.log(output);
					});
				});
			});
		});
	});
}<commit_msg>add [p@html]<commit_after>var xray = require('x-ray');
var x = xray();

var signo;
var previsor = 'maya';
var duracao;
var duracaoTodos = [];
var signosTodos = [];
var previsorTodos = [];

function help() {
	//console.log('Utilização: node '+basename(process.argv[1])+' <signo> [diaria|semanal|semanal-amor|mensal|anual] [previsor]');
	console.log('Utilização: horos <signo> [diaria|semanal|semanal-amor|mensal|anual] [previsor]');
}

function basename(file) {
	if(file.lastIndexOf('/') !== -1) {
		return file.substring(file.lastIndexOf('/') + 1);
	}
	else if(file.lastIndexOf('\\') !== -1) {
		return file.substring(file.lastIndexOf('\\') + 1);
	} else {
		return file;
	}
}

function adicionarOutrosSignos(arraySignos) {
	var signosMatch = ['carneiro', 'cancer', 'balanca'];
	var signosAdicionar = ['aries', 'caranguejo', 'libra'];

	if(arraySignos.length === 0) return;

	for (var i = 0; i < signosMatch.length; i++) {
		var insertIndex = arraySignos.indexOf(signosMatch[i]);
		if(insertIndex !== -1) {
			arraySignos.splice(insertIndex, 0, signosAdicionar[i]);
		}
	}
}

switch(process.argv.length) {
	case 3:
		signo = process.argv[2].toLowerCase();
		if(signo === '-h' || signo === '--help') {
			help();
			return;
		}
		break;
	case 4:
		signo = process.argv[2].toLowerCase();
		duracao = process.argv[3].toLowerCase();
		break;
	case 5:
		signo = process.argv[2].toLowerCase();
		duracao = process.argv[3].toLowerCase();
		previsor = process.argv[4].toLowerCase();
		break;
	default:
		help();
		return;
	break;
}

switch(signo) {
	case 'caranguejo':
		signo = 'cancer';
	break;
	case 'aries':
		signo = 'carneiro';
	break;
	case 'libra':
		signo = 'balanca';
	break;
}

var http = require('http');

var options = {
    host: 'lifestyle.sapo.pt',
    port: 80,
    path: '/astral/previsoes/'+previsor+'?signo='+signo
};

var content = "";

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        HTML2Horoscopo(content);
    });
});

req.on('error', function(err) {
	console.error('Não foi possivel conectar. Provavelmente tem a ligacao em baixo.');
	return;
});

req.end();

function HTML2Horoscopo(string) {
	x(string, '#astrological_sign option', ['@value'])(function(err, data) {
		for (var i = 0; i < data.length; i++) {
			signosTodos.push(data[i]);
		}
		adicionarOutrosSignos(signosTodos);
		x(string, '#predictor option',
			[{
				value: '@value',
				selected: '@selected'
			}]
			)(function(err, data) {
			for (var i = 0; i < data.length; i++) {
				var obj = data[i];
				previsorTodos.push(obj.value);
				//if(obj.selected === 'selected') previsor = obj.value;
			}

			var getRealDataPromise = new Promise(function(resolve, reject) {
				if(signosTodos.length !== 0 && previsorTodos.length !== 0)  return resolve();
				var options2 = {
				    host: 'lifestyle.sapo.pt',
				    port: 80,
				    path: '/astral/previsoes/maya?signo=carneiro'
				};

				var content2 = "";

				var req2 = http.request(options2, function(res2) {
				    res2.setEncoding("utf8");
				    res2.on("data", function (chunk2) {
				        content2 += chunk2;
				    });

				    res2.on("end", function () {
				        x(content2, '#astrological_sign option', ['@value'])(function(err, data) {
							for (var i = 0; i < data.length; i++) {
								signosTodos.push(data[i]);
							}
							adicionarOutrosSignos(signosTodos);
							x(content2, '#predictor option',
								[{
									value: '@value',
									selected: '@selected'
								}]
								)(function(err, data) {
								for (var i = 0; i < data.length; i++) {
									var obj = data[i];
									previsorTodos.push(obj.value);
									//if(obj.selected === 'selected') previsor = obj.value;
								}
								/*x(content2, '.tabs-nav', ['a@href'])(function(err, data) {
									for (var i = 0; i < data.length; i++) {
										duracaoTodos.push(data[i].substring(data[i].indexOf('#') + 1));
									}*/

									if(signosTodos.length !== 0 && previsorTodos.length !== 0)  return resolve();
									else {
										var erroMsg = "Nao consegui encontrar";
										if(signosTodos.length === 0) {
											erroMsg += " os signos e";
										}
										if(previsorTodos.length === 0) {
											erroMsg += " os previsores e";
										}

										erroMsg = erroMsg.replace(/e$/, "");
										erroMsg += "existentes."
										return reject(new Error(erroMsg));
									}
								//});
							});
						});
				    });
				});

				req2.on('error', function(err) {
					console.error('Não foi possivel conectar. Tente outra vez.');
					return;
				});

				req2.end();
			});

			getRealDataPromise.catch(function(err) {
				console.error('Erro: '+err.message);
				return;
			});
			getRealDataPromise.then(function() {
				if(signosTodos.indexOf(signo) === -1) {
					var textoTodosSignos = signosTodos[0];
					for (var i = 1; i < signosTodos.length; i++) {
						textoTodosSignos += (i !== signosTodos.length - 1) ? (', '+signosTodos[i]) : (' ou '+signosTodos[i]);
					}
					console.error('Erro: Nao existe o signo "' + signo + '".\nEscolha '+textoTodosSignos+'.');
					return;
				}
				x(string, '.tabs-nav', ['a@href'])(function(err, data) { // isto e para ir buscar a duracaoTodos
					// a verificacao de previsor tem de vir antes da de duracao
					var textoTodosPrevisores = previsorTodos[0];
					for (var i = 1; i < previsorTodos.length; i++) {
						textoTodosPrevisores += (i !== previsorTodos.length - 1) ? (', '+previsorTodos[i]) : (' ou '+previsorTodos[i]);
					}
					if(previsorTodos.indexOf(previsor) === -1) {
						console.error('Erro: Nao existe o(a) previsor(a) "' + previsor + '".\nEscolha um de: '+textoTodosPrevisores+'.');
						return;
					}

					for (var i = 0; i < data.length; i++) {
						duracaoTodos.push(data[i].substring(data[i].lastIndexOf('#') + 1));
					}
					if(!duracao || duracao.length === 0 || duracao === '-') {
						duracao = duracaoTodos[0];
					} else {
						if(duracaoTodos.indexOf(duracao) === -1) { // duracao nao existe no array duracaoTodos
							console.error('Erro: ' + previsor + ' nao tem a opcao "' + duracao + '".\nEscolha "'+duracaoTodos.join('" ou "')+'".');
							return;
						}
					}

					x(string, '#'+duracao, ['p@html'])(function(err, data) {
						var output = "";
						for (var i = 0; i < data.length; i++) {
							output += (i !== data.length - 1) ? data[i] + '\n' : data[i];
						}
						output = output.replace(/<br\s*\/?>/mg,"\n");
						output = entities.decodeHTML(output);
						console.log(output);
					});
				});
			});
		});
	});
}<|endoftext|>


<commit_before>(function() {
    'strict mode';

    global.minify = {};

    var DIR,
        LIBDIR,

        path,
        Util;

    /* Constants */
    exports.LIBDIR      = LIBDIR    = './',
    exports.DIR         = DIR       = LIBDIR + '../',

    /* Functions */
    exports.require                 = mrequire,
    exports.librequire              = librequire,
    exports.rootrequire             = rootrequire,

    /* Native Modules*/
    exports.crypto                  = require('crypto'),
    exports.fs                      = require('fs'),
    exports.path    = path          = require('path'),
    /* compitability with old versions of node */
    exports.fs.exists               = exports.fs.exists || exports.path.exists;

    exports.optimize                = optimize,

    /* Needed Modules */
    exports.util    = Util          = require('util-io');
    exports.mainpackage             = rootrequire('package');

    Util.getExtension               = path.extname;

    global.minify.main = exports;

    var html        = librequire('html'),
        js          = librequire('js'),
        css         = librequire('css');

    function optimize(params, callback) {
        var ret    = Util.checkObjTrue(params, ['ext', 'data']),
            p       = params;

        if (ret)
            switch(p.ext) {
                case '.js':
                    js._uglifyJS(p.data, callback);
                    break;

                case '.html':
                    html.htmlMinify(p.data, callback);
                    break;

                case '.css':
                    css._cleanCSS(p.data, callback);
                    break;
            }
    }

    /**
     * function do safe require of needed module
     * @param {String} src
     */
    function mrequire(pSrc) {
        var module;

        Util.exec.tryLog(function() {
            module = require(pSrc);
        });

        return module;
    }

    function rootrequire(pSrc) { return mrequire(DIR + pSrc); }

    function librequire(pSrc) { return mrequire(LIBDIR + pSrc); }

})();
<commit_msg>fix(main) strict mode -> use strict<commit_after>(function() {
    'use strict';

    global.minify = {};

    var DIR,
        LIBDIR,

        path,
        Util;

    /* Constants */
    exports.LIBDIR      = LIBDIR    = './',
    exports.DIR         = DIR       = LIBDIR + '../',

    /* Functions */
    exports.require                 = mrequire,
    exports.librequire              = librequire,
    exports.rootrequire             = rootrequire,

    /* Native Modules*/
    exports.crypto                  = require('crypto'),
    exports.fs                      = require('fs'),
    exports.path    = path          = require('path'),
    /* compitability with old versions of node */
    exports.fs.exists               = exports.fs.exists || exports.path.exists;

    exports.optimize                = optimize,

    /* Needed Modules */
    exports.util    = Util          = require('util-io');
    exports.mainpackage             = rootrequire('package');

    Util.getExtension               = path.extname;

    global.minify.main = exports;

    var html        = librequire('html'),
        js          = librequire('js'),
        css         = librequire('css');

    function optimize(params, callback) {
        var ret    = Util.checkObjTrue(params, ['ext', 'data']),
            p       = params;

        if (ret)
            switch(p.ext) {
                case '.js':
                    js._uglifyJS(p.data, callback);
                    break;

                case '.html':
                    html.htmlMinify(p.data, callback);
                    break;

                case '.css':
                    css._cleanCSS(p.data, callback);
                    break;
            }
    }

    /**
     * function do safe require of needed module
     * @param {String} src
     */
    function mrequire(pSrc) {
        var module;

        Util.exec.tryLog(function() {
            module = require(pSrc);
        });

        return module;
    }

    function rootrequire(pSrc) { return mrequire(DIR + pSrc); }

    function librequire(pSrc) { return mrequire(LIBDIR + pSrc); }

})();
<|endoftext|>


<commit_before>const leftPad = require('left-pad')
const xor = require('bitwise-xor')

var Web3 = require('web3')
var web3 = new Web3()

const { sha3 } = require('./hash.js')

function getAddress (pub) {
  return '0x' + sha3(pub).slice(-20).toString('hex')
}

// ------------------------
// load the contract abi
// we only care about one function
var abi = [{
  constant: false,
  inputs: [
    {
      name: '_donor',
      type: 'address'
    },
    {
      name: '_returnAddress',
      type: 'address'
    },
    {
      name: 'checksum',
      type: 'bytes32'
    }
  ],
  name: 'donate',
  outputs: [],
  payable: true,
  type: 'function'
}]

let MyContract = web3.eth.contract(abi)
var contractInstance = MyContract.at('0x00')

function getTransactionData (cosmosAddr, ethAddr) {
  // checksum is sha3(xor(cosmosAddr, ethAddr)
  var paddedCosmos = leftPad(web3.toAscii(cosmosAddr), 32, '\x00')
  var paddedEth = leftPad(web3.toAscii(ethAddr), 32, '\x00')
  var xord = xor(
    Buffer(paddedCosmos, 'ascii'),
    Buffer(paddedEth, 'ascii')
  )
  var checksum = web3.sha3(xord.toString('hex'), {encoding: 'hex'})

  return contractInstance.donate.getData(cosmosAddr, ethAddr, checksum)
}

module.exports = {
  getAddress,
  getTransactionData
}
<commit_msg>Added ATOMS_PER_ETH constant<commit_after>const leftPad = require('left-pad')
const xor = require('bitwise-xor')

var Web3 = require('web3')
var web3 = new Web3()

const { sha3 } = require('./hash.js')

const ATOMS_PER_ETH = 2000

function getAddress (pub) {
  return '0x' + sha3(pub).slice(-20).toString('hex')
}

// ------------------------
// load the contract abi
// we only care about one function
var abi = [{
  constant: false,
  inputs: [
    {
      name: '_donor',
      type: 'address'
    },
    {
      name: '_returnAddress',
      type: 'address'
    },
    {
      name: 'checksum',
      type: 'bytes32'
    }
  ],
  name: 'donate',
  outputs: [],
  payable: true,
  type: 'function'
}]

let MyContract = web3.eth.contract(abi)
var contractInstance = MyContract.at('0x00')

function getTransactionData (cosmosAddr, ethAddr) {
  // checksum is sha3(xor(cosmosAddr, ethAddr)
  var paddedCosmos = leftPad(web3.toAscii(cosmosAddr), 32, '\x00')
  var paddedEth = leftPad(web3.toAscii(ethAddr), 32, '\x00')
  var xord = xor(
    Buffer(paddedCosmos, 'ascii'),
    Buffer(paddedEth, 'ascii')
  )
  var checksum = web3.sha3(xord.toString('hex'), {encoding: 'hex'})

  return contractInstance.donate.getData(cosmosAddr, ethAddr, checksum)
}

module.exports = {
  getAddress,
  getTransactionData,
  ATOMS_PER_ETH
}
<|endoftext|>


<commit_before>'use strict'

const LRU = require('lru-cache')
const FS = require('fs')

class SmartCache {
  constructor(cacheOptions, cacheValidator, cacheFetcher) {
    if (!cacheOptions) {
      cacheOptions = {max: 500, maxAge: 1000 * 60 * 60 * 24}
    }
    this.cache = new LRU(cacheOptions)
    this.cacheStats = new Map()
    this.validate = cacheValidator || SmartCache.DefaultValidator
    this.fetch = cacheFetcher || SmartCache.DefaultFetcher
  }

  get(filePath) {
    const Me = this
    return this.validate(filePath, this.cacheStats.get(filePath))
      .then(function(newValue) {
        if (newValue !== false || !this.cache.has(filePath)) {
          Me.cacheStats.set(filePath, newValue)
          return Me.fetch(filePath).then(function(contents) {
            Me.cache.set(filePath, contents)
            return contents
          })
        }
        return Me.cache.get(filePath)
      })
  }

  dispose() {
    this.cache.reset()
    this.cacheStats.clear()
  }

  // Return false to use previous result
  // Return anything else to be saved in oldValue and trigger fetch
  static DefaultValidator(filePath, oldValue) {
    const Deferred = Promise.defer()
    FS.stat(filePath, function(err, stats) {
      if (err) Deferred.resolve(false)
      else {
        const newValue = stats.ctime.toString()
        if (oldValue === newValue) Deferred.resolve(false)
        else Deferred.resolve(stats.ctime.toString())
      }
    })
    return Deferred.promise
  }

  static DefaultFetcher(filePath) {
    const Deferred = Promise.defer()
    FS.readFile(filePath, function(err, data) {
      if (err) Deferred.reject(err)
      else Deferred.resolve(data.toString())
    })
    return Deferred.promise
  }
}

module.exports = SmartCache
<commit_msg>:bug: Fix just another typo<commit_after>'use strict'

const LRU = require('lru-cache')
const FS = require('fs')

class SmartCache {
  constructor(cacheOptions, cacheValidator, cacheFetcher) {
    if (!cacheOptions) {
      cacheOptions = {max: 500, maxAge: 1000 * 60 * 60 * 24}
    }
    this.cache = new LRU(cacheOptions)
    this.cacheStats = new Map()
    this.validate = cacheValidator || SmartCache.DefaultValidator
    this.fetch = cacheFetcher || SmartCache.DefaultFetcher
  }

  get(filePath) {
    const Me = this
    return this.validate(filePath, this.cacheStats.get(filePath))
      .then(function(newValue) {
        if (newValue !== false || !Me.cache.has(filePath)) {
          Me.cacheStats.set(filePath, newValue)
          return Me.fetch(filePath).then(function(contents) {
            Me.cache.set(filePath, contents)
            return contents
          })
        }
        return Me.cache.get(filePath)
      })
  }

  dispose() {
    this.cache.reset()
    this.cacheStats.clear()
  }

  // Return false to use previous result
  // Return anything else to be saved in oldValue and trigger fetch
  static DefaultValidator(filePath, oldValue) {
    const Deferred = Promise.defer()
    FS.stat(filePath, function(err, stats) {
      if (err) Deferred.resolve(false)
      else {
        const newValue = stats.ctime.toString()
        if (oldValue === newValue) Deferred.resolve(false)
        else Deferred.resolve(stats.ctime.toString())
      }
    })
    return Deferred.promise
  }

  static DefaultFetcher(filePath) {
    const Deferred = Promise.defer()
    FS.readFile(filePath, function(err, data) {
      if (err) Deferred.reject(err)
      else Deferred.resolve(data.toString())
    })
    return Deferred.promise
  }
}

module.exports = SmartCache
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const self = require("sdk/self");
const panels = require("sdk/panel");
const utils = require("sdk/window/utils");
const system = require("sdk/system");
const winUtils = require("sdk/deprecated/window-utils");
const {storage} = require("sdk/simple-storage");
const {ActionButton} = require("sdk/ui/button/action");

// Import shared modifiers code.
const gModifiers = eval(self.data.load("shared-modifiers.js") + "gModifiers");

const hotkeys = require("hotkeys");
const command = require("command");

let panel = panels.Panel({
  width: 500,
  height: 500,
  contentURL: "chrome://customizable-shortcuts/content/panel.xul",
  contentScriptWhen: "ready",

  contentScriptFile: [
    "panel-bug995889.js",
    "panel-buttons.js",
    "panel-treeview.js",
    "panel-hotkeys.js",
    "panel-tree.js",
    "panel-keygroups.js",
    "panel-overlays.js",
    "panel-conflicts.js",
    "shared-modifiers.js",
    "panel.js"
  ].map(file => self.data.url(file)),

  onShow() {
    panel.port.emit("showing");
  },

  onHide() {
    panel.port.emit("hiding");
  }
});

let {getActiveView} = require("sdk/view/core");
let view = getActiveView(panel);
view.setAttribute("ignorekeys", "true");
view.setAttribute("noautohide", "true");

panel.port.on("ready", function () {
  panel.port.emit("platform", gPlatform = system.platform);
  panel.port.emit("overlays", gOverlays = storage.overlays || {});
  panel.port.emit("hotkeys", gHotKeys = hotkeys.get());
});

panel.port.on("hide", () => panel.hide());

let button = ActionButton({
  id: "shortcuts-button",
  label: "Customize Shortcuts",

  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png"
  },

  onClick: function () {
    panel.show({position: button});
  }
});

new winUtils.WindowTracker({
  onTrack(window) {
    if (utils.isBrowser(window)) {
      window.addEventListener("keydown", handlePossibleShortcut);
      window.addEventListener("mousedown", maybeHidePanel);
    }
  },

  onUntrack(window) {
    if (utils.isBrowser(window)) {
      window.removeEventListener("keydown", handlePossibleShortcut);
      window.removeEventListener("mousedown", maybeHidePanel);
    }
  }
});

let gPlatform;
let gHotKeys = {};
let gOverlays = {};

panel.port.on("overlays", function (overlays) {
  storage.overlays = gOverlays = overlays;
});

function findOverlay(event) {
  let evmodifiers = gModifiers.fromEvent(event);

  return Object.keys(gOverlays).find(id => {
    let {disabled, key, modifiers} = gOverlays[id];
    return !disabled && event.key == key && evmodifiers == modifiers;
  });
}

function findOverridden(event) {
  let modifiers = gModifiers.fromEvent(event);

  return Object.keys(gOverlays).map(id => gHotKeys[id]).some(hotkey => {
    return event.key == hotkey.key && modifiers == hotkey.modifiers;
  });
}

function handlePossibleShortcut(event) {
  // Ignore synthetic events.
  if (!event.isTrusted) {
    return;
  }

  let overlay = findOverlay(event);

  if (overlay) {
    command.execute(overlay);
  } else {
    overlay = findOverridden(event);
  }

  if (overlay) {
    event.preventDefault();
    event.stopPropagation();
  }
}

function maybeHidePanel(event) {
  panel.hide();
}
<commit_msg>use different storage key for new data format, fixes #89<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const self = require("sdk/self");
const panels = require("sdk/panel");
const utils = require("sdk/window/utils");
const system = require("sdk/system");
const winUtils = require("sdk/deprecated/window-utils");
const {storage} = require("sdk/simple-storage");
const {ActionButton} = require("sdk/ui/button/action");

// Import shared modifiers code.
const gModifiers = eval(self.data.load("shared-modifiers.js") + "gModifiers");

const hotkeys = require("hotkeys");
const command = require("command");

// Storage v2.
const STORAGE_KEY = "overlays_v2";

let panel = panels.Panel({
  width: 500,
  height: 500,
  contentURL: "chrome://customizable-shortcuts/content/panel.xul",
  contentScriptWhen: "ready",

  contentScriptFile: [
    "panel-bug995889.js",
    "panel-buttons.js",
    "panel-treeview.js",
    "panel-hotkeys.js",
    "panel-tree.js",
    "panel-keygroups.js",
    "panel-overlays.js",
    "panel-conflicts.js",
    "shared-modifiers.js",
    "panel.js"
  ].map(file => self.data.url(file)),

  onShow() {
    panel.port.emit("showing");
  },

  onHide() {
    panel.port.emit("hiding");
  }
});

let {getActiveView} = require("sdk/view/core");
let view = getActiveView(panel);
view.setAttribute("ignorekeys", "true");
view.setAttribute("noautohide", "true");

panel.port.on("ready", function () {
  panel.port.emit("platform", gPlatform = system.platform);
  panel.port.emit("overlays", gOverlays = storage[STORAGE_KEY] || {});
  panel.port.emit("hotkeys", gHotKeys = hotkeys.get());
});

panel.port.on("hide", () => panel.hide());

let button = ActionButton({
  id: "shortcuts-button",
  label: "Customize Shortcuts",

  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png"
  },

  onClick: function () {
    panel.show({position: button});
  }
});

new winUtils.WindowTracker({
  onTrack(window) {
    if (utils.isBrowser(window)) {
      window.addEventListener("keydown", handlePossibleShortcut);
      window.addEventListener("mousedown", maybeHidePanel);
    }
  },

  onUntrack(window) {
    if (utils.isBrowser(window)) {
      window.removeEventListener("keydown", handlePossibleShortcut);
      window.removeEventListener("mousedown", maybeHidePanel);
    }
  }
});

let gPlatform;
let gHotKeys = {};
let gOverlays = {};

panel.port.on("overlays", function (overlays) {
  storage[STORAGE_KEY] = gOverlays = overlays;
});

function findOverlay(event) {
  let evmodifiers = gModifiers.fromEvent(event);

  return Object.keys(gOverlays).find(id => {
    let {disabled, key, modifiers} = gOverlays[id];
    return !disabled && event.key == key && evmodifiers == modifiers;
  });
}

function findOverridden(event) {
  let modifiers = gModifiers.fromEvent(event);

  return Object.keys(gOverlays).map(id => gHotKeys[id]).some(hotkey => {
    return event.key == hotkey.key && modifiers == hotkey.modifiers;
  });
}

function handlePossibleShortcut(event) {
  // Ignore synthetic events.
  if (!event.isTrusted) {
    return;
  }

  let overlay = findOverlay(event);

  if (overlay) {
    command.execute(overlay);
  } else {
    overlay = findOverridden(event);
  }

  if (overlay) {
    event.preventDefault();
    event.stopPropagation();
  }
}

function maybeHidePanel(event) {
  panel.hide();
}
<|endoftext|>


<commit_before>/* @flow */

import {
  Emitter,
  CompositeDisposable,
  Disposable,
  Point,
  TextEditor
} from "atom";

import _ from "lodash";
import { autorun } from "mobx";
import React from "react";

import KernelPicker from "./kernel-picker";
import WSKernelPicker from "./ws-kernel-picker";
import ExistingKernelPicker from "./existing-kernel-picker";
import SignalListView from "./signal-list-view";
import * as codeManager from "./code-manager";

import Inspector from "./components/inspector";
import ResultView from "./components/result-view";
import StatusBar from "./components/status-bar";

import InspectorPane from "./panes/inspector";
import WatchesPane from "./panes/watches";
import OutputPane from "./panes/output-area";
import KernelMonitorPane from "./panes/kernel-monitor";

import { toggleInspector } from "./commands";

import store from "./store";
import OutputStore from "./store/output";

import Config from "./config";
import kernelManager from "./kernel-manager";
import ZMQKernel from "./zmq-kernel";
import WSKernel from "./ws-kernel";
import AutocompleteProvider from "./autocomplete-provider";
import HydrogenProvider from "./plugin-api/hydrogen-provider";

import {
  log,
  reactFactory,
  isMultilanguageGrammar,
  renderDevTools,
  INSPECTOR_URI,
  WATCHES_URI,
  OUTPUT_AREA_URI,
  KERNEL_MONITOR_URI,
  hotReloadPackage,
  openOrShowDock,
  kernelSpecProvidesGrammar
} from "./utils";

import type Kernel from "./kernel";

import exportNotebook from "./export-notebook";

const Hydrogen = {
  config: Config.schema,

  activate() {
    this.emitter = new Emitter();

    let skipLanguageMappingsChange = false;
    store.subscriptions.add(
      atom.config.onDidChange(
        "Hydrogen.languageMappings",
        ({ newValue, oldValue }) => {
          if (skipLanguageMappingsChange) {
            skipLanguageMappingsChange = false;
            return;
          }

          if (store.runningKernels.length != 0) {
            skipLanguageMappingsChange = true;

            atom.config.set("Hydrogen.languageMappings", oldValue);

            atom.notifications.addError("Hydrogen", {
              description:
                "`languageMappings` cannot be updated while kernels are running",
              dismissable: false
            });
          }
        }
      )
    );

    store.subscriptions.add(
      // enable/disable mobx-react-devtools logging
      atom.config.onDidChange("Hydrogen.debug", ({ newValue }) =>
        renderDevTools(newValue)
      )
    );

    store.subscriptions.add(
      atom.config.observe("Hydrogen.statusBarDisable", newValue => {
        store.setConfigValue("Hydrogen.statusBarDisable", Boolean(newValue));
      })
    );

    store.subscriptions.add(
      atom.commands.add("atom-text-editor:not([mini])", {
        "hydrogen:run": () => this.run(),
        "hydrogen:run-all": () => this.runAll(),
        "hydrogen:run-all-above": () => this.runAllAbove(),
        "hydrogen:run-and-move-down": () => this.run(true),
        "hydrogen:run-cell": () => this.runCell(),
        "hydrogen:run-cell-and-move-down": () => this.runCell(true),
        "hydrogen:toggle-watches": () => atom.workspace.toggle(WATCHES_URI),
        "hydrogen:toggle-output-area": () =>
          atom.workspace.toggle(OUTPUT_AREA_URI),
        "hydrogen:toggle-kernel-monitor": () =>
          atom.workspace.toggle(KERNEL_MONITOR_URI),
        "hydrogen:start-local-kernel": () => this.startZMQKernel(),
        "hydrogen:connect-to-remote-kernel": () => this.connectToWSKernel(),
        "hydrogen:connect-to-existing-kernel": () =>
          this.connectToExistingKernel(),
        "hydrogen:add-watch": () => {
          if (store.kernel) {
            store.kernel.watchesStore.addWatchFromEditor(store.editor);
            openOrShowDock(WATCHES_URI);
          }
        },
        "hydrogen:remove-watch": () => {
          if (store.kernel) {
            store.kernel.watchesStore.removeWatch();
            openOrShowDock(WATCHES_URI);
          }
        },
        "hydrogen:update-kernels": () => kernelManager.updateKernelSpecs(),
        "hydrogen:toggle-inspector": () => toggleInspector(store),
        "hydrogen:interrupt-kernel": () =>
          this.handleKernelCommand({ command: "interrupt-kernel" }),
        "hydrogen:restart-kernel": () =>
          this.handleKernelCommand({ command: "restart-kernel" }),
        "hydrogen:restart-kernel-and-re-evaluate-bubbles": () =>
          this.restartKernelAndReEvaluateBubbles(),
        "hydrogen:shutdown-kernel": () =>
          this.handleKernelCommand({ command: "shutdown-kernel" }),
        "hydrogen:toggle-bubble": () => this.toggleBubble(),
        "hydrogen:export-notebook": () => exportNotebook()
      })
    );

    store.subscriptions.add(
      atom.commands.add("atom-workspace", {
        "hydrogen:clear-results": () => {
          store.markers.clear();
          if (!store.kernel) return;
          store.kernel.outputStore.clear();
        }
      })
    );

    if (atom.inDevMode()) {
      store.subscriptions.add(
        atom.commands.add("atom-workspace", {
          "hydrogen:hot-reload-package": () => hotReloadPackage()
        })
      );
    }

    store.subscriptions.add(
      atom.workspace.observeActiveTextEditor(editor => {
        store.updateEditor(editor);
      })
    );

    store.subscriptions.add(
      atom.workspace.observeTextEditors(editor => {
        const editorSubscriptions = new CompositeDisposable();
        editorSubscriptions.add(
          editor.onDidChangeGrammar(() => {
            store.setGrammar(editor);
          })
        );

        if (isMultilanguageGrammar(editor.getGrammar())) {
          editorSubscriptions.add(
            editor.onDidChangeCursorPosition(
              _.debounce(() => {
                store.setGrammar(editor);
              }, 75)
            )
          );
        }

        editorSubscriptions.add(
          editor.onDidDestroy(() => {
            editorSubscriptions.dispose();
          })
        );

        store.subscriptions.add(editorSubscriptions);
      })
    );

    this.hydrogenProvider = null;

    store.subscriptions.add(
      atom.workspace.addOpener(uri => {
        switch (uri) {
          case INSPECTOR_URI:
            return new InspectorPane(store);
          case WATCHES_URI:
            return new WatchesPane(store);
          case OUTPUT_AREA_URI:
            return new OutputPane(store);
          case KERNEL_MONITOR_URI:
            return new KernelMonitorPane(store);
        }
      })
    );

    store.subscriptions.add(
      // Destroy any Panes when the package is deactivated.
      new Disposable(() => {
        atom.workspace.getPaneItems().forEach(item => {
          if (
            item instanceof InspectorPane ||
            item instanceof WatchesPane ||
            item instanceof OutputPane ||
            item instanceof KernelMonitorPane
          ) {
            item.destroy();
          }
        });
      })
    );

    renderDevTools(atom.config.get("Hydrogen.debug") === true);

    autorun(() => {
      this.emitter.emit("did-change-kernel", store.kernel);
    });
  },

  deactivate() {
    store.dispose();
  },

  provideHydrogen() {
    if (!this.hydrogenProvider) {
      this.hydrogenProvider = new HydrogenProvider(this);
    }

    return this.hydrogenProvider;
  },

  consumeStatusBar(statusBar: atom$StatusBar) {
    const statusBarElement = document.createElement("div");
    statusBarElement.className = "inline-block";

    statusBar.addLeftTile({
      item: statusBarElement,
      priority: 100
    });

    const onClick = this.showKernelCommands.bind(this);

    reactFactory(
      <StatusBar store={store} onClick={onClick} />,
      statusBarElement
    );

    // We should return a disposable here but Atom fails while calling .destroy()
    // return new Disposable(statusBarTile.destroy);
  },

  provide() {
    if (atom.config.get("Hydrogen.autocomplete") === true) {
      return AutocompleteProvider();
    }
    return null;
  },

  showKernelCommands() {
    if (!this.signalListView) {
      this.signalListView = new SignalListView();
      this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
        this.handleKernelCommand(kernelCommand);
    }
    this.signalListView.toggle();
  },

  connectToExistingKernel() {
    if (!this.existingKernelPicker) {
      this.existingKernelPicker = new ExistingKernelPicker();
    }
    this.existingKernelPicker.toggle();
  },

  handleKernelCommand({
    command,
    payload
  }: {
    command: string,
    payload: ?Kernelspec
  }) {
    log("handleKernelCommand:", arguments);

    const { kernel, grammar } = store;

    if (!grammar) {
      atom.notifications.addError("Undefined grammar");
      return;
    }

    if (!kernel) {
      const message = `No running kernel for grammar \`${grammar.name}\` found`;
      atom.notifications.addError(message);
      return;
    }

    if (command === "interrupt-kernel") {
      kernel.interrupt();
    } else if (command === "restart-kernel") {
      kernel.restart();
    } else if (command === "shutdown-kernel") {
      store.markers.clear();
      // Note that destroy alone does not shut down a WSKernel
      kernel.shutdown();
      kernel.destroy();
    } else if (command === "rename-kernel" && kernel.promptRename) {
      // $FlowFixMe Will only be called if remote kernel
      if (kernel instanceof WSKernel) kernel.promptRename();
    } else if (command === "disconnect-kernel") {
      store.markers.clear();
      kernel.destroy();
    }
  },

  createResultBubble(editor: atom$TextEditor, code: string, row: number) {
    const { grammar, filePath, kernel } = store;
    if (!grammar || !filePath) return;

    if (kernel) {
      this._createResultBubble(editor, kernel, code, row);
      return;
    }

    kernelManager.startKernelFor(
      grammar,
      editor,
      filePath,
      (kernel: ZMQKernel) => {
        this._createResultBubble(editor, kernel, code, row);
      }
    );
  },

  _createResultBubble(
    editor: atom$TextEditor,
    kernel: Kernel,
    code: string,
    row: number
  ) {
    if (atom.workspace.getActivePaneItem() instanceof WatchesPane) {
      kernel.watchesStore.run();
      return;
    }
    const globalOutputStore =
      atom.config.get("Hydrogen.outputAreaDefault") ||
      atom.workspace.getPaneItems().find(item => item instanceof OutputPane)
        ? kernel.outputStore
        : null;

    if (globalOutputStore) openOrShowDock(OUTPUT_AREA_URI);

    const { outputStore } = new ResultView(
      store.markers,
      kernel,
      editor,
      row,
      !globalOutputStore
    );

    kernel.execute(code, result => {
      outputStore.appendOutput(result);
      if (globalOutputStore) globalOutputStore.appendOutput(result);
    });
  },

  restartKernelAndReEvaluateBubbles() {
    const { editor, kernel, markers } = store;

    let breakpoints = [];
    markers.markers.forEach((bubble: ResultView) => {
      breakpoints.push(bubble.marker.getBufferRange().start);
    });
    store.markers.clear();

    if (!editor || !kernel) {
      this.runAll(breakpoints);
    } else {
      kernel.restart(() => this.runAll(breakpoints));
    }
  },

  toggleBubble() {
    const { editor, kernel, markers } = store;
    if (!editor) return;
    const [startRow, endRow] = editor.getLastSelection().getBufferRowRange();

    for (let row = startRow; row <= endRow; row++) {
      const destroyed = markers.clearOnRow(row);

      if (!destroyed) {
        const { outputStore } = new ResultView(
          markers,
          kernel,
          editor,
          row,
          true
        );
        outputStore.status = "empty";
      }
    }
  },

  run(moveDown: boolean = false) {
    const editor = store.editor;
    if (!editor) return;
    const codeBlock = codeManager.findCodeBlock(editor);
    if (!codeBlock) {
      return;
    }

    const [code, row] = codeBlock;
    if (code) {
      if (moveDown === true) {
        codeManager.moveDown(editor, row);
      }
      this.createResultBubble(editor, code, row);
    }
  },

  runAll(breakpoints: ?Array<atom$Point>) {
    const { editor, kernel, grammar, filePath } = store;
    if (!editor || !grammar || !filePath) return;
    if (isMultilanguageGrammar(editor.getGrammar())) {
      atom.notifications.addError(
        '"Run All" is not supported for this file type!'
      );
      return;
    }

    if (editor && kernel) {
      this._runAll(editor, kernel, breakpoints);
      return;
    }

    kernelManager.startKernelFor(
      grammar,
      editor,
      filePath,
      (kernel: ZMQKernel) => {
        this._runAll(editor, kernel, breakpoints);
      }
    );
  },

  _runAll(
    editor: atom$TextEditor,
    kernel: Kernel,
    breakpoints?: Array<atom$Point>
  ) {
    let cells = codeManager.getCells(editor, breakpoints);
    _.forEach(
      cells,
      ({ start, end }: { start: atom$Point, end: atom$Point }) => {
        const code = codeManager.getTextInRange(editor, start, end);
        const endRow = codeManager.escapeBlankRows(editor, start.row, end.row);
        this._createResultBubble(editor, kernel, code, endRow);
      }
    );
  },

  runAllAbove() {
    const editor = store.editor; // to make flow happy
    if (!editor) return;
    if (isMultilanguageGrammar(editor.getGrammar())) {
      atom.notifications.addError(
        '"Run All Above" is not supported for this file type!'
      );
      return;
    }

    const cursor = editor.getLastCursor();
    const row = codeManager.escapeBlankRows(editor, 0, cursor.getBufferRow());
    const code = codeManager.getRows(editor, 0, row);

    if (code) {
      this.createResultBubble(editor, code, row);
    }
  },

  runCell(moveDown: boolean = false) {
    const editor = store.editor;
    if (!editor) return;
    const { start, end } = codeManager.getCurrentCell(editor);
    const code = codeManager.getTextInRange(editor, start, end);
    const endRow = codeManager.escapeBlankRows(editor, start.row, end.row);

    if (code) {
      if (moveDown === true) {
        codeManager.moveDown(editor, endRow);
      }
      this.createResultBubble(editor, code, endRow);
    }
  },

  startZMQKernel() {
    kernelManager
      .getAllKernelSpecsForGrammar(store.grammar)
      .then(kernelSpecs => {
        if (this.kernelPicker) {
          this.kernelPicker.kernelSpecs = kernelSpecs;
        } else {
          this.kernelPicker = new KernelPicker(kernelSpecs);

          this.kernelPicker.onConfirmed = (kernelSpec: Kernelspec) => {
            const { editor, grammar, filePath } = store;
            if (!editor || !grammar || !filePath) return;
            store.markers.clear();

            kernelManager.startKernel(kernelSpec, grammar, editor, filePath);
          };
        }

        this.kernelPicker.toggle();
      });
  },

  connectToWSKernel() {
    if (!this.wsKernelPicker) {
      this.wsKernelPicker = new WSKernelPicker((kernel: Kernel) => {
        store.markers.clear();
        const { editor, grammar, filePath } = store;
        if (!editor || !grammar || !filePath) return;

        if (kernel instanceof ZMQKernel) kernel.destroy();

        store.newKernel(kernel, filePath, editor, grammar);
      });
    }

    this.wsKernelPicker.toggle((kernelSpec: Kernelspec) =>
      kernelSpecProvidesGrammar(kernelSpec, store.grammar)
    );
  }
};

export default Hydrogen;
<commit_msg>Add message when startup cancels due to unsaved file (#1161)<commit_after>/* @flow */

import {
  Emitter,
  CompositeDisposable,
  Disposable,
  Point,
  TextEditor
} from "atom";

import _ from "lodash";
import { autorun } from "mobx";
import React from "react";

import KernelPicker from "./kernel-picker";
import WSKernelPicker from "./ws-kernel-picker";
import ExistingKernelPicker from "./existing-kernel-picker";
import SignalListView from "./signal-list-view";
import * as codeManager from "./code-manager";

import Inspector from "./components/inspector";
import ResultView from "./components/result-view";
import StatusBar from "./components/status-bar";

import InspectorPane from "./panes/inspector";
import WatchesPane from "./panes/watches";
import OutputPane from "./panes/output-area";
import KernelMonitorPane from "./panes/kernel-monitor";

import { toggleInspector } from "./commands";

import store from "./store";
import OutputStore from "./store/output";

import Config from "./config";
import kernelManager from "./kernel-manager";
import ZMQKernel from "./zmq-kernel";
import WSKernel from "./ws-kernel";
import AutocompleteProvider from "./autocomplete-provider";
import HydrogenProvider from "./plugin-api/hydrogen-provider";

import {
  log,
  reactFactory,
  isMultilanguageGrammar,
  renderDevTools,
  INSPECTOR_URI,
  WATCHES_URI,
  OUTPUT_AREA_URI,
  KERNEL_MONITOR_URI,
  hotReloadPackage,
  openOrShowDock,
  kernelSpecProvidesGrammar
} from "./utils";

import type Kernel from "./kernel";

import exportNotebook from "./export-notebook";

const Hydrogen = {
  config: Config.schema,

  activate() {
    this.emitter = new Emitter();

    let skipLanguageMappingsChange = false;
    store.subscriptions.add(
      atom.config.onDidChange(
        "Hydrogen.languageMappings",
        ({ newValue, oldValue }) => {
          if (skipLanguageMappingsChange) {
            skipLanguageMappingsChange = false;
            return;
          }

          if (store.runningKernels.length != 0) {
            skipLanguageMappingsChange = true;

            atom.config.set("Hydrogen.languageMappings", oldValue);

            atom.notifications.addError("Hydrogen", {
              description:
                "`languageMappings` cannot be updated while kernels are running",
              dismissable: false
            });
          }
        }
      )
    );

    store.subscriptions.add(
      // enable/disable mobx-react-devtools logging
      atom.config.onDidChange("Hydrogen.debug", ({ newValue }) =>
        renderDevTools(newValue)
      )
    );

    store.subscriptions.add(
      atom.config.observe("Hydrogen.statusBarDisable", newValue => {
        store.setConfigValue("Hydrogen.statusBarDisable", Boolean(newValue));
      })
    );

    store.subscriptions.add(
      atom.commands.add("atom-text-editor:not([mini])", {
        "hydrogen:run": () => this.run(),
        "hydrogen:run-all": () => this.runAll(),
        "hydrogen:run-all-above": () => this.runAllAbove(),
        "hydrogen:run-and-move-down": () => this.run(true),
        "hydrogen:run-cell": () => this.runCell(),
        "hydrogen:run-cell-and-move-down": () => this.runCell(true),
        "hydrogen:toggle-watches": () => atom.workspace.toggle(WATCHES_URI),
        "hydrogen:toggle-output-area": () =>
          atom.workspace.toggle(OUTPUT_AREA_URI),
        "hydrogen:toggle-kernel-monitor": () =>
          atom.workspace.toggle(KERNEL_MONITOR_URI),
        "hydrogen:start-local-kernel": () => this.startZMQKernel(),
        "hydrogen:connect-to-remote-kernel": () => this.connectToWSKernel(),
        "hydrogen:connect-to-existing-kernel": () =>
          this.connectToExistingKernel(),
        "hydrogen:add-watch": () => {
          if (store.kernel) {
            store.kernel.watchesStore.addWatchFromEditor(store.editor);
            openOrShowDock(WATCHES_URI);
          }
        },
        "hydrogen:remove-watch": () => {
          if (store.kernel) {
            store.kernel.watchesStore.removeWatch();
            openOrShowDock(WATCHES_URI);
          }
        },
        "hydrogen:update-kernels": () => kernelManager.updateKernelSpecs(),
        "hydrogen:toggle-inspector": () => toggleInspector(store),
        "hydrogen:interrupt-kernel": () =>
          this.handleKernelCommand({ command: "interrupt-kernel" }),
        "hydrogen:restart-kernel": () =>
          this.handleKernelCommand({ command: "restart-kernel" }),
        "hydrogen:restart-kernel-and-re-evaluate-bubbles": () =>
          this.restartKernelAndReEvaluateBubbles(),
        "hydrogen:shutdown-kernel": () =>
          this.handleKernelCommand({ command: "shutdown-kernel" }),
        "hydrogen:toggle-bubble": () => this.toggleBubble(),
        "hydrogen:export-notebook": () => exportNotebook()
      })
    );

    store.subscriptions.add(
      atom.commands.add("atom-workspace", {
        "hydrogen:clear-results": () => {
          store.markers.clear();
          if (!store.kernel) return;
          store.kernel.outputStore.clear();
        }
      })
    );

    if (atom.inDevMode()) {
      store.subscriptions.add(
        atom.commands.add("atom-workspace", {
          "hydrogen:hot-reload-package": () => hotReloadPackage()
        })
      );
    }

    store.subscriptions.add(
      atom.workspace.observeActiveTextEditor(editor => {
        store.updateEditor(editor);
      })
    );

    store.subscriptions.add(
      atom.workspace.observeTextEditors(editor => {
        const editorSubscriptions = new CompositeDisposable();
        editorSubscriptions.add(
          editor.onDidChangeGrammar(() => {
            store.setGrammar(editor);
          })
        );

        if (isMultilanguageGrammar(editor.getGrammar())) {
          editorSubscriptions.add(
            editor.onDidChangeCursorPosition(
              _.debounce(() => {
                store.setGrammar(editor);
              }, 75)
            )
          );
        }

        editorSubscriptions.add(
          editor.onDidDestroy(() => {
            editorSubscriptions.dispose();
          })
        );

        store.subscriptions.add(editorSubscriptions);
      })
    );

    this.hydrogenProvider = null;

    store.subscriptions.add(
      atom.workspace.addOpener(uri => {
        switch (uri) {
          case INSPECTOR_URI:
            return new InspectorPane(store);
          case WATCHES_URI:
            return new WatchesPane(store);
          case OUTPUT_AREA_URI:
            return new OutputPane(store);
          case KERNEL_MONITOR_URI:
            return new KernelMonitorPane(store);
        }
      })
    );

    store.subscriptions.add(
      // Destroy any Panes when the package is deactivated.
      new Disposable(() => {
        atom.workspace.getPaneItems().forEach(item => {
          if (
            item instanceof InspectorPane ||
            item instanceof WatchesPane ||
            item instanceof OutputPane ||
            item instanceof KernelMonitorPane
          ) {
            item.destroy();
          }
        });
      })
    );

    renderDevTools(atom.config.get("Hydrogen.debug") === true);

    autorun(() => {
      this.emitter.emit("did-change-kernel", store.kernel);
    });
  },

  deactivate() {
    store.dispose();
  },

  provideHydrogen() {
    if (!this.hydrogenProvider) {
      this.hydrogenProvider = new HydrogenProvider(this);
    }

    return this.hydrogenProvider;
  },

  consumeStatusBar(statusBar: atom$StatusBar) {
    const statusBarElement = document.createElement("div");
    statusBarElement.className = "inline-block";

    statusBar.addLeftTile({
      item: statusBarElement,
      priority: 100
    });

    const onClick = this.showKernelCommands.bind(this);

    reactFactory(
      <StatusBar store={store} onClick={onClick} />,
      statusBarElement
    );

    // We should return a disposable here but Atom fails while calling .destroy()
    // return new Disposable(statusBarTile.destroy);
  },

  provide() {
    if (atom.config.get("Hydrogen.autocomplete") === true) {
      return AutocompleteProvider();
    }
    return null;
  },

  showKernelCommands() {
    if (!this.signalListView) {
      this.signalListView = new SignalListView();
      this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
        this.handleKernelCommand(kernelCommand);
    }
    this.signalListView.toggle();
  },

  connectToExistingKernel() {
    if (!this.existingKernelPicker) {
      this.existingKernelPicker = new ExistingKernelPicker();
    }
    this.existingKernelPicker.toggle();
  },

  handleKernelCommand({
    command,
    payload
  }: {
    command: string,
    payload: ?Kernelspec
  }) {
    log("handleKernelCommand:", arguments);

    const { kernel, grammar } = store;

    if (!grammar) {
      atom.notifications.addError("Undefined grammar");
      return;
    }

    if (!kernel) {
      const message = `No running kernel for grammar \`${grammar.name}\` found`;
      atom.notifications.addError(message);
      return;
    }

    if (command === "interrupt-kernel") {
      kernel.interrupt();
    } else if (command === "restart-kernel") {
      kernel.restart();
    } else if (command === "shutdown-kernel") {
      store.markers.clear();
      // Note that destroy alone does not shut down a WSKernel
      kernel.shutdown();
      kernel.destroy();
    } else if (command === "rename-kernel" && kernel.promptRename) {
      // $FlowFixMe Will only be called if remote kernel
      if (kernel instanceof WSKernel) kernel.promptRename();
    } else if (command === "disconnect-kernel") {
      store.markers.clear();
      kernel.destroy();
    }
  },

  createResultBubble(editor: atom$TextEditor, code: string, row: number) {
    const { grammar, filePath, kernel } = store;

    if (!filePath || !grammar) {
      return atom.notifications.addError(
        "Your file must be saved in order to start a kernel"
      );
    }

    if (kernel) {
      this._createResultBubble(editor, kernel, code, row);
      return;
    }

    kernelManager.startKernelFor(
      grammar,
      editor,
      filePath,
      (kernel: ZMQKernel) => {
        this._createResultBubble(editor, kernel, code, row);
      }
    );
  },

  _createResultBubble(
    editor: atom$TextEditor,
    kernel: Kernel,
    code: string,
    row: number
  ) {
    if (atom.workspace.getActivePaneItem() instanceof WatchesPane) {
      kernel.watchesStore.run();
      return;
    }
    const globalOutputStore =
      atom.config.get("Hydrogen.outputAreaDefault") ||
      atom.workspace.getPaneItems().find(item => item instanceof OutputPane)
        ? kernel.outputStore
        : null;

    if (globalOutputStore) openOrShowDock(OUTPUT_AREA_URI);

    const { outputStore } = new ResultView(
      store.markers,
      kernel,
      editor,
      row,
      !globalOutputStore
    );

    kernel.execute(code, result => {
      outputStore.appendOutput(result);
      if (globalOutputStore) globalOutputStore.appendOutput(result);
    });
  },

  restartKernelAndReEvaluateBubbles() {
    const { editor, kernel, markers } = store;

    let breakpoints = [];
    markers.markers.forEach((bubble: ResultView) => {
      breakpoints.push(bubble.marker.getBufferRange().start);
    });
    store.markers.clear();

    if (!editor || !kernel) {
      this.runAll(breakpoints);
    } else {
      kernel.restart(() => this.runAll(breakpoints));
    }
  },

  toggleBubble() {
    const { editor, kernel, markers } = store;
    if (!editor) return;
    const [startRow, endRow] = editor.getLastSelection().getBufferRowRange();

    for (let row = startRow; row <= endRow; row++) {
      const destroyed = markers.clearOnRow(row);

      if (!destroyed) {
        const { outputStore } = new ResultView(
          markers,
          kernel,
          editor,
          row,
          true
        );
        outputStore.status = "empty";
      }
    }
  },

  run(moveDown: boolean = false) {
    const editor = store.editor;
    if (!editor) return;
    const codeBlock = codeManager.findCodeBlock(editor);
    if (!codeBlock) {
      return;
    }

    const [code, row] = codeBlock;
    if (code) {
      if (moveDown === true) {
        codeManager.moveDown(editor, row);
      }
      this.createResultBubble(editor, code, row);
    }
  },

  runAll(breakpoints: ?Array<atom$Point>) {
    const { editor, kernel, grammar, filePath } = store;
    if (!editor || !grammar || !filePath) return;
    if (isMultilanguageGrammar(editor.getGrammar())) {
      atom.notifications.addError(
        '"Run All" is not supported for this file type!'
      );
      return;
    }

    if (editor && kernel) {
      this._runAll(editor, kernel, breakpoints);
      return;
    }

    kernelManager.startKernelFor(
      grammar,
      editor,
      filePath,
      (kernel: ZMQKernel) => {
        this._runAll(editor, kernel, breakpoints);
      }
    );
  },

  _runAll(
    editor: atom$TextEditor,
    kernel: Kernel,
    breakpoints?: Array<atom$Point>
  ) {
    let cells = codeManager.getCells(editor, breakpoints);
    _.forEach(
      cells,
      ({ start, end }: { start: atom$Point, end: atom$Point }) => {
        const code = codeManager.getTextInRange(editor, start, end);
        const endRow = codeManager.escapeBlankRows(editor, start.row, end.row);
        this._createResultBubble(editor, kernel, code, endRow);
      }
    );
  },

  runAllAbove() {
    const editor = store.editor; // to make flow happy
    if (!editor) return;
    if (isMultilanguageGrammar(editor.getGrammar())) {
      atom.notifications.addError(
        '"Run All Above" is not supported for this file type!'
      );
      return;
    }

    const cursor = editor.getLastCursor();
    const row = codeManager.escapeBlankRows(editor, 0, cursor.getBufferRow());
    const code = codeManager.getRows(editor, 0, row);

    if (code) {
      this.createResultBubble(editor, code, row);
    }
  },

  runCell(moveDown: boolean = false) {
    const editor = store.editor;
    if (!editor) return;
    const { start, end } = codeManager.getCurrentCell(editor);
    const code = codeManager.getTextInRange(editor, start, end);
    const endRow = codeManager.escapeBlankRows(editor, start.row, end.row);

    if (code) {
      if (moveDown === true) {
        codeManager.moveDown(editor, endRow);
      }
      this.createResultBubble(editor, code, endRow);
    }
  },

  startZMQKernel() {
    kernelManager
      .getAllKernelSpecsForGrammar(store.grammar)
      .then(kernelSpecs => {
        if (this.kernelPicker) {
          this.kernelPicker.kernelSpecs = kernelSpecs;
        } else {
          this.kernelPicker = new KernelPicker(kernelSpecs);

          this.kernelPicker.onConfirmed = (kernelSpec: Kernelspec) => {
            const { editor, grammar, filePath } = store;
            if (!editor || !grammar || !filePath) return;
            store.markers.clear();

            kernelManager.startKernel(kernelSpec, grammar, editor, filePath);
          };
        }

        this.kernelPicker.toggle();
      });
  },

  connectToWSKernel() {
    if (!this.wsKernelPicker) {
      this.wsKernelPicker = new WSKernelPicker((kernel: Kernel) => {
        store.markers.clear();
        const { editor, grammar, filePath } = store;
        if (!editor || !grammar || !filePath) return;

        if (kernel instanceof ZMQKernel) kernel.destroy();

        store.newKernel(kernel, filePath, editor, grammar);
      });
    }

    this.wsKernelPicker.toggle((kernelSpec: Kernelspec) =>
      kernelSpecProvidesGrammar(kernelSpec, store.grammar)
    );
  }
};

export default Hydrogen;
<|endoftext|>


<commit_before>'use babel';

// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
import fs from 'fs-plus';
import path from 'path';
import * as helpers from 'atom-linter';
import rangeHelpers from './rangeHelpers';

// Local variables
const parseRegex = /(\d+):(\d+):\s(([A-Z])\d{2,3})\s+(.*)/g;

const extractRange = ({ code, message, lineNumber, colNumber, textEditor }) => {
  let result;
  const line = lineNumber - 1;
  switch (code) {
    case 'C901':
      result = rangeHelpers.tooComplex(textEditor, message, line);
      break;
    case 'F401':
      result = rangeHelpers.importedUnused(textEditor, message, line);
      break;
    case 'H201':
      // H201 - no 'except:' at least use 'except Exception:'

      // For some reason this rule marks the ":" as the location by default
      result = {
        line,
        col: colNumber - 7,
        endCol: colNumber,
      };
      break;
    case 'H501':
      result = rangeHelpers.noLocalsString(textEditor, line);
      break;
    default:
      result = {
        line,
        col: colNumber - 1,
      };
      break;
  }

  if (Object.hasOwnProperty.call(result, 'endCol')) {
    return [
      [result.line, result.col],
      [result.line, result.endCol],
    ];
  }

  let range;
  try {
    range = helpers.rangeFromLineNumber(textEditor, result.line, result.col);
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(
      'linter-flake8:: Invalid point encountered in the attached message',
      {
        code,
        message,
        requestedPoint: result,
      }
    );
    throw Error('linter-flake8:: Invalid point encountered! See console for details.');
  }

  return range;
};

const applySubstitutions = (givenExecPath, projDir) => {
  let execPath = givenExecPath;
  const projectName = path.basename(projDir);
  execPath = execPath.replace(/\$PROJECT_NAME/i, projectName);
  execPath = execPath.replace(/\$PROJECT/i, projDir);
  const paths = execPath.split(';');
  for (let i = 0; i < paths.length; i += 1) {
    if (fs.existsSync(paths[i])) {
      return paths[i];
    }
  }
  return execPath;
};

export default {
  activate() {
    require('atom-package-deps').install('linter-flake8');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      atom.config.observe('linter-flake8.disableTimeout', (value) => {
        this.disableTimeout = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.projectConfigFile', (value) => {
        this.projectConfigFile = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.maxLineLength', (value) => {
        this.maxLineLength = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.ignoreErrorCodes', (value) => {
        this.ignoreErrorCodes = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.maxComplexity', (value) => {
        this.maxComplexity = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.selectErrors', (value) => {
        this.selectErrors = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.hangClosing', (value) => {
        this.hangClosing = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.executablePath', (value) => {
        this.executablePath = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.pycodestyleErrorsToWarnings', (value) => {
        this.pycodestyleErrorsToWarnings = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.flakeErrors', (value) => {
        this.flakeErrors = value;
      })
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    return {
      name: 'Flake8',
      grammarScopes: ['source.python', 'source.python.django'],
      scope: 'file',
      lintOnFly: true,
      lint: async (textEditor) => {
        const filePath = textEditor.getPath();
        const fileText = textEditor.getText();

        const parameters = ['--format=default'];

        const projectPath = atom.project.relativizePath(filePath)[0];
        const baseDir = projectPath !== null ? projectPath : path.dirname(filePath);
        const configFilePath = await helpers.findCachedAsync(baseDir, this.projectConfigFile);

        if (this.projectConfigFile && baseDir !== null && configFilePath !== null) {
          parameters.push('--config', configFilePath);
        } else {
          if (this.maxLineLength) {
            parameters.push('--max-line-length', this.maxLineLength);
          }
          if (this.ignoreErrorCodes.length) {
            parameters.push('--ignore', this.ignoreErrorCodes.join(','));
          }
          if (this.maxComplexity) {
            parameters.push('--max-complexity', this.maxComplexity);
          }
          if (this.hangClosing) {
            parameters.push('--hang-closing');
          }
          if (this.selectErrors.length) {
            parameters.push('--select', this.selectErrors.join(','));
          }
        }

        parameters.push('-');

        const execPath = fs.normalize(applySubstitutions(this.executablePath, baseDir));
        const options = {
          stdin: fileText,
          cwd: path.dirname(textEditor.getPath()),
          stream: 'both',
        };
        if (this.disableTimeout) {
          options.timeout = Infinity;
        }

        const result = await helpers.exec(execPath, parameters, options);

        if (textEditor.getText() !== fileText) {
          // Editor contents have changed, tell Linter not to update
          return null;
        }

        if (result.stderr && result.stderr.length && atom.inDevMode()) {
          // eslint-disable-next-line no-console
          console.log(`flake8 stderr: ${result.stderr}`);
        }
        const messages = [];

        let match = parseRegex.exec(result.stdout);
        while (match !== null) {
          const line = Number.parseInt(match[1], 10) || 0;
          const col = Number.parseInt(match[2], 10) || 0;
          const isErr = (match[4] === 'E' && !this.pycodestyleErrorsToWarnings)
            || (match[4] === 'F' && this.flakeErrors);
          const range = extractRange({
            code: match[3],
            message: match[5],
            lineNumber: line,
            colNumber: col,
            textEditor,
          });

          messages.push({
            type: isErr ? 'Error' : 'Warning',
            text: `${match[3]} — ${match[5]}`,
            filePath,
            range,
          });

          match = parseRegex.exec(result.stdout);
        }
        return messages;
      },
    };
  },
};
<commit_msg>Workaround a bug with E999 reporting<commit_after>'use babel';

// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
import fs from 'fs-plus';
import path from 'path';
import * as helpers from 'atom-linter';
import rangeHelpers from './rangeHelpers';

// Local variables
const parseRegex = /(\d+):(\d+):\s(([A-Z])\d{2,3})\s+(.*)/g;

const extractRange = ({ code, message, lineNumber, colNumber, textEditor }) => {
  let result;
  const line = lineNumber - 1;
  switch (code) {
    case 'C901':
      result = rangeHelpers.tooComplex(textEditor, message, line);
      break;
    case 'F401':
      result = rangeHelpers.importedUnused(textEditor, message, line);
      break;
    case 'H201':
      // H201 - no 'except:' at least use 'except Exception:'

      // For some reason this rule marks the ":" as the location by default
      result = {
        line,
        col: colNumber - 7,
        endCol: colNumber,
      };
      break;
    case 'H501':
      result = rangeHelpers.noLocalsString(textEditor, line);
      break;
    case 'E999':
      // E999 - SyntaxError: unexpected EOF while parsing

      // Workaround for https://gitlab.com/pycqa/flake8/issues/237
      result = {
        line,
        col: colNumber - 2,
      };
      break;
    default:
      result = {
        line,
        col: colNumber - 1,
      };
      break;
  }

  if (Object.hasOwnProperty.call(result, 'endCol')) {
    return [
      [result.line, result.col],
      [result.line, result.endCol],
    ];
  }

  let range;
  try {
    range = helpers.rangeFromLineNumber(textEditor, result.line, result.col);
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(
      'linter-flake8:: Invalid point encountered in the attached message',
      {
        code,
        message,
        requestedPoint: result,
      }
    );
    throw Error('linter-flake8:: Invalid point encountered! See console for details.');
  }

  return range;
};

const applySubstitutions = (givenExecPath, projDir) => {
  let execPath = givenExecPath;
  const projectName = path.basename(projDir);
  execPath = execPath.replace(/\$PROJECT_NAME/i, projectName);
  execPath = execPath.replace(/\$PROJECT/i, projDir);
  const paths = execPath.split(';');
  for (let i = 0; i < paths.length; i += 1) {
    if (fs.existsSync(paths[i])) {
      return paths[i];
    }
  }
  return execPath;
};

export default {
  activate() {
    require('atom-package-deps').install('linter-flake8');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      atom.config.observe('linter-flake8.disableTimeout', (value) => {
        this.disableTimeout = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.projectConfigFile', (value) => {
        this.projectConfigFile = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.maxLineLength', (value) => {
        this.maxLineLength = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.ignoreErrorCodes', (value) => {
        this.ignoreErrorCodes = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.maxComplexity', (value) => {
        this.maxComplexity = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.selectErrors', (value) => {
        this.selectErrors = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.hangClosing', (value) => {
        this.hangClosing = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.executablePath', (value) => {
        this.executablePath = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.pycodestyleErrorsToWarnings', (value) => {
        this.pycodestyleErrorsToWarnings = value;
      })
    );
    this.subscriptions.add(
      atom.config.observe('linter-flake8.flakeErrors', (value) => {
        this.flakeErrors = value;
      })
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    return {
      name: 'Flake8',
      grammarScopes: ['source.python', 'source.python.django'],
      scope: 'file',
      lintOnFly: true,
      lint: async (textEditor) => {
        const filePath = textEditor.getPath();
        const fileText = textEditor.getText();

        const parameters = ['--format=default'];

        const projectPath = atom.project.relativizePath(filePath)[0];
        const baseDir = projectPath !== null ? projectPath : path.dirname(filePath);
        const configFilePath = await helpers.findCachedAsync(baseDir, this.projectConfigFile);

        if (this.projectConfigFile && baseDir !== null && configFilePath !== null) {
          parameters.push('--config', configFilePath);
        } else {
          if (this.maxLineLength) {
            parameters.push('--max-line-length', this.maxLineLength);
          }
          if (this.ignoreErrorCodes.length) {
            parameters.push('--ignore', this.ignoreErrorCodes.join(','));
          }
          if (this.maxComplexity) {
            parameters.push('--max-complexity', this.maxComplexity);
          }
          if (this.hangClosing) {
            parameters.push('--hang-closing');
          }
          if (this.selectErrors.length) {
            parameters.push('--select', this.selectErrors.join(','));
          }
        }

        parameters.push('-');

        const execPath = fs.normalize(applySubstitutions(this.executablePath, baseDir));
        const options = {
          stdin: fileText,
          cwd: path.dirname(textEditor.getPath()),
          stream: 'both',
        };
        if (this.disableTimeout) {
          options.timeout = Infinity;
        }

        const result = await helpers.exec(execPath, parameters, options);

        if (textEditor.getText() !== fileText) {
          // Editor contents have changed, tell Linter not to update
          return null;
        }

        if (result.stderr && result.stderr.length && atom.inDevMode()) {
          // eslint-disable-next-line no-console
          console.log(`flake8 stderr: ${result.stderr}`);
        }
        const messages = [];

        let match = parseRegex.exec(result.stdout);
        while (match !== null) {
          const line = Number.parseInt(match[1], 10) || 0;
          const col = Number.parseInt(match[2], 10) || 0;
          const isErr = (match[4] === 'E' && !this.pycodestyleErrorsToWarnings)
            || (match[4] === 'F' && this.flakeErrors);
          const range = extractRange({
            code: match[3],
            message: match[5],
            lineNumber: line,
            colNumber: col,
            textEditor,
          });

          messages.push({
            type: isErr ? 'Error' : 'Warning',
            text: `${match[3]} — ${match[5]}`,
            filePath,
            range,
          });

          match = parseRegex.exec(result.stdout);
        }
        return messages;
      },
    };
  },
};
<|endoftext|>


<commit_before>'use strict';
<commit_msg>Update main interface<commit_after>'use strict';
module.exports.usage = require('./modules/usage');
/**
 * @TODO
 * module.exports.put   = require('./modules/put');
 * module.exports.stow  = require('./modules/stow');
 * module.exports.open  = require('./modules/open');
 * module.exports.boost = require('./modules/boost');
 * module.exports.close = require('./modules/close');
*/
<|endoftext|>


<commit_before>var data = require("sdk/self").data;
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
// Break on Firefox Mobile
// var clipboard = require("sdk/clipboard");
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "*.example.org",
  contentScriptFile: data.url("greaseshim.js"),
  contentScriptWhen: "start",
  onAttach: function(worker) {
    worker.port.emit("load-userscript", data.load("userscript.user.js"));

    //GM_openInTab
    worker.port.on("GM_openInTab", function(url) {
      tabs.open(url);
    });

//     GM_setClipboard
//     Break the script on Firefox mobile
//     worker.port.on("GM_setClipboard", function(text) {
//       clipboard.set(text);
//     });

    //GM_xmlhttpRequest
    worker.port.on("GM_xmlhttpRequest", function(details) {
      request = new Object();
      request.url = details.url;
      if (details.headers) {request.headers = details.headers};
      if (details.data) {request.content = encodeURIComponent(details.data)};
      if (details.headers) {
        if (details.headers.Content-Type) {request.contentType = details.headers.Content-Type};
      };
      if (details.overrideMimeType) {request.overrideMimeType = details.overrideMimeType};

      request.onComplete = function(response) {
        response.finalUrl = details.url;
        response.responseText = response.text;
        for (var headerName in response.headers) {
          _string = headerName + ": " + response.headers[headerName] + " \n";
          response.responseHeaders += _string;
        }
        response.readyState = 4;
        worker.port.emit("callback_GM_xmlhttpRequest", response);
      }

      xhr = Request(request);

      switch(details.method){
        case "GET":
          xhr.get();
          break;
        case "POST":
          xhr.post();
          break;
        case "HEAD":
          xhr.head();
          break;
        case "PUT":
          xhr.put();
          break;
        default: xhr.get();
      }
    });

    //GM_addStyle
    worker.port.on("GM_addStyle", function(css) {
      tabs.activeTab.attach({
        contentScript: "var style = document.createElement('style');" +
        "style.type = 'text/css';" +
        "style.innerHTML = '" + css + "';" +
        "document.head.appendChild(style);"
      });
    });

  }
});<commit_msg>Clean code<commit_after>var data = require("sdk/self").data;
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
// Break on Firefox Mobile
// var clipboard = require("sdk/clipboard");
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "*.example.org",
  contentScriptFile: data.url("greaseshim.js"),
  contentScriptWhen: "start",
  onAttach: function(worker) {
    worker.port.emit("load-userscript", data.load("userscript.user.js"));

    //GM_openInTab
    worker.port.on("GM_openInTab", function(url) {
      tabs.open(url);
    });

//     GM_setClipboard
//     Break the script on Firefox mobile
//     worker.port.on("GM_setClipboard", function(text) {
//       clipboard.set(text);
//     });

    //GM_xmlhttpRequest
    worker.port.on("GM_xmlhttpRequest", function(details) {
      request = new Object();
      request.url = details.url;
      if (details.headers) {
        request.headers = details.headers;
        if (details.headers.Content-Type) {request.contentType = details.headers.Content-Type};
      };
      if (details.data) {request.content = encodeURIComponent(details.data)};
      if (details.overrideMimeType) {request.overrideMimeType = details.overrideMimeType};

      request.onComplete = function(response) {
        response.finalUrl = details.url;
        response.responseText = response.text;
        for (var headerName in response.headers) {
          _string = headerName + ": " + response.headers[headerName] + " \n";
          response.responseHeaders += _string;
        }
        response.readyState = 4;
        worker.port.emit("callback_GM_xmlhttpRequest", response);
      }

      xhr = Request(request);

      switch(details.method){
        case "GET":
          xhr.get();
          break;
        case "POST":
          xhr.post();
          break;
        case "HEAD":
          xhr.head();
          break;
        case "PUT":
          xhr.put();
          break;
        default: xhr.get();
      }
    });

    //GM_addStyle
    worker.port.on("GM_addStyle", function(css) {
      tabs.activeTab.attach({
        contentScript: "var style = document.createElement('style');" +
        "style.type = 'text/css';" +
        "style.innerHTML = '" + css + "';" +
        "document.head.appendChild(style);"
      });
    });

  }
});<|endoftext|>


<commit_before>var data = require('self').data,
    contextMenu = require('context-menu'),
    prefsModule = require('simple-prefs');

var panel = require('panel').Panel({
  width: 620,
  height: 400,
  contentURL: data.url('panel.html'),
  contentScriptFile: data.url('panel.js'),
});

var shareMenuItem = contextMenu.Item({
  label: 'Share on Diaspora*',
  image: data.url('diaspora.png'),
  context: contextMenu.SelectorContext('img'),
  contentScriptFile: data.url('getdata.js'),
  onMessage: function handleMessage(message) {
    panel.show();
    panel.port.emit('show', message);
  }
});

var shareVideoMenuItem = contextMenu.Item({
  label: 'Share video on Diaspora*',
  image: data.url('diaspora.png'),
  context: [contextMenu.PageContext(),
            contextMenu.URLContext('http://www.youtube.com/watch?*')],
  contentScriptFile: data.url('getdata.js'),
  onMessage: function handleMessage(message) {
    panel.show();
    panel.port.emit('show', message);
  }
});

var onPrefChange = function () {
  panel.port.emit('prefs', prefsModule.prefs);
}

exports.main = function (options, callbacks) {
  panel.port.emit('prefs', prefsModule.prefs);
  prefsModule.on('', onPrefChange);
  if (options.loadReason == 'install' || options.loadReason == 'upgrade') {
    var tabs = require("tabs");
    tabs.open("http://arlogn.github.io/easyshare/index.html?q=" + options.loadReason);
    console.log('Easyshare: ' + options.loadReason);
  }
};
<commit_msg>Context menu item on secure (SSL) Youtube pages<commit_after>var data = require('self').data,
    contextMenu = require('context-menu'),
    prefsModule = require('simple-prefs');

var panel = require('panel').Panel({
  width: 620,
  height: 400,
  contentURL: data.url('panel.html'),
  contentScriptFile: data.url('panel.js'),
});

var shareMenuItem = contextMenu.Item({
  label: 'Share on Diaspora*',
  image: data.url('diaspora.png'),
  context: contextMenu.SelectorContext('img'),
  contentScriptFile: data.url('getdata.js'),
  onMessage: function handleMessage(message) {
    panel.show();
    panel.port.emit('show', message);
  }
});

var shareVideoMenuItem = contextMenu.Item({
  label: 'Share video on Diaspora*',
  image: data.url('diaspora.png'),
  context: [contextMenu.PageContext(),
            contextMenu.URLContext(/^\b(https?):\/\/www.youtube.com\/watch\?.*/)],
  contentScriptFile: data.url('getdata.js'),
  onMessage: function handleMessage(message) {
    panel.show();
    panel.port.emit('show', message);
  }
});

var onPrefChange = function () {
  panel.port.emit('prefs', prefsModule.prefs);
}

exports.main = function (options, callbacks) {
  panel.port.emit('prefs', prefsModule.prefs);
  prefsModule.on('', onPrefChange);
  if (options.loadReason == 'install' || options.loadReason == 'upgrade') {
    var tabs = require("tabs");
    tabs.open("http://arlogn.github.io/easyshare/index.html?q=" + options.loadReason);
    console.log('Easyshare: ' + options.loadReason);
  }
};
<|endoftext|>