<commit_before>$(document).ready(function() {

    var DrawChart = function() {
    //Create horizontal bar chart using JQuery
    $('.chart').horizBarChart({selector: '.bar',speed: 3000});
    };

    var cleanup = function() {
        $('#searchbox #intro').empty();
        $('#searchbox #intro2').empty();
        $('#askgithub').empty();
        $('#result').empty();
        $('#progress').show();
    }

    //Handle submit
    $('#askgithub').submit(function() {
        $('#searchbox #intro').empty();
        $('#result').empty();
        $('#progress').show();
    });

    //Handle project intro
    if ($('#result').html().trim()) {
        $('#searchbox #intro').hide();
    }

    //Bind to hyperlinks
    $('a.repositoryinfo').bind('click', cleanup);

   //Handle chart div
    $('.chart').horizBarChart({selector: '.bar',speed: 3000});

    //Find similar repositories on demand
    $('a#findsimilarrepos').bind('click', function() {
       ga('send', {
           'hitType': 'event',          // Required.
           'eventCategory': 'similarrepos',   // Required.
           'eventAction': 'click',      // Required.
           'eventLabel': $('input[name="reponame"]').val()
        });
        $("#wrapperfindsimilarrepos").empty();
        $("#wrapperfindsimilarrepos").html("finding similar repositories just for you ");
        var d2 = $.ajax({
            url : '/_findsimilarrepositories',
            dataType : 'json',
            timeout : (600000),
            data : {
                a : $('input[name="reponame"]').val()
            },
            success : function(data) {
                $("#similarrepos").html(data.similarrepos);
                $("#wrapperfindsimilarrepos").empty();
            },
            error : function(objAJAXRequest, strError) {
                $("#similarrepos").html("Query taking too long: Please try again latter");
                $("#wrapperfindsimilarrepos").empty();
            }
        });
        $.when( d2 ).done(function(){
            $('a.repositoryinfo').bind('click',cleanup);
        });
        return false;
    });

    //Find trending topics on demand
    $('a#findtrendingtopics').bind('click', function() {
    	ga('send', {
           'hitType': 'event',          // Required.
           'eventCategory': 'trendingtopics',   // Required.
           'eventAction': 'click',      // Required.
           'eventLabel': $('input[name="reponame"]').val()
        });
        $("#wrapperfindtrendingtopics").empty();
        $("#wrapperfindtrendingtopics").html("finding interesting topics just for you ");
        var d2 = $.ajax({
            url : '/_findtrendingtopics',
            dataType : 'json',
            timeout : (60000),
            data : {
                qvalue : $('input[name="qvalue"]').val(),qtype : $('input[name="qtype"]').val()
            },
            success : function(data) {
                $("#trendingtopics").html(data.trendingtopics);
                $("#wrapperfindtrendingtopics").empty();
            },
            error : function(objAJAXRequest, strError) {
                $("#trendingtopics").html("Query taking too long: Please try again latter");
                $("#wrapperfindtrendingtopics").empty();
            }
        });
        $.when( d2 ).done(function(){
            $('a.trendingtopics').bind('click',cleanup);
        });
        return false;
    });

    //Automatically display Horizontal Bar Charts
    if ($('#listlanguages').length > 0) {
           //Step1: Wait for the page to load!
           $(window).bind("load", function() {
           $("#listlanguages").empty();$("#listlanguages").html("Lising languages ");
           //Step2: Function call using AJAX
           var d1 = $.ajax({url:'/_listlanguages',dataType:'json', timeout: (60000) ,data: {a: $('input[name="reponame"]').val()},
                  success: function(data) {$("#listlanguages").empty();$("#listlanguages").html(data.languages);},
                  error: function(objAJAXRequest, strError){$("#listlanguages").html("Query taking too long: Please try again latter")}
                  });
           //Step3: Wait for AJAX to return, attach event handler to the new dynamic element
           $.when( d1 ).done(function(){
            $('#listlanguages').on('click',DrawChart);
            DrawChart(); //trigger a click event
            });
        });
     }

});

<commit_msg>update GA code; not using eventLabel<commit_after>$(document).ready(function() {

    var DrawChart = function() {
    //Create horizontal bar chart using JQuery
    $('.chart').horizBarChart({selector: '.bar',speed: 3000});
    };

    var cleanup = function() {
        $('#searchbox #intro').empty();
        $('#searchbox #intro2').empty();
        $('#askgithub').empty();
        $('#result').empty();
        $('#progress').show();
    }

    //Handle submit
    $('#askgithub').submit(function() {
        $('#searchbox #intro').empty();
        $('#result').empty();
        $('#progress').show();
    });

    //Handle project intro
    if ($('#result').html().trim()) {
        $('#searchbox #intro').hide();
    }

    //Bind to hyperlinks
    $('a.repositoryinfo').bind('click', cleanup);

   //Handle chart div
    $('.chart').horizBarChart({selector: '.bar',speed: 3000});

    //Find similar repositories on demand
    $('a#findsimilarrepos').bind('click', function() {
       ga('send', {
           'hitType': 'event',          // Required.
           'eventCategory': 'similarrepos',   // Required.
           'eventAction': $('input[name="reponame"]').val()      // Required.
        });
        $("#wrapperfindsimilarrepos").empty();
        $("#wrapperfindsimilarrepos").html("finding similar repositories just for you ");
        var d2 = $.ajax({
            url : '/_findsimilarrepositories',
            dataType : 'json',
            timeout : (600000),
            data : {
                a : $('input[name="reponame"]').val()
            },
            success : function(data) {
                $("#similarrepos").html(data.similarrepos);
                $("#wrapperfindsimilarrepos").empty();
            },
            error : function(objAJAXRequest, strError) {
                $("#similarrepos").html("Query taking too long: Please try again latter");
                $("#wrapperfindsimilarrepos").empty();
            }
        });
        $.when( d2 ).done(function(){
            $('a.repositoryinfo').bind('click',cleanup);
        });
        return false;
    });

    //Find trending topics on demand
    $('a#findtrendingtopics').bind('click', function() {
    	ga('send', {
           'hitType': 'event',          // Required.
           'eventCategory': 'trendingtopics',   // Required.
           'eventAction': $('input[name="reponame"]').val()      // Required.
        });
        $("#wrapperfindtrendingtopics").empty();
        $("#wrapperfindtrendingtopics").html("finding interesting topics just for you ");
        var d2 = $.ajax({
            url : '/_findtrendingtopics',
            dataType : 'json',
            timeout : (60000),
            data : {
                qvalue : $('input[name="qvalue"]').val(),qtype : $('input[name="qtype"]').val()
            },
            success : function(data) {
                $("#trendingtopics").html(data.trendingtopics);
                $("#wrapperfindtrendingtopics").empty();
            },
            error : function(objAJAXRequest, strError) {
                $("#trendingtopics").html("Query taking too long: Please try again latter");
                $("#wrapperfindtrendingtopics").empty();
            }
        });
        $.when( d2 ).done(function(){
            $('a.trendingtopics').bind('click',cleanup);
        });
        return false;
    });

    //Automatically display Horizontal Bar Charts
    if ($('#listlanguages').length > 0) {
           //Step1: Wait for the page to load!
           $(window).bind("load", function() {
           $("#listlanguages").empty();$("#listlanguages").html("Lising languages ");
           //Step2: Function call using AJAX
           var d1 = $.ajax({url:'/_listlanguages',dataType:'json', timeout: (60000) ,data: {a: $('input[name="reponame"]').val()},
                  success: function(data) {$("#listlanguages").empty();$("#listlanguages").html(data.languages);},
                  error: function(objAJAXRequest, strError){$("#listlanguages").html("Query taking too long: Please try again latter")}
                  });
           //Step3: Wait for AJAX to return, attach event handler to the new dynamic element
           $.when( d1 ).done(function(){
            $('#listlanguages').on('click',DrawChart);
            DrawChart(); //trigger a click event
            });
        });
     }

});

<|endoftext|>


<commit_before>'use strict';

var util = require('../util'),
    ono = require('ono'),
    swaggerMethods = require('swagger-methods'),
    primitiveTypes = ['array', 'boolean', 'integer', 'number', 'string'],
    schemaTypes = ['array', 'boolean', 'integer', 'number', 'string', 'object', 'null', undefined];

module.exports = validateSpec;

/**
 * Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema.
 *
 * @param {SwaggerObject} api
 */
function validateSpec (api) {
  util.debug('Validating against the Swagger 2.0 spec');

  var paths = Object.keys(api.paths || {});
  paths.forEach(function (pathName) {
    var path = api.paths[pathName];
    var pathId = '/paths' + pathName;

    if (path && pathName.indexOf('/') === 0) {
      validatePath(api, path, pathId);
    }
  });
  var definitions = Object.keys(api.definitions || {});
  definitions.forEach(function (definitionName) {
    var definition = api.definitions[definitionName];
    validateRequiredPropertiesExist(definition);
  });

  util.debug('    Validated successfully');
}

/**
 * Validates the given path.
 *
 * @param {SwaggerObject} api      - The entire Swagger API object
 * @param {object}        path     - A Path object, from the Swagger API
 * @param {string}        pathId   - A value that uniquely identifies the path
 */
function validatePath (api, path, pathId) {
  swaggerMethods.forEach(function (operationName) {
    var operation = path[operationName];
    var operationId = pathId + '/' + operationName;

    if (operation) {
      validateParameters(api, path, pathId, operation, operationId);

      var responses = Object.keys(operation.responses || {});
      responses.forEach(function (responseName) {
        var response = operation.responses[responseName];
        var responseId = operationId + '/responses/' + responseName;
        validateResponse(responseName, (response || {}), responseId);
      });
    }
  });
}

/**
 * Validates the parameters for the given operation.
 *
 * @param {SwaggerObject} api           - The entire Swagger API object
 * @param {object}        path          - A Path object, from the Swagger API
 * @param {string}        pathId        - A value that uniquely identifies the path
 * @param {object}        operation     - An Operation object, from the Swagger API
 * @param {string}        operationId   - A value that uniquely identifies the operation
 */
function validateParameters (api, path, pathId, operation, operationId) {
  var pathParams = path.parameters || [];
  var operationParams = operation.parameters || [];

  // Check for duplicate path parameters
  try {
    checkForDuplicates(pathParams);
  }
  catch (e) {
    throw ono.syntax(e, 'Validation failed. %s has duplicate parameters', pathId);
  }

  // Check for duplicate operation parameters
  try {
    checkForDuplicates(operationParams);
  }
  catch (e) {
    throw ono.syntax(e, 'Validation failed. %s has duplicate parameters', operationId);
  }

  // Combine the path and operation parameters,
  // with the operation params taking precedence over the path params
  var params = pathParams.reduce(function (combinedParams, value) {
    var duplicate = combinedParams.some(function (param) {
      return param.in === value.in && param.name === value.name;
    });
    if (!duplicate) {
      combinedParams.push(value);
    }
    return combinedParams;
  }, operationParams.slice());

  validateBodyParameters(params, operationId);
  validatePathParameters(params, pathId, operationId);
  validateParameterTypes(params, api, operation, operationId);
}

