<commit_before>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var linestring = require('turf-linestring');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of points with z values and an array of
 * value breaks and generates filled contour isobands. These are commonly
 * used to create elevation maps, but can be used for general data
 * interpolation as well.
 *
 * @module turf/isobands
 * @param {FeatureCollection} points
 * @param {string} z - a property name from which z values will be pulled
 * @param {number} resolution - resolution of the underlying grid
 * @param {Array<number>} breaks - where to draw contours
 * @returns {FeatureCollection} isolines
 * @example
 * var fs = require('fs')
 * var z = 'elevation'
 * var resolution = 15
 * var breaks = [.1, 22, 45, 55, 65, 85,  95, 105, 120, 180]
 * var points = JSON.parse(fs.readFileSync('/path/to/points.geojson'))
 * var isobanded = turf.isobands(points, z, resolution, breaks)
 * console.log(isobanded)
 */
module.exports = function(points, z, resolution, breaks){
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt){
    tinResult.features.forEach(function(triangle){
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties){
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++){
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint){
      if(verticalPoint.properties){
        xFlat.push(verticalPoint.properties[z]);
      } else{
        xFlat.push(0);
      }
    })
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++){
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num){
    if(num === 0){
      return .01;
    }
    else{
      return num;
    }
  })
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec;
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c){
    if(c.length > 2){
      var polyCoordinates = [];
      c.forEach(function(coord){
        polyCoordinates.push([coord.x, coord.y]);
      });
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;

      fc.features.push(poly);
    }
  });

  return fc;
}

function addEdges(points, z, resolution){
  var extentBBox = extent(points),
    squareBBox,
    sizeResult;

  if (typeof extentBBox === 'Error') {
    return extentBBox;
  }

  squareBBox = square(extentBBox);

  if (typeof squareBBox === 'Error') {
    return squareBBox;
  }

  sizeBBox = size(squareBBox, 0.35)

  if (typeof sizeBBox === 'Error') {
    return sizeBBox;
  }

  var edgeDistance = sizeBBox[2] - sizeBBox[0]
  var extendDistance = edgeDistance / resolution

  var xmin = sizeBBox[0]
  var ymin = sizeBBox[1]
  var xmax = sizeBBox[2]
  var ymax = sizeBBox[3]

  //left
  var left = [[xmin, ymin],[xmin, ymax]]
  for(var i = 0; i<=resolution; i++){
    var pt = point(xmin, ymin + (extendDistance * i))
    pt.properties = {}
    pt.properties[z] = -100
    points.features.push(pt)
  }

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]]
  for(var i = 0; i<=resolution; i++){
    var pt = point(xmin + (extendDistance * i), ymin)
    pt.properties = {}
    pt.properties[z] = -100
    points.features.push(pt)
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]]
  for(var i = 0; i<=resolution; i++){
    var pt = point(xmax, ymin + (extendDistance * i))
    pt.properties = {}
    pt.properties[z] = -100
    points.features.push(pt)
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]]
  for(var i = 0; i<=resolution; i++){
    var pt = point(xmin + (extendDistance * i), ymax)
    pt.properties = {}
    pt.properties[z] = -100
    points.features.push(pt)
  }

  return points
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<commit_msg>Fix example, fix geojson output. Fixes #4. Fixes #3<commit_after>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var linestring = require('turf-linestring');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of points with z values and an array of
 * value breaks and generates filled contour isobands. These are commonly
 * used to create elevation maps, but can be used for general data
 * interpolation as well.
 *
 * @module turf/isobands
 * @param {FeatureCollection} points
 * @param {string} z - a property name from which z values will be pulled
 * @param {number} resolution - resolution of the underlying grid
 * @param {Array<number>} breaks - where to draw contours
 * @returns {FeatureCollection} isolines
 * @example
 * // create random points with random
 * // z-values in their properties
 * var points = turf.random('point', 100, {
 *   bbox: [0, 30, 20, 50]
 * });
 * for (var i = 0; i < points.features.length; i++) {
 *   points.features[i].properties.z = Math.random() * 10;
 * }
 * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * var isolined = turf.isobands(points, 'z', 15, breaks);
 * //=isolined
 */
module.exports = function(points, z, resolution, breaks){
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt){
    tinResult.features.forEach(function(triangle){
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties){
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++){
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint){
      if(verticalPoint.properties){
        xFlat.push(verticalPoint.properties[z]);
      } else{
        xFlat.push(0);
      }
    });
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++){
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num) {
    if(num === 0){
      return 0.01;
    }
    else{
      return num;
    }
  });
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec();
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c){
    if(c.length > 2){
      var polyCoordinates = [];
      c.forEach(function(coord){
        polyCoordinates.push([coord.x, coord.y]);
      });
      polyCoordinates.push([c[0].x, c[0].y]);
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;
      fc.features.push(poly);
    }
  });

  return fc;
};

