<commit_before>//
// Strider Worker extension for Sauce Labs tests
//

var fs = require('fs')
var path = require('path')
var request = require('request')

// # of tries for application-under-test webserver to start up on specified port
// We test once per second
var HTTP_CHECK_RETRIES = 10

// Interval in between HTTP checks in ms
var HTTP_CHECK_INTERVAL = 1000

// Port on which the application-under-test webserver should bind to on localhost.
// Sauce Connector will tunnel from this to Sauce Cloud for Selenium tests
var HTTP_PORT = 8031

// Read & parse a JSON file
function getJson(filename, cb) {
  fs.readFile(filename, function(err, data) {
    if (err) return cb(err, null)
    try {
      var json = JSON.parse(data)
      cb(null, json)
    } catch(e) {
      cb(e, null)
    }
  })
}

// `npm install` has succeeded at this point.
// We run `npm test` and assuming that has passed,
// then we start the Sauce test process.
// If `npm test` fails, we don't bother with the overhead of running the Sauce tests.
function test(ctx, cb) {
  var sauceAccessKey = ctx.jobData.repo_config.sauce_access_key
  var sauceUsername = ctx.jobData.repo_config.sauce_username
  var sauceBrowsers = ctx.jobData.repo_config.sauce_browsers
  if (sauceBrowsers === undefined || sauceBrowsers.length === 0) {
    // Default to latest chrome on Windows Vista
    sauceBrowsers = [
      {
        browserName:"chrome",
        version:"",
        platform:"Windows 2008"
      }
    ]
  }
  if (sauceAccessKey === undefined || sauceUsername === undefined) {
    ctx.striderMessage(("Sauce tests detected but Sauce credentials have not been configured!\n"
      + "  Please visit project config page to enter them"))
    return cb(1)
  }
  var startPhaseDone = false
  var tsh = ctx.shellWrap(ctx.npmCmd + " test")
  // Run
  ctx.forkProc(ctx.workingDir, tsh.cmd, tsh.args, function(exitCode) {
    if (exitCode !== 0) {
      return cb(exitCode)
    } else {
      ctx.striderMessage("npm test success - trying Sauce tests...")
      // Parse package.json so we can run the start script directly.
      // This is important because `npm start` will fork a subprocess a la shell
      // which means we cannot track the PID and shut it down later.
      getJson(path.join(ctx.workingDir, "package.json"), npmTestPassed)
    }
  })
  function npmTestPassed(err, packageJson) {
    if (err || packageJson.scripts === undefined || packageJson.scripts.start === undefined) {
      striderMessage("could not read package.json to find start command - failing test")
      return cb(1)
    }
    // `npm test` succeeded, so we go through the Sauce tests.

    // Start the app, suggesting a port via PORT environment variable
    var tsh = ctx.shellWrap("exec " + packageJson.scripts.start)
    var serverProc = ctx.forkProc({
      args:tsh.args,
      cmd:tsh.cmd,
      cwd:ctx.workingDir,
      env:{PORT:HTTP_PORT},
    }, function(exitCode) {
      // Could perhaps be backgrounding itself. This should be avoided.
      if (exitCode !== 0 && !startPhaseDone) {
        // If we haven't already called back with completion,
        // and `npm start` exits with non-zero exit code,
        // call back with error and mark done.
        ctx.striderMessage("npm start failed - failing test")
        startPhaseDone = true
        return cb(exitCode)
      }
    })

    // The project webserver should be available via HTTP once started.
    // This section implements a check which will attempt to make a HTTP request for /
    // expecting a 200 response code. It will try HTTP_CHECK_RETRIES times, waiting 1 second
    // between checks. If it fails after HTTP_CHECK_RETRIES times, the server process will be killed
    // and the test failed.
    var tries = 0
    ctx.striderMessage("Waiting for webserver to come up on localhost:" + HTTP_PORT)
    var intervalId = setInterval(function() {
      // Check for http status 200 on http://localhost:HTTP_PORT/
      request("http://localhost:"+HTTP_PORT+"/", function(err, response) {
        if (startPhaseDone) {
          clearInterval(intervalId)
          return
        }
        if (!err && response.statusCode == 200) {
          ctx.striderMessage("Got HTTP 200 on localhost:" + HTTP_PORT + " indicating server is up")
          startPhaseDone = true
          clearInterval(intervalId)
          serverUp()
        } else {
          tries++
          console.log("Error on localhost:%d: %s", HTTP_PORT, err)
          if (tries >= HTTP_CHECK_RETRIES) {
            var msg = ("HTTP 200 check on localhost:" + HTTP_PORT + " failed after " + tries
              + " retries, server not up - failing test")
            ctx.striderMessage(msg)
            clearInterval(intervalId)
            startPhaseDone = true
            return cb(1)
          }
        }
      })
    }, HTTP_CHECK_INTERVAL)

    // Start the Sauce Connector. Returns childProcess object.
    function startConnector(username, apiKey, cb) {
      var jarPath = path.join(__dirname, "thirdparty", "Sauce-Connect.jar")
      var jsh = ctx.shellWrap("exec java -jar " + jarPath + " " + username + " " + apiKey)

      ctx.striderMessage("Starting Sauce Connector")
      return ctx.forkProc(__dirname, jsh.cmd, jsh.args, cb)
    }

    // Server is up, start Sauce Connector and run the tests via `npm sauce` invocations
    function serverUp() {
      var done = false
      var connectorProc = startConnector(sauceUsername, sauceAccessKey,
        function(exitCode) {
        console.log("Connector exited with code: %d", exitCode)
        serverProc.kill("SIGKILL")
        if (!done) {
          console.log("Killing connector")
          ctx.striderMessage("Error starting Sauce Connector - failing test")
          ctx.striderMessage("Shutting down server")
          done = true
          return cb(1)
        }
      })

      // Wait until connector outputs "You may start your tests"
      // before executing Sauce tests
      connectorProc.stdout.on('data', function(data) {
        if (/Connected! You may start your tests./.exec(data) !== null) {
          var saucesh = ctx.shellWrap(ctx.npmCmd + " run-script sauce")
          var sauceDoneCount = 0
          var finaleStatusCode = 0
          sauceBrowsers.forEach(function(o) {
            ctx.striderMessage("Starting: SAUCE_BROWSER="+o.browserName
              +" SAUCE_OS="+o.platform+" SAUCE_BROWSER_VERSION="+o.version+" npm run-script sauce")
            var sauceProc = ctx.forkProc({
              args: saucesh.args,
              cmd: saucesh.cmd,
              cwd: ctx.workingDir,
              env: {
                SAUCE_USERNAME:sauceUsername,
                SAUCE_ACCESS_KEY:sauceAccessKey,
                SAUCE_OS:o.platform,
                SAUCE_BROWSER_VERSION:o.version || '',
                SAUCE_BROWSER:o.browserName,
              }
            }, function(code) {
              ctx.striderMessage("Exit code "+code
                +" for: SAUCE_BROWSER="+o.browserName +" SAUCE_OS="+o.platform+" SAUCE_BROWSER_VERSION="+o.version+" npm run-script sauce")
              sauceDoneCount++
              // If a single test fails, the whole test job fails.
              if (finaleStatusCode === 0 && code !== 0) {
                finaleStatusCode = 1
              }
              if (!done && sauceDoneCount === sauceBrowsers.length) {
                done = true
                ctx.striderMessage("Shutting down Sauce Connector")
                connectorProc.kill("SIGINT")
                ctx.striderMessage("Shutting down server")
                serverProc.kill()
                // Give Sauce Connector & server 5 seconds to gracefully stop before sending SIGKILL
                setTimeout(function() {
                  connectorProc.kill("SIGKILL")
                  serverProc.kill("SIGKILL")
                  return cb(finaleStatusCode)
                }, 5000)
              }
            })
          })
        }
      })
    }
  }
}

module.exports = function(ctx, cb) {

  ctx.addDetectionRule({
    filename:"package.json",
    jsonKeyExists:"scripts.sauce",
    language:"node.js",
    framework:null,
    hasSauce:true,
    prepare:ctx.npmCmd + " install",
    test:test
  })

  function saucePlugin(schema, opts) {
    schema.add({
      sauce_access_key: String,
      sauce_username: String,
      sauce_browsers: [],
    })

  }

  // Extend RepoConfig model with 'Sauce' properties
  ctx.models.RepoConfig.plugin(saucePlugin)

  console.log("strider-sauce worker extension loaded")
  cb(null, null)
}
<commit_msg>set heap size max to 64M for sauce connector JVM<commit_after>//
// Strider Worker extension for Sauce Labs tests
//

var fs = require('fs')
var path = require('path')
var request = require('request')