/**
 * Validates body and formData parameters for the given operation.
 *
 * @param   {object[]}  params       -  An array of Parameter objects
 * @param   {string}    operationId  -  A value that uniquely identifies the operation
 */
function validateBodyParameters (params, operationId) {
  var bodyParams = params.filter(function (param) { return param.in === 'body'; });
  var formParams = params.filter(function (param) { return param.in === 'formData'; });

  // There can only be one "body" parameter
  if (bodyParams.length > 1) {
    throw ono.syntax(
      'Validation failed. %s has %d body parameters. Only one is allowed.',
      operationId, bodyParams.length
    );
  }
  else if (bodyParams.length > 0 && formParams.length > 0) {
    // "body" params and "formData" params are mutually exclusive
    throw ono.syntax(
      'Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.',
      operationId
    );
  }
}

/**
 * Validates path parameters for the given path.
 *
 * @param   {object[]}  params        - An array of Parameter objects
 * @param   {string}    pathId        - A value that uniquely identifies the path
 * @param   {string}    operationId   - A value that uniquely identifies the operation
 */
function validatePathParameters (params, pathId, operationId) {
  // Find all {placeholders} in the path string
  var placeholders = pathId.match(util.swaggerParamRegExp) || [];

  // Check for duplicates
  for (var i = 0; i < placeholders.length; i++) {
    for (var j = i + 1; j < placeholders.length; j++) {
      if (placeholders[i] === placeholders[j]) {
        throw ono.syntax(
          'Validation failed. %s has multiple path placeholders named %s', operationId, placeholders[i]);
      }
    }
  }

  params
    .filter(function (param) { return param.in === 'path'; })
    .forEach(function (param) {
      if (param.required !== true) {
        throw ono.syntax(
          'Validation failed. Path parameters cannot be optional. Set required=true for the "%s" parameter at %s',
          param.name,
          operationId
        );
      }
      var match = placeholders.indexOf('{' + param.name + '}');
      if (match === -1) {
        throw ono.syntax(
          'Validation failed. %s has a path parameter named "%s", ' +
          'but there is no corresponding {%s} in the path string',
          operationId,
          param.name,
          param.name
        );
      }
      placeholders.splice(match, 1);
    });

  if (placeholders.length > 0) {
    throw ono.syntax('Validation failed. %s is missing path parameter(s) for %s', operationId, placeholders);
  }
}

/**
 * Validates data types of parameters for the given operation.
 *
 * @param   {object[]}  params       -  An array of Parameter objects
 * @param   {object}    api          -  The entire Swagger API object
 * @param   {object}    operation    -  An Operation object, from the Swagger API
 * @param   {string}    operationId  -  A value that uniquely identifies the operation
 */
function validateParameterTypes (params, api, operation, operationId) {
  params.forEach(function (param) {
    var parameterId = operationId + '/parameters/' + param.name;
    var schema, validTypes;

    switch (param.in) {
      case 'body':
        schema = param.schema;
        validTypes = schemaTypes;
        break;
      case 'formData':
        schema = param;
        validTypes = primitiveTypes.concat('file');
        break;
      default:
        schema = param;
        validTypes = primitiveTypes;
    }

    validateSchema(schema, parameterId, validTypes);
    validateRequiredPropertiesExist(schema);

    if (schema.type === 'file') {
      // "file" params require specific "consumes" types
      var consumes = operation.consumes || api.consumes || [];
      if (consumes.indexOf('multipart/form-data') === -1 &&
        consumes.indexOf('application/x-www-form-urlencoded') === -1) {
        throw ono.syntax(
          'Validation failed. %s has a file parameter, so it must consume multipart/form-data ' +
          'or application/x-www-form-urlencoded',
          operationId
        );
      }
    }
  });
}

/**
 * Checks the given parameter list for duplicates, and throws an error if found.
 *
 * @param   {object[]}  params  - An array of Parameter objects
 */
function checkForDuplicates (params) {
  for (var i = 0; i < params.length - 1; i++) {
    var outer = params[i];
    for (var j = i + 1; j < params.length; j++) {
      var inner = params[j];
      if (outer.name === inner.name && outer.in === inner.in) {
        throw ono.syntax('Validation failed. Found multiple %s parameters named "%s"', outer.in, outer.name);
      }
    }
  }
}

/**
 * Validates the given response object.
 *
 * @param   {string}    code        -  The HTTP response code (or "default")
 * @param   {object}    response    -  A Response object, from the Swagger API
 * @param   {string}    responseId  -  A value that uniquely identifies the response
 */
function validateResponse (code, response, responseId) {
  if (code !== 'default' && (code < 100 || code > 599)) {
    throw ono.syntax('Validation failed. %s has an invalid response code (%s)', responseId, code);
  }

  var headers = Object.keys(response.headers || {});
  headers.forEach(function (headerName) {
    var header = response.headers[headerName];
    var headerId = responseId + '/headers/' + headerName;
    validateSchema(header, headerId, primitiveTypes);
  });

  if (response.schema) {
    var validTypes = schemaTypes.concat('file');
    if (validTypes.indexOf(response.schema.type) === -1) {
      throw ono.syntax(
        'Validation failed. %s has an invalid response schema type (%s)', responseId, response.schema.type);
    }
  }
}

/**
 * Validates the given Swagger schema object.
 *
 * @param {object}    schema      - A Schema object, from the Swagger API
 * @param {string}    schemaId    - A value that uniquely identifies the schema object
 * @param {string[]}  validTypes  - An array of the allowed schema types
 */
function validateSchema (schema, schemaId, validTypes) {
  if (validTypes.indexOf(schema.type) === -1) {
    throw ono.syntax(
      'Validation failed. %s has an invalid type (%s)', schemaId, schema.type);
  }

  if (schema.type === 'array' && !schema.items) {
    throw ono.syntax('Validation failed. %s is an array, so it must include an "items" schema', schemaId);
  }
}

/**
 * Validates that the declared properties of the given Swagger schema object actually exist.
 *
 * @param {object}    schema      - A Schema object, from the Swagger API
 */
function validateRequiredPropertiesExist (schema) {
  if (schema.required && schema.required.constructor === Array) {
    schema.required.forEach(function (requiredProperty) {
      if (!schema.properties[requiredProperty]) {
        throw ono.syntax('Validation failed. Required property \'%s\' does not exist in object', requiredProperty);
      }
    });
  }
}

<commit_msg>fixed some minor bugs in `validateRequiredPropertiesExist()`<commit_after>'use strict';

var util = require('../util'),
    ono = require('ono'),
    swaggerMethods = require('swagger-methods'),
    primitiveTypes = ['array', 'boolean', 'integer', 'number', 'string'],
    schemaTypes = ['array', 'boolean', 'integer', 'number', 'string', 'object', 'null', undefined];

module.exports = validateSpec;

/**
 * Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema.
 *
 * @param {SwaggerObject} api
 */
function validateSpec (api) {
  util.debug('Validating against the Swagger 2.0 spec');

  var paths = Object.keys(api.paths || {});
  paths.forEach(function (pathName) {
    var path = api.paths[pathName];
    var pathId = '/paths' + pathName;

    if (path && pathName.indexOf('/') === 0) {
      validatePath(api, path, pathId);
    }
  });
  var definitions = Object.keys(api.definitions || {});
  definitions.forEach(function (definitionName) {
    var definition = api.definitions[definitionName];
    validateRequiredPropertiesExist(definition);
  });

  util.debug('    Validated successfully');
}

/**
 * Validates the given path.
 *
 * @param {SwaggerObject} api      - The entire Swagger API object
 * @param {object}        path     - A Path object, from the Swagger API
 * @param {string}        pathId   - A value that uniquely identifies the path
 */
function validatePath (api, path, pathId) {
  swaggerMethods.forEach(function (operationName) {
    var operation = path[operationName];
    var operationId = pathId + '/' + operationName;

    if (operation) {
      validateParameters(api, path, pathId, operation, operationId);

      var responses = Object.keys(operation.responses || {});
      responses.forEach(function (responseName) {
        var response = operation.responses[responseName];
        var responseId = operationId + '/responses/' + responseName;
        validateResponse(responseName, (response || {}), responseId);
      });
    }
  });
}

/**
 * Validates the parameters for the given operation.
 *
 * @param {SwaggerObject} api           - The entire Swagger API object
 * @param {object}        path          - A Path object, from the Swagger API
 * @param {string}        pathId        - A value that uniquely identifies the path
 * @param {object}        operation     - An Operation object, from the Swagger API
 * @param {string}        operationId   - A value that uniquely identifies the operation
 */
function validateParameters (api, path, pathId, operation, operationId) {
  var pathParams = path.parameters || [];
  var operationParams = operation.parameters || [];

  // Check for duplicate path parameters
  try {
    checkForDuplicates(pathParams);
  }
  catch (e) {
    throw ono.syntax(e, 'Validation failed. %s has duplicate parameters', pathId);
  }

  // Check for duplicate operation parameters
  try {
    checkForDuplicates(operationParams);
  }
  catch (e) {
    throw ono.syntax(e, 'Validation failed. %s has duplicate parameters', operationId);
  }

  // Combine the path and operation parameters,
  // with the operation params taking precedence over the path params
  var params = pathParams.reduce(function (combinedParams, value) {
    var duplicate = combinedParams.some(function (param) {
      return param.in === value.in && param.name === value.name;
    });
    if (!duplicate) {
      combinedParams.push(value);
    }
    return combinedParams;
  }, operationParams.slice());

  validateBodyParameters(params, operationId);
  validatePathParameters(params, pathId, operationId);
  validateParameterTypes(params, api, operation, operationId);
}

/**
 * Validates body and formData parameters for the given operation.
 *
 * @param   {object[]}  params       -  An array of Parameter objects
 * @param   {string}    operationId  -  A value that uniquely identifies the operation
 */
function validateBodyParameters (params, operationId) {
  var bodyParams = params.filter(function (param) { return param.in === 'body'; });
  var formParams = params.filter(function (param) { return param.in === 'formData'; });

  // There can only be one "body" parameter
  if (bodyParams.length > 1) {
    throw ono.syntax(
      'Validation failed. %s has %d body parameters. Only one is allowed.',
      operationId, bodyParams.length
    );
  }
  else if (bodyParams.length > 0 && formParams.length > 0) {
    // "body" params and "formData" params are mutually exclusive
    throw ono.syntax(
      'Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.',
      operationId
    );
  }
}

/**
 * Validates path parameters for the given path.
 *
 * @param   {object[]}  params        - An array of Parameter objects
 * @param   {string}    pathId        - A value that uniquely identifies the path
 * @param   {string}    operationId   - A value that uniquely identifies the operation
 */
