<commit_before>// @flow

const uuid4 = require('uuid4');
const url = require('url');
const R = require('ramda');

import type { RawData, WebhookRequestData } from './types';

type Req = {
  method: string,
  url: string,
  headers: { [key: string]: string }
};

/**
 * This function will check request headers for
 * service specific data like github / gitlab / etc.
 * if the request method is POST.
 *
 * Will eventually generate 'custom' webhook data on
 * GET requests.
 *
 * Will throw an error on malformed request headers,
 * non-json body data or unsupported method.
 */
function extractWebhookData(req: Req, body?: string): WebhookRequestData {
  const { method, headers } = req;

  const parameters = {};
  let webhooktype;
  let event;
  let uuid;
  let bodyObj: ?RawData;
  let giturl;

  if (method === 'POST') {
    try {
      bodyObj = body == null || body === '' ? {} : JSON.parse(body);
    } catch (e) {
      throw new Error(`request body is not parsable as JSON: ${e}`);
    }

    if ('x-github-event' in req.headers) {
      webhooktype = 'github';
      event = req.headers['x-github-event'];
      uuid = req.headers['x-github-delivery'];
      giturl = R.path(['repository', 'ssh_url'], bodyObj);
    } else if ('x-gitlab-event' in req.headers) {
      webhooktype = 'gitlab';
      event = bodyObj.object_kind || bodyObj.event_name;
      uuid = uuid4();
      giturl = R.path(['project', 'git_ssh_url'], bodyObj);
    } else if ('x-event-key' in req.headers) {
      webhooktype = 'bitbucket'
      event = req.headers['x-event-key']
      uuid = req.headers['x-request-uuid']
      // Bitbucket does not provide a git-ssh URI to the repo in the webhook payload
      // We the html repo link (example https://bitbucket.org/teamawesome/repository) to extract the correct target domain (bitbucket.org)
      // this could be bitbuck.org(.com) or a private bitbucket server
      // Also the git server could be running on another port than 22, so there is a second regex match for `:[0-9]`
      const regexmatch = bodyObj.repository.links.html.href.match(/https?:\/\/([a-z0-9-_.]*)(:[0-9]*)?\//i)
      // The first match is the domain
      const domain = regexmatch[1]
      if (!regexmatch[2]) {
        // If there is no 2nd regex match, ther is no port found and it's not added to the URL
        // use the extracted domain and repo full_name (teamawesome/repository) to build the git URI, example git@bitbucket.org:teamawesome/repository.git
        giturl = `git@${domain}:${bodyObj.repository.full_name}.git`
      } else {
        // If there is a second regex match, we add the port to the url and also format the url with `ssh://` in front which is needed for requests with anoter port
        const port = regexmatch[2]
        giturl = `ssh://git@${domain}${port}/${bodyObj.repository.full_name}.git`
      }
    } else if (bodyObj.backup_metrics) {
      webhooktype = 'resticbackup';
      event = 'snapshot:finished'
      uuid = uuid4();
    } else if (R.allPass([ R.is(Array), R.compose(R.not(), R.isEmpty()), R.compose(R.has('hostname'), R.prop(0)) ])(bodyObj)) {
      // Check for a body that matches
      // [
      //   {
      //       "id": "80b698920f97e36616f638cb59c379787967ff45416c9ba23c1807e4e0703414",
      //       "time": "2018-11-12T04:16:28.320904074Z",
      //       "tree": "e100116d5477c1746402649fde5219ae506a8d6605ed2600f6ada5dd340b5c23",
      //       "paths": [
      //           "/data/solr"
      //       ],
      //       "hostname": "ci-local",
      //       "username": "",
      //       "uid": 0,
      //       "gid": 0,
      //       "tags": null
      //   }
      // ]
      webhooktype = 'resticbackup';
      event = 'snapshot:pruned'
      uuid = uuid4();
    } else if (bodyObj.restore_location) {
      webhooktype = 'resticbackup';
      event = 'restore:finished';
      uuid = uuid4();
    } else {
      throw new Error('No supported event header found on POST request');
    }
  } else if (method === 'GET') {
    try {
      webhooktype = 'custom';
      event = 'push';
      uuid = uuid4();

      const parsedUrl = url.parse(req.url, true); // true to get query as object
      const { query = {} } = parsedUrl;

      // TODO: Potential for refactor
      const getParam = (name: string, shouldThrow: boolean = false): string => {
        const value = query[name];
        if (value == null && shouldThrow) {
          throw new Error(`Query param '${name}' not found!`);
        }
        if (value === '' && shouldThrow) {
          throw new Error(`Query param '${name}' is empty!`);
        }
        return value;
      };

      giturl = req.url;
      parameters.url = getParam('url', true);
      parameters.branch = getParam('branch', true);
      parameters.sha = getParam('sha') || '';
      bodyObj = parameters;
    } catch (e) {
      throw new Error(`Error in handling GET request: ${e.message}`);
    }
  } else {
    throw new Error(`Unsupported request method: ${method}`);
  }

  const ret: WebhookRequestData = {
    webhooktype,
    event,
    body: bodyObj
  };

  if (giturl != null) {
    ret.giturl = giturl;
  }

  if (uuid != null) {
    ret.uuid = uuid;
  }

  return ret;
}

module.exports = extractWebhookData;
<commit_msg>GOV-287 Authenticate gitlab system hooks<commit_after>// @flow

const uuid4 = require('uuid4');
const url = require('url');
const R = require('ramda');

import type { RawData, WebhookRequestData } from './types';

type Req = {
  method: string,
  url: string,
  headers: { [key: string]: string }
};

/**
 * This function will check request headers for
 * service specific data like github / gitlab / etc.
 * if the request method is POST.
 *
 * Will eventually generate 'custom' webhook data on
 * GET requests.
 *
 * Will throw an error on malformed request headers,
 * non-json body data or unsupported method.
 */
function extractWebhookData(req: Req, body?: string): WebhookRequestData {
  const { method, headers } = req;

  const parameters = {};
  let webhooktype;
  let event;
  let uuid;
  let bodyObj: ?RawData;
  let giturl;

  if (method === 'POST') {
    try {
      bodyObj = body == null || body === '' ? {} : JSON.parse(body);
    } catch (e) {
      throw new Error(`request body is not parsable as JSON: ${e}`);
    }

    if ('x-github-event' in req.headers) {
      webhooktype = 'github';
      event = req.headers['x-github-event'];
      uuid = req.headers['x-github-delivery'];
      giturl = R.path(['repository', 'ssh_url'], bodyObj);
    } else if ('x-gitlab-event' in req.headers) {
      webhooktype = 'gitlab';
      event = bodyObj.object_kind || bodyObj.event_name;
      uuid = uuid4();
      giturl = R.path(['project', 'git_ssh_url'], bodyObj);

      // This is a system webhook
      if (!giturl) {
        // Ensure the system hook came from gitlab
        if (!('x-gitlab-token' in req.headers) || req.headers['x-gitlab-token'] !== process.env.GITLAB_SYSTEM_HOOK_TOKEN) {
          throw new Error('Gitlab system hook secret verification failed');
        }
      }
    } else if ('x-event-key' in req.headers) {
      webhooktype = 'bitbucket'
      event = req.headers['x-event-key']
      uuid = req.headers['x-request-uuid']
      // Bitbucket does not provide a git-ssh URI to the repo in the webhook payload
      // We the html repo link (example https://bitbucket.org/teamawesome/repository) to extract the correct target domain (bitbucket.org)
      // this could be bitbuck.org(.com) or a private bitbucket server
      // Also the git server could be running on another port than 22, so there is a second regex match for `:[0-9]`
      const regexmatch = bodyObj.repository.links.html.href.match(/https?:\/\/([a-z0-9-_.]*)(:[0-9]*)?\//i)
      // The first match is the domain
      const domain = regexmatch[1]
      if (!regexmatch[2]) {
        // If there is no 2nd regex match, ther is no port found and it's not added to the URL
        // use the extracted domain and repo full_name (teamawesome/repository) to build the git URI, example git@bitbucket.org:teamawesome/repository.git
        giturl = `git@${domain}:${bodyObj.repository.full_name}.git`
      } else {
        // If there is a second regex match, we add the port to the url and also format the url with `ssh://` in front which is needed for requests with anoter port
        const port = regexmatch[2]
        giturl = `ssh://git@${domain}${port}/${bodyObj.repository.full_name}.git`
      }
    } else if (bodyObj.backup_metrics) {
      webhooktype = 'resticbackup';
      event = 'snapshot:finished'
      uuid = uuid4();
    } else if (R.allPass([ R.is(Array), R.compose(R.not(), R.isEmpty()), R.compose(R.has('hostname'), R.prop(0)) ])(bodyObj)) {
      // Check for a body that matches
      // [
      //   {
      //       "id": "80b698920f97e36616f638cb59c379787967ff45416c9ba23c1807e4e0703414",
      //       "time": "2018-11-12T04:16:28.320904074Z",
      //       "tree": "e100116d5477c1746402649fde5219ae506a8d6605ed2600f6ada5dd340b5c23",
      //       "paths": [
      //           "/data/solr"
      //       ],
      //       "hostname": "ci-local",
      //       "username": "",
      //       "uid": 0,
      //       "gid": 0,
      //       "tags": null
      //   }
      // ]
      webhooktype = 'resticbackup';
      event = 'snapshot:pruned'
      uuid = uuid4();
    } else if (bodyObj.restore_location) {
      webhooktype = 'resticbackup';
      event = 'restore:finished';
      uuid = uuid4();
    } else {
      throw new Error('No supported event header found on POST request');
    }
  } else if (method === 'GET') {
    try {
      webhooktype = 'custom';
      event = 'push';
      uuid = uuid4();

      const parsedUrl = url.parse(req.url, true); // true to get query as object
      const { query = {} } = parsedUrl;

      // TODO: Potential for refactor
      const getParam = (name: string, shouldThrow: boolean = false): string => {
        const value = query[name];
        if (value == null && shouldThrow) {
          throw new Error(`Query param '${name}' not found!`);
        }
        if (value === '' && shouldThrow) {
          throw new Error(`Query param '${name}' is empty!`);
        }
        return value;
      };

      giturl = req.url;
      parameters.url = getParam('url', true);
      parameters.branch = getParam('branch', true);
      parameters.sha = getParam('sha') || '';
      bodyObj = parameters;
    } catch (e) {
      throw new Error(`Error in handling GET request: ${e.message}`);
    }
  } else {
    throw new Error(`Unsupported request method: ${method}`);
  }

  const ret: WebhookRequestData = {
    webhooktype,
    event,
    body: bodyObj
  };

  if (giturl != null) {
    ret.giturl = giturl;
  }

  if (uuid != null) {
    ret.uuid = uuid;
  }

  return ret;
}

module.exports = extractWebhookData;
<|endoftext|>


<commit_before>
var app = angular.module("app", ["xeditable","ngCookies"]);

app.controller('NodeCtrl', ['$scope','$http','$cookies', function($scope,$http,$cookies) {
  var keyPrefix = '/v2/keys',
      statsPrefix = '/v2/stats';

  if($cookies.urlPrefix){
    $scope.urlPrefix = $cookies.urlPrefix;
  } else {
    $scope.urlPrefix = "http://" + document.location.host;
  }

  $scope.getPrefix = function() {
    splitted = $scope.urlPrefix.split("/")
    return splitted[0] + "//" + splitted[2]
  }

  $scope.setActiveNode = function(node){
    $scope.activeNode = node;
    if(!node.open){
      $scope.toggleNode(node);
    }else{
      $scope.loadNode(node);
    }
  }

  function errorHandler(data, status, headers, config){
    var message = data;
    if(data.message) {
      message = data.message;
    }
    $scope.error = "Request failed - " + message + " - " + config.url;
  }

  $scope.loadNode = function(node){
    delete $scope.error;
    $http({method: 'GET', url: $scope.getPrefix() + keyPrefix + node.key}).
      success(function(data) {
        prepNodes(data.node.nodes,node);
        node.nodes = data.node.nodes;
        $scope.urlPrefix = $scope.getPrefix() + keyPrefix + node.key
      }).
      error(errorHandler);
  }

  $scope.toggleNode = function(node) {
    node.open = !node.open;
    if(node.open){
      $scope.loadNode(node);
    } else {
      node.nodes = [];
    }
  };
  $scope.hasProperties = function(node){
    for(var key in node.nodes){
      if(!node.nodes[key].dir){
        return true;
      }
    }
  }
  $scope.submit = function(){
    console.log($cookies);
    $cookies.urlPrefix = $scope.getPrefix();
    $scope.root = {key:'/'};
    delete $scope.activeNode;
    $scope.loadNode($scope.root);
  }
  $scope.addNode = function(node){
    var name = prompt("Enter Property Name", "");
    var value = prompt("Enter Property value", "");
    if(!name || name == "") return;

    $http({method: 'PUT',
    	   url: $scope.getPrefix() + keyPrefix + node.key + (node.key != "/" ? "/" : "") + name,
    	   params: {"value": value}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.updateNode = function(node,value){
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + node.key,
      params: {"value": value}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.deleteNode = function(node){
    $http({method: 'DELETE', url: $scope.getPrefix() + keyPrefix + node.key}).
    success(function(data) {
      $scope.loadNode(node.parent);
    }).
    error(errorHandler);
  }

  $scope.copyNode = function(node){
    var dirName = prompt("Copy property to directory","/");
    if(!dirName || dirName == "") return;
    dirName = $scope.formatDir(dirName);
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + dirName + node.name,
      params: {"value": node.value}}).
    error(errorHandler);
  }

  $scope.createDir = function(node){
    var dirName = prompt("Enter Directory Name", "");
    if(!dirName || dirName == "") return;
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + node.key + (node.key != "/" ? "/" : "") + dirName,
      params: {"dir": true}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.copyDirAux = function(node, tarjet){
    $http({method: 'GET', url: $scope.getPrefix() + keyPrefix + node.key}).
      success(function(data) {
        prepNodes(data.node.nodes,node);
        node.nodes = data.node.nodes;
        for(var key in node.nodes){
          if (node.nodes[key].dir) {
            $scope.copyDirAux(node.nodes[key], tarjet + node.nodes[key].name + "/")
          } else {
            var url = $scope.getPrefix() + keyPrefix + tarjet + node.nodes[key].name
            $http({method: 'PUT',
              url: url,
              params: {"value": node.nodes[key].value}}).
            error(errorHandler);
          }
        }
      }).
      error(errorHandler);
  }

  $scope.copyDir = function(node){
    var dirName = prompt("Copy properties to directory", node.key);
    if(!dirName || dirName == "") return;
    dirName = $scope.formatDir(dirName);
    $scope.copyDirAux(node, dirName)
  }

  $scope.deleteDir = function(node) {
    if(!confirm("Are you sure you want to delete " + node.key)) return;
    $http({method: 'DELETE',
      url: $scope.getPrefix() + keyPrefix + node.key + "?dir=true&recursive=true"}).
    success(function(data) {
      $scope.loadNode(node.parent);
    }).
    error(errorHandler);
  }

  $scope.formatDir = function(dirName){
    if(dirName.substr(dirName.trim().length - 1) != '/'){
      dirName += '/';
    }
    return dirName;
  }

  $scope.submit();

  function prepNodes(nodes,parent){
    for(var key in nodes){
      var node = nodes[key];
      var name = node.key.substring(node.key.lastIndexOf("/")+1);
      node.name = name;
      node.parent = parent;
    }
  }

  $scope.loadStats = function(){
    console.log("LOAD STATS");
    $scope.stats = {};
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/store"}).
    success(function(data) {
      $scope.stats.store = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
    delete $scope.storeStats;
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/leader"}).
    success(function(data) {
      $scope.stats.leader = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
    delete $scope.storeStats;
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/self"}).
    success(function(data) {
      $scope.stats.self = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
  }

}]);

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});
<commit_msg>Added JSON syntax validation.<commit_after>
var app = angular.module("app", ["xeditable","ngCookies"]);

function validate_json(value) {
  try {
    JSON.parse(value);
    return true;
  } catch (exception) {
    return false;
  }
}

app.controller('NodeCtrl', ['$scope','$http','$cookies', function($scope,$http,$cookies) {
  var keyPrefix = '/v2/keys',
      statsPrefix = '/v2/stats';

  if($cookies.urlPrefix){
    $scope.urlPrefix = $cookies.urlPrefix;
  } else {
    $scope.urlPrefix = "http://" + document.location.host;
  }

  $scope.getPrefix = function() {
    splitted = $scope.urlPrefix.split("/")
    return splitted[0] + "//" + splitted[2]
  }

  $scope.setActiveNode = function(node){
    $scope.activeNode = node;
    if(!node.open){
      $scope.toggleNode(node);
    }else{
      $scope.loadNode(node);
    }
  }

  function errorHandler(data, status, headers, config){
    var message = data;
    if(data.message) {
      message = data.message;
    }
    $scope.error = "Request failed - " + message + " - " + config.url;
  }

  $scope.loadNode = function(node){
    delete $scope.error;
    $http({method: 'GET', url: $scope.getPrefix() + keyPrefix + node.key}).
      success(function(data) {
        prepNodes(data.node.nodes,node);
        node.nodes = data.node.nodes;
        $scope.urlPrefix = $scope.getPrefix() + keyPrefix + node.key
      }).
      error(errorHandler);
  }

  $scope.toggleNode = function(node) {
    node.open = !node.open;
    if(node.open){
      $scope.loadNode(node);
    } else {
      node.nodes = [];
    }
  };
  $scope.hasProperties = function(node){
    for(var key in node.nodes){
      if(!node.nodes[key].dir){
        return true;
      }
    }
  }
  $scope.submit = function(){
    console.log($cookies);
    $cookies.urlPrefix = $scope.getPrefix();
    $scope.root = {key:'/'};
    delete $scope.activeNode;
    $scope.loadNode($scope.root);
  }
  $scope.addNode = function(node){
    var name = prompt("Enter Property Name", "");
    var value = prompt("Enter Property value", "");
    if(!name || name == "") return;

    if(!validate_json(value)) {
      $scope.error = "Invalid JSON syntax";
      return;
    }

    $http({method: 'PUT',
    	   url: $scope.getPrefix() + keyPrefix + node.key + (node.key != "/" ? "/" : "") + name,
    	   params: {"value": value}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.updateNode = function(node,value){
    if(!validate_json(value)) {
      $scope.error = "Invalid JSON syntax";
      return;
    }
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + node.key,
      params: {"value": value}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.deleteNode = function(node){
    $http({method: 'DELETE', url: $scope.getPrefix() + keyPrefix + node.key}).
    success(function(data) {
      $scope.loadNode(node.parent);
    }).
    error(errorHandler);
  }

  $scope.copyNode = function(node){
    var dirName = prompt("Copy property to directory","/");
    if(!dirName || dirName == "") return;
    dirName = $scope.formatDir(dirName);
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + dirName + node.name,
      params: {"value": node.value}}).
    error(errorHandler);
  }

  $scope.createDir = function(node){
    var dirName = prompt("Enter Directory Name", "");
    if(!dirName || dirName == "") return;
    $http({method: 'PUT',
      url: $scope.getPrefix() + keyPrefix + node.key + (node.key != "/" ? "/" : "") + dirName,
      params: {"dir": true}}).
    success(function(data) {
      $scope.loadNode(node);
    }).
    error(errorHandler);
  }

  $scope.copyDirAux = function(node, tarjet){
    $http({method: 'GET', url: $scope.getPrefix() + keyPrefix + node.key}).
      success(function(data) {
        prepNodes(data.node.nodes,node);
        node.nodes = data.node.nodes;
        for(var key in node.nodes){
          if (node.nodes[key].dir) {
            $scope.copyDirAux(node.nodes[key], tarjet + node.nodes[key].name + "/")
          } else {
            var url = $scope.getPrefix() + keyPrefix + tarjet + node.nodes[key].name
            $http({method: 'PUT',
              url: url,
              params: {"value": node.nodes[key].value}}).
            error(errorHandler);
          }
        }
      }).
      error(errorHandler);
  }

  $scope.copyDir = function(node){
    var dirName = prompt("Copy properties to directory", node.key);
    if(!dirName || dirName == "") return;
    dirName = $scope.formatDir(dirName);
    $scope.copyDirAux(node, dirName)
  }

  $scope.deleteDir = function(node) {
    if(!confirm("Are you sure you want to delete " + node.key)) return;
    $http({method: 'DELETE',
      url: $scope.getPrefix() + keyPrefix + node.key + "?dir=true&recursive=true"}).
    success(function(data) {
      $scope.loadNode(node.parent);
    }).
    error(errorHandler);
  }

  $scope.formatDir = function(dirName){
    if(dirName.substr(dirName.trim().length - 1) != '/'){
      dirName += '/';
    }
    return dirName;
  }

  $scope.submit();

  function prepNodes(nodes,parent){
    for(var key in nodes){
      var node = nodes[key];
      var name = node.key.substring(node.key.lastIndexOf("/")+1);
      node.name = name;
      node.parent = parent;
    }
  }

  $scope.loadStats = function(){
    console.log("LOAD STATS");
    $scope.stats = {};
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/store"}).
    success(function(data) {
      $scope.stats.store = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
    delete $scope.storeStats;
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/leader"}).
    success(function(data) {
      $scope.stats.leader = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
    delete $scope.storeStats;
    $http({method: 'GET', url: $scope.getPrefix() + statsPrefix + "/self"}).
    success(function(data) {
      $scope.stats.self = JSON.stringify(data, null, " ");
    }).
    error(errorHandler);
  }

}]);

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});
<|endoftext|>


<commit_before>var matriz = new Array([],[]);
var iteracoes;
var prodqtd;
var maqqtd;
function isInt(value) {
  return !isNaN(value) &&
         parseInt(Number(value)) == value &&
         !isNaN(parseInt(value, 10));
}
function limpaTabela()
{
	var table = document.getElementById("tblin");
		table.innerHTML = "";
}
function criaTabela(prodqtd,maqqtd)
{

		var b,c;
		var table = document.getElementById("tblin");
		table.innerHTML = "";
		for(b=0;b<maqqtd;b++)
		{
			var row = table.insertRow(b);
			row.innerHTML = "Máquina " + (b+1);
			for(c=0;c<prodqtd;c++)
			{		var cell = row.insertCell(c);
					cell.innerHTML = '<input type="checkbox" id="p'+(c+1) +'m'+(b+1)+'">';

			}
		}
		var head = table.insertRow(0);
			for(c=0;c<prodqtd;c++)
		{
			var cell1 = head.insertCell(c);
			cell1.innerHTML = "P"+(c+1);
		}
		cell1 = head.insertCell(0);
		cell1.innerHTML = "VHDL";
}

function Magica()
{
	// Tentando pegar entradas
        prodqtd = document.getElementById("prodtxt").value;
        maqqtd = document.getElementById("maqtxt").value;
	// Verificando se as entradas são válidas
	if(!isInt(prodqtd) || !isInt(maqqtd)){
		alert("Por favor, entre com entradas válidas primeiramente!");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	if(prodqtd<=0 || maqqtd<=0)
	{
		alert("Apenas Números válidos por favor");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	else if(prodqtd>=45 || maqqtd>=45)
	{
		alert("Por limitações computacionais, entre com uma matriz de até 45x45");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	document.getElementById("entradas").style.display = "none"; // OCULTA INPUT FIELDS
 	document.getElementById("bnt2").style.display = "inline"; // E MOSTRA BT2
  document.getElementById("bnt3").style.display = "inline";
	criaTabela(prodqtd,maqqtd);
}

function Magica2()
{
//	 alert("Chama funcao calcular do codigo.js");
   lerMatriz();
   document.getElementById("resultado").style.display = "inline";
   iteracoes = 0;
   roc();

	 /*if (confirm('Gostaria de tentar com outra entrada?')) {
		document.getElementById("entradas").style.display = "initial"; // OCULTA INPUT FIELDS
		document.getElementById("bnt2").style.display = "none";
		limpaTabela();
}	 else {
		window.location.href = "obrigado.html";
}*/
}

function lerMatriz()
{
    var a,b;
    matriz = new Array();
    for(b=0;b<prodqtd;b++){
        matriz[b] = new Array();
        for(a=0; a<maqqtd;a++)
        {
            if ($("#p"+(b+1)+"m"+(a+1)).is(":checked"))
                matriz[b][a] = 1;
            else
                matriz[b][a] = 0;
        }
    }
    matriz[prodqtd] = new Array();
    matriz[+prodqtd+1] = new Array();
    for(b=0;b<prodqtd;b++)
      matriz[b][maqqtd] = b; // Definiu os prods ids
    for(a=0; a<maqqtd;a++)
      matriz[prodqtd][a] = a; // Definiu os maqs ids
}

function gerarMatrizcna()
{

}

function imprimeMatriz(matriz_arg,destino)
{
  iteracoes++;
  document.getElementById(destino).innerHTML += "A matriz ficará assim na "+iteracoes+"ª iteração:

";
  var table = document.getElementById("ite"+iteracoes);
  for(b=0;b<maqqtd;b++)
  {
    var row = table.insertRow(b);
    row.innerHTML = "Máquina " + (b+1);
    for(c=0;c<prodqtd;c++)
    {		var cell = row.insertCell(c);
        cell.innerHTML = '<input type="checkbox" id="p'+(c+1) +'m'+(b+1)+'i'+iteracoes+'">';
        if(matriz_arg[c][b]==1)
          $('#p'+(c+1) +'m'+(b+1)+'i'+iteracoes+'').prop('checked', true);
    }
  }
  var head = table.insertRow(0);
    for(c=0;c<prodqtd;c++)
  {
    var cell1 = head.insertCell(c);
    cell1.innerHTML = "P"+(c+1);
  }
  cell1 = head.insertCell(0);
  cell1.innerHTML = "VHDL";

}
function roc()
{
    imprimeMatriz(matriz_aux, "roc");
    var matriz_aux = new Array([],[]);
    copiarMatrizes(matriz, matriz_aux, prodqtd,maqqtd);
    somarLinhas(matriz_aux, prodqtd, maqqtd);
    ordenaMatrizLinhas(matriz_aux, prodqtd, maqqtd);
    somarColunas(matriz_aux, prodqtd, maqqtd);
    ordenaMatrizColunas(matriz_aux, prodqtd, maqqtd);

    if(!compararMatrizes(matriz, matriz_aux, i,j)) // Se tem que fazer mais iteracoes
    {
        copiarMatrizes(matriz_aux,matriz, prodqtd, maqqtd);
        roc();
    }
}
function compararMatrizes(matriz1, matriz2, i,j)
{
    var b,c;
    for(b=0;b<i;jb++)
        for(c=o;c<j;c++)
            if(matriz1[b][c]!==matriz2[b][c])
                return 0;
    return 1;
}

function somarLinhas(matriz_arg, i, j)
{
    var a,b;
    for(b=0;b<j;b++)
      for(a=0;a<i;a++)
      {
        matriz_arg[i+1][b] += matriz_arg[a][b];
      }
}

function somarColunas(matriz_arg, i, j)
{
  var a,b;
  for(b=0;b<i;b++)
    for(a=0;a<j;a++)
    {
      matriz_arg[b][j+1] += matriz_arg[b][a];
    }
}

var aux = new Array();
for(c=0; c<linha+2; c++)
  aux[c]= m[l][c];
  m[l][c] = m[d][c];
  m[d][c] = aux[c];
/*
// Dada uma matriz de I produtos e J máquinas, onde no slot i,j temos o número do produto/máquina
// e no slot i+1, j+1 temos os slots destinado para as somas

function copiarMatrizes(matriz1, matriz2, i,j)
{

}

function ordenaMatrizLinha(matriz_arg, i, j)
{
    // Usar como referencia a função ordenar
    // trocar a linha inteira
}

function ordenaMatrizColuna(matriz_arg, i, j)
{
  //idem acima
}

function ordenar(vetor,i,j)
{
    var min,c, aux;
    if(i<j)
    {
        min = i;
        for(c=i+1; c<j;c++)
            if(vetor[i]<vetor[min])
                min = i;
        aux = vetor[i]; // A troca aqui seria a linha toda e não só um elemento
        vetor[i] = vetor[min]; //idem, forzinho
        vetor[min] = i; //idem
        ordenaVetor(vetor, ++i,j);
    }
}
*/
<commit_msg>acrescentei a potencia de 2 na soma<commit_after>var matriz = new Array([],[]);
var iteracoes;
var prodqtd;
var maqqtd;
function isInt(value) {
  return !isNaN(value) &&
         parseInt(Number(value)) == value &&
         !isNaN(parseInt(value, 10));
}
function limpaTabela()
{
	var table = document.getElementById("tblin");
		table.innerHTML = "";
}
function criaTabela(prodqtd,maqqtd)
{

		var b,c;
		var table = document.getElementById("tblin");
		table.innerHTML = "";
		for(b=0;b<maqqtd;b++)
		{
			var row = table.insertRow(b);
			row.innerHTML = "Máquina " + (b+1);
			for(c=0;c<prodqtd;c++)
			{		var cell = row.insertCell(c);
					cell.innerHTML = '<input type="checkbox" id="p'+(c+1) +'m'+(b+1)+'">';

			}
		}
		var head = table.insertRow(0);
			for(c=0;c<prodqtd;c++)
		{
			var cell1 = head.insertCell(c);
			cell1.innerHTML = "P"+(c+1);
		}
		cell1 = head.insertCell(0);
		cell1.innerHTML = "VHDL";
}

function Magica()
{
	// Tentando pegar entradas
        prodqtd = document.getElementById("prodtxt").value;
        maqqtd = document.getElementById("maqtxt").value;
	// Verificando se as entradas são válidas
	if(!isInt(prodqtd) || !isInt(maqqtd)){
		alert("Por favor, entre com entradas válidas primeiramente!");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	if(prodqtd<=0 || maqqtd<=0)
	{
		alert("Apenas Números válidos por favor");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	else if(prodqtd>=45 || maqqtd>=45)
	{
		alert("Por limitações computacionais, entre com uma matriz de até 45x45");
		document.getElementById("prodtxt").value = "";
		document.getElementById("maqtxt").value = "";
		document.getElementById("prodtxt").focus();
		return;
	}
	document.getElementById("entradas").style.display = "none"; // OCULTA INPUT FIELDS
 	document.getElementById("bnt2").style.display = "inline"; // E MOSTRA BT2
  document.getElementById("bnt3").style.display = "inline";
	criaTabela(prodqtd,maqqtd);
}

function Magica2()
{
//	 alert("Chama funcao calcular do codigo.js");
   lerMatriz();
   document.getElementById("resultado").style.display = "inline";
   iteracoes = 0;
   roc();

	 /*if (confirm('Gostaria de tentar com outra entrada?')) {
		document.getElementById("entradas").style.display = "initial"; // OCULTA INPUT FIELDS
		document.getElementById("bnt2").style.display = "none";
		limpaTabela();
}	 else {
		window.location.href = "obrigado.html";
}*/
}

function lerMatriz()
{
    var a,b;
    matriz = new Array();
    for(b=0;b<prodqtd;b++){
        matriz[b] = new Array();
        for(a=0; a<maqqtd;a++)
        {
            if ($("#p"+(b+1)+"m"+(a+1)).is(":checked"))
                matriz[b][a] = 1;
            else
                matriz[b][a] = 0;
        }
    }
    matriz[prodqtd] = new Array();
    matriz[+prodqtd+1] = new Array();
    for(b=0;b<prodqtd;b++)
      matriz[b][maqqtd] = b; // Definiu os prods ids
    for(a=0; a<maqqtd;a++)
      matriz[prodqtd][a] = a; // Definiu os maqs ids
}

function gerarMatrizcna()
{

}

function imprimeMatriz(matriz_arg,destino)
{
  iteracoes++;
  document.getElementById(destino).innerHTML += "A matriz ficará assim na "+iteracoes+"ª iteração:

";
  var table = document.getElementById("ite"+iteracoes);
  for(b=0;b<maqqtd;b++)
  {
    var row = table.insertRow(b);
    row.innerHTML = "Máquina " + (b+1);
    for(c=0;c<prodqtd+1;c++)
    {		var cell = row.insertCell(c);
        cell.innerHTML = '<input type="checkbox" id="p'+(c+1) +'m'+(b+1)+'i'+iteracoes+'">';
        if(matriz_arg[c][b]==1)
          $('#p'+(c+1) +'m'+(b+1)+'i'+iteracoes+'').prop('checked', true);
    }
  }
  var head = table.insertRow(0);
    for(c=0;c<prodqtd;c++)
  {
    var cell1 = head.insertCell(c);
    cell1.innerHTML = "P"+(c+1);
  }
  cell1 = head.insertCell(0);
  cell1.innerHTML = "VHDL";

}
function roc()
{
    imprimeMatriz(matriz_aux, "roc");
    var matriz_aux = new Array([],[]);
    copiarMatrizes(matriz, matriz_aux, prodqtd,maqqtd);
    somarLinhas(matriz_aux, prodqtd, maqqtd);
    ordenaMatrizLinhas(matriz_aux, prodqtd, maqqtd);
    somarColunas(matriz_aux, prodqtd, maqqtd);
    ordenaMatrizColunas(matriz_aux, prodqtd, maqqtd);

    if(!compararMatrizes(matriz, matriz_aux, i,j)) // Se tem que fazer mais iteracoes
    {
        copiarMatrizes(matriz_aux,matriz, prodqtd, maqqtd);
        roc();
    }
}
function compararMatrizes(matriz1, matriz2, i,j)
{
    var b,c;
    for(b=0;b<i;jb++)
        for(c=o;c<j;c++)
            if(matriz1[b][c]!==matriz2[b][c])
                return 0;
    return 1;
}

function somarLinhas(matriz_arg)
{
	var a,b,c;

	for(a=0; a<maq; a++){
		matriz_arg[a][prodqtd+1] = 0;
	}

	for(a=0;a<maqqtd;a++){
    	c=1;
    	for(b=prodqtd-1;b>=0;b++){
        	matriz_arg[a][prod+1] += matriz_arg[a][b]*c;
        	c *= 2;
      	}
   }
}

function somarColunas(matriz_arg)
{
  var a,b;
  for(a=0; a<prodqtd; a++){
		matriz_arg[maqqtd+1][a] = 0;
	}

	for(b=0; b<prodqtd; b++){
	c=1;
		for(a=maqqtd-1; a>=0; a--){
			matriz_arg[maqqtd+1][b] += matriz_arg[a][b]*c;
			c *= 2;
		}
	}
}

var aux = new Array();
for(c=0; c<linha+2; c++)
  aux[c]= m[l][c];
  m[l][c] = m[d][c];
  m[d][c] = aux[c];
/*
// Dada uma matriz de I produtos e J máquinas, onde no slot i,j temos o número do produto/máquina
// e no slot i+1, j+1 temos os slots destinado para as somas

function copiarMatrizes(matriz1, matriz2, i,j)
{

}

function ordenaMatrizLinha(matriz_arg, i, j)
{
    // Usar como referencia a função ordenar
    // trocar a linha inteira
}

function ordenaMatrizColuna(matriz_arg, i, j)
{
  //idem acima
}

function ordenar(vetor,i,j)
{
    var min,c, aux;
    if(i<j)
    {
        min = i;
        for(c=i+1; c<j;c++)
            if(vetor[i]<vetor[min])
                min = i;
        aux = vetor[i]; // A troca aqui seria a linha toda e não só um elemento
        vetor[i] = vetor[min]; //idem, forzinho
        vetor[min] = i; //idem
        ordenaVetor(vetor, ++i,j);
    }
}
*/
<|endoftext|>


<commit_before>/**
 * Listens to pub sub events from the VFS server and reconnects VFS as neccessary
 */
define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "pubsub", "vfs", "metrics", "vfs.endpoint", "dialog.alert"
    ];
    main.provides = ["vfs.listener"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var pubsub = imports.pubsub;
        var vfs = imports.vfs;
        var vfsEndpoint = imports["vfs.endpoint"];
        var metrics = imports.metrics;
        var showAlert = imports["dialog.alert"].show;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            pubsub.on("message", function(m) {
                if (m.type !== "workspace") return;

                if (m.action == "state_changed") {
                    metrics.increment("vfs.state_changed", 1, true);

                    vfsEndpoint.clearCache();
                    vfs.reconnect();
                }
                else if (m.action == "remote_changed") {
                    metrics.increment("vfs.remote_changed", 1, true);
                    vfsEndpoint.clearCache();

                    showAlert("Workspace configuration changed!",
                        "The configuration of this workspace has changed.",
                        "Cloud9 will be reloaded in order to activate the changes.",
                        function() {
                            setTimeout(function() {
                                window.location.reload()
                            }, 500);
                        }
                    );
                }
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("unload", function() {
            loaded = false;
        });

        /***** Register and define API *****/

        plugin.freezePublicAPI({});

        register(null, {
            "vfs.listener": plugin
        });
    }
});<commit_msg>coding style<commit_after>/**
 * Listens to pub sub events from the VFS server and reconnects VFS as neccessary
 */
define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "pubsub", "vfs", "metrics", "vfs.endpoint", "dialog.alert"
    ];
    main.provides = ["vfs.listener"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var pubsub = imports.pubsub;
        var vfs = imports.vfs;
        var vfsEndpoint = imports["vfs.endpoint"];
        var metrics = imports.metrics;
        var showAlert = imports["dialog.alert"].show;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            pubsub.on("message", function(m) {
                if (m.type !== "workspace") return;

                if (m.action == "state_changed") {
                    metrics.increment("vfs.state_changed", 1, true);

                    vfsEndpoint.clearCache();
                    vfs.reconnect();
                }
                else if (m.action == "remote_changed") {
                    metrics.increment("vfs.remote_changed", 1, true);
                    vfsEndpoint.clearCache();

                    showAlert("Workspace configuration changed!",
                        "The configuration of this workspace has changed.",
                        "Cloud9 will be reloaded in order to activate the changes.",
                        function() {
                            setTimeout(function() {
                                window.location.reload();
                            }, 500);
                        }
                    );
                }
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("unload", function() {
            loaded = false;
        });

        /***** Register and define API *****/

        plugin.freezePublicAPI({});

        register(null, {
            "vfs.listener": plugin
        });
    }
});<|endoftext|>


<commit_before>import { checkParamOrThrow } from 'apify-client/build/utils';
import log from 'apify-shared/log';
import _ from 'underscore';
import Promise from 'bluebird';
import BasicCrawler from './basic_crawler';
import PuppeteerPool from './puppeteer_pool';
import { isPromise } from './utils';

const DEFAULT_OPTIONS = {
    gotoFunction: ({ request, page }) => page.goto(request.url, { timeout: 60000 }),
    pageOpsTimeoutMillis: 300000,
};

const PAGE_CLOSE_TIMEOUT_MILLIS = 30000;

/**
 * Provides a simple framework for parallel crawling of web pages
 * using headless Chrome with [Puppeteer](https://github.com/GoogleChrome/puppeteer).
 * The URLs of pages to visit are given by `Request` objects that are fed from a list (see `RequestList` class)
 * or from a dynamic queue (see `RequestQueue` class).
 *
 * `PuppeteerCrawler` opens a new Chrome page (i.e. tab) for each `Request` object to crawl
 * and then calls the function provided by user as the `handlePageFunction` option.
 * New tasks are only started if there is enough free CPU and memory available,
 * using the `AutoscaledPool` class internally.
 *
 * Basic usage:
 *
 * ```javascript
 * const crawler = new Apify.PuppeteerCrawler({
 *     requestList,
 *     handlePageFunction: async ({ page, request }) => {
 *         // This function is called to extract data from a single web page
 *         // 'page' is an instance of Puppeteer.Page with page.goto(request.url) already called
 *         // 'request' is an instance of Request class with information about the page to load
 *         await Apify.pushData({
 *             title: await page.title(),
 *             url: request.url,
 *             succeeded: true,
 *         })
 *     },
 *     handleFailedRequestFunction: async ({ request }) => {
 *         // This function is called when crawling of a request failed too many time
 *         await Apify.pushData({
 *             url: request.url,
 *             succeeded: false,
 *             errors: request.errorMessages,
 *         })
 *     },
 * });
 *
 * await crawler.run();
 * ```
 *
 * @param {RequestList} [options.requestList]
 *   List of the requests to be processed.
 *   See the `requestList` parameter of `BasicCrawler` for more details.
 * @param {RequestQueue} [options.requestQueue]
 *   Queue of the requests to be processed.
 *   See the `requestQueue` parameter of `BasicCrawler` for more details.
 * @param {Function} [options.handlePageFunction]
 *   Function that is called to process each request.
 *   It is passed an object with the following fields:
 *   `request` is an instance of the `Request` object with details about the URL to open, HTTP method etc.
 *   `page` is an instance of the `Puppeteer.Page` class with `page.goto(request.url)` already called.
 * @param {Number} [options.pageOpsTimeoutMillis=300000]
 *   Timeout in which the function passed as `options.handlePageFunction` needs to finish.
 * @param {Function} [options.gotoFunction=({ request, page }) => page.goto(request.url, { timeout: 60000 })]
 *   Overrides the function that opens the request in Puppeteer.
 *   The function should return a result of Puppeteer's
 *   page.goto() function,
 *   i.e. a promise resolving to the Response object.
 *
 *   For example, this is useful if you need to extend the page load timeout or select a different criteria
 *   to determine that the navigation succeeded.
 *
 *   Note that a single page object is only used to process a single request and it is closed afterwards.
 * @param {Function} [options.handleFailedRequestFunction=({ request }) => log.error('Request failed', _.pick(request, 'url', 'uniqueKey'))]
 *   Function to handle requests that failed more than `option.maxRequestRetries` times. See the `handleFailedRequestFunction`
 *   parameter of `Apify.BasicCrawler` for details.
 * @param {Number} [options.maxRequestRetries=3]
 *   Indicates how many times each request is retried if `handleRequestFunction` failed.
 *   See `maxRequestRetries` parameter of `BasicCrawler`.
 * @param {Number} [options.maxRequestsPerCrawl]
 *   Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
 *   Always set this value in order to prevent infinite loops in misconfigured crawlers.
 *   Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
 *   See `maxRequestsPerCrawl` parameter of `BasicCrawler`.
 * @param {Number} [options.maxMemoryMbytes]
 *   Maximum memory available for crawling. See `maxMemoryMbytes` parameter of `AutoscaledPool`.
 * @param {Number} [options.maxConcurrency=1000]
 *   Maximum concurrency of request processing. See `maxConcurrency` parameter of `AutoscaledPool`.
 * @param {Number} [options.minConcurrency=1]
 *   Minimum concurrency of requests processing. See `minConcurrency` parameter of `AutoscaledPool`.
 * @param {Number} [options.minFreeMemoryRatio=0.2]
 *   Minimum ratio of free memory kept in the system. See `minFreeMemoryRatio` parameter of `AutoscaledPool`.
 * @param {Function} [opts.isFinishedFunction]
 *   By default PuppeteerCrawler finishes when all the requests have been processed.
 *   You can override this behaviour by providing custom `isFinishedFunction`.
 *   This function that is called every time there are no requests being processed.
 *   If it resolves to `true` then the crawler's run finishes.
 *   See `isFinishedFunction` parameter of `AutoscaledPool`.
 * @param {Number} [options.maxOpenPagesPerInstance=50]
 *   Maximum number of opened tabs per browser. If this limit is reached then a new
 *   browser instance is started. See `maxOpenPagesPerInstance` parameter of `PuppeteerPool`.
 * @param {Number} [options.retireInstanceAfterRequestCount=100]
 *   Maximum number of requests that can be processed by a single browser instance.
 *   After the limit is reached the browser will be retired and new requests will
 *   be handled by a new browser instance.
 *   See `retireInstanceAfterRequestCount` parameter of `PuppeteerPool`.
 * @param {Number} [options.instanceKillerIntervalMillis=60000]
 *   How often the launched Puppeteer instances are checked whether they can be
 *   closed. See `instanceKillerIntervalMillis` parameter of `PuppeteerPool`.
 * @param {Number} [options.killInstanceAfterMillis=300000]
 *   If Puppeteer instance reaches the `options.retireInstanceAfterRequestCount` limit then
 *   it is considered retired and no more tabs will be opened. After the last tab is closed
 *   the whole browser is closed too. This parameter defines a time limit for inactivity
 *   after which the browser is closed even if there are pending tabs. See
 *   `killInstanceAfterMillis` parameter of `PuppeteerPool`.
 * @param {Object} [options.puppeteerConfig={ dumpio: process.env.NODE_ENV !== 'production', slowMo: 0, args: []}]
 *   Default options for each new `Puppeteer` instance. See `puppeteerConfig` parameter of `PuppeteerPool`.
 * @param {Function} [options.launchPuppeteerFunction=launchPuppeteerOptions => Apify.launchPuppeteer(launchPuppeteerOptions)]
 *   Overrides the default function to launch a new Puppeteer instance.
 *   See `launchPuppeteerFunction` parameter of `PuppeteerPool`.
 * @param {LaunchPuppeteerOptions} [options.launchPuppeteerOptions]
 *   Options used by `Apify.launchPuppeteer()` to start new Puppeteer instances.
 *   See `launchPuppeteerOptions` parameter of `PuppeteerPool`.
 */
export default class PuppeteerCrawler {
    constructor(opts) {
        // For backwards compatibility, in the future we can remove this...
        if (!opts.retireInstanceAfterRequestCount && opts.abortInstanceAfterRequestCount) {
            log.warning('PuppeteerCrawler: Parameter `abortInstanceAfterRequestCount` is deprecated! Use `retireInstanceAfterRequestCount` instead!');
            opts.retireInstanceAfterRequestCount = opts.abortInstanceAfterRequestCount;
        }

        const {
            handlePageFunction,
            gotoFunction,
            pageOpsTimeoutMillis,

            // Autoscaled pool options
            maxMemoryMbytes,
            maxConcurrency,
            minConcurrency,
            minFreeMemoryRatio,
            isFinishedFunction,

            // Basic crawler options
            requestList,
            requestQueue,
            maxRequestRetries,
            maxRequestsPerCrawl,
            handleFailedRequestFunction,

            // Puppeteer Pool options
            maxOpenPagesPerInstance,
            retireInstanceAfterRequestCount,
            instanceKillerIntervalMillis,
            killInstanceAfterMillis,
            launchPuppeteerFunction,
            launchPuppeteerOptions,
        } = _.defaults(opts, DEFAULT_OPTIONS);

        checkParamOrThrow(handlePageFunction, 'opts.handlePageFunction', 'Function');
        checkParamOrThrow(handleFailedRequestFunction, 'opts.handleFailedRequestFunction', 'Maybe Function');
        checkParamOrThrow(gotoFunction, 'opts.gotoFunction', 'Function');

        this.handlePageFunction = handlePageFunction;
        this.gotoFunction = gotoFunction;
        this.pageOpsTimeoutMillis = pageOpsTimeoutMillis;

        this.puppeteerPool = new PuppeteerPool({
            maxOpenPagesPerInstance,
            retireInstanceAfterRequestCount,
            instanceKillerIntervalMillis,
            killInstanceAfterMillis,
            launchPuppeteerFunction,
            launchPuppeteerOptions,
        });

        this.basicCrawler = new BasicCrawler({
            // Basic crawler options.
            requestList,
            requestQueue,
            maxRequestRetries,
            maxRequestsPerCrawl,
            handleRequestFunction: (...args) => this._handleRequestFunction(...args),
            handleFailedRequestFunction,

            // Autoscaled pool options.
            maxMemoryMbytes,
            maxConcurrency,
            minConcurrency,
            minFreeMemoryRatio,
            isFinishedFunction,
            ignoreMainProcess: true,
        });
    }

    /**
     * Runs the crawler. Returns promise that gets resolved once all the requests got processed.
     *
     * @return {Promise}
     */
    run() {
        return this.basicCrawler.run()
            .finally(() => this.puppeteerPool.destroy());
    }

    /**
     * Wrapper around handlePageFunction that opens and closes pages etc.
     *
     * @ignore
     */
    _handleRequestFunction({ request }) {
        let page;

        return this.puppeteerPool
            .newPage()
            .then((newPage) => { page = newPage; })
            .then(() => this.gotoFunction({ page, request, puppeteerPool: this.puppeteerPool }))
            .then((response) => {
                const promise = this.handlePageFunction({
                    page,
                    request,
                    puppeteerPool: this.puppeteerPool,
                    response,
                });

                if (!isPromise(promise)) throw new Error('User provided handlePageFunction must return a Promise.');

                return promise;
            })
            .timeout(this.pageOpsTimeoutMillis, 'PuppeteerCrawler: handlePageFunction timed out.')
            .finally(() => {
                return Promise
                    .try(() => {
                        if (page) return page.close();
                    })
                    .timeout(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.')
                    .catch(err => log.debug('PuppeteerCrawler: Page.close() failed.', { reason: err ? err.message : err }));
            });
    }
}
<commit_msg>Applied feedback from PR comments<commit_after>import { checkParamOrThrow } from 'apify-client/build/utils';
import log from 'apify-shared/log';
import _ from 'underscore';
import Promise from 'bluebird';
import BasicCrawler from './basic_crawler';
import PuppeteerPool from './puppeteer_pool';
import { isPromise } from './utils';

const DEFAULT_OPTIONS = {
    gotoFunction: ({ request, page }) => page.goto(request.url, { timeout: 60000 }),
    pageOpsTimeoutMillis: 300000,
};

const PAGE_CLOSE_TIMEOUT_MILLIS = 30000;

/**
 * Provides a simple framework for parallel crawling of web pages
 * using headless Chrome with [Puppeteer](https://github.com/GoogleChrome/puppeteer).
 * The URLs of pages to visit are given by `Request` objects that are fed from a list (see `RequestList` class)
 * or from a dynamic queue (see `RequestQueue` class).
 *
 * `PuppeteerCrawler` opens a new Chrome page (i.e. tab) for each `Request` object to crawl
 * and then calls the function provided by user as the `handlePageFunction` option.
 * New tasks are only started if there is enough free CPU and memory available,
 * using the `AutoscaledPool` class internally.
 *
 * Basic usage:
 *
 * ```javascript
 * const crawler = new Apify.PuppeteerCrawler({
 *     requestList,
 *     handlePageFunction: async ({ page, request }) => {
 *         // This function is called to extract data from a single web page
 *         // 'page' is an instance of Puppeteer.Page with page.goto(request.url) already called
 *         // 'request' is an instance of Request class with information about the page to load
 *         await Apify.pushData({
 *             title: await page.title(),
 *             url: request.url,
 *             succeeded: true,
 *         })
 *     },
 *     handleFailedRequestFunction: async ({ request }) => {
 *         // This function is called when crawling of a request failed too many time
 *         await Apify.pushData({
 *             url: request.url,
 *             succeeded: false,
 *             errors: request.errorMessages,
 *         })
 *     },
 * });
 *
 * await crawler.run();
 * ```
 *
 * @param {RequestList} [options.requestList]
 *   List of the requests to be processed.
 *   See the `requestList` parameter of `BasicCrawler` for more details.
 * @param {RequestQueue} [options.requestQueue]
 *   Queue of the requests to be processed.
 *   See the `requestQueue` parameter of `BasicCrawler` for more details.
 * @param {Function} [options.handlePageFunction]
 *   Function that is called to process each request.
 *   It is passed an object with the following fields:
 *   `request` is an instance of the `Request` object with details about the URL to open, HTTP method etc.
 *   `page` is an instance of the `Puppeteer.Page` class with `page.goto(request.url)` already called.
 * @param {Number} [options.pageOpsTimeoutMillis=300000]
 *   Timeout in which the function passed as `options.handlePageFunction` needs to finish.
 * @param {Function} [options.gotoFunction=({ request, page }) => page.goto(request.url, { timeout: 60000 })]
 *   Overrides the function that opens the request in Puppeteer.
 *   The function should return a result of Puppeteer's
 *   page.goto() function,
 *   i.e. a promise resolving to the Response object.
 *
 *   For example, this is useful if you need to extend the page load timeout or select a different criteria
 *   to determine that the navigation succeeded.
 *
 *   Note that a single page object is only used to process a single request and it is closed afterwards.
 * @param {Function} [options.handleFailedRequestFunction=({ request }) => log.error('Request failed', _.pick(request, 'url', 'uniqueKey'))]
 *   Function to handle requests that failed more than `option.maxRequestRetries` times. See the `handleFailedRequestFunction`
 *   parameter of `Apify.BasicCrawler` for details.
 * @param {Number} [options.maxRequestRetries=3]
 *   Indicates how many times each request is retried if `handleRequestFunction` failed.
 *   See `maxRequestRetries` parameter of `BasicCrawler`.
 * @param {Number} [options.maxRequestsPerCrawl]
 *   Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
 *   Always set this value in order to prevent infinite loops in misconfigured crawlers.
 *   Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
 *   See `maxRequestsPerCrawl` parameter of `BasicCrawler`.
 * @param {Number} [options.maxMemoryMbytes]
 *   Maximum memory available for crawling. See `maxMemoryMbytes` parameter of `AutoscaledPool`.
 * @param {Number} [options.maxConcurrency=1000]
 *   Maximum concurrency of request processing. See `maxConcurrency` parameter of `AutoscaledPool`.
 * @param {Number} [options.minConcurrency=1]
 *   Minimum concurrency of requests processing. See `minConcurrency` parameter of `AutoscaledPool`.
 * @param {Number} [options.minFreeMemoryRatio=0.2]
 *   Minimum ratio of free memory kept in the system. See `minFreeMemoryRatio` parameter of `AutoscaledPool`.
 * @param {Function} [opts.isFinishedFunction]
 *   By default PuppeteerCrawler finishes when all the requests have been processed.
 *   You can override this behaviour by providing custom `isFinishedFunction`.
 *   This function that is called every time there are no requests being processed.
 *   If it resolves to `true` then the crawler's run finishes.
 *   See `isFinishedFunction` parameter of `AutoscaledPool`.
 * @param {Number} [options.maxOpenPagesPerInstance=50]
 *   Maximum number of opened tabs per browser. If this limit is reached then a new
 *   browser instance is started. See `maxOpenPagesPerInstance` parameter of `PuppeteerPool`.
 * @param {Number} [options.retireInstanceAfterRequestCount=100]
 *   Maximum number of requests that can be processed by a single browser instance.
 *   After the limit is reached the browser will be retired and new requests will
 *   be handled by a new browser instance.
 *   See `retireInstanceAfterRequestCount` parameter of `PuppeteerPool`.
 * @param {Number} [options.instanceKillerIntervalMillis=60000]
 *   How often the launched Puppeteer instances are checked whether they can be
 *   closed. See `instanceKillerIntervalMillis` parameter of `PuppeteerPool`.
 * @param {Number} [options.killInstanceAfterMillis=300000]
 *   If Puppeteer instance reaches the `options.retireInstanceAfterRequestCount` limit then
 *   it is considered retired and no more tabs will be opened. After the last tab is closed
 *   the whole browser is closed too. This parameter defines a time limit for inactivity
 *   after which the browser is closed even if there are pending tabs. See
 *   `killInstanceAfterMillis` parameter of `PuppeteerPool`.
 * @param {Object} [options.puppeteerConfig={ dumpio: process.env.NODE_ENV !== 'production', slowMo: 0, args: []}]
 *   Default options for each new `Puppeteer` instance. See `puppeteerConfig` parameter of `PuppeteerPool`.
 * @param {Function} [options.launchPuppeteerFunction=launchPuppeteerOptions => Apify.launchPuppeteer(launchPuppeteerOptions)]
 *   Overrides the default function to launch a new Puppeteer instance.
 *   See `launchPuppeteerFunction` parameter of `PuppeteerPool`.
 * @param {LaunchPuppeteerOptions} [options.launchPuppeteerOptions]
 *   Options used by `Apify.launchPuppeteer()` to start new Puppeteer instances.
 *   See `launchPuppeteerOptions` parameter of `PuppeteerPool`.
 */
export default class PuppeteerCrawler {
    constructor(opts) {
        // For backwards compatibility, in the future we can remove this...
        if (!opts.retireInstanceAfterRequestCount && opts.abortInstanceAfterRequestCount) {
            log.warning('PuppeteerCrawler: Parameter `abortInstanceAfterRequestCount` is deprecated! Use `retireInstanceAfterRequestCount` instead!');
            opts.retireInstanceAfterRequestCount = opts.abortInstanceAfterRequestCount;
        }

        const {
            handlePageFunction,
            gotoFunction,
            pageOpsTimeoutMillis,

            // Autoscaled pool options
            maxMemoryMbytes,
            maxConcurrency,
            minConcurrency,
            minFreeMemoryRatio,
            isFinishedFunction,

            // Basic crawler options
            requestList,
            requestQueue,
            maxRequestRetries,
            maxRequestsPerCrawl,
            handleFailedRequestFunction,

            // Puppeteer Pool options
            maxOpenPagesPerInstance,
            retireInstanceAfterRequestCount,
            instanceKillerIntervalMillis,
            killInstanceAfterMillis,
            launchPuppeteerFunction,
            launchPuppeteerOptions,
        } = _.defaults(opts, DEFAULT_OPTIONS);

        checkParamOrThrow(handlePageFunction, 'opts.handlePageFunction', 'Function');
        checkParamOrThrow(handleFailedRequestFunction, 'opts.handleFailedRequestFunction', 'Maybe Function');
        checkParamOrThrow(gotoFunction, 'opts.gotoFunction', 'Function');

        this.handlePageFunction = handlePageFunction;
        this.gotoFunction = gotoFunction;
        this.pageOpsTimeoutMillis = pageOpsTimeoutMillis;

        this.puppeteerPool = new PuppeteerPool({
            maxOpenPagesPerInstance,
            retireInstanceAfterRequestCount,
            instanceKillerIntervalMillis,
            killInstanceAfterMillis,
            launchPuppeteerFunction,
            launchPuppeteerOptions,
        });

        this.basicCrawler = new BasicCrawler({
            // Basic crawler options.
            requestList,
            requestQueue,
            maxRequestRetries,
            maxRequestsPerCrawl,
            handleRequestFunction: (...args) => this._handleRequestFunction(...args),
            handleFailedRequestFunction,

            // Autoscaled pool options.
            maxMemoryMbytes,
            maxConcurrency,
            minConcurrency,
            minFreeMemoryRatio,
            isFinishedFunction,
            ignoreMainProcess: true,
        });
    }

    /**
     * Runs the crawler. Returns promise that gets resolved once all the requests got processed.
     *
     * @return {Promise}
     */
    run() {
        return this.basicCrawler.run()
            .finally(() => this.puppeteerPool.destroy());
    }

    /**
     * Wrapper around handlePageFunction that opens and closes pages etc.
     *
     * @ignore
     */
    _handleRequestFunction({ request }) {
        let page;

        return this.puppeteerPool
            .newPage()
            .then((newPage) => { page = newPage; })
            .then(() => this.gotoFunction({ page, request, puppeteerPool: this.puppeteerPool }))
            .then((response) => {
                const promise = this.handlePageFunction({
                    page,
                    request,
                    puppeteerPool: this.puppeteerPool,
                    response,
                });

                if (!isPromise(promise)) throw new Error('User provided handlePageFunction must return a Promise.');

                return promise;
            })
            .timeout(this.pageOpsTimeoutMillis, 'PuppeteerCrawler: handlePageFunction timed out.')
            .finally(() => {
                return Promise.resolve()
                    .then(() => {
                        if (page) return page.close();
                    })
                    .timeout(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.')
                    .catch(err => log.debug('PuppeteerCrawler: Page.close() failed.', { reason: err ? err.message : err }));
            });
    }
}
<|endoftext|>


<commit_before>import pkg from '../package';

export default {
  status: {
    handler: (request, reply) => {
      reply({
        name: pkg.name,
        version: pkg.version,
        description: pkg.description,
        author: pkg.author,
        contributors: pkg.contributors,
      });
    },
  },
};
<commit_msg>Add env, uptime and memory usage to the status page<commit_after>import pkg from '../package';

export default {
  status: {
    handler: (request, reply) => {
      reply({
        name: pkg.name,
        version: pkg.version,
        description: pkg.description,
        author: pkg.author,
        contributors: pkg.contributors,
        env: process.env.NODE_ENV,
        uptime: process.uptime(),
        memory: process.memoryUsage(),
      });
    },
  },
};
<|endoftext|>


<commit_before>/*!
 * api.prabhatkumar.org® [v0.0.1]
 * @author    : Prabhat Kumar [http://prabhatkumar.org/]
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/]
 */
<commit_msg>invoking strict mode - commit.<commit_after>/*!
 * api.prabhatkumar.org® [v0.0.1]
 * @author    : Prabhat Kumar [http://prabhatkumar.org/]
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/]
 */

/* @Invoking strict mode */
"use strict";
<|endoftext|>


<commit_before> /**
 * Initialisation
 ******************************************/

(function ($)
{

  if(!('contains' in String.prototype)) {
      String.prototype.contains = function(str, startIndex) {
               return -1 !== String.prototype.indexOf.call(this, str, startIndex);
      };
  }

    var options = {
        selectors: {
            ajaxModal: '#ajax-modal'
        }
    };

    $(document).ready(function ()
    {
        $(document).initAdvancedElements();
        $.initQueryHash();
        $.initTableSelection();

        $(options.selectors.ajaxModal).on("show.bs.modal", function (e) {
            var link = $(e.relatedTarget);
            $(this).load(link.attr("href"), function () {
                $(this).initAdvancedElements();
            });
        });
        $(options.selectors.ajaxModal).on("hidden.bs.modal", function (e) {
            $(this).html("");
        });

    });

  	/**
  	 * Sélection de lignes de tableau
  	 * $.initTableSelection();
  	 ******************************************/
  	$.initTableSelection = function()
  	{
  		var tables = $('.table_selection');

  		tables.each(function()
  		{
  			var table = $(this);
  			var selecteurGlobal = table.find('thead .selecteur input');
  			var selecteursLignes = table.find('tbody .selecteur input');

  			// Selection / Déselection globale
  			selecteurGlobal.click(function()
  			{
  				if(selecteurGlobal.is(':checked'))
  				{
  					selecteursLignes.attr('checked', 'checked');
  				}
  				else
  				{
  					selecteursLignes.removeAttr('checked');
  				}
  			});

  			// Déselection unique
  			selecteursLignes.click(function()
  			{
  				var selecteur = $(this);

  				if(!selecteur.is(':checked'))
  				{
  					selecteurGlobal.removeAttr('checked');
  				}
  			});
  		});
  	};

    $.fn.initAdvancedElements = function () {

        var element = $(this);

        $(this).find('.input-float').inputNumberFormat({'decimal': 4, 'decimalAuto': 2});
        $(this).find('.input-integer').inputNumberFormat({'decimal': 0, 'decimalAuto': 0});

        $(this).find('[data-toggle="tooltip"]').tooltip({'container': 'body'});
        $(this).find('[data-toggle="popover"], .toggle-popover').popover({'container': 'body', trigger: "manual" , html: true, animation:false})
        .on("mouseenter", function () {
            var _this = this;
            $(this).popover("show");
            $(".popover").on("mouseleave", function () {
                $(_this).popover('hide');
            });
        })
        .on("mouseleave", function () {
            var _this = this;
            setTimeout(function () {
                if (!$(".popover:hover").length) {
                    $(_this).popover("hide");
                }
            }, 50);
        });

        $(this).find('[data-toggle="popover"], .toggle-popover').each(function() {
            if($(this).attr('data-content').match(/^#/)) {
                $(this).attr('data-content', $($(this).attr('data-content')).html());
            };
        });

        $(this).find('[data-toggle="popover"], .toggle-popover').on("shown.bs.popover", function(e) {
            $('.popover').initAdvancedElements();
        });

        $(this).find("select.select2").select2({
            allowClear: true
        });

        $(this).find(".select2autocomplete").each(function () {
            var urlAjax = $(this).data('ajax');
            var defaultValue = $(this).val();
            var defaultValueSplitted = defaultValue.split(',');
            var select2 = $(this);
            $(this).select2({
                onselected: function () {
                },
                initSelection: function (element, callback) {
                    if (defaultValue != '') {
                        callback({id: defaultValueSplitted[0], text: defaultValueSplitted[1]});
                        select2.val(defaultValueSplitted[0]);
                    }
                },
                placeholder: 'Entrer un nom',
                minimumInputLength: 3,
                formatInputTooShort: function (input, min) {
                    var n = min - input.length;
                    return  min + " caractère" + (n == 1 ? "" : "s") + " min";
                },
                formatNoMatches: function () {
                    return "Aucun résultat";
                },
                formatSearching: function () {
                    return "Recherche…";
                },
                allowClear: true,
                ajax: {
                    quietMillis: 150,
                    url: urlAjax,
                    dataType: 'json',
                    type: "GET",
                    data: function (term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function (data) {
                        var results = [];
                        $.each(data, function (index, item) {
                            results.push({
                                id: index,
                                text: item
                            });
                        });
                        return {
                            results: results
                        }

                    }}
            });
        });

        $(this).find(".select2SubmitOnChange").on("change", function (e) {
            if (e.val) {
                $(this).parents('form').submit();
            }
        });

        $(this).find("a.to_autofocus").focus();

        $(this).find("input[type='radio'][autofocus='autofocus']").each(function(){
            var name = $(this).attr("name");
            $(document).find("input[name='"+name+"']").each(function(){
                if(!$(this).is(":checked") && $(this).is(':focus')){
                    $(this).blur();
                }
                if($(this).is(":checked") && !$(this).is(':focus')){
                     $(this).focus();
                }
            });

        });

        $(this).find('.select2permissifNoAjax').each(function() {
	    var element = $(this);
	    var id = $(this).attr('id');
	    $(this).select2({
                data: JSON.parse($(this).attr('data-choices')),
                allowClear: true,
                multiple: false,
                createSearchChoice: function (term, data) {
                    if ($(data).filter(function () {
                        return this.text.localeCompare(term) === 0;
                    }).length === 0) {
                        return {id: term, text: term + ' (nouveau)'};
                    }
                }
            }).on("select2-close", function (e) {
		lastValue = $('#'+id).val();
                $(this).select2("val", lastValue);
                $(this).val(lastValue);
                $('#s2id_'+id).find('.select2-chosen').text(lastValue);
            })
        });

        $(this).find('.hamzastyle').each(function () {
            var select2 = $(this);
            select2.select2({
                multiple: true,
                data: function () {
                    var data = [];
                    element.find('.hamzastyle-item').each(function () {
                        data = data.concat(JSON.parse($(this).attr('data-words')));
                    });

                    var data = unique(data.sort());

                    dataFinal = [];
                    for (key in data) {
                        if (data[key] + "") {
                            dataFinal.push({id: (data[key] + ""), text: (data[key] + "")});
                        }
                    }

                    return {results: dataFinal};
                }
            })
        });

        $(this).find('.hamzastyle').on("change", function (e) {
            var select2Data = $(this).select2("data");
            var selectedWords = [];
            for (key in select2Data) {
                selectedWords.push(select2Data[key].text);
            }

            if (!selectedWords.length) {
                document.location.hash = "";
            } else {
                document.location.hash = encodeURI("#filtre=" + JSON.stringify(selectedWords));
            }
        });

        $(this).find('.input-group.date').datetimepicker({
            locale: 'fr_FR',
            format: 'L',
            allowInputToggle: true,
            focusOnShow: true,
            useCurrent: false
        });

        $(this).find("form.form-ajax-modal").on('submit', function () {
            var form = $(this);
            var callback = $(this).attr('callback');
            $.post($(this).attr('action'),
                    $(this).serialize(),
                    function (data)
                    {
                        if (!data.success) {
                            var content = form.find(form.attr('data-content')).html(data.content);
                            content.initAdvancedElements();
                            return;
                        }

                        if (form.data('related-element')) {
                            $(form.data('related-element')).trigger("modal_callback", data);
                        }

                        $(options.selectors.ajaxModal).modal('hide');
                    }, "json");

            return false;
        });

        $(this).find('.modal-autoshow').modal({
            'show': true
        });

        $(this).find('.link-submit').on('click', function () {
            var form = $($(this).attr('data-form'));
            form.attr('action', $(this).attr('href'));
            form.submit();

            return false;
        });
        $(this).find('.pointer').on('click', function () {
            if ($(this).attr('data-pointer')) {
                $($(this).attr('data-pointer')).click();
            }

            return false;
        });

        $(this).find('.dynamic-element-add').on('click', function () {
            var content = $($($(this).attr('data-template')).html().replace(/var---nbItem---/g, UUID.generate()));
            $($(this).attr('data-container')).append(content);
            content.initAdvancedElements();
        });

        $(this).find('.dynamic-element-delete').on('click', function () {
            $($(this).attr('data-line')).find('input').val("");
            $($(this).attr('data-line')).find('input').trigger('keyup');
            $($(this).attr('data-line')).remove();
            if ($($(this).attr('data-lines')).length < 1 && $(this).attr('data-add')) {
                $($(this).attr('data-add')).trigger('click');
            }
        });

        $(this).find('.btn-dynamic-element-submit').on('click', function(e) {
            var vals = $(this).parents('form').serializeArray();

            $(this).parents('form').find('.dynamic-element-delete').each(function(){
                var ligne = $($(this).attr('data-line'));
                var hasValue = false;
                ligne.find('input, select, textarea').each(function() {
                    if($(this).attr('name') && $(this).val()) {
                        hasValue = true;
                    }
                });

                if(!hasValue) {
                    $($(this).attr('data-line')).remove();
                }
            });

            return true;
        });

        /**
      	 * Sélection de lignes de tableau
      	 ******************************************/
      	$(this).find('.table_selection thead .selecteur input').each(function(){
            $(this).on('click', function(){
    			var selecteursLignes = $(this).parents('table').find('tbody .selecteur input');
      			if($(this).is(':checked')) {
      				selecteursLignes.attr('checked', 'checked');
      			} else {
      				selecteursLignes.removeAttr('checked');
      			}
            });
      	});

        $(this).find('.table_selection tbody .selecteur input').on('click', function(e){

      				var selecteur = $(this).parents('table').find('thead .selecteur input');

      				if(!$(this).is(':checked'))
      				{
      					selecteur.removeAttr('checked');
      				}
      			});

        /**
         * Contrôle la bonne saisie de nombres dans
         * un champ
         * $(s).saisieNum(float, callbackKeypress);
         ******************************************/
        $.fn.saisieNum = function (float, callbackKeypress, callbackBlur)
        {
            var champ = $(this);

            // A chaque touche pressée
            champ.keypress(function (e)
            {
                var val = $(this).val();
                var touche = e.which;
                var ponctuationPresente = (val.indexOf('.') != -1 || val.indexOf(',') != -1);
                var chiffre = (touche >= 48 && touche <= 57); // Si chiffre

                // touche "entrer"
                if (touche == 13)
                    return e;

                // touche "entrer"
                if (touche == 0)
                    return e;

                // Champ nombre décimal
                if (float)
                {
                    // !backspace && !null && !point && !virgule && !chiffre
                    if (touche != 8 && touche != 0 && touche != 46 && touche != 44 && !chiffre)
                        return false;
                    // point déjà présent
                    if (touche == 46 && ponctuationPresente)
                        e.preventDefault();
                    // virgule déjà présente
                    if (touche == 44 && ponctuationPresente)
                        e.preventDefault();
                    // 2 décimales
                    if (val.match(/[\.\,][0-9][0-9]/) && chiffre && e.currentTarget && e.currentTarget.selectionStart > val.length - 3)
                        e.preventDefault();
                }
                // Champ nombre entier
                else
                {
                    if (touche != 8 && touche != 0 && !chiffre)
                        e.preventDefault();
                }

                if (callbackKeypress)
                    callbackKeypress();
                return e;
            });
          }

          $(this).find('.btn-loading').on('click', function (e) {
                $(this).addClass('disabled');
                $(this).text($(this).attr('data-loading-text'));
          });

    }

    $.initQueryHash = function () {
        $(window).on('hashchange', function () {
            if ($(document).find('.hamzastyle').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                var filtres = [];
                if (params.filtre && params.filtre.match(/\[/)) {
                    filtres = JSON.parse(params.filtre);
                } else if (params.filtre) {
                    filtres.push(params.filtre);
                }

                var select2Data = [];
                for (key in filtres) {
                    select2Data.push({id: filtres[key], text: filtres[key]});
                }

                $(document).find('.hamzastyle').select2("data", select2Data);

                $(document).find('.hamzastyle-item').each(function () {
                    var words = $(this).attr('data-words');
                    var find = true;
                    for (key in filtres) {
                        var word = filtres[key];
                        if (words.indexOf(word) === -1) {
                            find = false;
                        }
                    }
                    if (find) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            }
            if ($(document).find('.nav.nav-tabs').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                if (params.tab) {
                    $('.nav.nav-tabs a[aria-controls="' + params.tab + '"]').tab('show');
                }
            }
        });

        if (location.hash) {
            $(window).trigger('hashchange');
        }
    }

})(jQuery);
<commit_msg>Gère les 5 décimales en js<commit_after> /**
 * Initialisation
 ******************************************/

(function ($)
{

  if(!('contains' in String.prototype)) {
      String.prototype.contains = function(str, startIndex) {
               return -1 !== String.prototype.indexOf.call(this, str, startIndex);
      };
  }

    var options = {
        selectors: {
            ajaxModal: '#ajax-modal'
        }
    };

    $(document).ready(function ()
    {
        $(document).initAdvancedElements();
        $.initQueryHash();
        $.initTableSelection();

        $(options.selectors.ajaxModal).on("show.bs.modal", function (e) {
            var link = $(e.relatedTarget);
            $(this).load(link.attr("href"), function () {
                $(this).initAdvancedElements();
            });
        });
        $(options.selectors.ajaxModal).on("hidden.bs.modal", function (e) {
            $(this).html("");
        });

    });

  	/**
  	 * Sélection de lignes de tableau
  	 * $.initTableSelection();
  	 ******************************************/
  	$.initTableSelection = function()
  	{
  		var tables = $('.table_selection');

  		tables.each(function()
  		{
  			var table = $(this);
  			var selecteurGlobal = table.find('thead .selecteur input');
  			var selecteursLignes = table.find('tbody .selecteur input');

  			// Selection / Déselection globale
  			selecteurGlobal.click(function()
  			{
  				if(selecteurGlobal.is(':checked'))
  				{
  					selecteursLignes.attr('checked', 'checked');
  				}
  				else
  				{
  					selecteursLignes.removeAttr('checked');
  				}
  			});

  			// Déselection unique
  			selecteursLignes.click(function()
  			{
  				var selecteur = $(this);

  				if(!selecteur.is(':checked'))
  				{
  					selecteurGlobal.removeAttr('checked');
  				}
  			});
  		});
  	};

    $.fn.initAdvancedElements = function () {

        var element = $(this);

        $(this).find('.input-float').inputNumberFormat({'decimal': 5, 'decimalAuto': 2});
        $(this).find('.input-integer').inputNumberFormat({'decimal': 0, 'decimalAuto': 0});

        $(this).find('[data-toggle="tooltip"]').tooltip({'container': 'body'});
        $(this).find('[data-toggle="popover"], .toggle-popover').popover({'container': 'body', trigger: "manual" , html: true, animation:false})
        .on("mouseenter", function () {
            var _this = this;
            $(this).popover("show");
            $(".popover").on("mouseleave", function () {
                $(_this).popover('hide');
            });
        })
        .on("mouseleave", function () {
            var _this = this;
            setTimeout(function () {
                if (!$(".popover:hover").length) {
                    $(_this).popover("hide");
                }
            }, 50);
        });

        $(this).find('[data-toggle="popover"], .toggle-popover').each(function() {
            if($(this).attr('data-content').match(/^#/)) {
                $(this).attr('data-content', $($(this).attr('data-content')).html());
            };
        });

        $(this).find('[data-toggle="popover"], .toggle-popover').on("shown.bs.popover", function(e) {
            $('.popover').initAdvancedElements();
        });

        $(this).find("select.select2").select2({
            allowClear: true
        });

        $(this).find(".select2autocomplete").each(function () {
            var urlAjax = $(this).data('ajax');
            var defaultValue = $(this).val();
            var defaultValueSplitted = defaultValue.split(',');
            var select2 = $(this);
            $(this).select2({
                onselected: function () {
                },
                initSelection: function (element, callback) {
                    if (defaultValue != '') {
                        callback({id: defaultValueSplitted[0], text: defaultValueSplitted[1]});
                        select2.val(defaultValueSplitted[0]);
                    }
                },
                placeholder: 'Entrer un nom',
                minimumInputLength: 3,
                formatInputTooShort: function (input, min) {
                    var n = min - input.length;
                    return  min + " caractère" + (n == 1 ? "" : "s") + " min";
                },
                formatNoMatches: function () {
                    return "Aucun résultat";
                },
                formatSearching: function () {
                    return "Recherche…";
                },
                allowClear: true,
                ajax: {
                    quietMillis: 150,
                    url: urlAjax,
                    dataType: 'json',
                    type: "GET",
                    data: function (term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function (data) {
                        var results = [];
                        $.each(data, function (index, item) {
                            results.push({
                                id: index,
                                text: item
                            });
                        });
                        return {
                            results: results
                        }

                    }}
            });
        });

        $(this).find(".select2SubmitOnChange").on("change", function (e) {
            if (e.val) {
                $(this).parents('form').submit();
            }
        });

        $(this).find("a.to_autofocus").focus();

        $(this).find("input[type='radio'][autofocus='autofocus']").each(function(){
            var name = $(this).attr("name");
            $(document).find("input[name='"+name+"']").each(function(){
                if(!$(this).is(":checked") && $(this).is(':focus')){
                    $(this).blur();
                }
                if($(this).is(":checked") && !$(this).is(':focus')){
                     $(this).focus();
                }
            });

        });

        $(this).find('.select2permissifNoAjax').each(function() {
	    var element = $(this);
	    var id = $(this).attr('id');
	    $(this).select2({
                data: JSON.parse($(this).attr('data-choices')),
                allowClear: true,
                multiple: false,
                createSearchChoice: function (term, data) {
                    if ($(data).filter(function () {
                        return this.text.localeCompare(term) === 0;
                    }).length === 0) {
                        return {id: term, text: term + ' (nouveau)'};
                    }
                }
            }).on("select2-close", function (e) {
		lastValue = $('#'+id).val();
                $(this).select2("val", lastValue);
                $(this).val(lastValue);
                $('#s2id_'+id).find('.select2-chosen').text(lastValue);
            })
        });

        $(this).find('.hamzastyle').each(function () {
            var select2 = $(this);
            select2.select2({
                multiple: true,
                data: function () {
                    var data = [];
                    element.find('.hamzastyle-item').each(function () {
                        data = data.concat(JSON.parse($(this).attr('data-words')));
                    });

                    var data = unique(data.sort());

                    dataFinal = [];
                    for (key in data) {
                        if (data[key] + "") {
                            dataFinal.push({id: (data[key] + ""), text: (data[key] + "")});
                        }
                    }

                    return {results: dataFinal};
                }
            })
        });

        $(this).find('.hamzastyle').on("change", function (e) {
            var select2Data = $(this).select2("data");
            var selectedWords = [];
            for (key in select2Data) {
                selectedWords.push(select2Data[key].text);
            }

            if (!selectedWords.length) {
                document.location.hash = "";
            } else {
                document.location.hash = encodeURI("#filtre=" + JSON.stringify(selectedWords));
            }
        });

        $(this).find('.input-group.date').datetimepicker({
            locale: 'fr_FR',
            format: 'L',
            allowInputToggle: true,
            focusOnShow: true,
            useCurrent: false
        });

        $(this).find("form.form-ajax-modal").on('submit', function () {
            var form = $(this);
            var callback = $(this).attr('callback');
            $.post($(this).attr('action'),
                    $(this).serialize(),
                    function (data)
                    {
                        if (!data.success) {
                            var content = form.find(form.attr('data-content')).html(data.content);
                            content.initAdvancedElements();
                            return;
                        }

                        if (form.data('related-element')) {
                            $(form.data('related-element')).trigger("modal_callback", data);
                        }

                        $(options.selectors.ajaxModal).modal('hide');
                    }, "json");

            return false;
        });

        $(this).find('.modal-autoshow').modal({
            'show': true
        });

        $(this).find('.link-submit').on('click', function () {
            var form = $($(this).attr('data-form'));
            form.attr('action', $(this).attr('href'));
            form.submit();

            return false;
        });
        $(this).find('.pointer').on('click', function () {
            if ($(this).attr('data-pointer')) {
                $($(this).attr('data-pointer')).click();
            }

            return false;
        });

        $(this).find('.dynamic-element-add').on('click', function () {
            var content = $($($(this).attr('data-template')).html().replace(/var---nbItem---/g, UUID.generate()));
            $($(this).attr('data-container')).append(content);
            content.initAdvancedElements();
        });

        $(this).find('.dynamic-element-delete').on('click', function () {
            $($(this).attr('data-line')).find('input').val("");
            $($(this).attr('data-line')).find('input').trigger('keyup');
            $($(this).attr('data-line')).remove();
            if ($($(this).attr('data-lines')).length < 1 && $(this).attr('data-add')) {
                $($(this).attr('data-add')).trigger('click');
            }
        });

        $(this).find('.btn-dynamic-element-submit').on('click', function(e) {
            var vals = $(this).parents('form').serializeArray();

            $(this).parents('form').find('.dynamic-element-delete').each(function(){
                var ligne = $($(this).attr('data-line'));
                var hasValue = false;
                ligne.find('input, select, textarea').each(function() {
                    if($(this).attr('name') && $(this).val()) {
                        hasValue = true;
                    }
                });

                if(!hasValue) {
                    $($(this).attr('data-line')).remove();
                }
            });

            return true;
        });

        /**
      	 * Sélection de lignes de tableau
      	 ******************************************/
      	$(this).find('.table_selection thead .selecteur input').each(function(){
            $(this).on('click', function(){
    			var selecteursLignes = $(this).parents('table').find('tbody .selecteur input');
      			if($(this).is(':checked')) {
      				selecteursLignes.attr('checked', 'checked');
      			} else {
      				selecteursLignes.removeAttr('checked');
      			}
            });
      	});

        $(this).find('.table_selection tbody .selecteur input').on('click', function(e){

      				var selecteur = $(this).parents('table').find('thead .selecteur input');

      				if(!$(this).is(':checked'))
      				{
      					selecteur.removeAttr('checked');
      				}
      			});

        /**
         * Contrôle la bonne saisie de nombres dans
         * un champ
         * $(s).saisieNum(float, callbackKeypress);
         ******************************************/
        $.fn.saisieNum = function (float, callbackKeypress, callbackBlur)
        {
            var champ = $(this);

            // A chaque touche pressée
            champ.keypress(function (e)
            {
                var val = $(this).val();
                var touche = e.which;
                var ponctuationPresente = (val.indexOf('.') != -1 || val.indexOf(',') != -1);
                var chiffre = (touche >= 48 && touche <= 57); // Si chiffre

                // touche "entrer"
                if (touche == 13)
                    return e;

                // touche "entrer"
                if (touche == 0)
                    return e;

                // Champ nombre décimal
                if (float)
                {
                    // !backspace && !null && !point && !virgule && !chiffre
                    if (touche != 8 && touche != 0 && touche != 46 && touche != 44 && !chiffre)
                        return false;
                    // point déjà présent
                    if (touche == 46 && ponctuationPresente)
                        e.preventDefault();
                    // virgule déjà présente
                    if (touche == 44 && ponctuationPresente)
                        e.preventDefault();
                    // 2 décimales
                    if (val.match(/[\.\,][0-9][0-9]/) && chiffre && e.currentTarget && e.currentTarget.selectionStart > val.length - 3)
                        e.preventDefault();
                }
                // Champ nombre entier
                else
                {
                    if (touche != 8 && touche != 0 && !chiffre)
                        e.preventDefault();
                }

                if (callbackKeypress)
                    callbackKeypress();
                return e;
            });
          }

          $(this).find('.btn-loading').on('click', function (e) {
                $(this).addClass('disabled');
                $(this).text($(this).attr('data-loading-text'));
          });

    }

    $.initQueryHash = function () {
        $(window).on('hashchange', function () {
            if ($(document).find('.hamzastyle').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                var filtres = [];
                if (params.filtre && params.filtre.match(/\[/)) {
                    filtres = JSON.parse(params.filtre);
                } else if (params.filtre) {
                    filtres.push(params.filtre);
                }

                var select2Data = [];
                for (key in filtres) {
                    select2Data.push({id: filtres[key], text: filtres[key]});
                }

                $(document).find('.hamzastyle').select2("data", select2Data);

                $(document).find('.hamzastyle-item').each(function () {
                    var words = $(this).attr('data-words');
                    var find = true;
                    for (key in filtres) {
                        var word = filtres[key];
                        if (words.indexOf(word) === -1) {
                            find = false;
                        }
                    }
                    if (find) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            }
            if ($(document).find('.nav.nav-tabs').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                if (params.tab) {
                    $('.nav.nav-tabs a[aria-controls="' + params.tab + '"]').tab('show');
                }
            }
        });

        if (location.hash) {
            $(window).trigger('hashchange');
        }
    }

})(jQuery);
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s"<|endoftext|>