// # of tries for application-under-test webserver to start up on specified port
// We test once per second
var HTTP_CHECK_RETRIES = 10

// Interval in between HTTP checks in ms
var HTTP_CHECK_INTERVAL = 1000

// Port on which the application-under-test webserver should bind to on localhost.
// Sauce Connector will tunnel from this to Sauce Cloud for Selenium tests
var HTTP_PORT = 8031

// Read & parse a JSON file
function getJson(filename, cb) {
  fs.readFile(filename, function(err, data) {
    if (err) return cb(err, null)
    try {
      var json = JSON.parse(data)
      cb(null, json)
    } catch(e) {
      cb(e, null)
    }
  })
}

// `npm install` has succeeded at this point.
// We run `npm test` and assuming that has passed,
// then we start the Sauce test process.
// If `npm test` fails, we don't bother with the overhead of running the Sauce tests.
function test(ctx, cb) {
  var sauceAccessKey = ctx.jobData.repo_config.sauce_access_key
  var sauceUsername = ctx.jobData.repo_config.sauce_username
  var sauceBrowsers = ctx.jobData.repo_config.sauce_browsers
  if (sauceBrowsers === undefined || sauceBrowsers.length === 0) {
    // Default to latest chrome on Windows Vista
    sauceBrowsers = [
      {
        browserName:"chrome",
        version:"",
        platform:"Windows 2008"
      }
    ]
  }
  if (sauceAccessKey === undefined || sauceUsername === undefined) {
    ctx.striderMessage(("Sauce tests detected but Sauce credentials have not been configured!\n"
      + "  Please visit project config page to enter them"))
    return cb(1)
  }
  var startPhaseDone = false
  var tsh = ctx.shellWrap(ctx.npmCmd + " test")
  // Run
  ctx.forkProc(ctx.workingDir, tsh.cmd, tsh.args, function(exitCode) {
    if (exitCode !== 0) {
      return cb(exitCode)
    } else {
      ctx.striderMessage("npm test success - trying Sauce tests...")
      // Parse package.json so we can run the start script directly.
      // This is important because `npm start` will fork a subprocess a la shell
      // which means we cannot track the PID and shut it down later.
      getJson(path.join(ctx.workingDir, "package.json"), npmTestPassed)
    }
  })
  function npmTestPassed(err, packageJson) {
    if (err || packageJson.scripts === undefined || packageJson.scripts.start === undefined) {
      striderMessage("could not read package.json to find start command - failing test")
      return cb(1)
    }
    // `npm test` succeeded, so we go through the Sauce tests.

    // Start the app, suggesting a port via PORT environment variable
    var tsh = ctx.shellWrap("exec " + packageJson.scripts.start)
    var serverProc = ctx.forkProc({
      args:tsh.args,
      cmd:tsh.cmd,
      cwd:ctx.workingDir,
      env:{PORT:HTTP_PORT},
    }, function(exitCode) {
      // Could perhaps be backgrounding itself. This should be avoided.
      if (exitCode !== 0 && !startPhaseDone) {
        // If we haven't already called back with completion,
        // and `npm start` exits with non-zero exit code,
        // call back with error and mark done.
        ctx.striderMessage("npm start failed - failing test")
        startPhaseDone = true
        return cb(exitCode)
      }
    })

    // The project webserver should be available via HTTP once started.
    // This section implements a check which will attempt to make a HTTP request for /
    // expecting a 200 response code. It will try HTTP_CHECK_RETRIES times, waiting 1 second
    // between checks. If it fails after HTTP_CHECK_RETRIES times, the server process will be killed
    // and the test failed.
    var tries = 0
    ctx.striderMessage("Waiting for webserver to come up on localhost:" + HTTP_PORT)
    var intervalId = setInterval(function() {
      // Check for http status 200 on http://localhost:HTTP_PORT/
      request("http://localhost:"+HTTP_PORT+"/", function(err, response) {
        if (startPhaseDone) {
          clearInterval(intervalId)
          return
        }
        if (!err && response.statusCode == 200) {
          ctx.striderMessage("Got HTTP 200 on localhost:" + HTTP_PORT + " indicating server is up")
          startPhaseDone = true
          clearInterval(intervalId)
          serverUp()
        } else {
          tries++
          console.log("Error on localhost:%d: %s", HTTP_PORT, err)
          if (tries >= HTTP_CHECK_RETRIES) {
            var msg = ("HTTP 200 check on localhost:" + HTTP_PORT + " failed after " + tries
              + " retries, server not up - failing test")
            ctx.striderMessage(msg)
            clearInterval(intervalId)
            startPhaseDone = true
            return cb(1)
          }
        }
      })
    }, HTTP_CHECK_INTERVAL)

    // Start the Sauce Connector. Returns childProcess object.
    function startConnector(username, apiKey, cb) {
      var jarPath = path.join(__dirname, "thirdparty", "Sauce-Connect.jar")
      var jsh = ctx.shellWrap("exec java -Xmx64M -jar " + jarPath + " " + username + " " + apiKey)

      ctx.striderMessage("Starting Sauce Connector")
      return ctx.forkProc(__dirname, jsh.cmd, jsh.args, cb)
    }

    // Server is up, start Sauce Connector and run the tests via `npm sauce` invocations
    function serverUp() {
      var done = false
      var connectorProc = startConnector(sauceUsername, sauceAccessKey,
        function(exitCode) {
        console.log("Connector exited with code: %d", exitCode)
        serverProc.kill("SIGKILL")
        if (!done) {
          console.log("Killing connector")
          ctx.striderMessage("Error starting Sauce Connector - failing test")
          ctx.striderMessage("Shutting down server")
          done = true
          return cb(1)
        }
      })

      // Wait until connector outputs "You may start your tests"
      // before executing Sauce tests
      connectorProc.stdout.on('data', function(data) {
        if (/Connected! You may start your tests./.exec(data) !== null) {
          var saucesh = ctx.shellWrap(ctx.npmCmd + " run-script sauce")
          var sauceDoneCount = 0
          var finaleStatusCode = 0
          sauceBrowsers.forEach(function(o) {
            ctx.striderMessage("Starting: SAUCE_BROWSER="+o.browserName
              +" SAUCE_OS="+o.platform+" SAUCE_BROWSER_VERSION="+o.version+" npm run-script sauce")
            var sauceProc = ctx.forkProc({
              args: saucesh.args,
              cmd: saucesh.cmd,
              cwd: ctx.workingDir,
              env: {
                SAUCE_USERNAME:sauceUsername,
                SAUCE_ACCESS_KEY:sauceAccessKey,
                SAUCE_OS:o.platform,
                SAUCE_BROWSER_VERSION:o.version || '',
                SAUCE_BROWSER:o.browserName,
              }
            }, function(code) {
              ctx.striderMessage("Exit code "+code
                +" for: SAUCE_BROWSER="+o.browserName +" SAUCE_OS="+o.platform+" SAUCE_BROWSER_VERSION="+o.version+" npm run-script sauce")
              sauceDoneCount++
              // If a single test fails, the whole test job fails.
              if (finaleStatusCode === 0 && code !== 0) {
                finaleStatusCode = 1
              }
              if (!done && sauceDoneCount === sauceBrowsers.length) {
                done = true
                ctx.striderMessage("Shutting down Sauce Connector")
                connectorProc.kill("SIGINT")
                ctx.striderMessage("Shutting down server")
                serverProc.kill()
                // Give Sauce Connector & server 5 seconds to gracefully stop before sending SIGKILL
                setTimeout(function() {
                  connectorProc.kill("SIGKILL")
                  serverProc.kill("SIGKILL")
                  return cb(finaleStatusCode)
                }, 5000)
              }
            })
          })
        }
      })
    }
  }
}

module.exports = function(ctx, cb) {

  ctx.addDetectionRule({
    filename:"package.json",
    jsonKeyExists:"scripts.sauce",
    language:"node.js",
    framework:null,
    hasSauce:true,
    prepare:ctx.npmCmd + " install",
    test:test
  })

  function saucePlugin(schema, opts) {
    schema.add({
      sauce_access_key: String,
      sauce_username: String,
      sauce_browsers: [],
    })

  }

  // Extend RepoConfig model with 'Sauce' properties
  ctx.models.RepoConfig.plugin(saucePlugin)

  console.log("strider-sauce worker extension loaded")
  cb(null, null)
}
<|endoftext|>


<commit_before>var	sys = require("sys"),
	YQL = require('yql');

// Test #1
new YQL.exec("SELECT * FROM weather.forecast WHERE (location = @zip)", function(response) {

	if (response.error) {
		sys.puts("Error: " + response.error.description);
	}
	else {
		var	location 	= response.query.results.channel.location,
			condition 	= response.query.results.channel.item.condition;
		sys.puts("The current weather in " + location.city + ', ' + location.region + " is " + condition.temp + " degrees and " + condition.text);
	}

}, {"zip": 90066});