function validatePathParameters (params, pathId, operationId) {
  // Find all {placeholders} in the path string
  var placeholders = pathId.match(util.swaggerParamRegExp) || [];

  // Check for duplicates
  for (var i = 0; i < placeholders.length; i++) {
    for (var j = i + 1; j < placeholders.length; j++) {
      if (placeholders[i] === placeholders[j]) {
        throw ono.syntax(
          'Validation failed. %s has multiple path placeholders named %s', operationId, placeholders[i]);
      }
    }
  }

  params
    .filter(function (param) { return param.in === 'path'; })
    .forEach(function (param) {
      if (param.required !== true) {
        throw ono.syntax(
          'Validation failed. Path parameters cannot be optional. Set required=true for the "%s" parameter at %s',
          param.name,
          operationId
        );
      }
      var match = placeholders.indexOf('{' + param.name + '}');
      if (match === -1) {
        throw ono.syntax(
          'Validation failed. %s has a path parameter named "%s", ' +
          'but there is no corresponding {%s} in the path string',
          operationId,
          param.name,
          param.name
        );
      }
      placeholders.splice(match, 1);
    });

  if (placeholders.length > 0) {
    throw ono.syntax('Validation failed. %s is missing path parameter(s) for %s', operationId, placeholders);
  }
}

/**
 * Validates data types of parameters for the given operation.
 *
 * @param   {object[]}  params       -  An array of Parameter objects
 * @param   {object}    api          -  The entire Swagger API object
 * @param   {object}    operation    -  An Operation object, from the Swagger API
 * @param   {string}    operationId  -  A value that uniquely identifies the operation
 */
function validateParameterTypes (params, api, operation, operationId) {
  params.forEach(function (param) {
    var parameterId = operationId + '/parameters/' + param.name;
    var schema, validTypes;

    switch (param.in) {
      case 'body':
        schema = param.schema;
        validTypes = schemaTypes;
        break;
      case 'formData':
        schema = param;
        validTypes = primitiveTypes.concat('file');
        break;
      default:
        schema = param;
        validTypes = primitiveTypes;
    }

    validateSchema(schema, parameterId, validTypes);
    validateRequiredPropertiesExist(schema);

    if (schema.type === 'file') {
      // "file" params require specific "consumes" types
      var consumes = operation.consumes || api.consumes || [];
      if (consumes.indexOf('multipart/form-data') === -1 &&
        consumes.indexOf('application/x-www-form-urlencoded') === -1) {
        throw ono.syntax(
          'Validation failed. %s has a file parameter, so it must consume multipart/form-data ' +
          'or application/x-www-form-urlencoded',
          operationId
        );
      }
    }
  });
}

/**
 * Checks the given parameter list for duplicates, and throws an error if found.
 *
 * @param   {object[]}  params  - An array of Parameter objects
 */
function checkForDuplicates (params) {
  for (var i = 0; i < params.length - 1; i++) {
    var outer = params[i];
    for (var j = i + 1; j < params.length; j++) {
      var inner = params[j];
      if (outer.name === inner.name && outer.in === inner.in) {
        throw ono.syntax('Validation failed. Found multiple %s parameters named "%s"', outer.in, outer.name);
      }
    }
  }
}

/**
 * Validates the given response object.
 *
 * @param   {string}    code        -  The HTTP response code (or "default")
 * @param   {object}    response    -  A Response object, from the Swagger API
 * @param   {string}    responseId  -  A value that uniquely identifies the response
 */
function validateResponse (code, response, responseId) {
  if (code !== 'default' && (code < 100 || code > 599)) {
    throw ono.syntax('Validation failed. %s has an invalid response code (%s)', responseId, code);
  }

  var headers = Object.keys(response.headers || {});
  headers.forEach(function (headerName) {
    var header = response.headers[headerName];
    var headerId = responseId + '/headers/' + headerName;
    validateSchema(header, headerId, primitiveTypes);
  });

  if (response.schema) {
    var validTypes = schemaTypes.concat('file');
    if (validTypes.indexOf(response.schema.type) === -1) {
      throw ono.syntax(
        'Validation failed. %s has an invalid response schema type (%s)', responseId, response.schema.type);
    }
  }
}

/**
 * Validates the given Swagger schema object.
 *
 * @param {object}    schema      - A Schema object, from the Swagger API
 * @param {string}    schemaId    - A value that uniquely identifies the schema object
 * @param {string[]}  validTypes  - An array of the allowed schema types
 */
function validateSchema (schema, schemaId, validTypes) {
  if (validTypes.indexOf(schema.type) === -1) {
    throw ono.syntax(
      'Validation failed. %s has an invalid type (%s)', schemaId, schema.type);
  }

  if (schema.type === 'array' && !schema.items) {
    throw ono.syntax('Validation failed. %s is an array, so it must include an "items" schema', schemaId);
  }
}

/**
 * Validates that the declared properties of the given Swagger schema object actually exist.
 *
 * @param {object}    schema      - A Schema object, from the Swagger API
 */
function validateRequiredPropertiesExist (schema) {
  if (schema.required && Array.isArray(schema.required)) {
    schema.required.forEach(function (requiredProperty) {
      if (!(schema.properties && schema.properties[requiredProperty])) {
        throw ono.syntax('Validation failed. Required property \'%s\' does not exist in object', requiredProperty);
      }
    });
  }
}

<|endoftext|>


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

'use strict';

const m2ast = require('markdown-to-ast').parse;

process.stdin.resume();
process.stdin.setEncoding('utf8');

let article = '';

let stdinTimeout = setTimeout(() => {
  console.warn('No data received on stdin... Shutting down.');
  process.exit(1);
}, 2000);

function go() {
  clearTimeout(stdinTimeout);

  let ast = m2ast(article);

  let output = '';
  for (let n of ast.children) {
    let text = renderNode(n);
    if (text) {
      output += text;
    }
  }
  console.log(output);
}

process.stdin.on('data', chunk => {
  article += chunk;
});

process.stdin.on('end', go);

function renderNode(node) {
  let text = '';

  if (node.inList) {
    for (let c of (node.children || [])) {
      c.inList = true;
    }
  }

  switch (node.type) {
    case 'Header':
      for (let d = 0; d < node.depth; d++) {
        text += '=';
      }
      text += ' ';

      for (let c of node.children) {
        text += renderNode(c);
      }

      text += ' ';
      for (let d = 0; d < node.depth; d++) {
        text += '=';
      }

      text += '\n\n';

      break;

    case 'Str':
      text += node.value;
      break;

    case 'Paragraph':
      for (let c of node.children) {
        text += renderNode(c);
      }
      if (!node.inList) {
        text += '\n\n';
      }
      break;

    case 'Link':
      text += '[[' + node.url + ' | ';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += ']]';

      break;

    case 'Emphasis':
      text += '//';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += '//';

      break;

    case 'CodeBlock':
      text += '<>\n' + node.value + '\n<>\n\n';

      break;

    case 'Code':
      text += '**' + node.value + '##';
      break;

    case 'List':
      let li = node.ordered ? '#' : '*';

      let indent = '';

      if (node.inList) {
        text += '\n';
        indent = Array.apply(null, Array(4)).map(() => ' ').join('');
      }

      for (let c of node.children) {
        text += indent + li + ' ' + renderNode(c) + '\n';
      }

      if (!node.inList) {
        text += '\n';
      }

      break;

    case 'ListItem':
      for (let c of node.children) {
        c.inList = true;
        text += renderNode(c);
      }
      break;

    case 'Html':
      text += node.value;
      break;

    case 'HorizontalRule':
      text += '-\n\n'; // we should add this in mbed
      break;

    case 'Strong':
      text += '**';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += '**';
      break;

    case 'Image':
      text += '{{' + node.url + '}}';

    case 'linkReference':
    case 'definition':
      // ignore
      break;

    default:
      console.log('Unknown type', node.type, node);
      break;
  }

  return text;
}
<commit_msg>Fix inline code-blocks<commit_after>#!/usr/bin/env node

'use strict';

const m2ast = require('markdown-to-ast').parse;

process.stdin.resume();
process.stdin.setEncoding('utf8');

let article = '';

let stdinTimeout = setTimeout(() => {
  console.warn('No data received on stdin... Shutting down.');
  process.exit(1);
}, 2000);

function go() {
  clearTimeout(stdinTimeout);

  let ast = m2ast(article);

  let output = '';
  for (let n of ast.children) {
    let text = renderNode(n);
    if (text) {
      output += text;
    }
  }
  console.log(output);
}

process.stdin.on('data', chunk => {
  article += chunk;
});

process.stdin.on('end', go);