function addEdges(points, z, resolution){
  var extentBBox = extent(points),
    sizeResult;

  var squareBBox = square(extentBBox);
  var sizeBBox = size(squareBBox, 0.35);

  var edgeDistance = sizeBBox[2] - sizeBBox[0];
  var extendDistance = edgeDistance / resolution;

  var xmin = sizeBBox[0];
  var ymin = sizeBBox[1];
  var xmax = sizeBBox[2];
  var ymax = sizeBBox[3];

  //left
  var left = [[xmin, ymin],[xmin, ymax]];
  for(var i = 0; i<=resolution; i++){
    var pt = point(xmin, ymin + (extendDistance * i));
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  var i, pt;

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]];
  for(i = 0; i<=resolution; i++){
    pt = point(xmin + (extendDistance * i), ymin);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point(xmax, ymin + (extendDistance * i));
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point(xmin + (extendDistance * i), ymax);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  return points;
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<|endoftext|>


<commit_before>/*

  isType : 'object', 'array', 'function, 'string', 'number', 'boolean'
  hasLength : true, false, number
  minLength : number > 0
  maxLength : number > 0
  isExactly: Object, Array, Function, String, Number, Boolean
  isNull : true, false
  isUndefined : true, false
  isTruthy : true, false
  isFalsy: true, false
  hasAnyOf: [], checks if key is present if test item is an object
  hasNoneOf: [], checks if key is present if test item is an object
  hasNoneOf: [], checks if key is present if test item is an object
  hasNested: { path (string) : expects (obj) }
  cb: () => {} expects if cb returns true

*/

var expectType = function(input, isType, debug) {

  if (isType !== 'object' && isType !== 'array' && isType !== 'function' && isType !== 'string' && isType !== 'number' && isType !== 'boolean') {
    if (debug) {
      console.log('invalid type', isType, 'passed to isType');
    }
    return false;
  }

  if (isType === 'object' && (typeof(input) !== 'object' || Array.isArray(input))) {
    return false;
  }

  if (isType === 'array' && !Array.isArray(input)) {
    return false;
  }

  if (isType === 'function' && typeof(input) !== 'function') {
    return false;
  }

  if (isType === 'string' && typeof(input) !== 'string') {
    return false;
  }

  if (isType === 'number' && typeof(input) !== 'number') {
    return false;
  }

  if (isType === 'boolean' && typeof(input) !== 'boolean') {
    return false;
  }

  return true;

};

var expectLength = function(input, hasLength, minLength, maxLength, debug) {

  if (hasLength !== undefined) {
    if (typeof(hasLength) === 'number' && input.length !== hasLength) {
      return false;
    } else if (typeof(hasLength) === 'boolean' && input.length > 1 !== hasLength) {
      return false;
    }
  }

  if (minLength !== undefined && input.length < minLength) {
    return false;
  }

  if (maxLength !== undefined && input.length > maxLength) {
    return false;
  }

  return true;

};

var expectExactly = function(input, isExactly, debug) {

  if (input === isExactly) {
    return true;
  } else {
    return false;
  }

};

var expectNull = function(input, isNull, debug) {

  if (isNull && input !== null) {
    return false;
  }

  if (!isNull && input === null) {
    return false;
  }

  return true;

};

var expectUndefined = function(input, isUndefined, debug) {

  if (isUndefined && input !== undefined) {
    return false;
  }

  if (!isUndefined && input === undefined) {
    return false;
  }

  return true;

};

var expectTruthy = function(input, isTruthy, debug) {

  if (isTruthy && !input) {
    return false;
  }

  if (!isTruthy && input) {
    return false;
  }

  return true;

};

var expectFalsy = function(input, isFalsy, debug) {

  if (isFalsy && input) {
    return false;
  }

  if (!isFalsy && !input) {
    return false;
  }

  return true;

};

var expectAnyOf = function(input, hasAnyOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    input.forEach(function(item) {
      if (result) {
        if (hasAnyOf.indexOf(item) < 0) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    keys.forEach(function(key) {
      if (result) {
        if (hasAnyOf.indexOf(key) < 0) {
          result = false;
        }
      }
    });

  } else {
    if (hasAnyOf.indexOf(input) < 0) {
      return false;
    }
  }

  return result;

};

var expectNoneOf = function(input, hasNoneOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    input.forEach(function(item) {
      if (result) {
        if (hasNoneOf.indexOf(item) > -1) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    keys.forEach(function(key) {
      if (result) {
        if (hasNoneOf.indexOf(key) > -1) {
          result = false;
        }
      }
    });

  } else {
    if (hasNoneOf.indexOf(input) > -1) {
      return false;
    }
  }

  return result;

};

var expectAllOf = function(input, hasAllOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    hasAllOf.forEach(function(item) {
      if (result) {
        if (input.indexOf(item) < 0) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    hasAllOf.forEach(function(item) {
      if (result) {
        if (keys.indexOf(item) < 0) {
          result = false;
        }
      }
    });

  } else {
    if (hasAllOf.indexOf(input) < 0) {
      return false;
    }
  }

  return result;

};

var checkNested = function(input, hasNested, debug) {

  var result = true;
  var keys = Object.keys(hasNested);

  keys.forEach(function(key) {
    if (result) {

      var path = filterPath(input, key, debug);

      var expectedPathResult = expectPath(input, path);
      if (expectedPathResult === false) {
        result = false;
      } if (!expectInputs(expectedPathResult, hasNested[key], debug)) {
        result =  false;
      }

    }
  });

  return result;

};

var filterPath = function(base, path, debug) {

  var filteredPath;
  var components = path.split('.');
  var componentsString = components[0];

  components.forEach(function(component, index) {
    if (filteredPath === undefined) {
      if (eval(componentsString) === base) {
        var componentsForFilteredString = components.slice(index + 1);
        filteredPath = componentsForFilteredString.join('.');
      } else if (components[index + 1] !== undefined) {
        componentsString = componentsString + '.' + components[index + 1];
      }
    }
  });

  return filteredPath;

};

var expectPath = function(base, path, debug) {

  var result = true;
  var current = base;
  var components = path.split('.');

  components.forEach(function(component, index) {
    if (result) {

      if ((typeof(current) !== 'object') || (!current.hasOwnProperty(component))) {
        result = false;
      }

      current = current[component];
    }
  });

  if (result === false) {
    return result;
  } else {
    return current;
  }

};

var expectInputs = function(input, expects, debug) {

  if (expects.isType !== undefined && !expectType(input, expects.isType, debug)) {
    if (debug) {
      console.log('type check failed');
    }
    return false;
  }

  if ((expects.hasLength !== undefined || expects.minLength !== undefined || expects.maxLength !== undefined) && !expectLength(input, expects.hasLength, expects.minLength, expects.maxLength, debug)) {
    if (debug) {
      console.log('length check failed');
    }
    return false;
  }

  if (expects.isExactly !== undefined && !expectExactly(input, expects.isExactly, debug)) {
    if (debug) {
      console.log('isExactly check failed');
    }
    return false;
  }

  if (expects.isNull !== undefined && !expectNull(input, expects.isNull, debug)) {
    if (debug) {
      console.log('isNull check failed');
    }
    return false;
  }

  if (expects.isUndefined !== undefined && !expectUndefined(input, expects.isUndefined, debug)) {
    if (debug) {
      console.log('isUndefined check failed');
    }
    return false;
  }

  if (expects.isTruthy !== undefined && !expectTruthy(input, expects.isTruthy, debug)) {
    if (debug) {
      console.log('isTruthy check failed');
    }
    return false;
  }

  if (expects.isFalsy !== undefined && !expectFalsy(input, expects.isFalsy, debug)) {
    if (debug) {
      console.log('isFalsy check failed');
    }
    return false;
  }

  if (expects.hasAnyOf !== undefined && !expectAnyOf(input, expects.hasAnyOf, debug)) {
    if (debug) {
      console.log('hasAnyOf check failed');
    }
    return false;
  }

  if (expects.hasNoneOf !== undefined && !expectNoneOf(input, expects.hasNoneOf, debug)) {
    if (debug) {
      console.log('hasNoneOf check failed');
    }
    return false;
  }

  if (expects.hasAllOf !== undefined && !expectAllOf(input, expects.hasAllOf, debug)) {
    if (debug) {
      console.log('hasAllOf check failed');
    }
    return false;
  }

  if (expects.cb !== undefined && !expects.cb(input, debug)) {
    if (debug) {
      console.log('callback failed');
    }
    return false;
  }

  if (expects.hasNested !== undefined && !checkNested(input, expects.hasNested, debug)) {
    if (debug) {
      console.log('check of nested object failed');
    }
    return false;
  }

  return true;

};

var testItem = {
  thing: {
    nextThing: {
      nextNextThing: {
        a: [1, 2],
      },
      theOtherOne: {
        a: 'hello',
      }
    },
  },
};

console.log(expectInputs(testItem, {
    isType: 'object',
    hasNested: {
      'testItem.thing.nextThing.nextNextThing.a': {
        isType: 'array',
        hasLength: 2,
        hasAllOf: [2, 1],
        isExactly: testItem.thing.nextThing.nextNextThing.a,
      },
      'testItem.thing.nextThing.theOtherOne.a': {
        isType: 'string',
        hasAnyOf: ['hello'],
        hasNoneOf: ['bad'],
        hasAllOf: ['hello'],
        isExactly: 'hello',
      },
    },
  },
  true
));
<commit_msg>checks validity of lenght checks<commit_after>/*

  isType : 'object', 'array', 'function, 'string', 'number', 'boolean'
  hasLength : true, false, number
  minLength : number > 0
  maxLength : number > 0
  isExactly: Object, Array, Function, String, Number, Boolean
  isNull : true, false
  isUndefined : true, false
  isTruthy : true, false
  isFalsy: true, false
  hasAnyOf: [], checks if key is present if test item is an object
  hasNoneOf: [], checks if key is present if test item is an object
  hasNoneOf: [], checks if key is present if test item is an object
  hasNested: { path (string) : expects (obj) }
  cb: () => {} expects if cb returns true

*/

var expectType = function(input, isType, debug) {

  if (isType !== 'object' && isType !== 'array' && isType !== 'function' && isType !== 'string' && isType !== 'number' && isType !== 'boolean') {
    if (debug) {
      console.log('invalid option', isType, 'passed to isType');
    }
    return false;
  }

  if (isType === 'object' && (typeof(input) !== 'object' || Array.isArray(input))) {
    return false;
  }

  if (isType === 'array' && !Array.isArray(input)) {
    return false;
  }

  if (isType === 'function' && typeof(input) !== 'function') {
    return false;
  }

  if (isType === 'string' && typeof(input) !== 'string') {
    return false;
  }

  if (isType === 'number' && typeof(input) !== 'number') {
    return false;
  }

  if (isType === 'boolean' && typeof(input) !== 'boolean') {
    return false;
  }

  return true;

};

var expectLength = function(input, hasLength, minLength, maxLength, debug) {

  if (hasLength !== undefined) {

    if (typeof(hasLength) !== 'boolean' && (typeof(hasLength) !== 'number' || (typeof(hasLength) === 'number' && hasLength < 0))) {
      if (debug) {
        console.log('invalid option', hasLength, 'passed to hasLength');
      }
      return false;
    }

    if (typeof(hasLength) === 'number' && input.length !== hasLength) {
      return false;
    } else if (typeof(hasLength) === 'boolean' && input.length > 1 !== hasLength) {
      return false;
    }
  }

  if (minLength !== undefined) {

    if (typeof(minLength) !== 'number' || (typeof(minLength) === 'number' && minLength < 0)) {
      if (debug) {
        console.log('invalid option', minLength, 'passed to minLength');
      }
      return false;
    }

    if (input.length < minLength) {
      return false;
    }

  }

  if (maxLength !== undefined) {

    if (typeof(maxLength) !== 'number' || (typeof(maxLength) === 'number' && maxLength < 0)) {
      if (debug) {
        console.log('invalid option', maxLength, 'passed to maxLength');
      }
      return false;
    }

    if (input.length > maxLength) {
      return false;
    }

  }

  return true;

};

var expectExactly = function(input, isExactly, debug) {

  if (input === isExactly) {
    return true;
  } else {
    return false;
  }

};

var expectNull = function(input, isNull, debug) {

  if (isNull && input !== null) {
    return false;
  }

  if (!isNull && input === null) {
    return false;
  }

  return true;

};

var expectUndefined = function(input, isUndefined, debug) {

  if (isUndefined && input !== undefined) {
    return false;
  }

  if (!isUndefined && input === undefined) {
    return false;
  }

  return true;

};

var expectTruthy = function(input, isTruthy, debug) {

  if (isTruthy && !input) {
    return false;
  }

  if (!isTruthy && input) {
    return false;
  }

  return true;

};

var expectFalsy = function(input, isFalsy, debug) {

  if (isFalsy && input) {
    return false;
  }

  if (!isFalsy && !input) {
    return false;
  }

  return true;

};

var expectAnyOf = function(input, hasAnyOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    input.forEach(function(item) {
      if (result) {
        if (hasAnyOf.indexOf(item) < 0) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    keys.forEach(function(key) {
      if (result) {
        if (hasAnyOf.indexOf(key) < 0) {
          result = false;
        }
      }
    });

  } else {
    if (hasAnyOf.indexOf(input) < 0) {
      return false;
    }
  }

  return result;

};

var expectNoneOf = function(input, hasNoneOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    input.forEach(function(item) {
      if (result) {
        if (hasNoneOf.indexOf(item) > -1) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    keys.forEach(function(key) {
      if (result) {
        if (hasNoneOf.indexOf(key) > -1) {
          result = false;
        }
      }
    });

  } else {
    if (hasNoneOf.indexOf(input) > -1) {
      return false;
    }
  }

  return result;

};

var expectAllOf = function(input, hasAllOf, debug) {

  var result = true;

  if (Array.isArray(input)) {
    hasAllOf.forEach(function(item) {
      if (result) {
        if (input.indexOf(item) < 0) {
          result = false;
        }
      }
    });
  } else if (typeof(input) === 'object' && !Array.isArray(input)) {

    var keys = Object.keys(input);

    hasAllOf.forEach(function(item) {
      if (result) {
        if (keys.indexOf(item) < 0) {
          result = false;
        }
      }
    });

  } else {
    if (hasAllOf.indexOf(input) < 0) {
      return false;
    }
  }

  return result;

};

var checkNested = function(input, hasNested, debug) {

  var result = true;
  var keys = Object.keys(hasNested);

  keys.forEach(function(key) {
    if (result) {

      var path = filterPath(input, key, debug);

      var expectedPathResult = expectPath(input, path);
      if (expectedPathResult === false) {
        result = false;
      } if (!expectInputs(expectedPathResult, hasNested[key], debug)) {
        result =  false;
      }

    }
  });

  return result;

};

var filterPath = function(base, path, debug) {

  var filteredPath;
  var components = path.split('.');
  var componentsString = components[0];

  components.forEach(function(component, index) {
    if (filteredPath === undefined) {
      if (eval(componentsString) === base) {
        var componentsForFilteredString = components.slice(index + 1);
        filteredPath = componentsForFilteredString.join('.');
      } else if (components[index + 1] !== undefined) {
        componentsString = componentsString + '.' + components[index + 1];
      }
    }
  });

  return filteredPath;

};

var expectPath = function(base, path, debug) {

  var result = true;
  var current = base;
  var components = path.split('.');

  components.forEach(function(component, index) {
    if (result) {

      if ((typeof(current) !== 'object') || (!current.hasOwnProperty(component))) {
        result = false;
      }

      current = current[component];
    }
  });

  if (result === false) {
    return result;
  } else {
    return current;
  }

};

var expectInputs = function(input, expects, debug) {

  if (expects.isType !== undefined && !expectType(input, expects.isType, debug)) {
    if (debug) {
      console.log('type check failed');
    }
    return false;
  }

  if ((expects.hasLength !== undefined || expects.minLength !== undefined || expects.maxLength !== undefined) && !expectLength(input, expects.hasLength, expects.minLength, expects.maxLength, debug)) {
    if (debug) {
      console.log('length check failed');
    }
    return false;
  }

  if (expects.isExactly !== undefined && !expectExactly(input, expects.isExactly, debug)) {
    if (debug) {
      console.log('isExactly check failed');
    }
    return false;
  }

  if (expects.isNull !== undefined && !expectNull(input, expects.isNull, debug)) {
    if (debug) {
      console.log('isNull check failed');
    }
    return false;
  }

  if (expects.isUndefined !== undefined && !expectUndefined(input, expects.isUndefined, debug)) {
    if (debug) {
      console.log('isUndefined check failed');
    }
    return false;
  }

  if (expects.isTruthy !== undefined && !expectTruthy(input, expects.isTruthy, debug)) {
    if (debug) {
      console.log('isTruthy check failed');
    }
    return false;
  }

  if (expects.isFalsy !== undefined && !expectFalsy(input, expects.isFalsy, debug)) {
    if (debug) {
      console.log('isFalsy check failed');
    }
    return false;
  }

  if (expects.hasAnyOf !== undefined && !expectAnyOf(input, expects.hasAnyOf, debug)) {
    if (debug) {
      console.log('hasAnyOf check failed');
    }
    return false;
  }

  if (expects.hasNoneOf !== undefined && !expectNoneOf(input, expects.hasNoneOf, debug)) {
    if (debug) {
      console.log('hasNoneOf check failed');
    }
    return false;
  }

  if (expects.hasAllOf !== undefined && !expectAllOf(input, expects.hasAllOf, debug)) {
    if (debug) {
      console.log('hasAllOf check failed');
    }
    return false;
  }

  if (expects.cb !== undefined && !expects.cb(input, debug)) {
    if (debug) {
      console.log('callback failed');
    }
    return false;
  }

  if (expects.hasNested !== undefined && !checkNested(input, expects.hasNested, debug)) {
    if (debug) {
      console.log('check of nested object failed');
    }
    return false;
  }

  return true;

};

var testItem = {
  thing: {
    nextThing: {
      nextNextThing: {
        a: [1, 2],
      },
      theOtherOne: {
        a: 'hello',
      }
    },
  },
};

console.log(expectInputs(testItem, {
    isType: 'object',
    hasNested: {
      'testItem.thing.nextThing.nextNextThing.a': {
        isType: 'array',
        hasLength: 2,
        hasAllOf: [2, 1],
        maxLength: -1,
        isExactly: testItem.thing.nextThing.nextNextThing.a,
      },
      'testItem.thing.nextThing.theOtherOne.a': {
        isType: 'string',
        hasAnyOf: ['hello'],
        hasNoneOf: ['bad'],
        hasAllOf: ['hello'],
        isExactly: 'hello',
      },
    },
  },
  true
));
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy,
	User = require('mongoose').model('User');

module.exports = function() {
	// Use local strategy
	passport.use(new LocalStrategy({
			usernameField: 'username',
			passwordField: 'password'
		},
		function(username, password, done) {
			User.findOne({
				username: username
			}, function(err, user) {
				if (err) {
					return done(err);
				}
				if (!user) {
					return done(null, false, {
						message: 'Unknown user'
					});
				}
				if (!user.authenticate(password)) {
					return done(null, false, {
						message: 'Invalid password'
					});
				}

				return done(null, user);
			});
		}
	));
};
<commit_msg>Add some abstraction to local strategy login error<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy,
	User = require('mongoose').model('User');

module.exports = function() {
	// Use local strategy
	passport.use(new LocalStrategy({
			usernameField: 'username',
			passwordField: 'password'
		},
		function(username, password, done) {
			User.findOne({
				username: username
			}, function(err, user) {
				if (err) {
					return done(err);
				}
				if (!user || !user.authenticate(password)) {
					return done(null, false, {
						message: 'Invalid username or password'
					});
				}

				return done(null, user);
			});
		}
	));
};
<|endoftext|>


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

    angular.module(appName)
        .factory('languagesModel', function () {
            return [];
        })
})();<commit_msg>Fixed small codestyle issue in languagesModel.js<commit_after>(function () {
    'use strict';

	angular.module(appName)
		.factory('languagesModel', function() {
			return [];
		});
})();<|endoftext|>


<commit_before>// wrap all code in an if statement using global var to check if script has been run before.

var BTTC_ACTIVE_GLOBAL;
if ( ! BTTC_ACTIVE_GLOBAL ) {
// first set active to true
BTTC_ACTIVE_GLOBAL = true;

/**
* Variables
*/
var iframeOpen,
	mouseDown = false;

/**
* Functions and callbacks
*/

var initDrag = function(e) {
	startX = e.clientX;
	document.documentElement.addEventListener('mousemove', doDrag, false);
	document.documentElement.addEventListener('mouseup', stopDrag, false);
}

var stopDrag = function(e) {
	console.log('Drag over, phew!');
	document.documentElement.removeEventListener('mousemove', doDrag, false);
	document.documentElement.removeEventListener('mouseup', stopDrag, false);
}

var doDrag = function(e) {
	console.log(startX);
	console.log(e.clientX);
}

var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL = "https://news.ycombinator.com/" + commentPath;
		toggleComments( frameURL );
console.log(frameURL);
	}
}

var toggleComments = function( URL ) {
	var commentFrame,
		frameset,
		frameHasSrc;
	commentDiv = document.querySelector( "#bttc-comment-div" );
	commentFrame = document.querySelector( "#bttc-comment-frame" );
    body = document.querySelector( "body" );
	frameHasSrc = commentFrame.getAttribute("src");

	// set frame src if none is present
	if ( ! frameHasSrc ) {
		commentFrame.setAttribute( "src", URL );
	}

	// open/close iframe
	if ( ! iframeOpen ) {
        commentDiv.style.width = "50%";
        commentDiv.style.display = "block";
        body.style.opacity = 0.4;
	} else {
        commentDiv.style.width = "0";
        commentDiv.style.display = "none";
        body.style.opacity = 1;
	}

	// toggle iframeOpen flag
	iframeOpen = Math.abs( iframeOpen - 1 );

}

var drawIframe = function() {
    var pageURL,
		pageFrame,
        iframe,
		iframeContainer,
		dragBar,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
    iframeContainer = document.createElement( "div" );
    dragBar = document.createElement("div");
	iframe = document.createElement( "iframe" );
    iframeContainer.setAttribute("id", "bttc-comment-div");
    dragBar.setAttribute("id", "bttc-dragbar");
    iframe.setAttribute("id", "bttc-comment-frame");

    iframeContainer.appendChild( dragBar );
    iframeContainer.appendChild( iframe );
	html.insertBefore( iframeContainer, body );

	// add listeners for comment resize
	dragBar.addEventListener('mousedown', initDrag, false);
}

/**
* Events
*/
iframeOpen = 0;
drawIframe();
window.addEventListener("message", receiveMessage, false);
}
<commit_msg>Removed console.log from recieveMessage.<commit_after>// wrap all code in an if statement using global var to check if script has been run before.

var BTTC_ACTIVE_GLOBAL;
if ( ! BTTC_ACTIVE_GLOBAL ) {
// first set active to true
BTTC_ACTIVE_GLOBAL = true;

/**
* Variables
*/
var iframeOpen,
	mouseDown = false;

/**
* Functions and callbacks
*/

var initDrag = function(e) {
	startX = e.clientX;
	document.documentElement.addEventListener('mousemove', doDrag, false);
	document.documentElement.addEventListener('mouseup', stopDrag, false);
}

var stopDrag = function(e) {
	console.log('Drag over, phew!');
	document.documentElement.removeEventListener('mousemove', doDrag, false);
	document.documentElement.removeEventListener('mouseup', stopDrag, false);
}

var doDrag = function(e) {
	console.log(startX);
	console.log(e.clientX);
}

var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL = "https://news.ycombinator.com/" + commentPath;
		toggleComments( frameURL );
	}
}

var toggleComments = function( URL ) {
	var commentFrame,
		frameset,
		frameHasSrc;
	commentDiv = document.querySelector( "#bttc-comment-div" );
	commentFrame = document.querySelector( "#bttc-comment-frame" );
    body = document.querySelector( "body" );
	frameHasSrc = commentFrame.getAttribute("src");

	// set frame src if none is present
	if ( ! frameHasSrc ) {
		commentFrame.setAttribute( "src", URL );
	}

	// open/close iframe
	if ( ! iframeOpen ) {
        commentDiv.style.width = "50%";
        commentDiv.style.display = "block";
        body.style.opacity = 0.4;
	} else {
        commentDiv.style.width = "0";
        commentDiv.style.display = "none";
        body.style.opacity = 1;
	}

	// toggle iframeOpen flag
	iframeOpen = Math.abs( iframeOpen - 1 );

}

var drawIframe = function() {
    var pageURL,
		pageFrame,
        iframe,
		iframeContainer,
		dragBar,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
    iframeContainer = document.createElement( "div" );
    dragBar = document.createElement("div");
	iframe = document.createElement( "iframe" );
    iframeContainer.setAttribute("id", "bttc-comment-div");
    dragBar.setAttribute("id", "bttc-dragbar");
    iframe.setAttribute("id", "bttc-comment-frame");

    iframeContainer.appendChild( dragBar );
    iframeContainer.appendChild( iframe );
	html.insertBefore( iframeContainer, body );

	// add listeners for comment resize
	dragBar.addEventListener('mousedown', initDrag, false);
}

/**
* Events
*/
iframeOpen = 0;
drawIframe();
window.addEventListener("message", receiveMessage, false);
}
<|endoftext|>


<commit_before>// Working CASES:
// CASE_1, CASE_3, CASE_$, CASE_5

// Define main element which provides the string used as parameter of the Scheduler function
var class_name = 'date-5'; // change this to test other CASE
var date = document.getElementsByClassName(class_name);
var date_string = date[0].innerHTML;
var scheduledDateTime_CASE = Scheduler(date_string);
console.log(scheduledDateTime_CASE);

/** Process the received schedule like string into organized rows.
 * Return a JSON string.
 */
function Scheduler(string) {
  var scheduler = [];
  var periods = [];
  var allWeekDays = getAllWeekDays();
  var scheduleData = [];
  var scheduleDays = [];
  var scheduleHours = '';

  var schedule = [];

  if(string.length) {
    var strDate = string;
    var dateParts = strDate.split(",");

    var scheduledHours = getScheduledHours(dateParts);

    for(var i=0;i<dateParts.length;i++) {
      schedule = dateParts[i].split(/:(.+)/);
      scheduleDays = schedule[0];
      scheduleHours = scheduledHours[i];
      if(schedule[1]) {
        // If no scheduleHours are found in the current string, get the hours for the next found
        scheduleHours = schedule[1];
      }
      // Push initial arrays
      if(scheduleDays.match("-")) {
        // Process range of days given
        var givenWeekDays = [];

        for(j=0;j<scheduleDays.trim().split("-").length;j++) {
          givenWeekDays = scheduleDays.toLowerCase().trim().split("-");
        }

        var scheduledWeekDays = getAllScheduledWeekDays(allWeekDays, givenWeekDays);

        var openDay = '';
        var closeDay = '';
        var openHour = '';
        var closeHour = '';
        for(k=0;k<scheduledWeekDays.length;k++) {
          openDay = capitalize(scheduledWeekDays[k]);
          closeDay = capitalize(scheduledWeekDays[k]);
          if(scheduleHours) {
            openHour = scheduleHours.toLowerCase().trim().split("-")[0];
            closeHour = scheduleHours.toLowerCase().trim().split("-")[1];
          }

          scheduleData.push(
            {
              // 1. Open Day
              "openDay": openDay,
              // 2. Close Day
              "closeDay": closeDay,
              // 3. Open Hour
              "openHour": openHour,
              // 4. Close Hour
              "closeHour": closeHour
            }
          );
        }
      } else {
        // Process single day given
        openDay = scheduleDays.trim();
        closeDay = scheduleDays.trim();
        if(scheduleHours) {
          openHour = scheduleHours.trim().split("-")[0];
          closeHour = scheduleHours.trim().split("-")[1];
        }

        scheduleData.push(
          {
            // 1. Open Day
            "openDay": openDay,
            // 2. Close Day
            "closeDay": closeDay,
            // 3. Open Hour
            "openHour": openHour,
            // 4. Close Hour
            "closeHour": closeHour
          }
        );
      }
    }

    periods.push('periods', scheduleData);
    scheduler.push('regularHours', periods);
  }
  return JSON.stringify(scheduler);
}

/** Capitalize string
 */
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

/** Get All days of the week in an array
 */
function getAllWeekDays() {
  var weekDays = new Array(7);
  weekDays[0] = "monday";
  weekDays[1] = "tuesday";
  weekDays[2] = "wednesday";
  weekDays[3] = "thursday";
  weekDays[4] = "friday";
  weekDays[5] = "saturday";
  weekDays[6] = "sunday";
  return weekDays;
}

/** Get Day Full Name
 */
function getDayName(name) {
  switch(name) {
    case 'mon':
      name = 'monday';
      break;
    case 'tue':
      name = 'tuesday';
      break;
    case 'wed':
      name = 'wednesday';
      break;
    case 'thu':
      name = 'thursday';
      break;
    case 'fri':
      name = 'friday';
      break;
    case 'sat':
      name = 'saturday';
      break;
    case 'sun':
      name = 'sunday';
      break;
    default:
      break
  }
  return name;
}

/** Get All Week Days from schedule
 */
function getAllScheduledWeekDays(allWeekDays, givenWeekDays) {
  // Define empty array for the returned array
  var scheduledWeekDays = new Array();
  // Define the indexes for the start and end of days range
  var firstIndex = '';
  var lastIndex = '';

  // Establish the first and last indexes from the array of full week days
  for(k=0;k<allWeekDays.length;k++) {
    for(l=0;l<givenWeekDays.length;l++) {
      // Apply trim to remove whitespaces from the given week days array, as we need perfect match
      if(getDayName(givenWeekDays[0].trim()) == allWeekDays[k] && firstIndex == '') {
        firstIndex = k;
      }
      // Apply trim to remove whitespaces from the given week days array, as we need perfect match
      if(getDayName(givenWeekDays[1].trim()) == allWeekDays[k] && lastIndex == '') {
        lastIndex = k;
      }
    }
  }
  // Push the days from range in the return array
  for(m=0;m<allWeekDays.length;m++) {
    if(m >= firstIndex && m <= lastIndex) {
      scheduledWeekDays.push(allWeekDays[m]);
    }
  }

  return scheduledWeekDays;
}

/** Get Scheduled Hours for all array items
 */
function getScheduledHours(dateParts) {
  var hours = [];
  var hour = '';
  for(var i=0;i<dateParts.length;i++) {
    schedule = dateParts[i].split(/:(.+)/);
    if(schedule[1]) {
      hour = schedule[1];
    }
    hours.push(i, hour);
  }

  hours.forEach(function(i, v) {
    if(v >= 0 && i.length && i != '') {
      var i = i;
      hours.forEach(function(j,k) {
        if(k >= 0 && j == '' && v > k) {
          hours[k] = i;
        } else {
          return false;
        }
      });
    }
  });

  return hours;
}<commit_msg>DateTime Scheduler - Add trim() to hours.<commit_after>// Working CASES:
// CASE_1, CASE_3, CASE_$, CASE_5

// Define main element which provides the string used as parameter of the Scheduler function
var class_name = 'date-5'; // change this to test other CASE
var date = document.getElementsByClassName(class_name);
var date_string = date[0].innerHTML;
var scheduledDateTime_CASE = Scheduler(date_string);
console.log(scheduledDateTime_CASE);

/** Process the received schedule like string into organized rows.
 * Return a JSON string.
 */
function Scheduler(string) {
  var scheduler = [];
  var periods = [];
  var allWeekDays = getAllWeekDays();
  var scheduleData = [];
  var scheduleDays = [];
  var scheduleHours = '';

  var schedule = [];

  if(string.length) {
    var strDate = string;
    var dateParts = strDate.split(",");

    var scheduledHours = getScheduledHours(dateParts);

    for(var i=0;i<dateParts.length;i++) {
      schedule = dateParts[i].split(/:(.+)/);
      scheduleDays = schedule[0];
      scheduleHours = scheduledHours[i];
      if(schedule[1]) {
        // If no scheduleHours are found in the current string, get the hours for the next found
        scheduleHours = schedule[1];
      }
      // Push initial arrays
      if(scheduleDays.match("-")) {
        // Process range of days given
        var givenWeekDays = [];

        for(j=0;j<scheduleDays.trim().split("-").length;j++) {
          givenWeekDays = scheduleDays.toLowerCase().trim().split("-");
        }

        var scheduledWeekDays = getAllScheduledWeekDays(allWeekDays, givenWeekDays);

        var openDay = '';
        var closeDay = '';
        var openHour = '';
        var closeHour = '';
        for(k=0;k<scheduledWeekDays.length;k++) {
          openDay = capitalize(scheduledWeekDays[k]);
          closeDay = capitalize(scheduledWeekDays[k]);
          if(scheduleHours) {
            openHour = scheduleHours.toLowerCase().trim().split("-")[0].trim();
            closeHour = scheduleHours.toLowerCase().trim().split("-")[1].trim();
          }

          scheduleData.push(
            {
              // 1. Open Day
              "openDay": openDay,
              // 2. Close Day
              "closeDay": closeDay,
              // 3. Open Hour
              "openHour": openHour,
              // 4. Close Hour
              "closeHour": closeHour
            }
          );
        }
      } else {
        // Process single day given
        openDay = scheduleDays.trim();
        closeDay = scheduleDays.trim();
        if(scheduleHours) {
          openHour = scheduleHours.trim().split("-")[0].trim();
          closeHour = scheduleHours.trim().split("-")[1].trim();
        }

        scheduleData.push(
          {
            // 1. Open Day
            "openDay": openDay,
            // 2. Close Day
            "closeDay": closeDay,
            // 3. Open Hour
            "openHour": openHour,
            // 4. Close Hour
            "closeHour": closeHour
          }
        );
      }
    }

    periods.push('periods', scheduleData);
    scheduler.push('regularHours', periods);
  }
  return JSON.stringify(scheduler);
}

/** Capitalize string
 */
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

/** Get All days of the week in an array
 */
function getAllWeekDays() {
  var weekDays = new Array(7);
  weekDays[0] = "monday";
  weekDays[1] = "tuesday";
  weekDays[2] = "wednesday";
  weekDays[3] = "thursday";
  weekDays[4] = "friday";
  weekDays[5] = "saturday";
  weekDays[6] = "sunday";
  return weekDays;
}

/** Get Day Full Name
 */
function getDayName(name) {
  switch(name) {
    case 'mon':
      name = 'monday';
      break;
    case 'tue':
      name = 'tuesday';
      break;
    case 'wed':
      name = 'wednesday';
      break;
    case 'thu':
      name = 'thursday';
      break;
    case 'fri':
      name = 'friday';
      break;
    case 'sat':
      name = 'saturday';
      break;
    case 'sun':
      name = 'sunday';
      break;
    default:
      break
  }
  return name;
}

/** Get All Week Days from schedule
 */
function getAllScheduledWeekDays(allWeekDays, givenWeekDays) {
  // Define empty array for the returned array
  var scheduledWeekDays = new Array();
  // Define the indexes for the start and end of days range
  var firstIndex = '';
  var lastIndex = '';

  // Establish the first and last indexes from the array of full week days
  for(k=0;k<allWeekDays.length;k++) {
    for(l=0;l<givenWeekDays.length;l++) {
      // Apply trim to remove whitespaces from the given week days array, as we need perfect match
      if(getDayName(givenWeekDays[0].trim()) == allWeekDays[k] && firstIndex == '') {
        firstIndex = k;
      }
      // Apply trim to remove whitespaces from the given week days array, as we need perfect match
      if(getDayName(givenWeekDays[1].trim()) == allWeekDays[k] && lastIndex == '') {
        lastIndex = k;
      }
    }
  }
  // Push the days from range in the return array
  for(m=0;m<allWeekDays.length;m++) {
    if(m >= firstIndex && m <= lastIndex) {
      scheduledWeekDays.push(allWeekDays[m]);
    }
  }

  return scheduledWeekDays;
}

/** Get Scheduled Hours for all array items
 */
function getScheduledHours(dateParts) {
  var hours = [];
  var hour = '';
  for(var i=0;i<dateParts.length;i++) {
    schedule = dateParts[i].split(/:(.+)/);
    if(schedule[1]) {
      hour = schedule[1];
    }
    hours.push(i, hour);
  }

  hours.forEach(function(i, v) {
    if(v >= 0 && i.length && i != '') {
      var i = i;
      hours.forEach(function(j,k) {
        if(k >= 0 && j == '' && v > k) {
          hours[k] = i;
        } else {
          return false;
        }
      });
    }
  });

  return hours;
}<|endoftext|>


<commit_before>import $ from 'jquery';

const loadSticky = () => {
  var stickyHeaders = (function() {

    var $window = $(window),
      $stickies;

    var load = function(stickies) {

      if (typeof stickies === "object" && stickies.length > 0) {
        $stickies = stickies.each(function() {
          var $thisSticky = $(this).wrap('
');
          $thisSticky
              .data('originalPosition', $thisSticky.offset().top)
              .data('originalHeight', $thisSticky.outerHeight())
                .parent()
                .height($thisSticky.outerHeight());
        });

        $window.off("scroll.stickies").on("scroll.stickies", function() {
    		  _whenScrolling();
        });
      }
    };

    var _whenScrolling = function() {

      $stickies.each(function(i) {

        var $thisSticky = $(this),
          $stickyPosition = $thisSticky.data('originalPosition');

        if ($stickyPosition <= $window.scrollTop()) {
          var $nextSticky = $stickies.eq(i + 1),
            $nextStickyPosition = $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');

          $thisSticky.addClass("fixed");

          if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {
            $thisSticky.addClass("absolute").css("top", $nextStickyPosition);
          }
        } else {
          var $prevSticky = $stickies.eq(i - 1);

          $thisSticky.removeClass("fixed");

          if ($prevSticky.length > 0 && $window.scrollTop() <= $thisSticky.data('originalPosition') - $thisSticky.data('originalHeight')) {
            $prevSticky.removeClass("absolute").removeAttr("style");
          }
        }
      });
    };

    return {
      load: load
    };
  })();

  $(function() {
    stickyHeaders.load($(".followMeBar"));
  });
};

export { loadSticky };
<commit_msg>account for masthead in sticky calc<commit_after>import $ from 'jquery';

const loadSticky = () => {
  var stickyHeaders = (function() {

    var $window = $(window),
      $stickies;

    var load = function(stickies) {

      if (typeof stickies === "object" && stickies.length > 0) {
        $stickies = stickies.each(function() {
          var $thisSticky = $(this).wrap('
');
          $thisSticky
              .data('originalPosition', $thisSticky.offset().top)
              .data('originalHeight', $thisSticky.outerHeight())
                .parent()
                .height($thisSticky.outerHeight());
        });

        $window.off("scroll.stickies").on("scroll.stickies", function() {
    		  _whenScrolling();
        });
      }
    };

    var _whenScrolling = function() {

      $stickies.each(function(i) {

        var $thisSticky = $(this),
          $stickyPosition = $thisSticky.data('originalPosition');

        if ($stickyPosition <= $window.scrollTop()) {
          var $nextSticky = $stickies.eq(i + 1),
            $nextStickyPosition = $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');

          $thisSticky.addClass("fixed");

          if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {
            var $topHeight = $('.masthead-container').outerHeight(true) + $('.container').first().outerHeight(true) + 30;
            $thisSticky.addClass("absolute").css("top", $nextStickyPosition - $topHeight);

            // FOR DEV
            // $thisSticky.addClass("absolute").css("top", $nextStickyPosition);
          }
        } else {
          var $prevSticky = $stickies.eq(i - 1);

          $thisSticky.removeClass("fixed");

          if ($prevSticky.length > 0 && $window.scrollTop() <= $thisSticky.data('originalPosition') - $thisSticky.data('originalHeight')) {
            $prevSticky.removeClass("absolute").removeAttr("style");
          }
        }
      });
    };

    return {
      load: load
    };
  })();

  $(function() {
    stickyHeaders.load($(".followMeBar"));
  });
};

export { loadSticky };
<|endoftext|>


<commit_before>var request = superagent;

(function () {

	// for IE 7

	if (!window.localStorage) {
		window.localStorage = {
			getItem: function () {},
			setItem: function () {},
			removeItem: function () {}
		}
		window.sessionStorage = {
			getItem: function () {},
			setItem: function () {},
			removeItem: function () {}
		}
	}

	if (!window.console) {
		window.console = {
			log: function () {}
		}
	}

	window.msie = /msie/.test(navigator.userAgent.toLowerCase());

})();

(function () {

	window.init = {};

	var funcs = [];

	window.init.add = function (func) {
		funcs.push(func);
	};

	$(function () {
		console.log('init:');

		var i = 0;
		var len = funcs.length;

		for (i = 0; i < len; i++) {
			funcs[i]();
		}
	});

})();

init.add(function () {

	var error = window.error = {};

	error.ERROR_SET = 10;

	error.NOT_AUTHENTICATED = 101;
	error.NOT_AUTHORIZED = 102;

	error.INVALID_DATA = 201;

});

init.add(function () {

	window.$window = $(window);
	window.$document = $(document);
	window.$content = $('#content');

	window.url = {};
	window.url.pathnames = window.location.pathname.slice(1).split('/');
	window.url.query = (function () {
		var plusRe = /\+/g;
		var paramRe = /([^&=]+)=?([^&]*)/g;
		var search = window.location.search.slice(1);
		var query = {};
		var match;
		while (match = paramRe.exec(search)) {
			query[match[1]] = decodeURIComponent(match[2].replace(plusRe, " "));
		}
		return query;
	})();

});

<commit_msg>added tagUpText() in client.<commit_after>var request = superagent;

(function () {

	// for IE 7

	if (!window.localStorage) {
		window.localStorage = {
			getItem: function () {},
			setItem: function () {},
			removeItem: function () {}
		}
		window.sessionStorage = {
			getItem: function () {},
			setItem: function () {},
			removeItem: function () {}
		}
	}

	if (!window.console) {
		window.console = {
			log: function () {}
		}
	}

	window.msie = /msie/.test(navigator.userAgent.toLowerCase());

})();

(function () {

	window.init = {};

	var funcs = [];

	window.init.add = function (func) {
		funcs.push(func);
	};

	$(function () {
		console.log('init:');

		var i = 0;
		var len = funcs.length;

		for (i = 0; i < len; i++) {
			funcs[i]();
		}
	});

})();

init.add(function () {

	var error = window.error = {};

	error.ERROR_SET = 10;

	error.NOT_AUTHENTICATED = 101;
	error.NOT_AUTHORIZED = 102;

	error.INVALID_DATA = 201;

});

init.add(function () {

	window.$window = $(window);
	window.$document = $(document);
	window.$content = $('#content');

	window.url = {};
	window.url.pathnames = window.location.pathname.slice(1).split('/');
	window.url.query = (function () {
		var plusRe = /\+/g;
		var paramRe = /([^&=]+)=?([^&]*)/g;
		var search = window.location.search.slice(1);
		var query = {};
		var match;
		while (match = paramRe.exec(search)) {
			query[match[1]] = decodeURIComponent(match[2].replace(plusRe, " "));
		}
		return query;
	})();

});

init.add(function () {

	var patterns = [
		{	// url
			pattern: /(https?:\/\/[^ "'><)\n\r]+)/g,
			replace: '$1'
		}
	];

	window.tagUpText = function (s, pi) {
		if (pi == undefined) {
			pi = 0;
		}
		if (pi == patterns.length) {
			return s;
		}
		var p = patterns[pi];
		var r = '';
		var a = 0;
		var match;
		while(match = p.pattern.exec(s)) {
			r += tagUpText(s.slice(a, match.index), pi + 1);
			r += p.replace.replace(/\$1/g, match[1]);
			a = match.index + match[0].length;
		}
		r += tagUpText(s.slice(a), pi + 1);
		return r;
	};

});<|endoftext|>


<commit_before>/*
 * StromDAO Business Object: Meta Data Publish
 * =========================================
 * Distribution Public MetaData for StromDAO Energy Blockchain.
 *
 * @author Thorsten Zoerner thorsten.zoerner@stromdao.de
 *
 */
var request = require('request');

this.metaset=function(role_id) {

			var p1 = new Promise(function(resolve, reject) {

					var obj = {};

					obj.put=function(data_obj) {
						var p2 = new Promise(function(resolve2, reject2) {
							// First Publish Data and get MultiHash
							request.post("http://l2.stromdao.de:8001/put", {form:data_obj}).on('data', function(data) {

								var multihash=data.toString();

								parent.stringstoragefactory().then( function(ssf) {
									ssf.build(multihash).then(function(adr) {
									parent.roleLookup().then(function(rl) {
										rl.setRelation(role_id,adr).then(function(hash) {
											resolve2(adr);
										});
									});
								});
								});
							});
						});
						return p2;
						// Second set in Roles and return Promise
					}

					obj.get=function(address) {
						var p2 = new Promise(function(resolve2, reject2) {
							parent.roleLookup().then(function(rl) {
								rl.relations(address,role_id).then(function(roler) {
											parent.stringstorage(roler).then(function(ss) {
												ss.str().then(function(multihash) {
													request.post("http://l2.stromdao.de:8001/get",{form:{key:multihash}}).on('data',	function(d) {

														string = d.toString();
														//console.log(roler,multihash,string);
														resolve2(string);
													});;

												});
											});
								});
							});
						});
						return p2;
					}

					resolve(obj);

			});
			return p1;
		};
<commit_msg>Changed Default location of decentral bucket store (fall back for lighter nodes)<commit_after>/*
 * StromDAO Business Object: Meta Data Publish
 * =========================================
 * Distribution Public MetaData for StromDAO Energy Blockchain.
 *
 * @author Thorsten Zoerner thorsten.zoerner@stromdao.de
 *
 */
var request = require('request');

this.metaset=function(role_id) {

			var p1 = new Promise(function(resolve, reject) {

					var obj = {};

					obj.put=function(data_obj) {
						var p2 = new Promise(function(resolve2, reject2) {
							// First Publish Data and get MultiHash
							request.post("https://demo.stromdao.de/put", {form:data_obj}).on('data', function(data) {

								var multihash=data.toString();

								parent.stringstoragefactory().then( function(ssf) {
									ssf.build(multihash).then(function(adr) {
									parent.roleLookup().then(function(rl) {
										rl.setRelation(role_id,adr).then(function(hash) {
											resolve2(adr);
										});
									});
								});
								});
							});
						});
						return p2;
						// Second set in Role	s and return Promise
					}

					obj.get=function(address) {
						var p2 = new Promise(function(resolve2, reject2) {
							parent.roleLookup().then(function(rl) {
								rl.relations(address,role_id).then(function(roler) {
											parent.stringstorage(roler).then(function(ss) {
												ss.str().then(function(multihash) {
													request.post("https://demo.stromdao.de/get",{form:{key:multihash}}).on('data',	function(d) {

														string = d.toString();
														//console.log(roler,multihash,string);
														resolve2(string);
													});;

												});
											});
								});
							});
						});
						return p2;
					}

					resolve(obj);

			});
			return p1;
		};
<|endoftext|>


<commit_before>// SearchInput.js

'use strict';

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {StyleSheet, View, Text, TextInput, Image, LayoutAnimation, ViewPropTypes} from 'react-native';

import Theme from 'teaset/themes/Theme';

export default class SearchInput extends Component {

  static propTypes = {
    ...TextInput.propTypes,
    style: ViewPropTypes.style,
    inputStyle: TextInput.propTypes.style,
    iconSize: PropTypes.number,
    disabled: PropTypes.bool,
  };

  static defaultProps = {
    ...TextInput.defaultProps,
    disabled: false,
    underlineColorAndroid: 'rgba(0, 0, 0, 0)',
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value === undefined ? props.defaultValue : props.value,
      editing: false,
      width: null,
      placeholderWidth: null,
      selectionColor: null,
    };
  }

  componentWillUpdate(props, state) {
    if (state.editing !== this.state.editing) {
      LayoutAnimation.configureNext({
        duration: 500,
        create: {
          duration: 300,
          type: LayoutAnimation.Types.easeInEaseOut,
          property: LayoutAnimation.Properties.opacity,
        },
        update: {
          type: LayoutAnimation.Types.spring,
          springDamping: 200,
        }
      });
    }
  }

  buildProps() {
    let {style, inputStyle, iconSize, disabled, placeholderTextColor, pointerEvents, ...others} = this.props;

    style = [{
      backgroundColor: Theme.siColor,
      borderColor: Theme.siBorderColor,
      borderWidth: Theme.siBorderWidth,
      borderRadius: Theme.siBorderRadius,
    }].concat(style);
    if (disabled) style = style.concat({opacity: Theme.siDisabledOpacity})

    let height = StyleSheet.flatten(style).height;
    inputStyle = [{
      color: Theme.siTextColor,
      fontSize: Theme.siFontSize,
      height: height ? height : Theme.siHeight,
      paddingVertical: Theme.siPaddingVertical,
      paddingHorizontal: Theme.siPaddingHorizontal,
    }].concat(inputStyle).concat({
      backgroundColor: 'rgba(0, 0, 0, 0)',
    });

    if (!iconSize && iconSize !== 0) iconSize = Theme.siIconSize;

    if (!placeholderTextColor) placeholderTextColor = Theme.siPlaceholderTextColor;

    if (disabled) pointerEvents = 'none';

    this.props = {style, inputStyle, iconSize, disabled, placeholderTextColor, pointerEvents, ...others};
  }

  onContainerLayout(e) {
    this.setState({width: e.nativeEvent.layout.width});
  }

  onPlaceholderLayout(e) {
    this.setState({placeholderWidth: e.nativeEvent.layout.width});
  }

  onInputFocus() {
    this.setState({editing: true, selectionColor: 'rgba(0, 0, 0, 0)'});
    this.props.onFocus && this.props.onFocus();
    setTimeout(() => this.setState({selectionColor: null}), 500);
  }

  onInputBlur() {
    this.setState({editing: false});
    this.props.onBlur && this.props.onBlur();
  }

  onChangeText(text) {
    this.setState({value: text});
    this.props.onChangeText && this.props.onChangeText(text);
  }

  render() {
    this.buildProps();

    let {style, value, inputStyle, iconSize, placeholder, placeholderTextColor, selectionColor, pointerEvents, onBlur, onFocus, onChangeText, ...others} = this.props;

    if (value === undefined) value = this.state.value;

    let paddingSize;
    let fs = StyleSheet.flatten(inputStyle);
    if (fs.paddingLeft || fs.paddingLeft === 0) paddingSize = fs.paddingLeft;
    else if (fs.paddingHorizontal || fs.paddingHorizontal === 0) paddingSize = fs.paddingHorizontal;
    else if (fs.padding || fs.padding === 0) paddingSize = fs.padding;
    else paddingSize = 0;

    return (
      <View style={style} pointerEvents={pointerEvents}>
        <View style={styles.container} onLayout={e => this.onContainerLayout(e)}>
          <View style={this.state.editing || value ? {width: this.state.width} : null}>
            <View style={styles.placeholderContainer} onLayout={e => this.onPlaceholderLayout(e)}>
              <View style={{paddingLeft: iconSize * 0.5, alignItems: 'center'}}>
                <Image
                  style={{width: iconSize, height: iconSize, tintColor: placeholderTextColor}}
                  source={require('../../icons/search.png')}
                  />
              </View>
              <Text style={{paddingLeft: paddingSize, color: placeholderTextColor, fontSize: fs.fontSize}}>
                {value ? null : placeholder}
              </Text>
            </View>
          </View>
        </View>
        <View style={{backgroundColor: 'rgba(0, 0, 0, 0)', paddingLeft: iconSize * 1.5}}>
          <TextInput
            style={inputStyle}
            value={value}
            onBlur={() => this.onInputBlur()}
            onFocus={() => this.onInputFocus()}
            onChangeText={text => this.onChangeText(text)}
            selectionColor={this.state.selectionColor ? this.state.selectionColor : selectionColor}
            {...others}
            />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  placeholderContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});

<commit_msg>SearchInput: add focus, blur, isFocused and clear method, inherited from TextInput, #122<commit_after>// SearchInput.js

'use strict';

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {StyleSheet, View, Text, TextInput, Image, LayoutAnimation, ViewPropTypes} from 'react-native';

import Theme from 'teaset/themes/Theme';

export default class SearchInput extends Component {

  static propTypes = {
    ...TextInput.propTypes,
    style: ViewPropTypes.style,
    inputStyle: TextInput.propTypes.style,
    iconSize: PropTypes.number,
    disabled: PropTypes.bool,
  };

  static defaultProps = {
    ...TextInput.defaultProps,
    disabled: false,
    underlineColorAndroid: 'rgba(0, 0, 0, 0)',
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value === undefined ? props.defaultValue : props.value,
      editing: false,
      width: null,
      placeholderWidth: null,
      selectionColor: null,
    };
  }

  componentWillUpdate(props, state) {
    if (state.editing !== this.state.editing) {
      LayoutAnimation.configureNext({
        duration: 500,
        create: {
          duration: 300,
          type: LayoutAnimation.Types.easeInEaseOut,
          property: LayoutAnimation.Properties.opacity,
        },
        update: {
          type: LayoutAnimation.Types.spring,
          springDamping: 200,
        }
      });
    }
  }

  focus() {
    return this.refs.textInput && this.refs.textInput.focus();
  }

  blur() {
    return this.refs.textInput && this.refs.textInput.blur();
  }

  isFocused() {
    return this.refs.textInput && this.refs.textInput.isFocused();
  }

  clear() {
    return this.refs.textInput && this.refs.textInput.clear();
  }

  buildProps() {
    let {style, inputStyle, iconSize, disabled, placeholderTextColor, pointerEvents, ...others} = this.props;

    style = [{
      backgroundColor: Theme.siColor,
      borderColor: Theme.siBorderColor,
      borderWidth: Theme.siBorderWidth,
      borderRadius: Theme.siBorderRadius,
    }].concat(style);
    if (disabled) style = style.concat({opacity: Theme.siDisabledOpacity})

    let height = StyleSheet.flatten(style).height;
    inputStyle = [{
      color: Theme.siTextColor,
      fontSize: Theme.siFontSize,
      height: height ? height : Theme.siHeight,
      paddingVertical: Theme.siPaddingVertical,
      paddingHorizontal: Theme.siPaddingHorizontal,
    }].concat(inputStyle).concat({
      backgroundColor: 'rgba(0, 0, 0, 0)',
    });

    if (!iconSize && iconSize !== 0) iconSize = Theme.siIconSize;

    if (!placeholderTextColor) placeholderTextColor = Theme.siPlaceholderTextColor;

    if (disabled) pointerEvents = 'none';

    this.props = {style, inputStyle, iconSize, disabled, placeholderTextColor, pointerEvents, ...others};
  }

  onContainerLayout(e) {
    this.setState({width: e.nativeEvent.layout.width});
  }

  onPlaceholderLayout(e) {
    this.setState({placeholderWidth: e.nativeEvent.layout.width});
  }

  onInputFocus() {
    this.setState({editing: true, selectionColor: 'rgba(0, 0, 0, 0)'});
    this.props.onFocus && this.props.onFocus();
    setTimeout(() => this.setState({selectionColor: null}), 500);
  }

  onInputBlur() {
    this.setState({editing: false});
    this.props.onBlur && this.props.onBlur();
  }

  onChangeText(text) {
    this.setState({value: text});
    this.props.onChangeText && this.props.onChangeText(text);
  }

  render() {
    this.buildProps();

    let {style, value, inputStyle, iconSize, placeholder, placeholderTextColor, selectionColor, pointerEvents, onBlur, onFocus, onChangeText, ...others} = this.props;

    if (value === undefined) value = this.state.value;

    let paddingSize;
    let fs = StyleSheet.flatten(inputStyle);
    if (fs.paddingLeft || fs.paddingLeft === 0) paddingSize = fs.paddingLeft;
    else if (fs.paddingHorizontal || fs.paddingHorizontal === 0) paddingSize = fs.paddingHorizontal;
    else if (fs.padding || fs.padding === 0) paddingSize = fs.padding;
    else paddingSize = 0;

    return (
      <View style={style} pointerEvents={pointerEvents}>
        <View style={styles.container} onLayout={e => this.onContainerLayout(e)}>
          <View style={this.state.editing || value ? {width: this.state.width} : null}>
            <View style={styles.placeholderContainer} onLayout={e => this.onPlaceholderLayout(e)}>
              <View style={{paddingLeft: iconSize * 0.5, alignItems: 'center'}}>
                <Image
                  style={{width: iconSize, height: iconSize, tintColor: placeholderTextColor}}
                  source={require('../../icons/search.png')}
                  />
              </View>
              <Text style={{paddingLeft: paddingSize, color: placeholderTextColor, fontSize: fs.fontSize}}>
                {value ? null : placeholder}
              </Text>
            </View>
          </View>
        </View>
        <View style={{backgroundColor: 'rgba(0, 0, 0, 0)', paddingLeft: iconSize * 1.5}}>
          <TextInput
            style={inputStyle}
            value={value}
            onBlur={() => this.onInputBlur()}
            onFocus={() => this.onInputFocus()}
            onChangeText={text => this.onChangeText(text)}
            selectionColor={this.state.selectionColor ? this.state.selectionColor : selectionColor}
            {...others}
            ref='textInput'
            />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  placeholderContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});

<|endoftext|>


<commit_before>var cardsA = [];
var cardsB = [];

function dealer() {
	// Create Deck
	var deck = [];
		for (i = 0; i <= 51; i++) {
			deck[i] = i + 1;
		}

	// Deck shuffle
	function fisherYShuffle(cardArray) {
	  var m = cardArray.length, t, q;

	  while (m) {
	    q = Math.floor(Math.random() * m--);
	    t = array[m];
	    array[m] = array[q];
	    array[q] = t;
	  }
	}

	fisherYShuffle(deck);
		for (i = 0; i <= 51; i++) {
		}

	// Create hands
	var handA = [];
	var handB = [];
	for (i = 0; i <= 9; i++) {
			dealtCard = deck[i];
			if (i < 4) {
			handA.push(dealtCard);
			} else {
			handB.push(dealtCard);
			}
		}
}

// Card Ojects
for (i = 0; i <= 4; i++) {
		if (handA[i] <= 13) {
			cardValue = handA[i];
			cardsA[i] = {
				value: cardValue, suit: "d"
			};
		} else if ((handA[i] > 13) && (handA[i] <= 26)) {
			cardValue = handA[i] - 13;
			cardsA[i] = {
				value: cardValue, suit: 'c'
			};
		} else if ((handA[i] > 26) && (handA[i] <= 39)) {
			cardValue = handA[i] - 26;
			cardsA[i] = {
				value: cardValue, suit: 'h'
			};
		} else {
			cardValue = handA[i] - 39;
			cardsA[i] = {
				value: cardValue, suit: 's'
			};
		}
		if ((cardsA[i].value === 1) || (cardsA[i].value >= 10)) {
			cardsA[i].face = 'face';
		}
		if (handB[i] <= 13) {
			cardValue = handB[i];
			cardsB[i] = {
				value: cardValue, suit: "d"
			};
		} else if ((handB[i] > 13) && (handB[i] <= 26)) {
			cardValue = handB[i] - 13;
			cardsB[i] = {
				value: cardValue, suit: 'c'
			};
		} else if ((handB[i] > 26) && (handB[i] <= 39)) {
			cardValue = handB[i] - 26;
			cardsB[i] = {
				value: cardValue, suit: 'h'
			};
		} else {
			cardValue = handB[i] - 39;
			cardsB[i] = {
				value: cardValue, suit: 's'
			};
		}
		if ((cardsB[i].value === 1) || (cardsB[i].value >= 10)) {
			cardsB[i].face = 'face';
		}
}

function handComparison(){
	var i, j;
	var pointsA = 0;
	var pointsB = 0;

	// Straight check
	for (i=1; i <= handA.length; i++){
		j = i-1;
		if (cardsA[i].value !== cardsA[j].value +1 ) break;
		var straightStreakA = i;
	}

		if (straightStreakA === 4) {
		pointsA = pointsA + 400 + cardsA[4].value;
	}

	for (i=1; i <= handB.length; i++){
		j = i-1;
		if (cardsB[i].value !== cardsB[j].value +1 ) break;
		var straightStreakB = i;
	}

		if (straightStreakB === 4) {
		pointsB = pointsB + 400 + cardsB[4].value;
	}

	// Flush check
	for (i = 1; i <=4; i++) {
		if (cardsA[i].suit !== cardsA[j].suit) break;
		var flushStreakA = i;
	}

	if (flushStreakA === 4) {
		pointsA = pointsA + 500 + cardsA[4].value;
	}
	for (i = 1; i <=4; i++) {
		j = i - 1;
		if (cardsB[i].suit !== cardsB[j].suit) break;
		var flushStreakB = i;
	}
	if (flushStreakB === 4) {
		pointsB = pointsB + 500 + cardsB[4].value;
	}

	// Check for Pairs, Full House, 4 of a Kind and High Cards
	if (pointsA < 400) {
		var highCardA;
		var pairsA = [];
		for (i = 1; i <= handA.length; i++) {
			j = i - 1;
			if (cardsA[i].value === cardsA[j].value) {
				pairsA[j] = 1;
				highCardA = cardsA[i].value;
			} else {
				pairsA[j] = 0;
			}
		}
		var numPairsA = 0;
		for (i = 0; i <= 3; i++) {
			numPairsA = numPairsA + pairsA[i];
		}

		if (numPairsA === 1) {
			pointsA = pointsA + 100 + highCardA;
		}

		if (numPairsA === 2) {
			if ((pairsA[0] === 1 && pairsA[1] === 1) || (pairsA[1] === 1 && pairsA[2] === 1) || (pairsA[2] === 1 && pairsA[3] === 1)) {
				pointsA = pointsA + 300 + cardsA[2].value;

			} else {
				pointsA = pointsA + 200 + cardsA[3].value;

			}
		}

		if ((numPairsA === 3) && (pairsA[1] === 0 || pairsA[2] === 0)) {
			pointsA = pointsA + 600 + cardsA[4].value;
		}

		if ((numPairsA === 3) && (pairsA[0] === 0 || pairsA[3] === 0)) {
			mpointsA = pointsA + 700 + cardsA[3].value;
		}

		if (numPairsA === 0) {
			pointsA = pointsA + cardsA[4].value;
		}
	}

	//Repeat loop for handB
	if (pointsB < 400) {
		var highCardB;
		var pairsB = [];
		for (i = 1; i <= handA.length; i++) {
			j = i - 1;
			if (cardsB[i].value === cardsB[j].value) {
				pairsB[j] = 1;
				highCardB = cardsB[i].value;
			} else {
				pairsB[j] = 0;
			}
		}
		var numPairsB = 0;
		for (i = 0; i <= 3; i++) {
			numPairsB = numPairsB + pairsB[i];
		}

		if (numPairsB === 1) {
			pointsB = pointsB + 100 + highCardB;
		}

		if (numPairsB === 2) {
			if ((pairsB[0] === 1 && pairsB[1] === 1) || (pairsB[1] === 1 && pairsB[2] === 1) || (pairsB[2] === 1 && pairsB[3] === 1)) {
				pointsB = pointsB+ 300 + cardsB[2].value;

			} else {
				pointsB = pointsB + 200 + cardsB[3].value;

			}
		}

		if ((numPairsB === 3) && (pairsB[1] === 0 || pairsB[2] === 0)) {
			pointsB = pointsB + 600 + cardsB[4].value;
		}

		if ((numPairsB === 3) && (pairsB[0] === 0 || pairsB[3] === 0)) {
			mpointsB = pointsB + 700 + cardsB[3].value;
		}

		if (numPairsB === 0) {
			pointsB = pointsB + cardsB[4].value;
		}
	}

}
<commit_msg>Delete poker.js<commit_after><|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import withSeriesType from './components/WithSeriesType'

// Graphs
export { default as HighchartsChart }  from './components/HighchartsChart';
export { default as HighchartsSparkline }  from './components/HighchartsSparkline';
export { default as Highcharts3dChart }  from './components/Highcharts3dChart';

// Graph parts
export { default as Annotation }  from './components/Annotation';
export { default as Caption }  from './components/Caption';
export { default as Chart }  from './components/Chart';
export { default as Credits }  from './components/Credits';
export { default as Loading }  from './components/Loading';
export { default as Legend }  from './components/Legend';
export { default as Pane }  from './components/Pane';
export { PlotBand }  from './components/PlotBandLine';
export { PlotLine }  from './components/PlotBandLine';
export { default as Subtitle }  from './components/Subtitle';
export { default as Title }  from './components/Title';
export { default as Tooltip }  from './components/Tooltip';
export { default as XAxis }  from './components/XAxis';
export { default as YAxis }  from './components/YAxis';
export { default as ZAxis }  from './components/ZAxis';

const axisNotRequired = { requiresAxis: false };
const hasParentSeries = { baseSeries: PropTypes.string.isRequired };

// Series
export const AreaRangeSeries = withSeriesType('AreaRange');
export const AreaSeries = withSeriesType('Area');
export const AreaSplineRangeSeries = withSeriesType('AreaSplineRange');
export const AreaSplineSeries = withSeriesType('AreaSpline');
export { default as BarSeries }  from './components/BarSeries';
export const BellCurveSeries = withSeriesType('BellCurve', {}, hasParentSeries);
export const BoxPlotSeries = withSeriesType('BoxPlot');
export const BubbleSeries = withSeriesType('Bubble');
export const BulletSeries = withSeriesType('Bullet');
export const ColumnPyramidSeries = withSeriesType('ColumnPyramid');
export const ColumnRangeSeries = withSeriesType('ColumnRange');
export const ColumnSeries = withSeriesType('Column');
export const CylinderSeries = withSeriesType('Cylinder');
export const DependencyWheelSeries = withSeriesType('DependencyWheel');
export const ErrorBarSeries = withSeriesType('ErrorBar');
export const FunnelSeries = withSeriesType('Funnel', axisNotRequired);
export const Funnel3dSeries = withSeriesType('Funnel3d');
export const GaugeSeries = withSeriesType('Gauge');
export const HeatmapSeries = withSeriesType('Heatmap');
export const HistogramSeries = withSeriesType('Histogram', {}, hasParentSeries);
export const ItemSeries = withSeriesType('Item');
export const LineSeries = withSeriesType('Line');
export const NetworkGraphSeries = withSeriesType('NetworkGraph');
export const PackedBubbleSeries = withSeriesType('PackedBubble', axisNotRequired);
export const ParetoSeries = withSeriesType('Pareto', {}, hasParentSeries);
export const PieSeries = withSeriesType('Pie', axisNotRequired);
export const PolygonSeries = withSeriesType('Polygon');
export const PyramidSeries = withSeriesType('Pyramid', axisNotRequired);
export const Pyramid3dSeries = withSeriesType('Pyramid3d');
export const SankeySeries = withSeriesType('Sankey');
export const OrganizationSeries = withSeriesType('Organization');
export const ScatterSeries = withSeriesType('Scatter');
export const Scatter3dSeries = withSeriesType('Scatter3d');
export const SolidGaugeSeries = withSeriesType('SolidGauge');
export const SplineSeries = withSeriesType('Spline');
export const StreamGraphSeries = withSeriesType('StreamGraph');
export const SunburstSeries = withSeriesType('Sunburst');
export const TilemapSeries = withSeriesType('Tilemap');
export const TimelineSeries = withSeriesType('Timeline');
export const TreemapSeries = withSeriesType('Treemap');
export const VariablePieSeries = withSeriesType('VariablePie', axisNotRequired);
export const VariwideSeries = withSeriesType('Variwide');
export const VennSeries = withSeriesType('Venn', axisNotRequired);
export const VectorSeries = withSeriesType('Vector');
export const WaterfallSeries = withSeriesType('Waterfall');
export const WindBarbSeries = withSeriesType('WindBarb');
export const XRangeSeries = withSeriesType('XRange');

// Contexts
export { default as HighchartsContext } from './components/HighchartsContext';
export { default as HighchartsChartContext } from './components/ChartContext';
export { default as HighchartsAxisContext } from './components/AxisContext';
export { default as HighchartsSeriesContext } from './components/SeriesContext';

// Hooks
export { default as useHighcharts } from './components/UseHighcharts';
export { default as useChart } from './components/UseChart';
export { default as useAxis } from './components/UseAxis';
export { default as useSeries } from './components/UseSeries';

// utility hooks, not part of api
export { default as useModifiedProps } from './components/UseModifiedProps';

// Helpers
export { default as withHighcharts }  from './components/WithHighcharts';
export { default as Axis }  from './components/Axis';
export { default as BaseChart }  from './components/BaseChart';
export { default as Debug }  from './components/Debug';
export { default as Hidden }  from './components/Hidden';
export { default as Series }  from './components/Series';

// Utils
export { default as getModifiedProps } from './utils/getModifiedProps';
export { getNonEventHandlerProps } from './utils/events';
export { getEventsConfig } from './utils/events';
export { withSeriesType }
<commit_msg>Don't export getModifiedProps<commit_after>import PropTypes from 'prop-types';
import withSeriesType from './components/WithSeriesType'

// Graphs
export { default as HighchartsChart }  from './components/HighchartsChart';
export { default as HighchartsSparkline }  from './components/HighchartsSparkline';
export { default as Highcharts3dChart }  from './components/Highcharts3dChart';

// Graph parts
export { default as Annotation }  from './components/Annotation';
export { default as Caption }  from './components/Caption';
export { default as Chart }  from './components/Chart';
export { default as Credits }  from './components/Credits';
export { default as Loading }  from './components/Loading';
export { default as Legend }  from './components/Legend';
export { default as Pane }  from './components/Pane';
export { PlotBand }  from './components/PlotBandLine';
export { PlotLine }  from './components/PlotBandLine';
export { default as Subtitle }  from './components/Subtitle';
export { default as Title }  from './components/Title';
export { default as Tooltip }  from './components/Tooltip';
export { default as XAxis }  from './components/XAxis';
export { default as YAxis }  from './components/YAxis';
export { default as ZAxis }  from './components/ZAxis';

const axisNotRequired = { requiresAxis: false };
const hasParentSeries = { baseSeries: PropTypes.string.isRequired };

// Series
export const AreaRangeSeries = withSeriesType('AreaRange');
export const AreaSeries = withSeriesType('Area');
export const AreaSplineRangeSeries = withSeriesType('AreaSplineRange');
export const AreaSplineSeries = withSeriesType('AreaSpline');
export { default as BarSeries }  from './components/BarSeries';
export const BellCurveSeries = withSeriesType('BellCurve', {}, hasParentSeries);
export const BoxPlotSeries = withSeriesType('BoxPlot');
export const BubbleSeries = withSeriesType('Bubble');
export const BulletSeries = withSeriesType('Bullet');
export const ColumnPyramidSeries = withSeriesType('ColumnPyramid');
export const ColumnRangeSeries = withSeriesType('ColumnRange');
export const ColumnSeries = withSeriesType('Column');
export const CylinderSeries = withSeriesType('Cylinder');
export const DependencyWheelSeries = withSeriesType('DependencyWheel');
export const ErrorBarSeries = withSeriesType('ErrorBar');
export const FunnelSeries = withSeriesType('Funnel', axisNotRequired);
export const Funnel3dSeries = withSeriesType('Funnel3d');
export const GaugeSeries = withSeriesType('Gauge');
export const HeatmapSeries = withSeriesType('Heatmap');
export const HistogramSeries = withSeriesType('Histogram', {}, hasParentSeries);
export const ItemSeries = withSeriesType('Item');
export const LineSeries = withSeriesType('Line');
export const NetworkGraphSeries = withSeriesType('NetworkGraph');
export const PackedBubbleSeries = withSeriesType('PackedBubble', axisNotRequired);
export const ParetoSeries = withSeriesType('Pareto', {}, hasParentSeries);
export const PieSeries = withSeriesType('Pie', axisNotRequired);
export const PolygonSeries = withSeriesType('Polygon');
export const PyramidSeries = withSeriesType('Pyramid', axisNotRequired);
export const Pyramid3dSeries = withSeriesType('Pyramid3d');
export const SankeySeries = withSeriesType('Sankey');
export const OrganizationSeries = withSeriesType('Organization');
export const ScatterSeries = withSeriesType('Scatter');
export const Scatter3dSeries = withSeriesType('Scatter3d');
export const SolidGaugeSeries = withSeriesType('SolidGauge');
export const SplineSeries = withSeriesType('Spline');
export const StreamGraphSeries = withSeriesType('StreamGraph');
export const SunburstSeries = withSeriesType('Sunburst');
export const TilemapSeries = withSeriesType('Tilemap');
export const TimelineSeries = withSeriesType('Timeline');
export const TreemapSeries = withSeriesType('Treemap');
export const VariablePieSeries = withSeriesType('VariablePie', axisNotRequired);
export const VariwideSeries = withSeriesType('Variwide');
export const VennSeries = withSeriesType('Venn', axisNotRequired);
export const VectorSeries = withSeriesType('Vector');
export const WaterfallSeries = withSeriesType('Waterfall');
export const WindBarbSeries = withSeriesType('WindBarb');
export const XRangeSeries = withSeriesType('XRange');

// Contexts
export { default as HighchartsContext } from './components/HighchartsContext';
export { default as HighchartsChartContext } from './components/ChartContext';
export { default as HighchartsAxisContext } from './components/AxisContext';
export { default as HighchartsSeriesContext } from './components/SeriesContext';

// Hooks
export { default as useHighcharts } from './components/UseHighcharts';
export { default as useChart } from './components/UseChart';
export { default as useAxis } from './components/UseAxis';
export { default as useSeries } from './components/UseSeries';

// utility hooks, not part of api
export { default as useModifiedProps } from './components/UseModifiedProps';

// Helpers
export { default as withHighcharts }  from './components/WithHighcharts';
export { default as Axis }  from './components/Axis';
export { default as BaseChart }  from './components/BaseChart';
export { default as Debug }  from './components/Debug';
export { default as Hidden }  from './components/Hidden';
export { default as Series }  from './components/Series';

// Utils
export { getNonEventHandlerProps } from './utils/events';
export { getEventsConfig } from './utils/events';
export { withSeriesType }
<|endoftext|>


<commit_before>({
  renderIcon: function(component) {
    var prefix = "slds-";
    var svgns = "http://www.w3.org/2000/svg";
    var xlinkns = "http://www.w3.org/1999/xlink";
    var size = component.get("v.size");
    var name = component.get("v.name");
    var classname = component.get("v.class");
    var category = component.get("v.category");

    var containerClassName = [
        prefix+"icon__container",
        prefix+"icon-"+category+"-"+name,
        classname
        ].join(' ');
    var iconClassName = prefix+"icon "+prefix+"icon--" + size;
    component.set("v.containerClass", containerClassName);

    var svgroot = document.createElementNS(svgns, "svg");
    svgroot.setAttribute("aria-hidden", "true");
    svgroot.setAttribute("class", iconClassName);
    svgroot.setAttribute("name", name);

    // Add an "href" attribute (using the "xlink" namespace)
    var shape = document.createElementNS(svgns, "use");
    shape.setAttributeNS(xlinkns, "href", component.get("v.svgPath"));
    svgroot.appendChild(shape);

    var container = component.find("container").getElement();
    container.insertBefore(svgroot, container.firstChild);

    var svgPath = component.get("v.svgPath");
    var namespace = "";
    //This would work with any class. We are just using the one with the shortest name.
    var gettingnamespace = sforce.connection.query("SELECT NamespacePrefix FROM ApexClass where Name = 'REL_Utils' LIMIT 1");
    var getname = gettingnamespace.getArray("records");
	if(getname.length > 0 && getname[0] && getname[0].NamespacePrefix.length > 0) {
		namespace = getname[0].NamespacePrefix + "__";
		svgPath = svgPath.replace('/resource/', '/resource/' + namespace);
		console.log("svgPath after manipulation: " + svgPath);
	}
    component.set("v.svgPath", svgPath);
  }
})<commit_msg>I think we need to do the path manipulation before the href property is set.<commit_after>({
  renderIcon: function(component) {
    var prefix = "slds-";
    var svgns = "http://www.w3.org/2000/svg";
    var xlinkns = "http://www.w3.org/1999/xlink";
    var size = component.get("v.size");
    var name = component.get("v.name");
    var classname = component.get("v.class");
    var category = component.get("v.category");

    var containerClassName = [
        prefix+"icon__container",
        prefix+"icon-"+category+"-"+name,
        classname
        ].join(' ');
    var iconClassName = prefix+"icon "+prefix+"icon--" + size;
    component.set("v.containerClass", containerClassName);

    var svgroot = document.createElementNS(svgns, "svg");
    svgroot.setAttribute("aria-hidden", "true");
    svgroot.setAttribute("class", iconClassName);
    svgroot.setAttribute("name", name);

    var svgPath = component.get("v.svgPath");
    var namespace = "";
    //This would work with any class. We are just using the one with the shortest name.
    var gettingnamespace = sforce.connection.query("SELECT NamespacePrefix FROM ApexClass where Name = 'REL_Utils' LIMIT 1");
    var getname = gettingnamespace.getArray("records");
	if(getname.length > 0 && getname[0] && getname[0].NamespacePrefix.length > 0) {
		namespace = getname[0].NamespacePrefix + "__";
		svgPath = svgPath.replace('/resource/', '/resource/' + namespace);
		console.log("svgPath after manipulation: " + svgPath);
	}
    component.set("v.svgPath", svgPath);

    // Add an "href" attribute (using the "xlink" namespace)
    var shape = document.createElementNS(svgns, "use");
    shape.setAttributeNS(xlinkns, "href", svgPath);
    svgroot.appendChild(shape);

    var container = component.find("container").getElement();
    container.insertBefore(svgroot, container.firstChild);
  }
})<|endoftext|>


<commit_before>
/**
 * on (EventHandler)
 * @param  {Any} ...args
 * @return {Function}
 */
export default function on(...args) {

	if(!args.length){
		throw new Error('Please pass an event type e.g "click"');
	}

	return (target, method, descriptor) => {

		// register events
		on.helper.registerEvent(target, ...args, method, descriptor.value);

	}
}

/*****************************************
 * ########## Decorator Helper ###########
 *****************************************/

// define namespace
on.helper = {};

/**
 * Helper for registering events
 * @param  {String} event
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerEvent = (target, eventDomain, method, callback = function(){}) => {

	// define namespaces
	on.helper.registerNamespaces(target);

	if(target.$appDecorators.on.events[eventDomain]) {
		throw new Error(`The method: "${method}" already exists!`);
	}

	// define events
	target.$appDecorators.on.events[eventDomain] = callback;

	return target;

};

/**
 * Prepare eventDomain
 * @param  {String} eventDomain
 * @return {Array}
 */
on.helper.prepareEventDomain = (eventDomain) => {

	let splitedEventDomain = eventDomain.split(' ');
	let event = splitedEventDomain[0];
	let delegateSelector = undefined;
	if(splitedEventDomain[1]){
		delegateSelector = splitedEventDomain.splice(1).join(' ');
	}

	return [ event, delegateSelector ];

}

/**
 * Register on created callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnCreatedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onCreated) {
		target.$onCreated = [];
	}

	// init render engine
	target.$onCreated.push(callback);

	return target;

};

/**
 * Register on Detached callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnDeatchedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onDetached) {
		target.$Detached = [];
	}

	// init render engine
	target.$onDetached.push(callback);

	return target;

};

/**
 * Register namespace of on decorator
 * @param  {Function|Objet} target
 * @return {Function} target
 */
on.helper.registerNamespaces = (target) => {

	// if namespace already exists do nothing
	if(target.$appDecorators && target.$appDecorators.on){
		return target;
	}

	// define namespace
	target.$appDecorators = {
		on: {
			events: {},
		},
	};

	return target;
};
<commit_msg>src/decorators/on.js: removed on.helper.prepareEventDomain - prepareEventDomain is now in src/libs/eventhandler.js<commit_after>
/**
 * on (EventHandler)
 * @param  {Any} ...args
 * @return {Function}
 */
export default function on(...args) {

	if(!args.length){
		throw new Error('Please pass an event type e.g "click"');
	}

	return (target, method, descriptor) => {

		// register events
		on.helper.registerEvent(target, ...args, method, descriptor.value);

	}
}

/*****************************************
 * ########## Decorator Helper ###########
 *****************************************/

// define namespace
on.helper = {};

/**
 * Helper for registering events
 * @param  {String} event
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerEvent = (target, eventDomain, method, callback = function(){}) => {

	// define namespaces
	on.helper.registerNamespaces(target);

	if(target.$appDecorators.on.events[eventDomain]) {
		throw new Error(`The method: "${method}" already exists!`);
	}

	// define events
	target.$appDecorators.on.events[eventDomain] = callback;

	return target;

};

/**
 * Register on created callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnCreatedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onCreated) {
		target.$onCreated = [];
	}

	// init render engine
	target.$onCreated.push(callback);

	return target;

};

/**
 * Register on Detached callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnDeatchedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onDetached) {
		target.$Detached = [];
	}

	// init render engine
	target.$onDetached.push(callback);

	return target;

};

/**
 * Register namespace of on decorator
 * @param  {Function|Objet} target
 * @return {Function} target
 */
on.helper.registerNamespaces = (target) => {

	// if namespace already exists do nothing
	if(target.$appDecorators && target.$appDecorators.on){
		return target;
	}

	// define namespace
	target.$appDecorators = {
		on: {
			events: {},
		},
	};

	return target;
};
<|endoftext|>