<commit_msg>Updated README<commit_after>var	sys = require("sys"),
	YQL = require('yql');

// Test #1
new YQL.exec("SELECT * FROM weather.forecast WHERE (location = @zip)", function(response) {

	if (response.error) {
		sys.puts("Error: " + response.error.description);
	}
	else {
		var	location 	= response.query.results.channel.location,
			condition 	= response.query.results.channel.item.condition;
		sys.puts("Test #1... " + "The current weather in " + location.city + ', ' + location.region + " is " + condition.temp + " degrees and " + condition.text);
	}

}, {"zip": 90066});

// Test #2
new YQL.exec("SELECT * FROM foobar.badTable WHERE (location = 66213)", function(response) {

	if (response.error) {
		sys.puts("Test #2... " + "Error: " + response.error.description);
	}
	else {
		// Intentionally blank
	}

}, {}, {foo: "bar"});

// Test #3
new YQL.exec("select * from twitter.user.timeline where (id = @id)", function(response) {

	if (response.error) {
		sys.puts("Test #3... Error: " + response.error.description);
	}
	else {
		var tweets = response.query.results.statuses.status;
		sys.puts("Test #3... Latest tweet from @" + tweets[0].user.screen_name + ": " + tweets[0].text);
	}

}, {id:"derek"}, {https:true});<|endoftext|>


<commit_before>var util = require('util')
  , isUrl = require('is-url')
  , fs = require('fs')
  , path = require('path')
  , request = require('request')
  , crypto = require('crypto')
  , async = require('async')
  , mime = require('mime')
  , url = require('url')
  , pjsonld = require('package-jsonld')
  , gm = require('gm')
  , zlib = require('zlib')
  , clone = require('clone')
  , concat = require('concat-stream')
  , sutil = require('../../proxy/lib/util')
  , previewTabularData = require('preview-tabular-data').preview
  , ldstars = require('ldstars');

/**
 * post publish
 * modifies pkg in place
 */
module.exports = function(conf, msg, callback){

  request( { url: conf.rootCouchRegistry + '/' + msg.id }, function(err, resp, pkg){

    if(err) return callback(err);
    if (resp.statusCode >= 400){
      return callback(sutil.errorCode('oops something went wrong when trying to GET ' + msg.id, resp.statusCode));
    }
    pkg = JSON.parse(pkg);

    processDataset(conf, pkg, msg.rev, function(err, pkg, rev){
      if(err) console.error(err);
      processCode(conf, pkg, rev, function(err, pkg, rev){
        if(err) console.error(err);
        processArticle(conf, pkg, rev, function(err, pkg, rev){
          if(err) console.error(err);
          processFigure(conf, pkg, rev, function(err, pkg, rev){
            if(err) console.error(err);

            //TODO Audio and Video

            pkg.contentRating = ldstars.rate(pjsonld.linkPackage(clone(pkg)), {string:true});
            callback(err, pkg, rev);

          });
        });
      });
    });
  });

};

/**
 * store contentData on S3 and rate
 */