function renderNode(node) {
  let text = '';

  if (node.inList) {
    for (let c of (node.children || [])) {
      c.inList = true;
    }
  }

  switch (node.type) {
    case 'Header':
      for (let d = 0; d < node.depth; d++) {
        text += '=';
      }
      text += ' ';

      for (let c of node.children) {
        text += renderNode(c);
      }

      text += ' ';
      for (let d = 0; d < node.depth; d++) {
        text += '=';
      }

      text += '\n\n';

      break;

    case 'Str':
      text += node.value;
      break;

    case 'Paragraph':
      for (let c of node.children) {
        text += renderNode(c);
      }
      if (!node.inList) {
        text += '\n\n';
      }
      break;

    case 'Link':
      text += '[[' + node.url + ' | ';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += ']]';

      break;

    case 'Emphasis':
      text += '//';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += '//';

      break;

    case 'CodeBlock':
      text += '<>\n' + node.value + '\n<>\n\n';

      break;

    case 'Code':
      text += '##' + node.value + '##';
      break;

    case 'List':
      let li = node.ordered ? '#' : '*';

      let indent = '';

      if (node.inList) {
        text += '\n';
        indent = Array.apply(null, Array(4)).map(() => ' ').join('');
      }

      for (let c of node.children) {
        text += indent + li + ' ' + renderNode(c) + '\n';
      }

      if (!node.inList) {
        text += '\n';
      }

      break;

    case 'ListItem':
      for (let c of node.children) {
        c.inList = true;
        text += renderNode(c);
      }
      break;

    case 'Html':
      text += node.value;
      break;

    case 'HorizontalRule':
      text += '-\n\n'; // we should add this in mbed
      break;

    case 'Strong':
      text += '**';
      for (let c of node.children) {
        text += renderNode(c);
      }
      text += '**';
      break;

    case 'Image':
      text += '{{' + node.url + '}}';

    case 'linkReference':
    case 'definition':
      // ignore
      break;

    default:
      console.log('Unknown type', node.type, node);
      break;
  }

  return text;
}
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * View for the 'Standard Form' screen.
 *
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var GQScreenView = require( 'GRAPHING_QUADRATICS/common/view/GQScreenView' );
  var graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  var inherit = require( 'PHET_CORE/inherit' );
  var SceneControl = require( 'GRAPHING_QUADRATICS/standardform/view/SceneControl' );
  var EquationControls = require( 'GRAPHING_QUADRATICS/common/view/EquationControls' );
  var IntegersGraphControls = require( 'GRAPHING_QUADRATICS/standardform/view/IntegersGraphControls' );
  var DecimalsGraphControls = require( 'GRAPHING_QUADRATICS/standardform/view/DecimalsGraphControls' );
  var GQSceneNode = require( 'GRAPHING_QUADRATICS/common/view/GQSceneNode' );
  var IntegersInteractiveEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/IntegersInteractiveEquationNode' );
  var DecimalsInteractiveEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/DecimalsInteractiveEquationNode' );
  var StandardFormEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/StandardFormEquationNode' );
  var LineFormsViewProperties = require( 'GRAPHING_LINES/common/view/LineFormsViewProperties' );

  /**
   * @param {StandardFormModel} model
   * @constructor
   */
  function StandardFormScreenView( model ) {
    var self = this;

    var integersViewProperties = new LineFormsViewProperties();

    var decimalsViewProperties = new LineFormsViewProperties();

    GQScreenView.call( this, model, [ integersViewProperties, decimalsViewProperties ] );

    // view for the integers scene
    var integersInteractiveEquationNode = new IntegersInteractiveEquationNode(
      model.integersScene.aProperty,
      model.integersScene.bProperty,
      model.integersScene.cProperty
    );

    var integersSceneNode = new GQSceneNode(
      model.integersScene,
      this.layoutBounds,
      new EquationControls( new StandardFormEquationNode(), integersInteractiveEquationNode ),
      new IntegersGraphControls(
        integersViewProperties.vertexVisibleProperty,
        integersViewProperties.axisOfSymmetryVisibleProperty,
        integersViewProperties.rootsVisibleProperty
      ),
      integersViewProperties
    );

    // view for the decimals scene
    var decimalsInteractiveEquationNode = new DecimalsInteractiveEquationNode(
      model.decimalsScene.aProperty,
      model.decimalsScene.bProperty,
      model.decimalsScene.cProperty
    );

    var decimalsSceneNode = new GQSceneNode(
      model.decimalsScene,
      this.layoutBounds,
      new EquationControls( new StandardFormEquationNode(), decimalsInteractiveEquationNode ),
      new DecimalsGraphControls(),
      decimalsViewProperties
    );

    // managing the scene nodes
    var sceneNodes = [ integersSceneNode, decimalsSceneNode ];

    sceneNodes.forEach( function( sceneNode ) {
      self.addChild( sceneNode );
    } );

    // Get the bounds of the control panels
    var controlsParent = sceneNodes[ 0 ].controlsParent;

    // Center the scene control in the space below the Snapshots accordion box
    var sceneControl = new SceneControl( model.sceneProperty, model.scenes, {
      centerX: controlsParent.centerX,
      centerY: this.resetAllButton.top - 100
    } );
    this.addChild( sceneControl );

    // Make the selected scene visible. unlink not needed, as scenes last for the entire life of the sim.
    model.sceneProperty.link( function( scene ) {
      for ( var i = 0; i < sceneNodes.length; i++ ) {
        sceneNodes[ i ].visible = ( sceneNodes[ i ].scene === scene );
      }
    } );
  }

  graphingQuadratics.register( 'StandardFormScreenView', StandardFormScreenView );

  return inherit( GQScreenView, StandardFormScreenView );
} );
<commit_msg>move scene control down next to reset all button<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * View for the 'Standard Form' screen.
 *
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var GQScreenView = require( 'GRAPHING_QUADRATICS/common/view/GQScreenView' );
  var graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  var inherit = require( 'PHET_CORE/inherit' );
  var SceneControl = require( 'GRAPHING_QUADRATICS/standardform/view/SceneControl' );
  var EquationControls = require( 'GRAPHING_QUADRATICS/common/view/EquationControls' );
  var IntegersGraphControls = require( 'GRAPHING_QUADRATICS/standardform/view/IntegersGraphControls' );
  var DecimalsGraphControls = require( 'GRAPHING_QUADRATICS/standardform/view/DecimalsGraphControls' );
  var GQSceneNode = require( 'GRAPHING_QUADRATICS/common/view/GQSceneNode' );
  var IntegersInteractiveEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/IntegersInteractiveEquationNode' );
  var DecimalsInteractiveEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/DecimalsInteractiveEquationNode' );
  var StandardFormEquationNode = require( 'GRAPHING_QUADRATICS/standardform/view/StandardFormEquationNode' );
  var LineFormsViewProperties = require( 'GRAPHING_LINES/common/view/LineFormsViewProperties' );

  /**
   * @param {StandardFormModel} model
   * @constructor
   */
  function StandardFormScreenView( model ) {
    var self = this;

    var integersViewProperties = new LineFormsViewProperties();

    var decimalsViewProperties = new LineFormsViewProperties();

    GQScreenView.call( this, model, [ integersViewProperties, decimalsViewProperties ] );

    // view for the integers scene
    var integersInteractiveEquationNode = new IntegersInteractiveEquationNode(
      model.integersScene.aProperty,
      model.integersScene.bProperty,
      model.integersScene.cProperty
    );

    var integersSceneNode = new GQSceneNode(
      model.integersScene,
      this.layoutBounds,
      new EquationControls( new StandardFormEquationNode(), integersInteractiveEquationNode ),
      new IntegersGraphControls(
        integersViewProperties.vertexVisibleProperty,
        integersViewProperties.axisOfSymmetryVisibleProperty,
        integersViewProperties.rootsVisibleProperty
      ),
      integersViewProperties
    );

    // view for the decimals scene
    var decimalsInteractiveEquationNode = new DecimalsInteractiveEquationNode(
      model.decimalsScene.aProperty,
      model.decimalsScene.bProperty,
      model.decimalsScene.cProperty
    );

    var decimalsSceneNode = new GQSceneNode(
      model.decimalsScene,
      this.layoutBounds,
      new EquationControls( new StandardFormEquationNode(), decimalsInteractiveEquationNode ),
      new DecimalsGraphControls(),
      decimalsViewProperties
    );

    // managing the scene nodes
    var sceneNodes = [ integersSceneNode, decimalsSceneNode ];

    sceneNodes.forEach( function( sceneNode ) {
      self.addChild( sceneNode );
    } );

    // Get the bounds of the control panels
    var controlsParent = sceneNodes[ 0 ].controlsParent;

    // Center the scene control in the space below the Snapshots accordion box
    var sceneControl = new SceneControl( model.sceneProperty, model.scenes, {
      centerX: controlsParent.centerX,
      bottom: this.resetAllButton.bottom
    } );
    this.addChild( sceneControl );

    // Make the selected scene visible. unlink not needed, as scenes last for the entire life of the sim.
    model.sceneProperty.link( function( scene ) {
      for ( var i = 0; i < sceneNodes.length; i++ ) {
        sceneNodes[ i ].visible = ( sceneNodes[ i ].scene === scene );
      }
    } );
  }

  graphingQuadratics.register( 'StandardFormScreenView', StandardFormScreenView );

  return inherit( GQScreenView, StandardFormScreenView );
} );
<|endoftext|>


<commit_before>

L.TileLayer.addInitHook(function() {

	if (!this.options.useCache) {
		this._db     = null;
		this._canvas = null;
		return;
	}

	this._db = new PouchDB('offline-tiles');
	this._canvas = document.createElement('canvas');

	if (!(this._canvas.getContext && this._canvas.getContext('2d'))) {
		// HTML5 canvas is needed to pack the tiles as base64 data. If
		//   the browser doesn't support canvas, the code will forcefully
		//   skip caching the tiles.
		this._canvas = null;
	}
});

L.TileLayer.prototype.options.useCache     = false;
L.TileLayer.prototype.options.saveToCache  = true;
L.TileLayer.prototype.options.useOnlyCache = false;
L.TileLayer.prototype.options.cacheMaxAge  = 24*3600*1000;

L.TileLayer.include({

	// Overwrites L.TileLayer.prototype.createTile
	createTile: function(coords, done) {
		var tile = document.createElement('img');

		tile.onerror = L.bind(this._tileOnError, this, done, tile);

		if (this.options.crossOrigin) {
			tile.crossOrigin = '';
		}

		/*
		 Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons
		 http://www.w3.org/TR/WCAG20-TECHS/H67
		 */
		tile.alt = '';

		var tileUrl = this.getTileUrl(coords);

		if (this.options.useCache && this._canvas) {
			this._db.get(tileUrl, {revs_info: true}, this._onCacheLookup(tile, tileUrl, done));
		} else {
			// Fall back to standard behaviour
			tile.onload = L.bind(this._tileOnLoad, this, done, tile);
		}

		tile.src = tileUrl;
		return tile;
	},

	// Returns a callback (closure over tile/key/originalSrc) to be run when the DB
	//   backend is finished with a fetch operation.
	_onCacheLookup: function(tile, tileUrl, done) {
		return function(err,data) {
			if (data) {
				this.fire('tilecachehit', {
					tile: tile,
					url: tileUrl
				});
				if (Date.now() > data.timestamp + this.options.cacheMaxAge && !this.options.useOnlyCache) {
					// Tile is too old, try to refresh it
					console.log('Tile is too old: ', tileUrl);

					if (this.options.saveToCache) {
						tile.onload = L.bind(this._saveTile, this, tile, tileUrl, data._revs_info[0].rev, done);
					}
					tile.crossOrigin = 'Anonymous';
					tile.src = tileUrl;
					tile.onerror = function(ev) {
						// If the tile is too old but couldn't be fetched from the network,
						//   serve the one still in cache.
						this.src = data.dataUrl;
					}
				} else {
					// Serve tile from cached data
					console.log('Tile is cached: ', tileUrl);
					tile.onload = L.bind(this._tileOnLoad, this, done, tile);
					tile.src = data.dataUrl;    // data.dataUrl is already a base64-encoded PNG image.
				}
			} else {
				this.fire('tilecachemiss', {
					tile: tile,
					url: tileUrl
				});
				if (this.options.useOnlyCache) {
					// Offline, not cached
// 					console.log('Tile not in cache', tileUrl);
					tile.onload  = this._tileOnLoad;
					tile.src = L.Util.emptyImageUrl;
				} else {
					// Online, not cached, request the tile normally
// 					console.log('Requesting tile normally', tileUrl);
					if (this.options.saveToCache) {
						tile.onload = L.bind(this._saveTile, this, tile, tileUrl, null, done);
					} else {
						tile.onload = L.bind(this._tileOnLoad, this, done, tile);
					}
					tile.crossOrigin = 'Anonymous';
					tile.src = tileUrl;
				}
			}
		}.bind(this);
	},

	// Returns an event handler (closure over DB key), which runs
	//   when the tile (which is an <img>) is ready.
	// The handler will delete the document from pouchDB if an existing revision is passed.
	//   This will keep just the latest valid copy of the image in the cache.
	_saveTile: function(tile, tileUrl, existingRevision, done) {
		if (this._canvas === null) return;
		this._canvas.width  = tile.naturalWidth  || tile.width;
		this._canvas.height = tile.naturalHeight || tile.height;

		var context = this._canvas.getContext('2d');
		context.drawImage(tile, 0, 0);

		var dataUrl = this._canvas.toDataURL('image/png');
		var doc = {dataUrl: dataUrl, timestamp: Date.now()};

		if (existingRevision) {
			this._db.remove(tileUrl, existingRevision);
		}
		this._db.put(doc, tileUrl, doc.timestamp);

		if (done) { done(); }
	},

	// Seeds the cache given a bounding box (latLngBounds), and
	//   the minimum and maximum zoom levels
	// Use with care! This can spawn thousands of requests and
	//   flood tileservers!
	seed: function(bbox, minZoom, maxZoom) {
		if (minZoom > maxZoom) return;
		if (!this._map) return;

		var queue = [];

		for (var z = minZoom; z<maxZoom; z++) {

			var northEastPoint = this._map.project(bbox.getNorthEast(),z);
			var southWestPoint = this._map.project(bbox.getSouthWest(),z);

			// Calculate tile indexes as per L.TileLayer._update and
			//   L.TileLayer._addTilesFromCenterOut
			var tileSize   = this._getTileSize();
			var tileBounds = L.bounds(
				northEastPoint.divideBy(tileSize)._floor(),
				southWestPoint.divideBy(tileSize)._floor());

			for (var j = tileBounds.min.y; j <= tileBounds.max.y; j++) {
				for (var i = tileBounds.min.x; i <= tileBounds.max.x; i++) {
					point = new L.Point(i, j);
					point.z = z;
					queue.push(this.getTileUrl(point));
				}
			}
		}

		var seedData = {
			bbox: bbox,
			minZoom: minZoom,
			maxZoom: maxZoom,
			queueLength: queue.length
		}
		this.fire('seedstart', seedData);
		var tile = this._createTile();
		tile._layer = this;
		this._seedOneTile(tile, queue, seedData);
	},

	// Uses a defined tile to eat through one item in the queue and
	//   asynchronously recursively call itself when the tile has
	//   finished loading.
	_seedOneTile: function(tile, remaining, seedData) {
		if (!remaining.length) {
			this.fire('seedend', seedData);
			return;
		}
		this.fire('seedprogress', {
			bbox:    seedData.bbox,
			minZoom: seedData.minZoom,
			maxZoom: seedData.maxZoom,
			queueLength: seedData.queueLength,
			remainingLength: remaining.length
		});

		var url = remaining.pop();

		this._db.get(url, function(err,data){
			if (!data) {
				/// FIXME: Do something on tile error!!
				tile.onload = function(ev){
					this._saveTile(tile, url, null)(ev);
					this._seedOneTile(tile, remaining, seedData);
				}.bind(this);
				tile.crossOrigin = 'Anonymous';
				tile.src = url;
			} else {
				this._seedOneTile(tile, remaining, seedData);
			}
		}.bind(this));

	}

});

<commit_msg>seed function fix for leaflet 1.0-beta<commit_after>

L.TileLayer.addInitHook(function() {

	if (!this.options.useCache) {
		this._db     = null;
		this._canvas = null;
		return;
	}

	this._db = new PouchDB('offline-tiles');
	this._canvas = document.createElement('canvas');

	if (!(this._canvas.getContext && this._canvas.getContext('2d'))) {
		// HTML5 canvas is needed to pack the tiles as base64 data. If
		//   the browser doesn't support canvas, the code will forcefully
		//   skip caching the tiles.
		this._canvas = null;
	}
});

L.TileLayer.prototype.options.useCache     = false;
L.TileLayer.prototype.options.saveToCache  = true;
L.TileLayer.prototype.options.useOnlyCache = false;
L.TileLayer.prototype.options.cacheMaxAge  = 24*3600*1000;

L.TileLayer.include({

	// Overwrites L.TileLayer.prototype.createTile
	createTile: function(coords, done) {
		var tile = document.createElement('img');

		tile.onerror = L.bind(this._tileOnError, this, done, tile);

		if (this.options.crossOrigin) {
			tile.crossOrigin = '';
		}

		/*
		 Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons
		 http://www.w3.org/TR/WCAG20-TECHS/H67
		 */
		tile.alt = '';

		var tileUrl = this.getTileUrl(coords);

		if (this.options.useCache && this._canvas) {
			this._db.get(tileUrl, {revs_info: true}, this._onCacheLookup(tile, tileUrl, done));
		} else {
			// Fall back to standard behaviour
			tile.onload = L.bind(this._tileOnLoad, this, done, tile);
		}

		tile.src = tileUrl;
		return tile;
	},

	// Returns a callback (closure over tile/key/originalSrc) to be run when the DB
	//   backend is finished with a fetch operation.
	_onCacheLookup: function(tile, tileUrl, done) {
		return function(err, data) {
			if (data) {
				this.fire('tilecachehit', {
					tile: tile,
					url: tileUrl
				});
				if (Date.now() > data.timestamp + this.options.cacheMaxAge && !this.options.useOnlyCache) {
					// Tile is too old, try to refresh it
					//console.log('Tile is too old: ', tileUrl);

					if (this.options.saveToCache) {
						tile.onload = L.bind(this._saveTile, this, tile, tileUrl, data._revs_info[0].rev, done);
					}
					tile.crossOrigin = 'Anonymous';
					tile.src = tileUrl;
					tile.onerror = function(ev) {
						// If the tile is too old but couldn't be fetched from the network,
						//   serve the one still in cache.
						this.src = data.dataUrl;
					}
				} else {
					// Serve tile from cached data
					//console.log('Tile is cached: ', tileUrl);
					tile.onload = L.bind(this._tileOnLoad, this, done, tile);
					tile.src = data.dataUrl;    // data.dataUrl is already a base64-encoded PNG image.
				}
			} else {
				this.fire('tilecachemiss', {
					tile: tile,
					url: tileUrl
				});
				if (this.options.useOnlyCache) {
					// Offline, not cached
// 					console.log('Tile not in cache', tileUrl);
					tile.onload = L.Util.falseFn;
					tile.src = L.Util.emptyImageUrl;
				} else {
					//Online, not cached, request the tile normally
// 					console.log('Requesting tile normally', tileUrl);
					if (this.options.saveToCache) {
						tile.onload = L.bind(this._saveTile, this, tile, tileUrl, null, done);
					} else {
						tile.onload = L.bind(this._tileOnLoad, this, done, tile);
					}
					tile.crossOrigin = 'Anonymous';
					tile.src = tileUrl;
				}
			}
		}.bind(this);
	},

	// Returns an event handler (closure over DB key), which runs
	//   when the tile (which is an <img>) is ready.
	// The handler will delete the document from pouchDB if an existing revision is passed.
	//   This will keep just the latest valid copy of the image in the cache.
	_saveTile: function(tile, tileUrl, existingRevision, done) {
		if (this._canvas === null) return;
		this._canvas.width  = tile.naturalWidth  || tile.width;
		this._canvas.height = tile.naturalHeight || tile.height;

		var context = this._canvas.getContext('2d');
		context.drawImage(tile, 0, 0);

		var dataUrl = this._canvas.toDataURL('image/png');
		var doc = {dataUrl: dataUrl, timestamp: Date.now()};

		if (existingRevision) {
			this._db.remove(tileUrl, existingRevision);
		}
		this._db.put(doc, tileUrl, doc.timestamp);

		if (done) { done(); }
	},

	// Seeds the cache given a bounding box (latLngBounds), and
	//   the minimum and maximum zoom levels
	// Use with care! This can spawn thousands of requests and
	//   flood tileservers!
	seed: function(bbox, minZoom, maxZoom) {
		if (!this.options.useCache) return;
		if (minZoom > maxZoom) return;
		if (!this._map) return;

		var queue = [];

		for (var z = minZoom; z<=maxZoom; z++) {

			var northEastPoint = this._map.project(bbox.getNorthEast(),z);
			var southWestPoint = this._map.project(bbox.getSouthWest(),z);

			// Calculate tile indexes as per L.TileLayer._update and
			//   L.TileLayer._addTilesFromCenterOut
			var tileSize = this.getTileSize(); //_getTileSize(), used to return an integer?
			var tileBounds = L.bounds(
				northEastPoint.divideBy(tileSize.x).floor(), //tileSize.x !== tileSize.y?
				southWestPoint.divideBy(tileSize.x).floor());

			for (var j = tileBounds.min.y; j <= tileBounds.max.y; j++) {
				for (var i = tileBounds.min.x; i <= tileBounds.max.x; i++) {
					point = new L.Point(i, j);
					point.z = z;
					queue.push(this._getTileUrl(point));
				}
			}
		}

		var seedData = {
			bbox: bbox,
			minZoom: minZoom,
			maxZoom: maxZoom,
			queueLength: queue.length
		}
		this.fire('seedstart', seedData);
		var tile = this._createTile();
		tile._layer = this;
		this._seedOneTile(tile, queue, seedData);
	},

	_createTile: function () {
		return document.createElement('img');
	},

	_getTileUrl: function (coords) {
		return L.Util.template(this._url, L.extend({
			r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? '@2x' : '',
			s: this._getSubdomain(coords),
			x: coords.x,
			y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y,
			z: coords.z
		}, this.options));
	},

	// Uses a defined tile to eat through one item in the queue and
	//   asynchronously recursively call itself when the tile has
	//   finished loading.
	_seedOneTile: function(tile, remaining, seedData) {
		if (!remaining.length) {
			this.fire('seedend', seedData);
			return;
		}
		this.fire('seedprogress', {
			bbox:    seedData.bbox,
			minZoom: seedData.minZoom,
			maxZoom: seedData.maxZoom,
			queueLength: seedData.queueLength,
			remainingLength: remaining.length
		});

		var url = remaining.pop();

		this._db.get(url, function(err, data) {
			if (!data) {
				/// FIXME: Do something on tile error!!
				tile.onload = function(ev) {
					this._saveTile(tile, url, null); //(ev)
					this._seedOneTile(tile, remaining, seedData);
				}.bind(this);
				tile.crossOrigin = 'Anonymous';
				tile.src = url;
			} else {
				this._seedOneTile(tile, remaining, seedData);
			}
		}.bind(this));

	}

});

<|endoftext|>


<commit_before>/**
 * OfflineMobile Android Index
 * Sustainable Solutions (NZ) Ltd. 2016
 */

export class Scheduler {
  constructor() {
    this.intervalIds = [];
  }

  schedule(onInterval, interval) {
    const intervalId = setInterval(onInterval, interval);
    this.intervalIds = [...this.intervalIds, intervalId];
  }

  clearAll() {
    for (let intervalId of this.intervalIds) {
      clearInterval(intervalId);
    }
    this.intervalIds = [];
  }
}
<commit_msg>Change a let to a const<commit_after>/**
 * OfflineMobile Android Index
 * Sustainable Solutions (NZ) Ltd. 2016
 */

export class Scheduler {
  constructor() {
    this.intervalIds = [];
  }

  schedule(onInterval, interval) {
    const intervalId = setInterval(onInterval, interval);
    this.intervalIds = [...this.intervalIds, intervalId];
  }

  clearAll() {
    for (const intervalId of this.intervalIds) {
      clearInterval(intervalId);
    }
    this.intervalIds = [];
  }
}
<|endoftext|>


<commit_before>var medium_breakpoint = 700;
var small_breakpoint = 500;

$( document ).ready(function() {
    console.log( "ready!" );
    resizeGridItems();

    $(".needs-ready").addClass("ready");

    /* Listeners */
    $( window ).resize(function() {
        resizeGridItems();
    });
});