function processDataset(conf, pkg, rev, callback){

  var dataset = pkg.dataset || [];
  async.eachSeries(dataset, function(r, cb){

    if(!r.distribution) return cb(null);

    r.contentRating = ldstars.rateResource(pjsonld.linkDataset(clone(r), r.name, r.version), pkg.license, {string:true});

    async.eachSeries(r.distribution, function(d, cb2){

      if('contentData' in d){

        var s = (typeof d.contentData === 'string') ? d.contentData: JSON.stringify(d.contentData);

        var format;
        if( typeof d.encodingFormat === 'string' ){
          format =  d.encodingFormat; //trust user ??? would be good to validate
        } else {
          format = (typeof d.contentData === 'string') ? 'text/plain':
            (s.indexOf('@context') !== -1) ? 'application/ld+json' : 'application/json';
        }

        d.contentSize = Buffer.byteLength(s, 'utf-8');
        d.encodingFormat = format;
        d.hashAlgorithm = 'sha1';
        d.hashValue = crypto.createHash('sha1').update(s).digest('hex');

        //put to S3
        zlib.gzip(s, function(errGzip, dataGzip){
          if(errGzip) console.error(errGzip);

          var opts = {
            Key: (errGzip) ? d.hashValue: crypto.createHash('sha1').update(dataGzip).digest('hex'),
            Body: (errGzip) ? s: dataGzip,
            ContentType: format,
            ContentLength: (errGzip) ? d.contentSize: dataGzip.length
          };

          if(!errGzip){
            opts.ContentEncoding = 'gzip';
          }

          conf.s3.putObject(opts, function(errS3, resS3){
            if(errS3) {
              console.error(errS3);
              r.contentRating = ldstars.rateResource(pjsonld.linkDataset(clone(r), r.name, r.version), pkg.license, {string:true});
              return cb2(null);
            }

            d.contentUrl = 'r/' + opts.Key;

            if(!errGzip){
              d.encoding = {
                contentSize: opts.ContentLength,
                encodingFormat: 'gzip',
                hashAlgorithm: 'sha1',
                hashValue: opts.Key
              };
            }

            cb2(null);
          });
        });

      } else if('contentUrl' in d) {

        //only preview once.
        if(r.preview){
          return cb2(null);
        }

        if(d.encodingFormat && ['application/x-ldjson', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv','text/tab-separated-values'].indexOf(d.encodingFormat) === -1){
          return cb2(null);
        }

        sutil.stream(d.contentUrl, conf.s3, function(err, streamContent){

          if(err){
            console.error(err);
            return cb2(null);
          }

          //preview if tabular data
          previewTabularData(streamContent.readable, {
            'content-type': streamContent.ContentType || d.encodingFormat || 'application/octet-stream',
            'content-length': streamContent.ContentLength,
            'content-encoding':streamContent.ContentEncoding
          }, {nPreview: 10}, function(err, preview){
            if(err) return cb2(null);

            if(preview){
              r.preview = preview
            }
            cb2(null);
          });

        });

      } else {
        cb2(null);
      }

    }, cb);

  }, function(err){
    return callback(err, pkg, rev);
  });

};

/**
 * might be async one day hence the callback
 */
function processCode(conf, pkg, rev, callback){

  var code = pkg.code || [];
  code.forEach(function(r){
    if(!r.targetProduct) return;

    r.targetProduct.forEach(function(d){
      if('filePath' in d && '_attachments' in pkg){
        var basename = path.basename(d.filePath);

        //if absolute path || bundlePath: delete (use for codeBundle created by ldc for instance)
        var normal = path.normalize(d.filePath);
        var absolute = path.resolve(d.filePath);
        if ( (normal === absolute) || d.bundlePath ) {
          delete d.filePath;
        };
      }
    });

    r.contentRating = ldstars.rateResource(pjsonld.linkCode(clone(r), r.name, r.version), pkg.license, {string:true});
  });

  callback(null, pkg, rev);
};

/**
 * create thumbnail of the first page of the pdf (if any)
 */
function processArticle(conf, pkg, rev, callback){

  var article = pkg.article || [];
  var cnt = 0;

  _thumbnailArticle(article, cnt, rev, conf.rootCouchRegistry, conf.admin, conf.s3, pkg, callback);
};

/**
 * recursively thumbnail articles (has to be sequential so that latest _rev is passed to couch)
 */
function _thumbnailArticle(articles, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback){

  if(!articles.length){
    return callback(null, pkg, rev);
  }

  var r = articles[cnt];

  function _next(rev){
    if (++cnt < articles.length) {
      return _thumbnailArticle(articles, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback);
    } else {
      return callback(null, pkg, rev);
    }
  }

  if ('encoding' in r) {
    r.contentRating = ldstars.rateResource(pjsonld.linkArticle(clone(r), pkg.name, pkg.version), pkg.license, {string:true});

    //find an encoding in PDF AND having a contentUrl
    var enc = r.encoding.filter(function(x){
      return ('contentUrl' in r.encoding) && (r.encoding.encodingFormat === 'application/pdf' );
    })[0];

    if(!enc){
      return _next(rev);
    }

    sutil.dereference(enc.contentUrl, s3, function(err, data){
      if(err) {
        console.error(err);
        return _next(rev);
      }

      gm(data.Body, 'article.pdf[0]')
        .resize(400, 400)
        .toBuffer('png', function (err, buffer) {
          if (err) return _next(rev);

          var contentType = 'image/png';
          var thumbnailName = 'thumb-' + r.name + '-' + '400' + '.' + mime.extension(contentType);

          var ropts = {
            url: rootCouchRegistry + '/' + encodeURIComponent(pkg.name + '@' + pkg.version) + '/' + thumbnailName,
            method: 'PUT',
            headers:{
              'Content-Length': buffer.length,
              'Content-Type': contentType,
              'If-Match': rev
            },
            auth: admin,
            body: buffer
          };

          request(ropts, function(err, resp, body){
            if(err) return _next(rev);

            if (resp.statusCode === 201) {
              body = JSON.parse(body);

              r.thumbnailUrl = pkg.name + '/' + pkg.version + '/thumbnail/' + thumbnailName;

              return _next(body.rev);

            } else {

              return _next(rev);

            }
          });

        });

    });

  } else {
    return _next(rev);
  }

};

/**
 * create thubnails and store them as attachments
 */
function processFigure(conf, pkg, rev, callback){

  var figure = pkg.figure || [];
  var cnt = 0;

  _thumbnailFigure(figure, cnt, rev, conf.rootCouchRegistry, conf.admin, conf.s3, pkg, callback);

};

/**
 * recursively thumbnail figures (has to be sequential so that latest _rev is passed to couch)
 */
function _thumbnailFigure(figures, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback){

  if(!figures.length){
    return callback(null, pkg, rev);
  }

  var r = figures[cnt];

  function _next(rev){
    if (++cnt < figures.length) {
      return _thumbnailFigure(figures, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback);
    } else {
      return callback(null, pkg, rev);
    }
  }

  if('figure' in r){
    r.contentRating = ldstars.rateResource(pjsonld.linkFigure(clone(r), pkg.name, pkg.version), pkg.license, {string:true});

    _thumbnailImage(r, cnt, rev, rootCouchRegistry, admin, s3, pkg, _next);

  } else {
    return _next(rev);
  }

};

function _thumbnailImage(figure, cnt, rev, rootCouchRegistry, admin, s3, pkg, next){

  if(!figure.figure){
    return next(rev);
  }

  var img = figure.figure[cnt];

  function _next(rev){
    if(++cnt < figure.figure.length) {
      return _thumbnailImage(figure, cnt, rev, rootCouchRegistry, admin, s3, pkg, next);
    } else {
      return next(rev);
    }
  }

  if(img.contentUrl){

    sutil.dereference(img.contentUrl, s3, function(err, data){
      if(err) {
        console.error(err);
        return _next(rev);
      }

      gm(data.Body)
        .size(function (err, size) {

          if (err) return _next(rev);

          img.width =  { value: size.width,  unitCode: 'E37', description: size.width + 'px'  };
          img.height = { value: size.height, unitCode: 'E37', description: size.height + 'px' };

          if(figure.thumbnailUrl){
            return _next(rev);
          }
          //if not try to generate a thumbnail

          if(size.width > 400 || size.height > 400){
            this.resize('400', '400')
          }

          this.toBuffer('png', function (err, buffer) {

            if (err) return _next(rev);

            var contentType = 'image/png';
            var thumbnailName = 'thumb-' + figure.name + '-' + '400' + '.' + mime.extension(contentType);

            var ropts = {
              url: rootCouchRegistry + '/' + encodeURIComponent(pkg.name + '@' + pkg.version) + '/' + thumbnailName,
              method: 'PUT',
              headers:{
                'Content-Length': buffer.length,
                'Content-Type': contentType,
                'If-Match': rev
              },
              auth: admin,
              body: buffer
            };

            request(ropts, function(err, resp, body){
              if(err) return _next(rev);

              if (resp.statusCode === 201) {
                body = JSON.parse(body);

                figure.thumbnailUrl = pkg.name + '/' + pkg.version + '/thumbnail/' + thumbnailName;

                return _next(body.rev);

              } else {

                return _next(rev);

              }
            });

          });
        });
    });

  } else {
    return _next(rev);
  }

};
<commit_msg>postprocess audio and video<commit_after>var util = require('util')
  , isUrl = require('is-url')
  , fs = require('fs')
  , path = require('path')
  , request = require('request')
  , crypto = require('crypto')
  , async = require('async')
  , mime = require('mime')
  , url = require('url')
  , pjsonld = require('package-jsonld')
  , gm = require('gm')
  , zlib = require('zlib')
  , clone = require('clone')
  , concat = require('concat-stream')
  , sutil = require('../../proxy/lib/util')
  , previewTabularData = require('preview-tabular-data').preview
  , ldstars = require('ldstars');

/**
 * post publish
 * modifies pkg in place
 */
module.exports = function(conf, msg, callback){

  request( { url: conf.rootCouchRegistry + '/' + msg.id }, function(err, resp, pkg){

    if(err) return callback(err);
    if (resp.statusCode >= 400){
      return callback(sutil.errorCode('oops something went wrong when trying to GET ' + msg.id, resp.statusCode));
    }
    pkg = JSON.parse(pkg);

    processDataset(conf, pkg, msg.rev, function(err, pkg, rev){
      if(err) console.error(err);
      processCode(conf, pkg, rev, function(err, pkg, rev){
        if(err) console.error(err);
        processArticle(conf, pkg, rev, function(err, pkg, rev){
          if(err) console.error(err);
          processFigure(conf, pkg, rev, function(err, pkg, rev){
            if(err) console.error(err);
            processAudio(conf, pkg, rev, function(err, pkg, rev){
              if(err) console.error(err);
              processVideo(conf, pkg, rev, function(err, pkg, rev){
                if(err) console.error(err);

                pkg.contentRating = ldstars.rate(pjsonld.linkPackage(clone(pkg)), {string:true});
                callback(err, pkg, rev);

              });
            });
          });
        });
      });
    });
  });

};

/**
 * store contentData on S3 and rate
 */
function processDataset(conf, pkg, rev, callback){

  var dataset = pkg.dataset || [];
  async.eachSeries(dataset, function(r, cb){

    if(!r.distribution) return cb(null);

    r.contentRating = ldstars.rateResource(pjsonld.linkDataset(clone(r), pkg.name, pkg.version), pkg.license, {string:true});

    async.eachSeries(r.distribution, function(d, cb2){

      if('contentData' in d){

        var s = (typeof d.contentData === 'string') ? d.contentData: JSON.stringify(d.contentData);

        var format;
        if( typeof d.encodingFormat === 'string' ){
          format =  d.encodingFormat; //trust user ??? would be good to validate
        } else {
          format = (typeof d.contentData === 'string') ? 'text/plain':
            (s.indexOf('@context') !== -1) ? 'application/ld+json' : 'application/json';
        }

        d.contentSize = Buffer.byteLength(s, 'utf-8');
        d.encodingFormat = format;
        d.hashAlgorithm = 'sha1';
        d.hashValue = crypto.createHash('sha1').update(s).digest('hex');

        //put to S3
        zlib.gzip(s, function(errGzip, dataGzip){
          if(errGzip) console.error(errGzip);

          var opts = {
            Key: (errGzip) ? d.hashValue: crypto.createHash('sha1').update(dataGzip).digest('hex'),
            Body: (errGzip) ? s: dataGzip,
            ContentType: format,
            ContentLength: (errGzip) ? d.contentSize: dataGzip.length
          };

          if(!errGzip){
            opts.ContentEncoding = 'gzip';
          }

          conf.s3.putObject(opts, function(errS3, resS3){
            if(errS3) {
              console.error(errS3);
              r.contentRating = ldstars.rateResource(pjsonld.linkDataset(clone(r), r.name, r.version), pkg.license, {string:true});
              return cb2(null);
            }

            d.contentUrl = 'r/' + opts.Key;

            if(!errGzip){
              d.encoding = {
                contentSize: opts.ContentLength,
                encodingFormat: 'gzip',
                hashAlgorithm: 'sha1',
                hashValue: opts.Key
              };
            }

            cb2(null);
          });
        });

      } else if('contentUrl' in d) {

        //only preview once.
        if(r.preview){
          return cb2(null);
        }

        if(d.encodingFormat && ['application/x-ldjson', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv','text/tab-separated-values'].indexOf(d.encodingFormat) === -1){
          return cb2(null);
        }

        sutil.stream(d.contentUrl, conf.s3, function(err, streamContent){

          if(err){
            console.error(err);
            return cb2(null);
          }

          //preview if tabular data
          previewTabularData(streamContent.readable, {
            'content-type': streamContent.ContentType || d.encodingFormat || 'application/octet-stream',
            'content-length': streamContent.ContentLength,
            'content-encoding':streamContent.ContentEncoding
          }, {nPreview: 10}, function(err, preview){
            if(err) return cb2(null);

            if(preview){
              r.preview = preview
            }
            cb2(null);
          });

        });

      } else {
        cb2(null);
      }

    }, cb);

  }, function(err){
    return callback(err, pkg, rev);
  });

};

/**
 * might be async one day hence the callback
 */
function processCode(conf, pkg, rev, callback){

  var code = pkg.code || [];
  code.forEach(function(r){
    if(!r.targetProduct) return;

    r.targetProduct.forEach(function(d){
      if('filePath' in d && '_attachments' in pkg){
        var basename = path.basename(d.filePath);

        //if absolute path || bundlePath: delete (use for codeBundle created by ldc for instance)
        var normal = path.normalize(d.filePath);
        var absolute = path.resolve(d.filePath);
        if ( (normal === absolute) || d.bundlePath ) {
          delete d.filePath;
        };
      }
    });

    r.contentRating = ldstars.rateResource(pjsonld.linkCode(clone(r), pkg.name, pkg.version), pkg.license, {string:true});
  });

  callback(null, pkg, rev);
};

/**
 * might be async one day hence the callback
 */
function processAudio(conf, pkg, rev, callback){

  var audio = pkg.audio || [];
  audio.forEach(function(r){
    if(!r.audio) return;

    r.contentRating = ldstars.rateResource(pjsonld.linkAudio(clone(r), pkg.name, pkg.version), pkg.license, {string:true});
  });

  callback(null, pkg, rev);
};

/**
 * might be async one day hence the callback
 */
function processVideo(conf, pkg, rev, callback){

  var video = pkg.video || [];
  video.forEach(function(r){
    if(!r.video) return;

    r.contentRating = ldstars.rateResource(pjsonld.linkVideo(clone(r), pkg.name, pkg.version), pkg.license, {string:true});
  });

  callback(null, pkg, rev);
};

/**
 * create thumbnail of the first page of the pdf (if any)
 */
function processArticle(conf, pkg, rev, callback){

  var article = pkg.article || [];
  var cnt = 0;

  _thumbnailArticle(article, cnt, rev, conf.rootCouchRegistry, conf.admin, conf.s3, pkg, callback);
};

/**
 * recursively thumbnail articles (has to be sequential so that latest _rev is passed to couch)
 */
function _thumbnailArticle(articles, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback){

  if(!articles.length){
    return callback(null, pkg, rev);
  }

  var r = articles[cnt];

  function _next(rev){
    if (++cnt < articles.length) {
      return _thumbnailArticle(articles, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback);
    } else {
      return callback(null, pkg, rev);
    }
  }

  if ('encoding' in r) {
    r.contentRating = ldstars.rateResource(pjsonld.linkArticle(clone(r), pkg.name, pkg.version), pkg.license, {string:true});

    //find an encoding in PDF AND having a contentUrl
    var enc = r.encoding.filter(function(x){
      return ('contentUrl' in r.encoding) && (r.encoding.encodingFormat === 'application/pdf' );
    })[0];

    if(!enc){
      return _next(rev);
    }

    sutil.dereference(enc.contentUrl, s3, function(err, data){
      if(err) {
        console.error(err);
        return _next(rev);
      }

      gm(data.Body, 'article.pdf[0]')
        .resize(400, 400)
        .toBuffer('png', function (err, buffer) {
          if (err) return _next(rev);

          var contentType = 'image/png';
          var thumbnailName = 'thumb-' + r.name + '-' + '400' + '.' + mime.extension(contentType);

          var ropts = {
            url: rootCouchRegistry + '/' + encodeURIComponent(pkg.name + '@' + pkg.version) + '/' + thumbnailName,
            method: 'PUT',
            headers:{
              'Content-Length': buffer.length,
              'Content-Type': contentType,
              'If-Match': rev
            },
            auth: admin,
            body: buffer
          };

          request(ropts, function(err, resp, body){
            if(err) return _next(rev);

            if (resp.statusCode === 201) {
              body = JSON.parse(body);

              r.thumbnailUrl = pkg.name + '/' + pkg.version + '/thumbnail/' + thumbnailName;

              return _next(body.rev);

            } else {

              return _next(rev);

            }
          });

        });

    });

  } else {
    return _next(rev);
  }

};

/**
 * create thubnails and store them as attachments
 */
function processFigure(conf, pkg, rev, callback){

  var figure = pkg.figure || [];
  var cnt = 0;

  _thumbnailFigure(figure, cnt, rev, conf.rootCouchRegistry, conf.admin, conf.s3, pkg, callback);

};

/**
 * recursively thumbnail figures (has to be sequential so that latest _rev is passed to couch)
 */
function _thumbnailFigure(figures, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback){

  if(!figures.length){
    return callback(null, pkg, rev);
  }

  var r = figures[cnt];

  function _next(rev){
    if (++cnt < figures.length) {
      return _thumbnailFigure(figures, cnt, rev, rootCouchRegistry, admin, s3, pkg, callback);
    } else {
      return callback(null, pkg, rev);
    }
  }

  if('figure' in r){
    r.contentRating = ldstars.rateResource(pjsonld.linkFigure(clone(r), pkg.name, pkg.version), pkg.license, {string:true});

    _thumbnailImage(r, 0, rev, rootCouchRegistry, admin, s3, pkg, _next);

  } else {
    return _next(rev);
  }

};

function _thumbnailImage(figure, cnt, rev, rootCouchRegistry, admin, s3, pkg, next){

  if(!figure.figure){
    return next(rev);
  }

  var img = figure.figure[cnt];

  function _next(rev){
    if(++cnt < figure.figure.length) {
      return _thumbnailImage(figure, cnt, rev, rootCouchRegistry, admin, s3, pkg, next);
    } else {
      return next(rev);
    }
  }

  if(img.contentUrl){

    sutil.dereference(img.contentUrl, s3, function(err, data){
      if(err) {
        console.error(err);
        return _next(rev);
      }

      gm(data.Body)
        .size(function (err, size) {

          if (err) return _next(rev);

          img.width =  { value: size.width,  unitCode: 'E37', description: size.width + 'px'  };
          img.height = { value: size.height, unitCode: 'E37', description: size.height + 'px' };

          if(figure.thumbnailUrl){
            return _next(rev);
          }
          //if not try to generate a thumbnail

          if(size.width > 400 || size.height > 400){
            this.resize('400', '400')
          }

          this.toBuffer('png', function (err, buffer) {

            if (err) return _next(rev);

            var contentType = 'image/png';
            var thumbnailName = 'thumb-' + figure.name + '-' + '400' + '.' + mime.extension(contentType);

            var ropts = {
              url: rootCouchRegistry + '/' + encodeURIComponent(pkg.name + '@' + pkg.version) + '/' + thumbnailName,
              method: 'PUT',
              headers:{
                'Content-Length': buffer.length,
                'Content-Type': contentType,
                'If-Match': rev
              },
              auth: admin,
              body: buffer
            };

            request(ropts, function(err, resp, body){
              if(err) return _next(rev);

              if (resp.statusCode === 201) {
                body = JSON.parse(body);

                figure.thumbnailUrl = pkg.name + '/' + pkg.version + '/thumbnail/' + thumbnailName;

                return _next(body.rev);

              } else {

                return _next(rev);

              }
            });

          });
        });
    });

  } else {
    return _next(rev);
  }

};
<|endoftext|>


<commit_before>/*
* Script que permite simular la escritura en tiempo real para un elemento
* Creado en 29/04/2016
* @author: kamarena
*/

window.onload = iniciarWriter();

function iniciarWriter() {
  var elemento = document.getElementsByClassName('writer');

  for (var i = 0; i < elemento.length; i++) {
    var pause = elemento[i].getAttribute('pause');
    if (pause == null) pause = 100;
    escribir(elemento[i], pause)
  }
}

function escribir(elemento, pause) {
  var texto = elemento.innerHTML;
  elemento.innerHTML = ''; // se borra al iniciarWriter
  var posicion = 0;
  var escritura = setInterval(function() {
    if (posicion == texto.length) {
      elemento.innerHTML = texto;
      clearInterval(escritura);
    } else {
      elemento.innerHTML = texto.substring(0, posicion) + '|';
      posicion++;
    }
  }, pause);
}
<commit_msg>Añadido delay<commit_after>/*
* Script que permite simular la escritura en tiempo real para un elemento
* Creado en 29/04/2016
* @author: kamarena
*/

window.onload = iniciarWriter(); // inicia js cuando la página está cargada

// se ocupa de los procesos de carga del js
function iniciarWriter() {

  // obtiene los elementos de la página que tienen la clase writer
  var elementos = document.getElementsByClassName('writer');

  // itera los elementos para modificar el comportamiento de cada uno de ellos
  for (var i = 0; i < elementos.length; i++) {
    escribir(elementos[i]); // ejecuta la animación de escritura
  }

}

// se ocupa de darle el efecto al texto de estar escribiendo en tiempo real
function escribir(elemento) {

  var interval = elemento.getAttribute('interval'); // atributo interval
  var delay = elemento.getAttribute('delay'); // atributo delay

  if (interval == null) interval = 100; // por defecto pause vale 100sm
  if (delay == null) delay = 0; // por defecto delay vale 0ms

  var texto = elemento.innerHTML; // obtiene el texto que contiene
  elemento.innerHTML = ''; // se borra al iniciarWriter
  var posicion = 0; // posición inicial del puntero

  // se establece retardo según el atributo
  setTimeout(function() {
    // se inicia el intervalo para ir añadiendo las letras
    var escritura = setInterval(function() {
      if (posicion < texto.length) {
        // se introduce la parte de la cadena que corresponde en cada posición
        elemento.innerHTML = texto.substring(0, posicion) + '|';
        posicion++;
      } else {
        elemento.innerHTML = texto;
        clearInterval(escritura); // se sale del intervalo por haber llegado al fin
      }
    }, interval);
  }, delay);

}<|endoftext|>


<commit_before>import addons from 'react-addons';
import update from 'react-addons-update';

import {
  UPDATE_GUEST_NAME,
  UPDATE_GUEST_EMAIL,
  ADD_GUEST,
  UPDATE_SHORT_NAME,
  UPDATE_PLUS_ALLOWED
} from '../actions/actionTypes';

const initialState = {
  shortName: '',
  plus: {
    allowed: 0,
    bringing: 0
  },
  guests: [
    {
      name: {
        first: '',
        last: ''
      },
      email: '',
      rsvp: false
    }
  ]
};
// initialState.guests.push(emptyGuest);

export default function invitationReducers(state = initialState, action) {
  switch (action.type) {
    case UPDATE_GUEST_NAME: {
      const guests = state.guests;

      const updatedPerson = guests[action.guestIndex];
      updatedPerson.name[action.nameProperty] = action.nameValue;

      const updatedGuests = update(guests, {
        $splice: [[action.guestIndex, 1, updatedPerson]]
      });

      const updatedRsvp = update(state, { guests: { $set: updatedGuests } });

      return updatedRsvp;
    }
    case UPDATE_GUEST_EMAIL: {
      const guests = state.guests;
      const updatedPerson = update(guests[action.guestIndex], { email: { $set: action.email } });
      const updatedGuests = update(guests, {
        $splice: [[action.index, 1, updatedPerson]]
      });
      const updatedRsvp = update(state, { guests: { $set: updatedGuests } });

      return updatedRsvp;
    }
    case ADD_GUEST: {
      const guests = state.guests;
      const updatedGuests = update(guests, { $push : [
        {
          name: {
            first: '',
            last: ''
          },
          email: '',
          rsvp: false
        }] });

      const newGuestState = update(state, { guests: { $set: updatedGuests } });

      return newGuestState;
    }
    case UPDATE_SHORT_NAME: {
      return update(state, { shortName: { $set: action.shortName } });
    }
    case UPDATE_PLUS_ALLOWED: {
      return update(state, { plus: { allowed: { $set: action.allowed } } });
    }
    default:
      return state;
  }
}
<commit_msg>Removed unused<commit_after>import update from 'react-addons-update';

import {
  UPDATE_GUEST_NAME,
  UPDATE_GUEST_EMAIL,
  ADD_GUEST,
  UPDATE_SHORT_NAME,
  UPDATE_PLUS_ALLOWED
} from '../actions/actionTypes';

const initialState = {
  shortName: '',
  plus: {
    allowed: 0,
    bringing: 0
  },
  guests: [
    {
      name: {
        first: '',
        last: ''
      },
      email: '',
      rsvp: false
    }
  ]
};

export default function invitationReducers(state = initialState, action) {
  switch (action.type) {
    case UPDATE_GUEST_NAME: {
      const guests = state.guests;

      const updatedPerson = guests[action.guestIndex];
      updatedPerson.name[action.nameProperty] = action.nameValue;

      const updatedGuests = update(guests, {
        $splice: [[action.guestIndex, 1, updatedPerson]]
      });

      const updatedRsvp = update(state, { guests: { $set: updatedGuests } });

      return updatedRsvp;
    }
    case UPDATE_GUEST_EMAIL: {
      const guests = state.guests;
      const updatedPerson = update(guests[action.guestIndex], { email: { $set: action.email } });
      const updatedGuests = update(guests, {
        $splice: [[action.index, 1, updatedPerson]]
      });
      const updatedRsvp = update(state, { guests: { $set: updatedGuests } });

      return updatedRsvp;
    }
    case ADD_GUEST: {
      const guests = state.guests;
      const updatedGuests = update(guests, { $push : [
        {
          name: {
            first: '',
            last: ''
          },
          email: '',
          rsvp: false
        }] });

      const newGuestState = update(state, { guests: { $set: updatedGuests } });

      return newGuestState;
    }
    case UPDATE_SHORT_NAME: {
      return update(state, { shortName: { $set: action.shortName } });
    }
    case UPDATE_PLUS_ALLOWED: {
      return update(state, { plus: { allowed: { $set: action.allowed } } });
    }
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>class GeoMap {

	constructor(arg) {

		this.id = arg.id;
		this.container = arg.container;

		this.x = arg.x;
		this.y = arg.y;
		this.width = arg.width;
		this.height = arg.height;

		this.color = d3.scaleOrdinal(["lightyellow", "indianred"]);

		this.canvas = this.container.append("g");
		this.canvas.attr("transform", "translate(" + this.x + "," + this.y + ")");

		this.param = {
			projection: {scale: [150]},
			extent: {zoom: [1, 300], translate: [[0, 0], [this.width, this.height]]},
			tooltip: {x: 5, y: -20, on: 400, off: 100},
			elements: {bound: "black", stroke: 0.4, select: "darkred"},
		};

		this.classes = {
			elements: "",
			tooltip: "label label-success",
			hide: "hidden",
		};

		this.setProjection();
		this.setDataset(arg.dataset);

		this.setZoom();
		this.setTooltip();

		this.setClipPath();

		this.setConnection();
	}

	setProjection() {

		this.back = this.canvas.append("rect")
			.attr("width", this.width)
			.attr("height", this.height)
			.attr("fill", "lightcyan");

		this.clip = this.canvas.append("g");
		this.view = this.clip.append("g");

		this.projection = d3.geoFahey()
			.translate([this.width/2, this.height/2])
			.scale(this.param.projection.scale);

		this.path = d3.geoPath()
			.projection(this.projection);
	}

	setDataset(data) {

		var that = this;
		var teste = 6;

		this.dataset = data;

		this.elements = this.view.selectAll("path")
			.data(this.dataset.features);

		this.elements.exit()
			.remove();

		this.elements = this.elements.enter()
			.append("path")
			.merge(this.elements)
			.attr("d", this.path)
			.attr("fill", function(d, i) { return that.color("lightyellow"); })
			.attr("stroke", this.param.elements.bound)
			.attr("stroke-width", this.param.elements.stroke)
			.attr("class", this.classes.elements);
	}

	setZoom() {

		var that = this;

		this.zoom = d3.zoom()
			.scaleExtent(this.param.extent.zoom)
			// .translateExtent(this.param.extent.translate)
			.on("zoom", function() {
				that.view.attr("transform", d3.event.transform.translate(-that.x/2, -that.y/2));
				that.elements.attr("stroke-width", that.param.elements.stroke/d3.event.transform.k)
			});

		this.zoom(this.canvas);
	}

	setTooltip() {

		var that = this;

		this.tooltip = d3.select("body").append("div")
			.style("position", "absolute")
			.attr("class", this.classes.hide);

		this.elements
			.on("mousemove", function(d) {
				that.tooltip.transition()
					.duration(that.param.tooltip.on);

				that.tooltip.html(d.properties.name)
					.style("left", (d3.event.pageX + that.param.tooltip.x) + "px")
					.style("top", (d3.event.pageY + that.param.tooltip.y) + "px")
					.attr("class", that.classes.tooltip);
			})
			.on("mouseout", function(d) {
				that.tooltip.transition()
					.duration(that.param.tooltip.off)
					.attr("class", that.classes.hide);
			});
	}

	setConnection(data) {

		var that = this;
		this.selection = null;

		this.elements.on("click", function(d) {
			that.select(d.properties)
		});

		this.back.on("click", function() {
			that.select(that.selection);
		});
	}

	select(prop) {

		var that = this;
		var primary, secondary;

		if(prop == null)
			return;

		primary = prop.code;
		secondary = prop.enemies;

		var side1 = prop.side1;
		var side2 = prop.side2;

		this.selection = (this.selection != prop)? prop: null;

		if (this.selection == null) {
			primary = -1;
			secondary = [];
		}

		this.elements.attr("fill", function(d) {

			var code = d.properties.code;
			var fill;

			if (primary == code) {
				fill = that.param.elements.select;
			}
			else if ((secondary != undefined) && (secondary.includes(code))) {
				fill = that.color("indianred");
			}
			else if ((side1 != undefined) && (side1.includes(code))){
				fill = "blue";
			}
			else if ((side2 != undefined) && (side2.includes(code))){
				fill = "orange";
			}
			else {
				fill = that.color("lightyellow");
			}

			return fill;
		});
	}

	setClipPath() {

		this.clip.attr("clip-path", "url(#clip-geomap)");

		this.container.append("defs").append("clipPath")
	        .attr("id", "clip-geomap")
	        .append("rect")
	        .attr("opacity", 0)
	        .attr("width", this.width)
	        .attr("height", this.height);
	}

}<commit_msg>adicionada cores para os vira-casaca<commit_after>class GeoMap {

	constructor(arg) {

		this.id = arg.id;
		this.container = arg.container;

		this.x = arg.x;
		this.y = arg.y;
		this.width = arg.width;
		this.height = arg.height;

		this.color = d3.scaleOrdinal(["lightyellow", "indianred"]);

		this.canvas = this.container.append("g");
		this.canvas.attr("transform", "translate(" + this.x + "," + this.y + ")");

		this.param = {
			projection: {scale: [150]},
			extent: {zoom: [1, 300], translate: [[0, 0], [this.width, this.height]]},
			tooltip: {x: 5, y: -20, on: 400, off: 100},
			elements: {bound: "black", stroke: 0.4, select: "darkred"},
		};

		this.classes = {
			elements: "",
			tooltip: "label label-success",
			hide: "hidden",
		};

		this.setProjection();
		this.setDataset(arg.dataset);

		this.setZoom();
		this.setTooltip();

		this.setClipPath();

		this.setConnection();
	}

	setProjection() {

		this.back = this.canvas.append("rect")
			.attr("width", this.width)
			.attr("height", this.height)
			.attr("fill", "lightcyan");

		this.clip = this.canvas.append("g");
		this.view = this.clip.append("g");

		this.projection = d3.geoFahey()
			.translate([this.width/2, this.height/2])
			.scale(this.param.projection.scale);

		this.path = d3.geoPath()
			.projection(this.projection);
	}

	setDataset(data) {

		var that = this;
		var teste = 6;

		this.dataset = data;

		this.elements = this.view.selectAll("path")
			.data(this.dataset.features);

		this.elements.exit()
			.remove();

		this.elements = this.elements.enter()
			.append("path")
			.merge(this.elements)
			.attr("d", this.path)
			.attr("fill", function(d, i) { return that.color("lightyellow"); })
			.attr("stroke", this.param.elements.bound)
			.attr("stroke-width", this.param.elements.stroke)
			.attr("class", this.classes.elements);
	}

	setZoom() {

		var that = this;

		this.zoom = d3.zoom()
			.scaleExtent(this.param.extent.zoom)
			// .translateExtent(this.param.extent.translate)
			.on("zoom", function() {
				that.view.attr("transform", d3.event.transform.translate(-that.x/2, -that.y/2));
				that.elements.attr("stroke-width", that.param.elements.stroke/d3.event.transform.k)
			});

		this.zoom(this.canvas);
	}

	setTooltip() {

		var that = this;

		this.tooltip = d3.select("body").append("div")
			.style("position", "absolute")
			.attr("class", this.classes.hide);

		this.elements
			.on("mousemove", function(d) {
				that.tooltip.transition()
					.duration(that.param.tooltip.on);

				that.tooltip.html(d.properties.name)
					.style("left", (d3.event.pageX + that.param.tooltip.x) + "px")
					.style("top", (d3.event.pageY + that.param.tooltip.y) + "px")
					.attr("class", that.classes.tooltip);
			})
			.on("mouseout", function(d) {
				that.tooltip.transition()
					.duration(that.param.tooltip.off)
					.attr("class", that.classes.hide);
			});
	}

	setConnection(data) {

		var that = this;
		this.selection = null;

		this.elements.on("click", function(d) {
			that.select(d.properties)
		});

		this.back.on("click", function() {
			that.select(that.selection);
		});
	}

	select(prop) {

		var that = this;
		var primary, secondary;

		if(prop == null)
			return;

		primary = prop.code;
		secondary = prop.enemies;

		var side1 = prop.side1;
		var side2 = prop.side2;

		this.selection = (this.selection != prop)? prop: null;

		if (this.selection == null) {
			primary = -1;
			secondary = [];
		}

		this.elements.attr("fill", function(d) {

			var code = d.properties.code;
			var fill;

			if (primary == code) {
				fill = that.param.elements.select;
			}
			else if ((secondary != undefined) && (secondary.includes(code))) {
				fill = that.color("indianred");
			}
			else if (((side1 != undefined) && (side1.includes(code))) && ((side2 != undefined) && (side2.includes(code)))){
				fill = "gray";
			}
			else if ((side1 != undefined) && (side1.includes(code))){
				fill = "blue";
			}
			else if ((side2 != undefined) && (side2.includes(code))){
				fill = "red";
			}
			else {
				fill = that.color("lightyellow");
			}

			return fill;
		});
	}

	setClipPath() {

		this.clip.attr("clip-path", "url(#clip-geomap)");

		this.container.append("defs").append("clipPath")
	        .attr("id", "clip-geomap")
	        .append("rect")
	        .attr("opacity", 0)
	        .attr("width", this.width)
	        .attr("height", this.height);
	}

}<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const Filter = require('./Filter.js').Filter;
const TranslationsRepository = require('../../model/translation/TranslationsRepository.js').TranslationsRepository;
const SystemModuleConfiguration = require('../../configuration/SystemModuleConfiguration.js').SystemModuleConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const waitForPromise = require('../../utils/synchronize.js').waitForPromise;
const isPlainObject = require('lodash.isplainobject');

/**
 * @memberOf nunjucks.filter
 */
class TranslationsFilter extends Filter
{
    /**
     * @inheritDocs
     */
    constructor(translationsRepository, moduleConfiguration)
    {
        super();

        // Check params
        assertParameter(this, 'translationsRepository', translationsRepository, true, TranslationsRepository);
        assertParameter(this, 'moduleConfiguration', moduleConfiguration, true, SystemModuleConfiguration);

        // Assign options
        this._name = 'translations';
        this._translationsRepository = translationsRepository;
        this._moduleConfiguration = moduleConfiguration;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [TranslationsRepository, SystemModuleConfiguration] };
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'nunjucks.filter/TranslationsFilter';
    }

    /**
     * @type {model.translation.TranslationsRepository}
     */
    get translationsRepository()
    {
        return this._translationsRepository;
    }

    /**
     * @type {configuration.SystemModuleConfiguration}
     */
    get moduleConfiguration()
    {
        return this._moduleConfiguration;
    }

    /**
     * @inheritDoc
     * value - Queries
     * languages - Language(s) to return (array, locale, all, current)
     * excludeQuery - if true will omit the query portion of the key
     */
    filter()
    {
        const scope = this;
        return function (value, languages, excludeQuery)
        {
            // Only handle strings
            if (isPlainObject(value))
            {
                return scope.applyCallbacks(value, arguments);
            }
            if (!value)
            {
                return scope.applyCallbacks({}, arguments);
            }

            // Site
            const globals = scope.getGlobals(this);
            const site = globals.location.site || false;

            // Languages
            let langs = scope.moduleConfiguration.languages;
            if (languages == 'current')
            {
                langs = (globals.configuration && typeof globals.configuration.getByPath == 'function')
                    ? [globals.configuration.getByPath('language', scope.moduleConfiguration.language)]
                    : [scope.moduleConfiguration.language];
            }
            else
            {
                langs = Array.isArray(languages)
                    ? languages
                    : [languages];
            }

            // Get translations
            const queries = Array.isArray(value)
                ? value
                : [value];
            const result = {};
            for (const language of langs)
            {
                for (const query of queries)
                {
                    const translations = waitForPromise(scope.translationsRepository.getByQuerySiteAndLanguage(query, site, language)) || {};
                    result[language] = result[language] || {};
                    if (excludeQuery)
                    {
                        for (const key in translations)
                        {
                            result[language][key.replace(query, '')] = translations[key];
                        }
                    }
                    else
                    {
                        Object.assign(result[language], translations);
                    }
                }
            }
            return scope.applyCallbacks(result, arguments);
        };
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.TranslationsFilter = TranslationsFilter;
<commit_msg>fix(nunjucks.filter.TranslationsFilter): fix default languages<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const Filter = require('./Filter.js').Filter;
const TranslationsRepository = require('../../model/translation/TranslationsRepository.js').TranslationsRepository;
const SystemModuleConfiguration = require('../../configuration/SystemModuleConfiguration.js').SystemModuleConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const waitForPromise = require('../../utils/synchronize.js').waitForPromise;
const isPlainObject = require('lodash.isplainobject');

/**
 * @memberOf nunjucks.filter
 */
class TranslationsFilter extends Filter
{
    /**
     * @inheritDocs
     */
    constructor(translationsRepository, moduleConfiguration)
    {
        super();

        // Check params
        assertParameter(this, 'translationsRepository', translationsRepository, true, TranslationsRepository);
        assertParameter(this, 'moduleConfiguration', moduleConfiguration, true, SystemModuleConfiguration);

        // Assign options
        this._name = 'translations';
        this._translationsRepository = translationsRepository;
        this._moduleConfiguration = moduleConfiguration;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [TranslationsRepository, SystemModuleConfiguration] };
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'nunjucks.filter/TranslationsFilter';
    }

    /**
     * @type {model.translation.TranslationsRepository}
     */
    get translationsRepository()
    {
        return this._translationsRepository;
    }

    /**
     * @type {configuration.SystemModuleConfiguration}
     */
    get moduleConfiguration()
    {
        return this._moduleConfiguration;
    }

    /**
     * @inheritDoc
     * value - Queries
     * languages - Language(s) to return (array, locale, all, current)
     * excludeQuery - if true will omit the query portion of the key
     */
    filter()
    {
        const scope = this;
        return function (value, languages, excludeQuery)
        {
            // Only handle strings
            if (isPlainObject(value))
            {
                return scope.applyCallbacks(value, arguments);
            }

            // Site
            const globals = scope.getGlobals(this);
            const site = globals.location.site || false;

            // Languages
            let langs = scope.moduleConfiguration.languages;
            if (languages == 'current')
            {
                langs = (globals.configuration && typeof globals.configuration.getByPath == 'function')
                    ? [globals.configuration.getByPath('language', scope.moduleConfiguration.language)]
                    : [scope.moduleConfiguration.language];
            }
            else if (languages)
            {
                langs = Array.isArray(languages)
                    ? languages
                    : [languages];
            }

            // Get translations
            const queries = Array.isArray(value)
                ? value
                : [value];
            const result = {};
            for (const language of langs)
            {
                for (const query of queries)
                {
                    const translations = waitForPromise(scope.translationsRepository.getByQuerySiteAndLanguage(query, site, language)) || {};
                    result[language] = result[language] || {};
                    if (excludeQuery)
                    {
                        for (const key in translations)
                        {
                            result[language][key.replace(query, '')] = translations[key];
                        }
                    }
                    else
                    {
                        Object.assign(result[language], translations);
                    }
                }
            }
            return scope.applyCallbacks(result, arguments);
        };
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.TranslationsFilter = TranslationsFilter;
<|endoftext|>


<commit_before>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "virus-wars-extension") {
      checkVersion(design, name, value);
  }
}

var isAlive = function(design, board, group) {
  for (var i = 0; i < group.length; i++) {
       var f = false;
       _.each(design.allDirections(), function(dir) {
           var p = design.navigate(board.player, group[i], dir);
           if (p !== null) {
               var piece = board.getPiece(p);
               if ((piece !== null) && (piece.player == board.player)) {
                   if (piece.type == 0) {
                       f = true;
                       return;
                   }
                   if (_.indexOf(group, p) < 0) {
                       group.push(p);
                   }
               }
           }
       });
       if (f) return true;
  }
  return false;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      if ((move.actions.length == 1) && (move.actions[0][0] === null) && (move.actions[0][1] !== null)) {
          var pos = move.actions[0][1][0];
          if (!isAlive(design, board, [ pos ])) {
              move.failed = true;
          }
      }
  });
  CheckInvariants(board);
}

})();
<commit_msg>Virus Wars (AI)<commit_after>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "virus-wars-extension") {
      checkVersion(design, name, value);
  }
}