/* GRID STUFF */
function resizeGridItems(){
    var grid_width = $('.grid').width();

    if(grid_width > medium_breakpoint){
        var grid_item_width = grid_width / 3;

        $(".grid-item.double").css("height", 2*grid_item_width);
        $(".grid-item.double").css("width", grid_item_width);

    }else if(grid_width <= medium_breakpoint && grid_width > small_breakpoint){
        var grid_item_width = grid_width / 2;

        $(".grid-item.double").css("height", grid_item_width);
        $(".grid-item.double").css("width", 2*grid_item_width);
    }else{
        var grid_item_width = grid_width;

        $(".grid-item.double").css("height", grid_item_width);
        $(".grid-item.double").css("width", grid_item_width);
    }

    $(".grid-item").css("width", grid_item_width);
    $(".grid-item").css("height", grid_item_width);

    $(".inner-grid-item").css("width", grid_item_width);
    $(".inner-grid-item").css("height", grid_item_width);

}<commit_msg>working on homepage<commit_after>var medium_breakpoint = 700;
var small_breakpoint = 500;

$( document ).ready(function() {
    console.log( "ready!" );
    resizeGridItems();

    $(".needs-ready").addClass("ready");

    /* Listeners */
    $( window ).resize(function() {
        resizeGridItems();
    });
});

/* GRID STUFF */
function resizeGridItems(){
    var grid_width = $('.grid').width();

    var layout_size = (grid_width > medium_breakpoint) ? "large" : (grid_width <= medium_breakpoint && grid_width > small_breakpoint)? "medium" : "small";
    var grid_item_width = (grid_width > medium_breakpoint) ? grid_width / 3 : (grid_width <= medium_breakpoint && grid_width > small_breakpoint)? grid_width / 2 : grid_width;

    $(".grid-item").css("width", grid_item_width);
    $(".grid-item").css("height", grid_item_width);

    $(".inner-grid-item").css("width", grid_item_width);
    $(".inner-grid-item").css("height", grid_item_width);

    if(layout_size=="large"){
        $(".grid-item.double").css("height", 2*grid_item_width);
        $(".grid-item.double").css("width", grid_item_width);
    }else if(layout_size=="medium"){
        $(".grid-item.double").css("height", grid_item_width);
        $(".grid-item.double").css("width", 2*grid_item_width);
    }else{
        $(".grid-item.double").css("height", grid_item_width);
        $(".grid-item.double").css("width", grid_item_width);
    }

}<|endoftext|>


<commit_before>var yargs = require('yargs')

var argv = yargs
  .command(
    "history",
    "render some history",
    require("./_history")
  )
  .demand(1)
  .help('help')
  .argv;

<commit_msg>Added shebang.<commit_after>#!/usr/bin/env node
var yargs = require('yargs')

var argv = yargs
  .command(
    "history",
    "render some history",
    require("./_history")
  )
  .demand(1)
  .help('help')
  .argv;

<|endoftext|>


<commit_before>var DOMMode = require('./DOMMode'),
	EventUtils = require('browser-event-adder'),
	Signal = require('signals').Signal,
	AdaptiveResolutionManager = require('./AdaptiveResolutionManager'),
	Resize = require('input-resize'),
	_ = require('lodash'),
	RenderStats = require('./RenderStats'),
	RenderManager = require('./RenderManager');
/**
 * View is the viewport canvas and the renderer
 * @param {Object} props an object of properties to override default dehaviours
 */
function View(props) {
	props = props || {};
	this.addCanvasContainerToDOMBody = this.addCanvasContainerToDOMBody.bind(this);
	this.addCanvasToContainer = this.addCanvasToContainer.bind(this);

	this.adaptiveResolution = props.adaptiveResolution;
	this.adaptiveResolutionManager = new AdaptiveResolutionManager(props.adaptiveResolutionSettings);

	this.fitAxis = props.fitAxis || 'y';

	this.skipRender = Boolean(props.skipRender);
	this.scene = props.scene || new THREE.Scene();
	props.rendererSettings = props.rendererSettings || {};
	if(props.camera) {
		this.camera = props.camera;
	} else {
		this.camera = new THREE.PerspectiveCamera();
		this.scene.add(this.camera);
		this.camera.position.z = 8.50;
		this.camera.position.y = 8.0;
		this.camera.lookAt(this.scene.position);
	}
	if(this.camera instanceof THREE.PerspectiveCamera) {
		this.setCamera = this.setCameraPerspective;
	} else if (this.camera instanceof THREE.OrthographicCamera) {
		this.setCamera = this.setCameraOthrographic;
	}
	this.autoStartRender = props.autoStartRender !== (undefined ? props.autoStartRender : true);
	this.canvasContainerID = props.canvasContainerID || "WebGLCanvasContainer";

	this.domMode = props.domMode || (props.canvasContainer ? DOMMode.CONTAINER : DOMMode.FULLSCREEN);
	this.canvasContainer = props.canvasContainer || this.createCanvasContainer(this.canvasContainerID);
	this.canvasID = props.canvasID || "WebGLCanvas";
	this.domMode = props.domMode || (this.canvasContainer ? DOMMode.CONTAINER : DOMMode.FULLSCREEN);
	this.domSize = {x:0, y:0};

	//use provided canvas or make your own
	this.canvas = document.getElementById(this.canvasID) || this.createCanvas();
	this.rendererSettings = _.merge({
		canvas: this.canvas,
		antialias: true,
	}, props.rendererSettings);

	if( props.renderer !== undefined) {
		this.renderer = props.renderer;
	} else {
		this.renderer = new THREE.WebGLRenderer(this.rendererSettings);
	}

	if(this.rendererSettings.autoClear === false) this.renderer.autoClear = false;

	this.renderManager = new RenderManager(this, props.useRafPolyfill);
	if(this.autoStartRender) this.renderManager.start();

	this.adaptiveResolutionManager.onChange.add(this.onAdaptiveResolutionManagerChangeResolution.bind(this));

	this.setupResizing();

	if(props.stats) {
		this.stats = new RenderStats(this.renderer);
		this.renderManager.onEnterFrame.add(this.stats.onEnterFrame);
		this.renderManager.onExitFrame.add(this.stats.onExitFrame);
	}

	this.dpr = this.renderer.devicePixelRatio;

}

View.prototype = {
	setupResizing: function() {
		this.onResizeSignal = Resize.onResize;
		this.setSize = this.setSize.bind(this);
		this.onResizeSignal.add(this.setSize);
		Resize.bump();
	},
	/**
	 * Renders the scene to the canvas using the renderer
	 * @return {[type]} [description]
	 */
	render: function () {
		if(this.adaptiveResolution) this.adaptiveResolutionManager.update();
		if (!this.skipRender) {
			this.renderer.render(this.scene, this.camera);
		}
	},

	/**
	 * Creates the canvas DOM Element and appends it to the document body
	 * @return {CanvasElement} The newly created canvas element.
	 */
	createCanvasContainer: function(id) {
		var canvasContainer = document.createElement("div");
		canvasContainer.id = id;
		canvasContainer.width = window.innerWidth;
		canvasContainer.height = window.innerHeight;
		this.addCanvasContainerToDOMBody(canvasContainer);
		this.setDOMMode(canvasContainer, this.domMode);
		return canvasContainer;
	},

	createCanvas: function() {
		var canvas = document.createElement("canvas");
		canvas.id = this.canvasID;
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
		this.addCanvasToContainer(canvas);
		this.setDOMMode(canvas, this.domMode);
		return canvas;
	},

	addCanvasContainerToDOMBody: function(canvasContainer) {
		canvasContainer = canvasContainer || this.canvasContainer;
		if(document.body) {
			document.body.appendChild(canvasContainer);
		} else {
			setTimeout(this.addCanvasContainerToDOMBody, 50);
		}
	},

	addCanvasToContainer: function(canvas) {
		canvas = canvas || this.canvas;
		if(this.canvasContainer) {
			this.canvasContainer.appendChild(canvas);
		} else {
			setTimeout(this.addCanvasToContainer, 50);
		}
	},

	/**
	 * sets the DOM Mode, which controls the css rules of the canvas element
	 * @param {String} mode string, enumerated in DOMMode
	 */
	setDOMMode: function(element, mode) {
		var style = element.style;
		switch(mode) {
			case DOMMode.FULLSCREEN:
				style.position = "fixed";
				style.left = "0px";
				style.top = "0px";
				style.width = '100%';
				style.height = '100%';
				break;
			case DOMMode.CONTAINER:
				style.position = "absolute";
				style.left = "0px";
				style.top = "0px";
				style.width = this.canvasContainer.clientWidth + 'px';
				style.height = this.canvasContainer.clientHeight + 'px';
				break;
			default:
		}
	},

	setSize: function(w, h, force) {
		if(this.domMode == DOMMode.CONTAINER && !force) {
			w = this.canvasContainer.clientWidth;
			h = this.canvasContainer.clientHeight;
		}
		this.domSize.x = w;
		this.domSize.y = h;
		this.canvas.style.width = w;
		this.canvas.style.height = h;
		this.setCamera(w, h);

		this.setResolution(
			~~(w / this.adaptiveResolutionManager.denominator),
			~~(h / this.adaptiveResolutionManager.denominator)
		);
	},

	setCameraPerspective: function(w, h) {
		this.camera.aspect = w/h;
		if(this.fitAxis == 'x') this.camera.setLens(w, h);
		if(w == 720) {
			console.log(w, h);
		}
		this.camera.updateProjectionMatrix();
	},

	setCameraOthrographic: function(w, h) {
		this.camera.left = 0;
		this.camera.right = w;
		this.camera.top = 0;
		this.camera.bottom = h;
		this.camera.updateProjectionMatrix();
	},

	getSize: function() {
		return {
			width: this.domSize.x,
			height: this.domSize.y
		};
	},

	setResolution: function(w, h) {
		this.canvas.width = w * this.dpr;
		this.canvas.height = h * this.dpr;
		this.renderer.setSize(w, h, false);
		this.canvas.style.width = this.domSize.x + 'px';
		this.canvas.style.height = this.domSize.y + 'px';
	},

	getResolution: function() {
		return {
			width: this.canvas.width,
			height: this.canvas.height
		}
	},

	onAdaptiveResolutionManagerChangeResolution: function(dynamicScale) {
		this.setResolution(
			~~(window.innerWidth * dynamicScale),
			~~(window.innerHeight * dynamicScale)
		);
	},

	captureImageData: function(options) {
		var canvas = this.canvas;
		var oldWidth = this.domSize.x;
		var oldHeight = this.domSize.y;

		options = _.merge({
			width: oldWidth,
			height: oldHeight,
			format: 'jpeg'
		}, options);
		var format = options.format === 'jpg' ? 'jpeg' : options.format;
		this.setSize(options.width/this.dpr, options.height/this.dpr, true);

		var type = 'image/' + format;
		var originalSkip = this.skipRender;
		this.skipRender = false;
		this.renderManager.render();
		this.skipRender = originalSkip;

		var imageData = canvas.toDataURL(type, options.encoderOptions);
		this.setSize(oldWidth, oldHeight, true);
		return imageData;
	}
};

module.exports = View;<commit_msg>bugfixed resizing signal for containers<commit_after>var DOMMode = require('./DOMMode'),
	EventUtils = require('browser-event-adder'),
	Signal = require('signals').Signal,
	AdaptiveResolutionManager = require('./AdaptiveResolutionManager'),
	Resize = require('input-resize'),
	_ = require('lodash'),
	RenderStats = require('./RenderStats'),
	RenderManager = require('./RenderManager');
/**
 * View is the viewport canvas and the renderer
 * @param {Object} props an object of properties to override default dehaviours
 */
function View(props) {
	props = props || {};
	this.addCanvasContainerToDOMBody = this.addCanvasContainerToDOMBody.bind(this);
	this.addCanvasToContainer = this.addCanvasToContainer.bind(this);

	this.adaptiveResolution = props.adaptiveResolution;
	this.adaptiveResolutionManager = new AdaptiveResolutionManager(props.adaptiveResolutionSettings);

	this.fitAxis = props.fitAxis || 'y';

	this.skipRender = Boolean(props.skipRender);
	this.scene = props.scene || new THREE.Scene();
	props.rendererSettings = props.rendererSettings || {};
	if(props.camera) {
		this.camera = props.camera;
	} else {
		this.camera = new THREE.PerspectiveCamera();
		this.scene.add(this.camera);
		this.camera.position.z = 8.50;
		this.camera.position.y = 8.0;
		this.camera.lookAt(this.scene.position);
	}
	if(this.camera instanceof THREE.PerspectiveCamera) {
		this.setCamera = this.setCameraPerspective;
	} else if (this.camera instanceof THREE.OrthographicCamera) {
		this.setCamera = this.setCameraOthrographic;
	}
	this.autoStartRender = props.autoStartRender !== (undefined ? props.autoStartRender : true);
	this.canvasContainerID = props.canvasContainerID || "WebGLCanvasContainer";

	this.domMode = props.domMode || (props.canvasContainer ? DOMMode.CONTAINER : DOMMode.FULLSCREEN);
	this.canvasContainer = props.canvasContainer || this.createCanvasContainer(this.canvasContainerID);
	this.canvasID = props.canvasID || "WebGLCanvas";
	this.domMode = props.domMode || (this.canvasContainer ? DOMMode.CONTAINER : DOMMode.FULLSCREEN);
	this.domSize = {x:0, y:0};

	//use provided canvas or make your own
	this.canvas = document.getElementById(this.canvasID) || this.createCanvas();
	this.rendererSettings = _.merge({
		canvas: this.canvas,
		antialias: true,
	}, props.rendererSettings);

	if( props.renderer !== undefined) {
		this.renderer = props.renderer;
	} else {
		this.renderer = new THREE.WebGLRenderer(this.rendererSettings);
	}

	if(this.rendererSettings.autoClear === false) this.renderer.autoClear = false;

	this.renderManager = new RenderManager(this, props.useRafPolyfill);
	if(this.autoStartRender) this.renderManager.start();

	this.adaptiveResolutionManager.onChange.add(this.onAdaptiveResolutionManagerChangeResolution.bind(this));

	this.setupResizing();

	if(props.stats) {
		this.stats = new RenderStats(this.renderer);
		this.renderManager.onEnterFrame.add(this.stats.onEnterFrame);
		this.renderManager.onExitFrame.add(this.stats.onExitFrame);
	}

	this.dpr = this.renderer.devicePixelRatio;

}

View.prototype = {
	setupResizing: function() {
		this._onResizeSignal = Resize.onResize;
		this.setSize = this.setSize.bind(this);
		this._onResizeSignal.add(this.setSize);
		this.onResizeSignal = new Signal();
		Resize.bump();
	},
	/**
	 * Renders the scene to the canvas using the renderer
	 * @return {[type]} [description]
	 */
	render: function () {
		if(this.adaptiveResolution) this.adaptiveResolutionManager.update();
		if (!this.skipRender) {
			this.renderer.render(this.scene, this.camera);
		}
	},

	/**
	 * Creates the canvas DOM Element and appends it to the document body
	 * @return {CanvasElement} The newly created canvas element.
	 */
	createCanvasContainer: function(id) {
		var canvasContainer = document.createElement("div");
		canvasContainer.id = id;
		canvasContainer.width = window.innerWidth;
		canvasContainer.height = window.innerHeight;
		this.addCanvasContainerToDOMBody(canvasContainer);
		this.setDOMMode(canvasContainer, this.domMode);
		return canvasContainer;
	},

	createCanvas: function() {
		var canvas = document.createElement("canvas");
		canvas.id = this.canvasID;
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
		this.addCanvasToContainer(canvas);
		this.setDOMMode(canvas, this.domMode);
		return canvas;
	},

	addCanvasContainerToDOMBody: function(canvasContainer) {
		canvasContainer = canvasContainer || this.canvasContainer;
		if(document.body) {
			document.body.appendChild(canvasContainer);
		} else {
			setTimeout(this.addCanvasContainerToDOMBody, 50);
		}
	},

	addCanvasToContainer: function(canvas) {
		canvas = canvas || this.canvas;
		if(this.canvasContainer) {
			this.canvasContainer.appendChild(canvas);
		} else {
			setTimeout(this.addCanvasToContainer, 50);
		}
	},

	/**
	 * sets the DOM Mode, which controls the css rules of the canvas element
	 * @param {String} mode string, enumerated in DOMMode
	 */
	setDOMMode: function(element, mode) {
		var style = element.style;
		switch(mode) {
			case DOMMode.FULLSCREEN:
				style.position = "fixed";
				style.left = "0px";
				style.top = "0px";
				style.width = '100%';
				style.height = '100%';
				break;
			case DOMMode.CONTAINER:
				style.position = "absolute";
				style.left = "0px";
				style.top = "0px";
				style.width = this.canvasContainer.clientWidth + 'px';
				style.height = this.canvasContainer.clientHeight + 'px';
				break;
			default:
		}
	},

	setSize: function(w, h, force) {
		if(this.domMode == DOMMode.CONTAINER && !force) {
			w = this.canvasContainer.clientWidth;
			h = this.canvasContainer.clientHeight;
		}
		this.domSize.x = w;
		this.domSize.y = h;
		this.canvas.style.width = w;
		this.canvas.style.height = h;
		this.setCamera(w, h);

		this.setResolution(
			~~(w / this.adaptiveResolutionManager.denominator),
			~~(h / this.adaptiveResolutionManager.denominator)
		);

		this.onResizeSignal.dispatch(w, h);
	},

	setCameraPerspective: function(w, h) {
		this.camera.aspect = w/h;
		if(this.fitAxis == 'x') this.camera.setLens(w, h);
		if(w == 720) {
			console.log(w, h);
		}
		this.camera.updateProjectionMatrix();
	},

	setCameraOthrographic: function(w, h) {
		this.camera.left = 0;
		this.camera.right = w;
		this.camera.top = 0;
		this.camera.bottom = h;
		this.camera.updateProjectionMatrix();
	},

	getSize: function() {
		return {
			width: this.domSize.x,
			height: this.domSize.y
		};
	},

	setResolution: function(w, h) {
		this.canvas.width = w * this.dpr;
		this.canvas.height = h * this.dpr;
		this.renderer.setSize(w, h, false);
		this.canvas.style.width = this.domSize.x + 'px';
		this.canvas.style.height = this.domSize.y + 'px';
	},

	getResolution: function() {
		return {
			width: this.canvas.width,
			height: this.canvas.height
		}
	},

	onAdaptiveResolutionManagerChangeResolution: function(dynamicScale) {
		this.setResolution(
			~~(window.innerWidth * dynamicScale),
			~~(window.innerHeight * dynamicScale)
		);
	},

	captureImageData: function(options) {
		var canvas = this.canvas;
		var oldWidth = this.domSize.x;
		var oldHeight = this.domSize.y;

		options = _.merge({
			width: oldWidth,
			height: oldHeight,
			format: 'jpeg'
		}, options);
		var format = options.format === 'jpg' ? 'jpeg' : options.format;
		this.setSize(options.width/this.dpr, options.height/this.dpr, true);

		var type = 'image/' + format;
		var originalSkip = this.skipRender;
		this.skipRender = false;
		this.renderManager.render();
		this.skipRender = originalSkip;

		var imageData = canvas.toDataURL(type, options.encoderOptions);
		this.setSize(oldWidth, oldHeight, true);
		return imageData;
	}
};

module.exports = View;<|endoftext|>


<commit_before>import Immutable from 'seamless-immutable';
import { GAMETES_RESET } from '../modules/gametes';
import { LOCATION_CHANGE } from 'react-router-redux';
import actionTypes from '../action-types';
import t from '../utilities/translate';
import GuideProtocol from '../utilities/guide-protocol';

export const GUIDE_CONNECTED = "Guide connected";
export const GUIDE_MESSAGE_RECEIVED = "Guide message received";
export const GUIDE_ALERT_RECEIVED = "Guide alert received";
export const GUIDE_ERRORED = "Guide errored";
export const ADVANCE_NOTIFICATIONS = "Advance notifications";
export const CLOSE_NOTIFICATIONS = "Close notifications";

export const notificationType = {
  NARRATIVE: "narrative"
};

const initialState = {
  messages: Immutable([]),
  closeButton: null
};

export default function notifications(state = initialState, action) {
  switch (action.type) {
    case GUIDE_MESSAGE_RECEIVED:
      if (action.data) {
        let data = GuideProtocol.TutorDialog.fromJson(action.data);
        if (data.reason) {
          console.log(`%c ITS Message Reason: ${data.reason.why || ""}`, `color: #f99a00`, action.data.reason);
        }

        if (state.messages[0] && state.messages[0].type === notificationType.NARRATIVE) {
          console.log(`%c Not showing ITS Message due to narrative`, `color: #f99a00`);
          return state;
        }

        let trait = data.message.args ? data.message.args.trait : null;
        let currentText = state.messages.length > 0 ? state.messages[0].text + " " : "";
        let newMessage = {
          text: currentText + data.message.asString()
        };
        if (trait) {
          newMessage.trait = trait;
        }
        return Object.assign({}, state, {messages: [newMessage]});
      }
      else
        return state;
    case actionTypes.NOTIFICATIONS_SHOWN: {
      const translatedMessages = action.messages.map(message => {
        return Object.assign({}, message, {text: t(message.text)});
      });
      return {messages: state.messages.concat(translatedMessages), closeButton: action.closeButton};
    }
    case ADVANCE_NOTIFICATIONS:
      return Object.assign({}, state, {messages: state.messages.length > 1 ? state.messages.slice(1, state.length) : initialState});
    case CLOSE_NOTIFICATIONS:
      return initialState;
    // actions which don't clear the guide message
    case GAMETES_RESET:
    case GUIDE_CONNECTED:
    case GUIDE_ALERT_RECEIVED:
    case actionTypes.MODAL_DIALOG_SHOWN:
    case actionTypes.MODAL_DIALOG_DISMISSED:
    case LOCATION_CHANGE:
      return state;
    // For now, clear all messages every time the user does anything else
    default:
      return initialState;
  }
}

export function advanceNotifications() {
  return {
    type: ADVANCE_NOTIFICATIONS
  };
}