var checkGoals = Dagaz.Model.checkGoals;

Dagaz.Model.checkGoals = function(design, board, player) {
  var enemies = 0;
  var friends = 0;
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if ((piece !== null) && (piece.type == 0)) {
          if (piece.player != player) {
              enemies++;
          } else {
              friends++;
          }
      }
  });
  if (enemies < 1) {
      return 1;
  }
  if (friends < 1) {
      return -1;
  }
  return checkGoals(design, board, player);
}

var getSteps = function(board) {
  var c = board.turn;
  while (c >= 3) c -= 3;
  return 3 - c;
}

Dagaz.AI.heuristic = function(ai, design, board, move) {
  var r = 0;
  if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null)) {
      var pos = move.actions[0][1][0];
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var friends  = 0;
          var dead     = 0;
          var mobility = 0;
          var group    = [ pos ];
          _.each(design.allDirections(), function(dir) {
              var p = design.navigate(board.player, pos, dir);
              if (p !== null) {
                  var piece = board.getPiece(p);
                  if (piece !== null) {
                      if ((piece.player == board.player) && (piece.type == 0)) {
                          friends++;
                          mobility++;
                      }
                      if (piece.player != board.player) {
                          if (piece.type == 1) {
                              dead++;
                          }
                          group.push(p);
                      }
                  } else {
                      mobility++;
                  }
              }
          });
          if (friends > 0) {
              r = 1000 + friends;
          } else {
              if (dead > 0) {
                  r += 100 + dead;
              }
              for (var i = 0; i < group.length; i++) {
                   var q = group[i];
                   _.each(design.allDirections(), function(dir) {
                       var p = design.navigate(board.player, q, dir);
                       if (p !== null) {
                           var piece = board.getPiece(p);
                           if (piece !== null) {
                               if ((piece.player == board.player) && (piece.type == 0)) {
                                   friends++;
                                   mobility++;
                               }
                               if ((piece.player != board.player) && (_.indexOf(group, p) < 0)) {
                                   group.push(p);
                               }
                           } else {
                               mobility++;
                           }
                       }
                   });
              }
              if (friends > 0) {
                  r += 500 + friends;
              }
              r += 100 + mobility;
          }
      } else {
          var dist  = 0;
          var all   = [ pos ];
          var curr  = [ pos ];
          var next  = [];
          var dead  = [];
          var alive = [];
          while (curr.length > 0) {
              dist++;
              _.each(curr, function(q) {
                  _.each(design.allDirections(), function(dir) {
                       var p = design.navigate(board.player, q, dir);
                       if ((p !== null) && (_.indexOf(all, p) < 0)) {
                           next.push(p);
                           all.push(p);
                       }
                  });
              });
              dead  = [];
              alive = [];
              _.each(next, function(p) {
                  var piece = board.getPiece(p);
                  if ((piece !== null) && (piece.player != board.player)) {
                      if (piece.type == 0) {
                          alive.push(p);
                      } else {
                          dead.push(p);
                      }
                  }
              });
              if ((dead.length > 0) && (alive.length == 0)) {
                  for (var i = 0; i < dead.length; i++) {
                       var q = dead[i];
                       _.each(design.allDirections(), function(dir) {
                           var p = design.navigate(board.player, q, dir);
                           if ((p !== null) && (_.indexOf(dead, p) < 0)) {
                               var piece = board.getPiece(p);
                               if ((piece !== null) && (piece.player != board.player)) {
                                   if (piece.type == 0) {
                                       alive.push(p);
                                   }
                                   dead.push(p);
                               }
                           }
                       });
                  }
              }
              if (alive.length > 0) break;
              curr = next;
              next = [];
          }
          if (dist > 3) {
              r += 30 - dist;
          } else {
              if (dead.length == 0) {
                  if (alive.length + dist - 1 <= getSteps(board)) {
                      r += 50 + alive.length;
                  }
              }
          }
      }
      return r + _.random(0, 10);
  } else {
      return -1;
  }
}

var isAlive = function(design, board, group) {
  for (var i = 0; i < group.length; i++) {
       var f = false;
       _.each(design.allDirections(), function(dir) {
           var p = design.navigate(board.player, group[i], dir);
           if (p !== null) {
               var piece = board.getPiece(p);
               if ((piece !== null) && (piece.player == board.player)) {
                   if (piece.type == 0) {
                       f = true;
                       return;
                   }
                   if (_.indexOf(group, p) < 0) {
                       group.push(p);
                   }
               }
           }
       });
       if (f) return true;
  }
  return false;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      if ((move.actions.length == 1) && (move.actions[0][0] === null) && (move.actions[0][1] !== null)) {
          var pos = move.actions[0][1][0];
          if (!isAlive(design, board, [ pos ])) {
              move.failed = true;
          }
      }
  });
  CheckInvariants(board);
}

})();
<|endoftext|>