export function closeNotifications() {
  return {
    type: CLOSE_NOTIFICATIONS
  };
}
<commit_msg>Update ITS traits to read `reason.trait`<commit_after>import Immutable from 'seamless-immutable';
import { GAMETES_RESET } from '../modules/gametes';
import { LOCATION_CHANGE } from 'react-router-redux';
import actionTypes from '../action-types';
import t from '../utilities/translate';
import GuideProtocol from '../utilities/guide-protocol';

export const GUIDE_CONNECTED = "Guide connected";
export const GUIDE_MESSAGE_RECEIVED = "Guide message received";
export const GUIDE_ALERT_RECEIVED = "Guide alert received";
export const GUIDE_ERRORED = "Guide errored";
export const ADVANCE_NOTIFICATIONS = "Advance notifications";
export const CLOSE_NOTIFICATIONS = "Close notifications";

export const notificationType = {
  NARRATIVE: "narrative"
};

const initialState = {
  messages: Immutable([]),
  closeButton: null
};

export default function notifications(state = initialState, action) {
  switch (action.type) {
    case GUIDE_MESSAGE_RECEIVED:
      if (action.data) {
        let data = GuideProtocol.TutorDialog.fromJson(action.data);
        if (data.reason) {
          console.log(`%c ITS Message Reason: ${data.reason.why || ""}`, `color: #f99a00`, data.reason);
        }

        if (state.messages[0] && state.messages[0].type === notificationType.NARRATIVE) {
          console.log(`%c Not showing ITS Message due to narrative`, `color: #f99a00`);
          return state;
        }

        let currentText = state.messages.length > 0 ? state.messages[0].text + " " : "";
        let newMessage = {
          text: currentText + data.message.asString()
        };

        let trait;
        // check reason.trait first, then message.args.trait
        if (data.reason && data.reason.trait) {
          trait = data.reason.trait;
        } else if (data.message.args) {
          trait = data.message.args.trait;
        }
        if (trait) {
          newMessage.trait = trait;
        }

        return Object.assign({}, state, {messages: [newMessage]});
      }
      else
        return state;
    case actionTypes.NOTIFICATIONS_SHOWN: {
      const translatedMessages = action.messages.map(message => {
        return Object.assign({}, message, {text: t(message.text)});
      });
      return {messages: state.messages.concat(translatedMessages), closeButton: action.closeButton};
    }
    case ADVANCE_NOTIFICATIONS:
      return Object.assign({}, state, {messages: state.messages.length > 1 ? state.messages.slice(1, state.length) : initialState});
    case CLOSE_NOTIFICATIONS:
      return initialState;
    // actions which don't clear the guide message
    case GAMETES_RESET:
    case GUIDE_CONNECTED:
    case GUIDE_ALERT_RECEIVED:
    case actionTypes.MODAL_DIALOG_SHOWN:
    case actionTypes.MODAL_DIALOG_DISMISSED:
    case LOCATION_CHANGE:
      return state;
    // For now, clear all messages every time the user does anything else
    default:
      return initialState;
  }
}

export function advanceNotifications() {
  return {
    type: ADVANCE_NOTIFICATIONS
  };
}

export function closeNotifications() {
  return {
    type: CLOSE_NOTIFICATIONS
  };
}
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, {Component} from 'react';
import Convert from 'ansi-to-html';

import { Col, Row,  TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import classnames from 'classnames';
import {AsyncTypeahead} from 'react-bootstrap-typeahead';
import ReactJson from 'react-json-view';

import Logs from "./Logs";
import "./Console.css";
import {EMBARK_PROCESS_NAME} from '../constants';

const convert = new Convert();

class Console extends Component {
  constructor(props) {
    super(props);
    this.state = {value: '', isLoading: true, options: [], activeTab: EMBARK_PROCESS_NAME};
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.postCommand(this.state.value);
    this.setState({value: ''});
    this.typeahead.getInstance().clear();
  }

  handleChange(value, cb) {
    this.setState({value: value}, cb);
  }

  toggle(tab) {
    if (this.state.activeTab !== tab) {
      this.setState({
        activeTab: tab
      });
      this.props.updateTab(tab);
    }
  }

  renderNav() {
    return (

        {this.props.processes.map((process) => (
          <NavItem key={process.name}>
            <NavLink
              className={classnames({ active: this.state.activeTab === process.name })}
              onClick={() => { this.toggle(process.name); }}
          >
            {process.name}
          </NavLink>
        </NavItem>
        ))}

    );
  }

  isJsonObject(item) {
    if (!item.result) return false;
    try {
      return typeof (JSON.parse(item.result)) === 'object';
    } catch(_err) {
      return false;
    }
  }

  logClassName(item) {
    return classnames('m-0', {
      'text-info': item.logLevel === 'debug',
      'text-danger': item.logLevel === 'error',
      'text-warning': item.logLevel === 'warning'
    });
  }

  renderTabs() {
    const {processLogs, processes} = this.props;

    return (
      <TabContent activeTab={this.state.activeTab}>
        {processes.map(process => (
          <TabPane key={process.name} tabId={process.name}>
            <Logs>
              {processLogs
                .filter((item) => item.name === process.name)
                .reverse()
                .map((item, i) => {

                  if (this.isJsonObject(item)) {
                    return(

                        <ReactJson src={JSON.parse(item.result)} theme="monokai" sortKeys={true} collapsed={1} />

                    );
                  }

                  return (

                  );
                })
              }
            </Logs>
            {process.name === "embark" &&
              <AsyncTypeahead
                autoFocus={true}
                emptyLabel={false}
                labelKey="value"
                multiple={false}
                maxResults={10}
                isLoading={this.state.isLoading}
                onInputChange={(text) => this.handleChange(text)}
                onChange={(text) => {
                  if (text && text[0]) {
                    this.handleChange(text[0].value);
                  }
                }}
                ref={(typeahead) => this.typeahead = typeahead}
                searchText={false}
                onKeyDown={(e) => {
                  if (e.keyCode === 13) {
                    this.handleChange(e.target.value, () => {
                      this.handleSubmit(e);
                    });
                  }
                }}
                onSearch={(value) => {
                  this.props.postCommandSuggestions(value);
                }}
                filterBy={['value', 'description']}
                maxHeight="200px"
                placeholder="Type a command (e.g help)"
                options={this.props.commandSuggestions}
                renderMenuItemChildren={(option) => (

                    {option.value}

                      {option.command_type} - {option.description}

                )}
              />
            }

          </TabPane>
        ))}
      </TabContent>
    );
  }

  render() {
    return (
      <Row>
        <Col>
          {this.renderNav()}
          {this.renderTabs()}
        </Col>
      </Row>
    );
  }
}

Console.propTypes = {
  postCommand: PropTypes.func,
  postCommandSuggestions: PropTypes.func,
  isEmbark: PropTypes.func,
  processes: PropTypes.arrayOf(PropTypes.object).isRequired,
  commandSuggestions: PropTypes.arrayOf(PropTypes.object),
  processLogs: PropTypes.arrayOf(PropTypes.object).isRequired,
  updateTab: PropTypes.func
};

export default Console;
<commit_msg>feat(ui): color console item info as success<commit_after>import PropTypes from "prop-types";
import React, {Component} from 'react';
import Convert from 'ansi-to-html';

import { Col, Row,  TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import classnames from 'classnames';
import {AsyncTypeahead} from 'react-bootstrap-typeahead';
import ReactJson from 'react-json-view';

import Logs from "./Logs";
import "./Console.css";
import {EMBARK_PROCESS_NAME} from '../constants';

const convert = new Convert();

class Console extends Component {
  constructor(props) {
    super(props);
    this.state = {value: '', isLoading: true, options: [], activeTab: EMBARK_PROCESS_NAME};
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.postCommand(this.state.value);
    this.setState({value: ''});
    this.typeahead.getInstance().clear();
  }

  handleChange(value, cb) {
    this.setState({value: value}, cb);
  }

  toggle(tab) {
    if (this.state.activeTab !== tab) {
      this.setState({
        activeTab: tab
      });
      this.props.updateTab(tab);
    }
  }

  renderNav() {
    return (

        {this.props.processes.map((process) => (
          <NavItem key={process.name}>
            <NavLink
              className={classnames({ active: this.state.activeTab === process.name })}
              onClick={() => { this.toggle(process.name); }}
          >
            {process.name}
          </NavLink>
        </NavItem>
        ))}

    );
  }

  isJsonObject(item) {
    if (!item.result) return false;
    try {
      return typeof (JSON.parse(item.result)) === 'object';
    } catch(_err) {
      return false;
    }
  }

  logClassName(item) {
    return classnames('m-0', {
      'text-success': item.logLevel === 'info',
      'text-info': item.logLevel === 'debug',
      'text-danger': item.logLevel === 'error',
      'text-warning': item.logLevel === 'warning'
    });
  }

  renderTabs() {
    const {processLogs, processes} = this.props;

    return (
      <TabContent activeTab={this.state.activeTab}>
        {processes.map(process => (
          <TabPane key={process.name} tabId={process.name}>
            <Logs>
              {processLogs
                .filter((item) => item.name === process.name)
                .reverse()
                .map((item, i) => {

                  if (this.isJsonObject(item)) {
                    return(

                        <ReactJson src={JSON.parse(item.result)} theme="monokai" sortKeys={true} collapsed={1} />

                    );
                  }
                  return (

                  );
                })
              }
            </Logs>
            {process.name === "embark" &&
              <AsyncTypeahead
                autoFocus={true}
                emptyLabel={false}
                labelKey="value"
                multiple={false}
                maxResults={10}
                isLoading={this.state.isLoading}
                onInputChange={(text) => this.handleChange(text)}
                onChange={(text) => {
                  if (text && text[0]) {
                    this.handleChange(text[0].value);
                  }
                }}
                ref={(typeahead) => this.typeahead = typeahead}
                searchText={false}
                onKeyDown={(e) => {
                  if (e.keyCode === 13) {
                    this.handleChange(e.target.value, () => {
                      this.handleSubmit(e);
                    });
                  }
                }}
                onSearch={(value) => {
                  this.props.postCommandSuggestions(value);
                }}
                filterBy={['value', 'description']}
                maxHeight="200px"
                placeholder="Type a command (e.g help)"
                options={this.props.commandSuggestions}
                renderMenuItemChildren={(option) => (

                    {option.value}

                      {option.command_type} - {option.description}

                )}
              />
            }

          </TabPane>
        ))}
      </TabContent>
    );
  }

  render() {
    return (
      <Row>
        <Col>
          {this.renderNav()}
          {this.renderTabs()}
        </Col>
      </Row>
    );
  }
}

Console.propTypes = {
  postCommand: PropTypes.func,
  postCommandSuggestions: PropTypes.func,
  isEmbark: PropTypes.func,
  processes: PropTypes.arrayOf(PropTypes.object).isRequired,
  commandSuggestions: PropTypes.arrayOf(PropTypes.object),
  processLogs: PropTypes.arrayOf(PropTypes.object).isRequired,
  updateTab: PropTypes.func
};

export default Console;
<|endoftext|>