<commit_before>
const RG = require('./rg');
const ROT = require('../../lib/rot');

const DIRS = [-1, 0, 1];
const DIRS_NO_ZERO = [-1, 1];

/* A OO wrapper around ROT.RNG. Adds method for serialisation. */
RG.Random = function() {
    this.seed = 0;
    this.rng = ROT.RNG.clone();
    this.rng.setSeed(this.seed);
};

RG.Random.prototype.setSeed = function(seed) {
    this.rng.setSeed(seed);
};

RG.Random.prototype.setState = function(state) {
    this.rng.setState(state);
};

/* Return random property from the object.*/
RG.Random.prototype.randProp = function(obj) {
    const keys = Object.keys(obj);
    const keyIndex = this.randIndex(keys);
    return obj[keys[keyIndex]];
};

/* Returns a random entry from the array.*/
RG.Random.prototype.arrayGetRand = function(arr) {
    const randIndex = this.randIndex(arr);
    return arr[randIndex];
};

RG.Random.prototype.getUniformInt = function(min, max) {
    return this.rng.getUniformInt(min, max);
};

/* Returns a random index number from given array. */
RG.Random.prototype.randIndex = function randIndex(arr) {
    return Math.floor(this.rng.getUniform() * arr.length);
};

RG.Random.prototype.getUniform = function() {
    return this.rng.getUniform();
};

RG.Random.prototype.getUniformRange = function(min, max) {
    const span = max - min;
    const uniform = this.getUniform();
    return min + span * uniform;
};

RG.Random.prototype.getNormal = function(mean, stddev) {
    return this.rng.getNormal(mean, stddev);
};

RG.Random.prototype.getWeighted = function(obj) {
    return this.rng.getWeightedValue(obj);
};

/* Given a number N, returns an integer from 0 to N weighted such that N has the
 * highest weight, and 0 the lowest.
 */
RG.Random.prototype.getWeightedLinear = function(N) {
    const weights = {};
    for (let i = 0; i < N; i++) {
        weights[i] = i + 1; // Without + 1, 0 will never be chosen
    }
    return this.rng.getWeightedValue(weights);
};

RG.Random.prototype.toJSON = function() {
    return {
        seed: this.seed,
        state: this.rng.getState()
    };
};

/* Returns random direction [x, y] while excluding [0, 0]. */
RG.Random.prototype.getRandDir = function() {
    const dX = this.arrayGetRand(DIRS);
    let dY = this.arrayGetRand(DIRS);
    if (dX === 0) {
        dY = RG.RAND.arrayGetRand(DIRS_NO_ZERO);
    }
    return [dX, dY];
};

/* Returns randomly one of the 4 cardinal directions. */
RG.Random.prototype.getCardinalDir = function() {
    return this.arrayGetRand(RG.CARDINAL_DIR);
};

/* Returns a random direction using weights for directions. */
RG.Random.prototype.getRandDirWeighted = function() {
    // TODO
};

/* Returns a random xy-coord in the given bounding box. */
RG.Random.prototype.getRandInBbox = function(bbox) {
    const {ulx, uly, lrx, lry} = bbox;
    // RG.nullOrUndefError([ulx, uly, lrx, lry]);
    return [
        this.getUniformInt(ulx, lrx),
        this.getUniformInt(uly, lry)
    ];
};

/*
 * From http://stackoverflow.com/questions/2450954/
 * how-to-randomize-shuffle-a-javascript-array
 */
RG.Random.prototype.shuffle = function(array) {
    if (array.length <= 1) {return array;}
    let currentIndex = array.length - 1;
    let temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = this.getUniformInt(0, currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
};

// Global RNG
RG.RAND = new RG.Random();

module.exports = RG.Random;
<commit_msg>Added getCardinalDirLetter().<commit_after>
const RG = require('./rg');
const ROT = require('../../lib/rot');

const DIRS = [-1, 0, 1];
const DIRS_NO_ZERO = [-1, 1];

/* A OO wrapper around ROT.RNG. Adds method for serialisation. */
RG.Random = function() {
    this.seed = 0;
    this.rng = ROT.RNG.clone();
    this.rng.setSeed(this.seed);
};

RG.Random.prototype.setSeed = function(seed) {
    this.rng.setSeed(seed);
};

RG.Random.prototype.setState = function(state) {
    this.rng.setState(state);
};

/* Return random property from the object.*/
RG.Random.prototype.randProp = function(obj) {
    const keys = Object.keys(obj);
    const keyIndex = this.randIndex(keys);
    return obj[keys[keyIndex]];
};

/* Returns a random entry from the array.*/
RG.Random.prototype.arrayGetRand = function(arr) {
    const randIndex = this.randIndex(arr);
    return arr[randIndex];
};

RG.Random.prototype.getUniformInt = function(min, max) {
    return this.rng.getUniformInt(min, max);
};

/* Returns a random index number from given array. */
RG.Random.prototype.randIndex = function randIndex(arr) {
    return Math.floor(this.rng.getUniform() * arr.length);
};

RG.Random.prototype.getUniform = function() {
    return this.rng.getUniform();
};

RG.Random.prototype.getUniformRange = function(min, max) {
    const span = max - min;
    const uniform = this.getUniform();
    return min + span * uniform;
};

RG.Random.prototype.getNormal = function(mean, stddev) {
    return this.rng.getNormal(mean, stddev);
};

RG.Random.prototype.getWeighted = function(obj) {
    return this.rng.getWeightedValue(obj);
};

/* Given a number N, returns an integer from 0 to N weighted such that N has the
 * highest weight, and 0 the lowest.
 */
RG.Random.prototype.getWeightedLinear = function(N) {
    const weights = {};
    for (let i = 0; i < N; i++) {
        weights[i] = i + 1; // Without + 1, 0 will never be chosen
    }
    return this.rng.getWeightedValue(weights);
};

RG.Random.prototype.toJSON = function() {
    return {
        seed: this.seed,
        state: this.rng.getState()
    };
};

/* Returns random direction [x, y] while excluding [0, 0]. */
RG.Random.prototype.getRandDir = function() {
    const dX = this.arrayGetRand(DIRS);
    let dY = this.arrayGetRand(DIRS);
    if (dX === 0) {
        dY = RG.RAND.arrayGetRand(DIRS_NO_ZERO);
    }
    return [dX, dY];
};

/* Returns randomly one of the 4 cardinal directions. */
RG.Random.prototype.getCardinalDir = function() {
    return this.arrayGetRand(RG.CARDINAL_DIR);
};

RG.Random.prototype.getCardinalDirLetter = function() {
    return this.arrayGetRand(RG.CARDINAL_DIR_ABBR);
};

/* Returns a random direction using weights for directions. */
RG.Random.prototype.getRandDirWeighted = function() {
    // TODO
};

/* Returns a random xy-coord in the given bounding box. */
RG.Random.prototype.getRandInBbox = function(bbox) {
    const {ulx, uly, lrx, lry} = bbox;
    // RG.nullOrUndefError([ulx, uly, lrx, lry]);
    return [
        this.getUniformInt(ulx, lrx),
        this.getUniformInt(uly, lry)
    ];
};

/*
 * From http://stackoverflow.com/questions/2450954/
 * how-to-randomize-shuffle-a-javascript-array
 */
RG.Random.prototype.shuffle = function(array) {
    if (array.length <= 1) {return array;}
    let currentIndex = array.length - 1;
    let temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = this.getUniformInt(0, currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
};

// Global RNG
RG.RAND = new RG.Random();

module.exports = RG.Random;
<|endoftext|>


<commit_before>import React from 'react'
import { View, Text, TouchableHighlight, TouchableOpacity, Image } from 'react-native'
import styles  from '../Style/style.js'

const LocationListItem = (props) => {

  const handleButtonPress = () => {
    props.navigator.push({
      name: 'ParkingDetails',
      description: props.location.description,
      id: props.location.id,
      coordinate: props.location.coordinate,
      title: props.location.title,
      backButtonText: 'map'
    });

  }

  return (
        <TouchableOpacity onPress={ () => { handleButtonPress();
                                            props.setModalVisible(!props.modalState)
                                          }}
                          style={styles.listItemView}
        >
          <View style={styles.listItemText}>
            <Text style={{fontWeight: 'bold'}}>{props.location.title}</Text>
            <Text>{props.location.description}</Text>
          </View>
            <Image
              style={styles.listItemArrow}
              source={require('../Public/Arrow-Icon.png')}
            />
        </TouchableOpacity>
  )
}

export default LocationListItem<commit_msg>More clean up<commit_after>import React from 'react'
import { View, Text, TouchableHighlight, TouchableOpacity, Image } from 'react-native'
import styles  from '../Style/style.js'

const LocationListItem = (props) => {

  const handleButtonPress = () => {
    props.navigator.push({
      name: 'ParkingDetails',
      description: props.location.description,
      id: props.location.id,
      coordinate: props.location.coordinate,
      title: props.location.title,
      backButtonText: 'map'
    });

  }

  return (
        <TouchableOpacity
          onPress={ () => { handleButtonPress();
                            props.setModalVisible(!props.modalState)
                          }}
          style={styles.listItemView}
        >
          <View style={styles.listItemText}>
            <Text style={{fontWeight: 'bold'}}>{props.location.title}</Text>
            <Text>{props.location.description}</Text>
          </View>
            <Image
              style={styles.listItemArrow}
              source={require('../Public/Arrow-Icon.png')}
            />
        </TouchableOpacity>
  )
}

export default LocationListItem<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(shared, testing) {

  var fills = 'backwards|forwards|both|none'.split('|');
  var directions = 'reverse|alternate|alternate-reverse'.split('|');
  var linear = function(x) { return x; };

  function cloneTimingInput(timingInput) {
    if (typeof timingInput == 'number') {
      return timingInput;
    }
    var clone = {};
    for (var m in timingInput) {
      clone[m] = timingInput[m];
    }
    return clone;
  }

  function AnimationEffectTiming() {
    this._delay = 0;
    this._endDelay = 0;
    this._fill = 'none';
    this._iterationStart = 0;
    this._iterations = 1;
    this._duration = 0;
    this._playbackRate = 1;
    this._direction = 'normal';
    this._easing = 'linear';
    this._easingFunction = linear;
  }

  function isInvalidTimingDeprecated() {
    return shared.isDeprecated('Invalid timing inputs', '2016-03-02', 'TypeError exceptions will be thrown instead.', true);
  }

  AnimationEffectTiming.prototype = {
    _setMember: function(member, value) {
      this['_' + member] = value;
      if (this._effect) {
        this._effect._timingInput[member] = value;
        this._effect._timing = shared.normalizeTimingInput(this._effect._timingInput);
        this._effect.activeDuration = shared.calculateActiveDuration(this._effect._timing);
        if (this._effect._animation) {
          this._effect._animation._rebuildUnderlyingAnimation();
        }
      }
    },
    get playbackRate() {
      return this._playbackRate;
    },
    set delay(value) {
      this._setMember('delay', value);
    },
    get delay() {
      return this._delay;
    },
    set endDelay(value) {
      this._setMember('endDelay', value);
    },
    get endDelay() {
      return this._endDelay;
    },
    set fill(value) {
      this._setMember('fill', value);
    },
    get fill() {
      return this._fill;
    },
    set iterationStart(value) {
      if (isNaN(value) || value < 0) {
        if (isInvalidTimingDeprecated()) {
          throw new TypeError('iterationStart must be a non-negative number, received: ' + timing.iterationStart);
        }
      }
      this._setMember('iterationStart', value);
    },
    get iterationStart() {
      return this._iterationStart;
    },
    set duration(value) {
      if (value != 'auto' && (isNaN(value) || value < 0)) {
        if (isInvalidTimingDeprecated()) {
          throw new TypeError('duration must be non-negative or auto, received: ' + value);
        }
      }
      this._setMember('duration', value);
    },
    get duration() {
      return this._duration;
    },
    set direction(value) {
      this._setMember('direction', value);
    },
    get direction() {
      return this._direction;
    },
    set easing(value) {
      this._easingFunction = toTimingFunction(value);
      this._setMember('easing', value);
    },
    get easing() {
      return this._easing;
    },
    set iterations(value) {
      if (isNaN(value) || value < 0) {
        if (isInvalidTimingDeprecated()) {
          throw new TypeError('iterations must be non-negative, received: ' + value);
        }
      }
      this._setMember('iterations', value);
    },
    get iterations() {
      return this._iterations;
    }
  };

  function makeTiming(timingInput, forGroup, effect) {
    var timing = new AnimationEffectTiming();
    if (forGroup) {
      timing.fill = 'both';
      timing.duration = 'auto';
    }
    if (typeof timingInput == 'number' && !isNaN(timingInput)) {
      timing.duration = timingInput;
    } else if (timingInput !== undefined) {
      Object.getOwnPropertyNames(timingInput).forEach(function(property) {
        if (timingInput[property] != 'auto') {
          if (typeof timing[property] == 'number' || property == 'duration') {
            if (typeof timingInput[property] != 'number' || isNaN(timingInput[property])) {
              return;
            }
          }
          if ((property == 'fill') && (fills.indexOf(timingInput[property]) == -1)) {
            return;
          }
          if ((property == 'direction') && (directions.indexOf(timingInput[property]) == -1)) {
            return;
          }
          if (property == 'playbackRate' && timingInput[property] !== 1 && shared.isDeprecated('AnimationEffectTiming.playbackRate', '2014-11-28', 'Use Animation.playbackRate instead.')) {
            return;
          }
          timing[property] = timingInput[property];
        }
      });
    }
    return timing;
  }

  function numericTimingToObject(timingInput) {
    if (typeof timingInput == 'number') {
      if (isNaN(timingInput)) {
        timingInput = { duration: 0 };
      } else {
        timingInput = { duration: timingInput };
      }
    }
    return timingInput;
  }

  function normalizeTimingInput(timingInput, forGroup) {
    timingInput = shared.numericTimingToObject(timingInput);
    return makeTiming(timingInput, forGroup);
  }

  function cubic(a, b, c, d) {
    if (a < 0 || a > 1 || c < 0 || c > 1) {
      return linear;
    }
    return function(x) {
      if (x == 0 || x == 1) {
        return x;
      }
      var start = 0, end = 1;
      while (1) {
        var mid = (start + end) / 2;
        function f(a, b, m) { return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m};
        var xEst = f(a, c, mid);
        if (Math.abs(x - xEst) < 0.0001) {
          return f(b, d, mid);
        }
        if (xEst < x) {
          start = mid;
        } else {
          end = mid;
        }
      }
    }
  }

  var Start = 1;
  var Middle = 0.5;
  var End = 0;

  function step(count, pos) {
    return function(x) {
      if (x >= 1) {
        return 1;
      }
      var stepSize = 1 / count;
      x += pos * stepSize;
      return x - x % stepSize;
    }
  }

  var presets = {
    'ease': cubic(0.25, 0.1, 0.25, 1),
    'ease-in': cubic(0.42, 0, 1, 1),
    'ease-out': cubic(0, 0, 0.58, 1),
    'ease-in-out': cubic(0.42, 0, 0.58, 1),
    'step-start': step(1, Start),
    'step-middle': step(1, Middle),
    'step-end': step(1, End)
  };

  var styleForCleaning = null;
  var numberString = '\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*';
  var cubicBezierRe = new RegExp('cubic-bezier\\(' + numberString + ',' + numberString + ',' + numberString + ',' + numberString + '\\)');
  var stepRe = /steps\(\s*(\d+)\s*,\s*(start|middle|end)\s*\)/;

  function toTimingFunction(easing) {
    if (!styleForCleaning) {
      styleForCleaning = document.createElement('div').style;
    }
    styleForCleaning.animationTimingFunction = '';
    styleForCleaning.animationTimingFunction = easing;
    var validatedEasing = styleForCleaning.animationTimingFunction;

    if (validatedEasing == '' && isInvalidTimingDeprecated()) {
      throw new TypeError(easing + ' is not a valid value for easing');
    }

    var cubicData = cubicBezierRe.exec(validatedEasing);
    if (cubicData) {
      return cubic.apply(this, cubicData.slice(1).map(Number));
    }
    var stepData = stepRe.exec(validatedEasing);
    if (stepData) {
      return step(Number(stepData[1]), {'start': Start, 'middle': Middle, 'end': End}[stepData[2]]);
    }
    var preset = presets[validatedEasing];
    if (preset) {
      return preset;
    }
    return linear;
  };

  function calculateActiveDuration(timing) {
    return Math.abs(repeatedDuration(timing) / timing.playbackRate);
  }

  function repeatedDuration(timing) {
    return timing.duration * timing.iterations;
  }

  var PhaseNone = 0;
  var PhaseBefore = 1;
  var PhaseAfter = 2;
  var PhaseActive = 3;

  function calculatePhase(activeDuration, localTime, timing) {
    if (localTime == null) {
      return PhaseNone;
    }
    if (localTime < timing.delay) {
      return PhaseBefore;
    }
    if (localTime >= timing.delay + activeDuration) {
      return PhaseAfter;
    }
    return PhaseActive;
  }

  function calculateActiveTime(activeDuration, fillMode, localTime, phase, delay) {
    switch (phase) {
      case PhaseBefore:
        if (fillMode == 'backwards' || fillMode == 'both')
          return 0;
        return null;
      case PhaseActive:
        return localTime - delay;
      case PhaseAfter:
        if (fillMode == 'forwards' || fillMode == 'both')
          return activeDuration;
        return null;
      case PhaseNone:
        return null;
    }
  }

  function calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing) {
    return (timing.playbackRate < 0 ? activeTime - activeDuration : activeTime) * timing.playbackRate + startOffset;
  }

  function calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, timing) {
    if (scaledActiveTime === Infinity || scaledActiveTime === -Infinity || (scaledActiveTime - startOffset == repeatedDuration && timing.iterations && ((timing.iterations + timing.iterationStart) % 1 == 0))) {
      return iterationDuration;
    }

    return scaledActiveTime % iterationDuration;
  }

  function calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, timing) {
    if (scaledActiveTime === 0) {
      return 0;
    }
    if (iterationTime == iterationDuration) {
      return timing.iterationStart + timing.iterations - 1;
    }
    return Math.floor(scaledActiveTime / iterationDuration);
  }

  function calculateTransformedTime(currentIteration, iterationDuration, iterationTime, timing) {
    var currentIterationIsOdd = currentIteration % 2 >= 1;
    var currentDirectionIsForwards = timing.direction == 'normal' || timing.direction == (currentIterationIsOdd ? 'alternate-reverse' : 'alternate');
    var directedTime = currentDirectionIsForwards ? iterationTime : iterationDuration - iterationTime;
    var timeFraction = directedTime / iterationDuration;
    return iterationDuration * timing._easingFunction(timeFraction);
  }

  function calculateTimeFraction(activeDuration, localTime, timing) {
    var phase = calculatePhase(activeDuration, localTime, timing);
    var activeTime = calculateActiveTime(activeDuration, timing.fill, localTime, phase, timing.delay);
    if (activeTime === null)
      return null;
    if (activeDuration === 0)
      return phase === PhaseBefore ? 0 : 1;
    var startOffset = timing.iterationStart * timing.duration;
    var scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing);
    var iterationTime = calculateIterationTime(timing.duration, repeatedDuration(timing), scaledActiveTime, startOffset, timing);
    var currentIteration = calculateCurrentIteration(timing.duration, iterationTime, scaledActiveTime, timing);
    return calculateTransformedTime(currentIteration, timing.duration, iterationTime, timing) / timing.duration;
  }

  shared.cloneTimingInput = cloneTimingInput;
  shared.makeTiming = makeTiming;
  shared.numericTimingToObject = numericTimingToObject;
  shared.normalizeTimingInput = normalizeTimingInput;
  shared.calculateActiveDuration = calculateActiveDuration;
  shared.calculateTimeFraction = calculateTimeFraction;
  shared.calculatePhase = calculatePhase;
  shared.toTimingFunction = toTimingFunction;

  if (WEB_ANIMATIONS_TESTING) {
    testing.normalizeTimingInput = normalizeTimingInput;
    testing.toTimingFunction = toTimingFunction;
    testing.calculateActiveDuration = calculateActiveDuration;
    testing.calculatePhase = calculatePhase;
    testing.PhaseNone = PhaseNone;
    testing.PhaseBefore = PhaseBefore;
    testing.PhaseActive = PhaseActive;
    testing.PhaseAfter = PhaseAfter;
    testing.calculateActiveTime = calculateActiveTime;
    testing.calculateScaledActiveTime = calculateScaledActiveTime;
    testing.calculateIterationTime = calculateIterationTime;
    testing.calculateCurrentIteration = calculateCurrentIteration;
    testing.calculateTransformedTime = calculateTransformedTime;
  }

})(webAnimationsShared, webAnimationsTesting);
<commit_msg>No double nesting<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(shared, testing) {

  var fills = 'backwards|forwards|both|none'.split('|');
  var directions = 'reverse|alternate|alternate-reverse'.split('|');
  var linear = function(x) { return x; };

  function cloneTimingInput(timingInput) {
    if (typeof timingInput == 'number') {
      return timingInput;
    }
    var clone = {};
    for (var m in timingInput) {
      clone[m] = timingInput[m];
    }
    return clone;
  }

  function AnimationEffectTiming() {
    this._delay = 0;
    this._endDelay = 0;
    this._fill = 'none';
    this._iterationStart = 0;
    this._iterations = 1;
    this._duration = 0;
    this._playbackRate = 1;
    this._direction = 'normal';
    this._easing = 'linear';
    this._easingFunction = linear;
  }

  function isInvalidTimingDeprecated() {
    return shared.isDeprecated('Invalid timing inputs', '2016-03-02', 'TypeError exceptions will be thrown instead.', true);
  }

  AnimationEffectTiming.prototype = {
    _setMember: function(member, value) {
      this['_' + member] = value;
      if (this._effect) {
        this._effect._timingInput[member] = value;
        this._effect._timing = shared.normalizeTimingInput(this._effect._timingInput);
        this._effect.activeDuration = shared.calculateActiveDuration(this._effect._timing);
        if (this._effect._animation) {
          this._effect._animation._rebuildUnderlyingAnimation();
        }
      }
    },
    get playbackRate() {
      return this._playbackRate;
    },
    set delay(value) {
      this._setMember('delay', value);
    },
    get delay() {
      return this._delay;
    },
    set endDelay(value) {
      this._setMember('endDelay', value);
    },
    get endDelay() {
      return this._endDelay;
    },
    set fill(value) {
      this._setMember('fill', value);
    },
    get fill() {
      return this._fill;
    },
    set iterationStart(value) {
      if ((isNaN(value) || value < 0) && isInvalidTimingDeprecated()) {
        throw new TypeError('iterationStart must be a non-negative number, received: ' + timing.iterationStart);
      }
      this._setMember('iterationStart', value);
    },
    get iterationStart() {
      return this._iterationStart;
    },
    set duration(value) {
      if (value != 'auto' && (isNaN(value) || value < 0) && isInvalidTimingDeprecated()) {
        throw new TypeError('duration must be non-negative or auto, received: ' + value);
      }
      this._setMember('duration', value);
    },
    get duration() {
      return this._duration;
    },
    set direction(value) {
      this._setMember('direction', value);
    },
    get direction() {
      return this._direction;
    },
    set easing(value) {
      this._easingFunction = toTimingFunction(value);
      this._setMember('easing', value);
    },
    get easing() {
      return this._easing;
    },
    set iterations(value) {
      if ((isNaN(value) || value < 0) && isInvalidTimingDeprecated()) {
        throw new TypeError('iterations must be non-negative, received: ' + value);
      }
      this._setMember('iterations', value);
    },
    get iterations() {
      return this._iterations;
    }
  };

  function makeTiming(timingInput, forGroup, effect) {
    var timing = new AnimationEffectTiming();
    if (forGroup) {
      timing.fill = 'both';
      timing.duration = 'auto';
    }
    if (typeof timingInput == 'number' && !isNaN(timingInput)) {
      timing.duration = timingInput;
    } else if (timingInput !== undefined) {
      Object.getOwnPropertyNames(timingInput).forEach(function(property) {
        if (timingInput[property] != 'auto') {
          if (typeof timing[property] == 'number' || property == 'duration') {
            if (typeof timingInput[property] != 'number' || isNaN(timingInput[property])) {
              return;
            }
          }
          if ((property == 'fill') && (fills.indexOf(timingInput[property]) == -1)) {
            return;
          }
          if ((property == 'direction') && (directions.indexOf(timingInput[property]) == -1)) {
            return;
          }
          if (property == 'playbackRate' && timingInput[property] !== 1 && shared.isDeprecated('AnimationEffectTiming.playbackRate', '2014-11-28', 'Use Animation.playbackRate instead.')) {
            return;
          }
          timing[property] = timingInput[property];
        }
      });
    }
    return timing;
  }

  function numericTimingToObject(timingInput) {
    if (typeof timingInput == 'number') {
      if (isNaN(timingInput)) {
        timingInput = { duration: 0 };
      } else {
        timingInput = { duration: timingInput };
      }
    }
    return timingInput;
  }

  function normalizeTimingInput(timingInput, forGroup) {
    timingInput = shared.numericTimingToObject(timingInput);
    return makeTiming(timingInput, forGroup);
  }

  function cubic(a, b, c, d) {
    if (a < 0 || a > 1 || c < 0 || c > 1) {
      return linear;
    }
    return function(x) {
      if (x == 0 || x == 1) {
        return x;
      }
      var start = 0, end = 1;
      while (1) {
        var mid = (start + end) / 2;
        function f(a, b, m) { return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m};
        var xEst = f(a, c, mid);
        if (Math.abs(x - xEst) < 0.0001) {
          return f(b, d, mid);
        }
        if (xEst < x) {
          start = mid;
        } else {
          end = mid;
        }
      }
    }
  }

  var Start = 1;
  var Middle = 0.5;
  var End = 0;

  function step(count, pos) {
    return function(x) {
      if (x >= 1) {
        return 1;
      }
      var stepSize = 1 / count;
      x += pos * stepSize;
      return x - x % stepSize;
    }
  }

  var presets = {
    'ease': cubic(0.25, 0.1, 0.25, 1),
    'ease-in': cubic(0.42, 0, 1, 1),
    'ease-out': cubic(0, 0, 0.58, 1),
    'ease-in-out': cubic(0.42, 0, 0.58, 1),
    'step-start': step(1, Start),
    'step-middle': step(1, Middle),
    'step-end': step(1, End)
  };

  var styleForCleaning = null;
  var numberString = '\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*';
  var cubicBezierRe = new RegExp('cubic-bezier\\(' + numberString + ',' + numberString + ',' + numberString + ',' + numberString + '\\)');
  var stepRe = /steps\(\s*(\d+)\s*,\s*(start|middle|end)\s*\)/;

  function toTimingFunction(easing) {
    if (!styleForCleaning) {
      styleForCleaning = document.createElement('div').style;
    }
    styleForCleaning.animationTimingFunction = '';
    styleForCleaning.animationTimingFunction = easing;
    var validatedEasing = styleForCleaning.animationTimingFunction;

    if (validatedEasing == '' && isInvalidTimingDeprecated()) {
      throw new TypeError(easing + ' is not a valid value for easing');
    }

    var cubicData = cubicBezierRe.exec(validatedEasing);
    if (cubicData) {
      return cubic.apply(this, cubicData.slice(1).map(Number));
    }
    var stepData = stepRe.exec(validatedEasing);
    if (stepData) {
      return step(Number(stepData[1]), {'start': Start, 'middle': Middle, 'end': End}[stepData[2]]);
    }
    var preset = presets[validatedEasing];
    if (preset) {
      return preset;
    }
    return linear;
  };

  function calculateActiveDuration(timing) {
    return Math.abs(repeatedDuration(timing) / timing.playbackRate);
  }

  function repeatedDuration(timing) {
    return timing.duration * timing.iterations;
  }

  var PhaseNone = 0;
  var PhaseBefore = 1;
  var PhaseAfter = 2;
  var PhaseActive = 3;

  function calculatePhase(activeDuration, localTime, timing) {
    if (localTime == null) {
      return PhaseNone;
    }
    if (localTime < timing.delay) {
      return PhaseBefore;
    }
    if (localTime >= timing.delay + activeDuration) {
      return PhaseAfter;
    }
    return PhaseActive;
  }

  function calculateActiveTime(activeDuration, fillMode, localTime, phase, delay) {
    switch (phase) {
      case PhaseBefore:
        if (fillMode == 'backwards' || fillMode == 'both')
          return 0;
        return null;
      case PhaseActive:
        return localTime - delay;
      case PhaseAfter:
        if (fillMode == 'forwards' || fillMode == 'both')
          return activeDuration;
        return null;
      case PhaseNone:
        return null;
    }
  }

  function calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing) {
    return (timing.playbackRate < 0 ? activeTime - activeDuration : activeTime) * timing.playbackRate + startOffset;
  }

  function calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, timing) {
    if (scaledActiveTime === Infinity || scaledActiveTime === -Infinity || (scaledActiveTime - startOffset == repeatedDuration && timing.iterations && ((timing.iterations + timing.iterationStart) % 1 == 0))) {
      return iterationDuration;
    }

    return scaledActiveTime % iterationDuration;
  }

  function calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, timing) {
    if (scaledActiveTime === 0) {
      return 0;
    }
    if (iterationTime == iterationDuration) {
      return timing.iterationStart + timing.iterations - 1;
    }
    return Math.floor(scaledActiveTime / iterationDuration);
  }

  function calculateTransformedTime(currentIteration, iterationDuration, iterationTime, timing) {
    var currentIterationIsOdd = currentIteration % 2 >= 1;
    var currentDirectionIsForwards = timing.direction == 'normal' || timing.direction == (currentIterationIsOdd ? 'alternate-reverse' : 'alternate');
    var directedTime = currentDirectionIsForwards ? iterationTime : iterationDuration - iterationTime;
    var timeFraction = directedTime / iterationDuration;
    return iterationDuration * timing._easingFunction(timeFraction);
  }

  function calculateTimeFraction(activeDuration, localTime, timing) {
    var phase = calculatePhase(activeDuration, localTime, timing);
    var activeTime = calculateActiveTime(activeDuration, timing.fill, localTime, phase, timing.delay);
    if (activeTime === null)
      return null;
    if (activeDuration === 0)
      return phase === PhaseBefore ? 0 : 1;
    var startOffset = timing.iterationStart * timing.duration;
    var scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing);
    var iterationTime = calculateIterationTime(timing.duration, repeatedDuration(timing), scaledActiveTime, startOffset, timing);
    var currentIteration = calculateCurrentIteration(timing.duration, iterationTime, scaledActiveTime, timing);
    return calculateTransformedTime(currentIteration, timing.duration, iterationTime, timing) / timing.duration;
  }

  shared.cloneTimingInput = cloneTimingInput;
  shared.makeTiming = makeTiming;
  shared.numericTimingToObject = numericTimingToObject;
  shared.normalizeTimingInput = normalizeTimingInput;
  shared.calculateActiveDuration = calculateActiveDuration;
  shared.calculateTimeFraction = calculateTimeFraction;
  shared.calculatePhase = calculatePhase;
  shared.toTimingFunction = toTimingFunction;

  if (WEB_ANIMATIONS_TESTING) {
    testing.normalizeTimingInput = normalizeTimingInput;
    testing.toTimingFunction = toTimingFunction;
    testing.calculateActiveDuration = calculateActiveDuration;
    testing.calculatePhase = calculatePhase;
    testing.PhaseNone = PhaseNone;
    testing.PhaseBefore = PhaseBefore;
    testing.PhaseActive = PhaseActive;
    testing.PhaseAfter = PhaseAfter;
    testing.calculateActiveTime = calculateActiveTime;
    testing.calculateScaledActiveTime = calculateScaledActiveTime;
    testing.calculateIterationTime = calculateIterationTime;
    testing.calculateCurrentIteration = calculateCurrentIteration;
    testing.calculateTransformedTime = calculateTransformedTime;
  }

})(webAnimationsShared, webAnimationsTesting);
<|endoftext|>


<commit_before>/** @module reflect-helpers */

(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root._R = factory();
}
}(this, function () {
var _R = {};
var indirectEval;
(function wow(){
   (1,eval)('var wow = 3');
   if (typeof wow === 'number') {
      indirectEval = function indirectEval(code) {
         return Function('code', 'return eval(code)')(code)
      }
   } else {
      indirectEval = eval;
   }
})();
var getNaiveFunctionSourceCode = Function.call.bind(Function.toString);

 _R.__directives = ['', 'use strict', 'use asm'];

 _R.DIRECTIVE_NORMAL = 0;
 _R.DIRECTIVE_STRICT = 1;
 _R.DIRECTIVE_ASM    = 2;

 /*
  * Changes directives used by created functions
 * @method
 * @param {integer|string} directive - directive to be used
 * @returns {boolean}
 */

 _R.$setDirective = function (directive) {
    if (typeof directive === 'number') {
        _R.__directive = JSON.stringify(_R.__directives[directive] || '');
    } else {
        _R.__directive = JSON.stringify(directive);
    }
 };

 _R.__directive = '';
 _R.$setDirective(_R.DIRECTIVE_STRICT);
/**
 * Tests variable name against current implementation rules.
 * " If you were to summarize all these rules in a single ASCII-only regular expression for JavaScript, it would be 11,236 characters long."
 * @method
 * @param {string} name - string to be tested
 * @returns {boolean}
 */

_R.isValidVariableName = function isValidVariableName(name) {
    try {
        Function(name, '');
    }
    catch (e) {
        return false;
    }
    return true;
}

function NativeFunctionSuppliedError() {
    var ret = Object.create(new Error());
    ret.message = '_R does not support native or bound functions as arguments!';
    ret.name = 'NativeFunctionSuppliedError';
    return ret;
}

_R.__boundFunction = (function(){}).bind(null);

/**
 * Tests if function is native or bound
 * @method
 * @param {function} func - function to be stringified
 * @throws {TypeError} when func isn't a function
 * @returns {boolean}
 */

_R.isBoundOrNativeFunction = function isBoundOrNativeFunction(func) {
    return getNaiveFunctionSourceCode(func) === getNaiveFunctionSourceCode(func.bind(null));
};

/**
 * Returns source code of function or throws error when it's impossible to retrieve
 * @method
 * @param {function} func - function to be stringified
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 * @returns {string}
 */

_R.getFunctionSourceCode = function getFunctionSourceCode(func) {
    var source = Function.toString.call(func);
    if (_R.isBoundOrNativeFunction(func)) {
        throw new NativeFunctionSuppliedError();
    }
    return source;
};

/**
 * Returns [[Class]] of what
 * @method
 * @param what - Object or primitive to be inspected
 */

_R.getInternalClass = function (what) {
    return Object.prototype.toString.call(what).match(/^\[object\s(.*)\]$/)[1];
};

/**
 * Returns function redefined in global context
 * @method
 * @param {function} func - function to be redefined
 * @param {function} [transformer] - transformation function applied to function source code. function callback(sourceCode, func)
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.declosureFunction = function(func, transformer) {
    transformer = transformer || function(a) {return a};
    return indirectEval('('+transformer(_R.getFunctionSourceCode(func), func)+')');
}

/**
 * Creates named function using Function constructor
 * @method
 * @param {string} name - function name (exists in function scope, used for recursive calls, shouldn't be confused with function.name property)
 * @param {...string} restArgs - arguments to Function constructor
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.createNamedFunction = function createNamedFunction(name, restArgs) {
    name = ''+name || 'anonymous';
    if (!_R.isValidVariableName(name)) {
        throw new NativeFunctionSuppliedError();
    }
    restArgs = Array.prototype.slice.call(arguments, 1);
    return _R.declosureFunction(
            function($$$1){
                $$$directive;
                $$$1 = $$$2;
                return $$$1;
            },
            function transformSource(sourceCode){
                return sourceCode
                    .replace('$$$1', name, 'g')
                    .replace('$$$directive', _R.__directive)
                    .replace('$$$2', '('+_R.getFunctionSourceCode(Function.apply(null, restArgs))+')', 'g');
            }
    )();
};

/**
 * Redefines function in context of given object;
 * Default function name is
 * @method
 * @param {function} func - function name (exists in function scope, shouldn't be confused with function.name property)
 * @param {Object} [context] - context of new function
 * @param {string} [name] - name of new function (defaults to 'anonymous' (will NOT shadow arguments from context))
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.createClosure = function createClosure(func, context, name) {
    context = context || {};
    name = isValidVariableName(name) ? name : 'anonymous';
    var varsList = [];
    var argumentsNames;
    var argumentsValues;
    for (var key in context) {
        if (Object.hasOwnProperty.call(context, key) && _R.isValidVariableName(key)) {
            argumentsNames.push({name: key, val: context[key]});
        }
    }
    var argumentsNames  = varsList.map(function(el){return el.name});
    var argumentsValues = varsList.map(function(el){return el.val});
    var sourceCode = _R.__directive+';\n var '+name+ '= ('+_R.getFunctionSourceCode(func)+'); return '+name+';';

    return Function.apply(null, argumentsNames.concat(sourceCode)).apply(null, argumentsValues);
};

/**
 * Returns prototype of first argument
 * If argument isn't an object, returns null
 * Can return invalid object in IE8 and lower.
 * @method
 * @param {*} what
 * @returns {Object?} returns object or null
 */

_R.getObjectPrototype = function getObjectPrototype(what) {
    if (typeof what !== 'object' || typeof what !== 'function') {
        return null;
    }
    if (Object.getPrototypeOf) {
        return Object.getPrototypeOf(what);
    }
    else if (({}).__proto__) {
        return what.__proto__
    }
    else {
        // This branch doesn't work in certain cases

        // check against null and undefined
        // != test is intentional
        if (what != null) {
            return what.constructor ? (what.constructor.prototype || null) : null;
        }
    }
    return null;
}

/**
 * Returns array of objects existing in prototype chains
 * @method
 * @param {*} what
 * @returns {Object*}
 */

_R.getPrototypesChain = function getPrototypesChain(what) {
    var prototypesList = [];
    do {
        prototypesList.push(what);
    } while (what = _R.getObjectPrototype(what) && prototypesList.indexOf(what) !== -1);
    return prototypesList;
};

_R.toString = function() {
    return '[Object _R]';
};

return _R;
}));<commit_msg>What I have done?<commit_after>/** @module reflect-helpers */

(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root._R = factory();
}
}(this, function () {
var _R = {};
var indirectEval;
(function wow(){
   (1,eval)('var wow = 3');
   if (typeof wow === 'number') {
      indirectEval = function indirectEval(code) {
         return Function('code', 'return eval(code)')(code)
      }
   } else {
      indirectEval = eval;
   }
})();
var getNaiveFunctionSourceCode = Function.call.bind(Function.toString);

 _R.__directives = ['', 'use strict', 'use asm'];

 _R.DIRECTIVE_NORMAL = 0;
 _R.DIRECTIVE_STRICT = 1;
 _R.DIRECTIVE_ASM    = 2;

 /*
  * Changes directives used by created functions
 * @method
 * @param {integer|string} directive - directive to be used
 * @returns {boolean}
 */

 _R.$setDirective = function (directive) {
    if (typeof directive === 'number') {
        _R.__directive = JSON.stringify(_R.__directives[directive] || '');
    } else {
        _R.__directive = JSON.stringify(directive);
    }
 };

 _R.__directive = '';
 _R.$setDirective(_R.DIRECTIVE_STRICT);
/**
 * Tests variable name against current implementation rules.
 * " If you were to summarize all these rules in a single ASCII-only regular expression for JavaScript, it would be 11,236 characters long."
 * @method
 * @param {string} name - string to be tested
 * @returns {boolean}
 */

_R.isValidVariableName = function isValidVariableName(name) {
    try {
        Function(name, '');
    }
    catch (e) {
        return false;
    }
    return true;
}

function NativeFunctionSuppliedError() {
    var ret = Object.create(new Error());
    ret.message = '_R does not support native or bound functions as arguments!';
    ret.name = 'NativeFunctionSuppliedError';
    return ret;
}

_R.__boundFunction = (function(){}).bind(null);

/**
 * Tests if function is native or bound
 * @method
 * @param {function} func - function to be stringified
 * @throws {TypeError} when func isn't a function
 * @returns {boolean}
 */

_R.isBoundOrNativeFunction = function isBoundOrNativeFunction(func) {
    return getNaiveFunctionSourceCode(func) === getNaiveFunctionSourceCode(func.bind(null));
};

/**
 * Returns source code of function or throws error when it's impossible to retrieve
 * @method
 * @param {function} func - function to be stringified
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 * @returns {string}
 */

_R.getFunctionSourceCode = function getFunctionSourceCode(func) {
    var source = Function.toString.call(func);
    if (_R.isBoundOrNativeFunction(func)) {
        throw new NativeFunctionSuppliedError();
    }
    return source;
};

/**
 * Returns [[Class]] of what
 * @method
 * @param what - Object or primitive to be inspected
 */

_R.getInternalClass = function (what) {
    return Object.prototype.toString.call(what).match(/^\[object\s(.*)\]$/)[1];
};

/**
 * Returns function redefined in global context
 * @method
 * @param {function} func - function to be redefined
 * @param {function} [transformer] - transformation function applied to function source code. function callback(sourceCode, func)
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.declosureFunction = function(func, transformer) {
    transformer = transformer || function(a) {return a};
    return indirectEval('('+transformer(_R.getFunctionSourceCode(func), func)+')');
}

/**
 * Creates named function using Function constructor
 * @method
 * @param {string} name - function name (exists in function scope, used for recursive calls, shouldn't be confused with function.name property)
 * @param {...string} restArgs - arguments to Function constructor
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.createNamedFunction = function createNamedFunction(name, restArgs) {
    name = ''+name || 'anonymous';
    if (!_R.isValidVariableName(name)) {
        throw new NativeFunctionSuppliedError();
    }
    restArgs = Array.prototype.slice.call(arguments, 1);
    return _R.declosureFunction(
            function($$$1){
                $$$directive;
                $$$1 = $$$2;
                return $$$1;
            },
            function transformSource(sourceCode){
                return sourceCode
                    .replace('$$$1', name, 'g')
                    .replace('$$$directive', _R.__directive)
                    .replace('$$$2', '('+_R.getFunctionSourceCode(Function.apply(null, restArgs))+')', 'g');
            }
    )();
};

/**
 * Redefines function in context of given object;
 * Default function name is
 * @method
 * @param {function} func - function name (exists in function scope, shouldn't be confused with function.name property)
 * @param {Object} [context] - context of new function
 * @param {string} [name] - name of new function (defaults to 'anonymous' (will NOT shadow arguments from context))
 * @throws {NativeFunctionSuppliedError} for bound functions and native code functions
 */

_R.createClosure = function createClosure(func, context, name) {
    context = context || {};
    name = isValidVariableName(name) ? name : 'anonymous';
    var argumentsNames  = [];
    var argumentsValues = [];
    for (var key in context) {
        if (Object.hasOwnProperty.call(context, key) && _R.isValidVariableName(key)) {
            argumentsNames.push(key);
            argumentsValues.push(context[key])
        }
    }

    var sourceCode = _R.__directive+';\n var '+name+ '= ('+_R.getFunctionSourceCode(func)+'); return '+name+';';

    return Function.apply(null, argumentsNames.concat(sourceCode)).apply(null, argumentsValues);
};

/**
 * Returns prototype of first argument
 * If argument isn't an object, returns null
 * Can return invalid object in IE8 and lower.
 * @method
 * @param {*} what
 * @returns {Object?} returns object or null
 */

_R.getObjectPrototype = function getObjectPrototype(what) {
    if (typeof what !== 'object' || typeof what !== 'function') {
        return null;
    }
    if (Object.getPrototypeOf) {
        return Object.getPrototypeOf(what);
    }
    else if (({}).__proto__) {
        return what.__proto__
    }
    else {
        // This branch doesn't work in certain cases

        // check against null and undefined
        // != test is intentional
        if (what != null) {
            return what.constructor ? (what.constructor.prototype || null) : null;
        }
    }
    return null;
}

/**
 * Returns array of objects existing in prototype chains
 * @method
 * @param {*} what
 * @returns {Object*}
 */

_R.getPrototypesChain = function getPrototypesChain(what) {
    var prototypesList = [];
    do {
        prototypesList.push(what);
    } while (what = _R.getObjectPrototype(what) && prototypesList.indexOf(what) !== -1);
    return prototypesList;
};

_R.toString = function() {
    return '[Object _R]';
};

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


<commit_before>'use strict'

import Morph from './Morph.js';

export default class TabView extends Morph {
  /*
   * HTMLElement callbacks
   */
  attachedCallback() {
    this.tabBar = this.shadowRoot.querySelector('#tab-bar');

    this.tabList = [];
    this.initObserver();

    this.renderTabBar();
    this.hideAllContents();
    this.showDefaultContent();
  }

  detachedCallback() {
    if (this.contentObserver) {
      this.contentObserver.disconnect();
    }
  }

  attributeChangedCallback(attrName, oldValue, newValue) {

  }

  initObserver() {
    this.contentObserver = new MutationObserver((record) => this.observerCallback(record));
    this.contentObserver.observe(this, {childList: true});
  }

  observerCallback(mutationRecord) {
    this.renderTabBar();
    this.hideAllContents();
    this.showDefaultContent();
  }

  renderTabBar() {
    let contentViews = this.children;
    this.tabList = [];

    if(this.tabBar.hasChildNodes()) {
      let bars = this.tabBar.querySelectorAll('*');

      for(let i = 0; i < bars.length; i++) {
        let bar = bars[i];
        bar.remove();
      }
    }

    for(let i = 0; i < contentViews.length; i++) {
      let view = contentViews[i];
      let title = "";

      if(view.hasAttribute('title')) {
        title = view.getAttribute('title');
      } else {
        title = "TAB[" + i + "]";
      }

      this.tabList[i] = {
        title: title,
        view: view
      };

      let barTitle = document.createElement('span');
      let tab = document.createElement('li');
      barTitle.innerHTML = title;
      barTitle.addEventListener('click', (e) => {
        this.showContent(i);

        let changeEvent = new CustomEvent("tabChange", {
          detail: {
            title: title,
            id: view.id
          }
        });
        this.dispatchEvent(changeEvent);
      });
      tab.appendChild(barTitle);
      this.tabBar.appendChild(tab);
    }
  }

  showContent(i) {
    let tab = this.tabList[i];

    for (let n = 0; n < this.tabBar.children.length; n++) {
      if (n === i) {
        this.tabBar.children[n].classList.add('active');
      } else {
        this.tabBar.children[n].classList.remove('active');
      }
    }
    this.tabBar.querySelector(':nth-child('+i+')')

    this.hideAllContents();
    this.showElement(tab.view);
  }

  hideAllContents() {
    for(let tab of this.tabList) {
      this.hideElement(tab.view);
    }
  }

  showDefaultContent() {
    if(this.tabList.length > 0) {
      this.showContent(0);
    }
  }

  hideElement(element) {
    element.classList.add("tab-view-inactive");
  }

  showElement(element) {
    element.classList.remove("tab-view-inactive");
  }
}
<commit_msg>tab view now observes its children title attributes<commit_after>'use strict'

import Morph from './Morph.js';

export default class TabView extends Morph {
  /*
   * HTMLElement callbacks
   */
  attachedCallback() {
    this.tabBar = this.shadowRoot.querySelector('#tab-bar');

    this.tabList = [];
    this.initObserver();

    this.renderTabBar();
    this.hideAllContents();
    this.showDefaultContent();
  }

  detachedCallback() {
    if (this.contentObserver) {
      this.contentObserver.disconnect();
    }
  }

  attributeChangedCallback(attrName, oldValue, newValue) {

  }

  initObserver() {
    this.contentObserver = new MutationObserver((record) => this.observerCallback(record));

    //observe for added/removed tab elements
    this.contentObserver.observe(this, {
      childList: true
    });

    //observe each tab element for title changes
    for(let i = 0; i < this.children.length; i++) {
      let child = this.children[i];

      this.contentObserver.observe(child, {
        attributes: true,
        attributeFilter: ['title']
      });
    }
  }

  reInitObserver() {
    this.contentObserver.disconnect();
    this.initObserver();
  }

  observerCallback(mutationRecord) {
    this.renderTabBar();
    this.hideAllContents();
    this.showDefaultContent();

    this.reInitObserver();
  }

  renderTabBar() {
    let contentViews = this.children;
    this.tabList = [];

    if(this.tabBar.hasChildNodes()) {
      let bars = this.tabBar.querySelectorAll('*');

      for(let i = 0; i < bars.length; i++) {
        let bar = bars[i];
        bar.remove();
      }
    }

    for(let i = 0; i < contentViews.length; i++) {
      let view = contentViews[i];
      let title = "";

      if(view.hasAttribute('title')) {
        title = view.getAttribute('title');
      } else {
        title = "TAB[" + i + "]";
      }

      this.tabList[i] = {
        title: title,
        view: view
      };

      let barTitle = document.createElement('span');
      let tab = document.createElement('li');
      barTitle.innerHTML = title;
      barTitle.addEventListener('click', (e) => {
        this.showContent(i);

        let changeEvent = new CustomEvent("tabChange", {
          detail: {
            title: title,
            id: view.id
          }
        });
        this.dispatchEvent(changeEvent);
      });
      tab.appendChild(barTitle);
      this.tabBar.appendChild(tab);
    }
  }

  showContent(i) {
    let tab = this.tabList[i];

    for (let n = 0; n < this.tabBar.children.length; n++) {
      if (n === i) {
        this.tabBar.children[n].classList.add('active');
      } else {
        this.tabBar.children[n].classList.remove('active');
      }
    }
    this.tabBar.querySelector(':nth-child('+i+')')

    this.hideAllContents();
    this.showElement(tab.view);
  }

  hideAllContents() {
    for(let tab of this.tabList) {
      this.hideElement(tab.view);
    }
  }

  showDefaultContent() {
    if(this.tabList.length > 0) {
      this.showContent(0);
    }
  }

  hideElement(element) {
    element.classList.add("tab-view-inactive");
  }

  showElement(element) {
    element.classList.remove("tab-view-inactive");
  }
}
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var cordova_util = require('./util'),
    ConfigParser = require('../configparser/ConfigParser'),
    path = require('path'),
    Q = require('q'),
    fs = require('fs'),
    plugin = require('./plugin'),
    events = require('../events'),
    cordova = require('./cordova'),
    semver = require('semver'),
    promiseutil = require('../util/promise-util');

exports.installPluginsFromConfigXML = installPluginsFromConfigXML;
exports.installPlatformsFromConfigXML = installPlatformsFromConfigXML;

function installPlatformsFromConfigXML(platforms, opts) {
    var projectHome = cordova_util.cdProjectRoot();
    var configPath = cordova_util.projectConfig(projectHome);
    var cfg = new ConfigParser(configPath);

    var engines = cfg.getEngines(projectHome);
    var installAllPlatforms = !platforms || platforms.length === 0;

    var targets = engines.map(function(engine) {
        var platformPath = path.join(projectHome, 'platforms', engine.name);
        var platformAlreadyAdded = fs.existsSync(platformPath);

        //if no platforms are specified we add all.
        if ((installAllPlatforms || platforms.indexOf(engine.name) > -1) && !platformAlreadyAdded) {
            var t = engine.name;
            if (engine.spec) {
                t += '@' + engine.spec;
            }
            return t;
        }
    });

    if (!targets || !targets.length) {
        return Q.all('No platforms are listed in config.xml to restore');
    }

    // Run `platform add` for all the platforms separately
    // so that failure on one does not affect the other.

    // CB-9278 : Run `platform add` serially, one platform after another
    // Otherwise, we get a bug where the following line: https://github.com/apache/cordova-lib/blob/0b0dee5e403c2c6d4e7262b963babb9f532e7d27/cordova-lib/src/util/npm-helper.js#L39
    // gets executed simultaneously by each platform and leads to an exception being thrown
    return promiseutil.Q_chainmap_graceful(targets, function(target) {
        if (target) {
            events.emit('log', 'Restoring platform ' + target + ' referenced on config.xml');
            return cordova.raw.platform('add', target, opts);
        }
        return Q();
    }, function(err) {
        events.emit('warn', err);
    });
}

//returns a Promise
function installPluginsFromConfigXML(args) {
    //Install plugins that are listed on config.xml
    var projectRoot = cordova_util.cdProjectRoot();
    var configPath = cordova_util.projectConfig(projectRoot);
    var cfg = new ConfigParser(configPath);
    var plugins_dir = path.join(projectRoot, 'plugins');

    // Get all configured plugins
    var plugins = cfg.getPluginIdList();
    if (0 === plugins.length) {
        return Q.all('No config.xml plugins to install');
    }

    var promises = plugins.map(function(featureId) {
        var pluginPath = path.join(plugins_dir, featureId);
        if (fs.existsSync(pluginPath)) {
            // Plugin already exists
            return Q();
        }
        events.emit('log', 'Discovered plugin "' + featureId + '" in config.xml. Installing to the project');
        var pluginEntry = cfg.getPlugin(featureId);

        // Install from given URL if defined or using a plugin id. If spec isn't a valid version or version range,
        // assume it is the location to install from.
        var pluginSpec = pluginEntry.spec;
        var installFrom = semver.validRange(pluginSpec, true) ? pluginEntry.name + '@' + pluginSpec : pluginSpec;

        // Add feature preferences as CLI variables if have any
        var options = {
            cli_variables: pluginEntry.variables,
            searchpath: args.searchpath
        };
        return plugin('add', installFrom, options);
    });
    return Q.allSettled(promises);
}<commit_msg>CB-9560 Issue using plugin restore for plugins with common dependencies (This closes #288)<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var cordova_util = require('./util'),
    ConfigParser = require('../configparser/ConfigParser'),
    path = require('path'),
    Q = require('q'),
    fs = require('fs'),
    plugin = require('./plugin'),
    events = require('../events'),
    cordova = require('./cordova'),
    semver = require('semver'),
    promiseutil = require('../util/promise-util');

exports.installPluginsFromConfigXML = installPluginsFromConfigXML;
exports.installPlatformsFromConfigXML = installPlatformsFromConfigXML;

function installPlatformsFromConfigXML(platforms, opts) {
    var projectHome = cordova_util.cdProjectRoot();
    var configPath = cordova_util.projectConfig(projectHome);
    var cfg = new ConfigParser(configPath);

    var engines = cfg.getEngines(projectHome);
    var installAllPlatforms = !platforms || platforms.length === 0;

    var targets = engines.map(function(engine) {
        var platformPath = path.join(projectHome, 'platforms', engine.name);
        var platformAlreadyAdded = fs.existsSync(platformPath);

        //if no platforms are specified we add all.
        if ((installAllPlatforms || platforms.indexOf(engine.name) > -1) && !platformAlreadyAdded) {
            var t = engine.name;
            if (engine.spec) {
                t += '@' + engine.spec;
            }
            return t;
        }
    });

    if (!targets || !targets.length) {
        return Q.all('No platforms are listed in config.xml to restore');
    }

    // Run `platform add` for all the platforms separately
    // so that failure on one does not affect the other.

    // CB-9278 : Run `platform add` serially, one platform after another
    // Otherwise, we get a bug where the following line: https://github.com/apache/cordova-lib/blob/0b0dee5e403c2c6d4e7262b963babb9f532e7d27/cordova-lib/src/util/npm-helper.js#L39
    // gets executed simultaneously by each platform and leads to an exception being thrown
    return promiseutil.Q_chainmap_graceful(targets, function(target) {
        if (target) {
            events.emit('log', 'Restoring platform ' + target + ' referenced on config.xml');
            return cordova.raw.platform('add', target, opts);
        }
        return Q();
    }, function(err) {
        events.emit('warn', err);
    });
}

//returns a Promise
function installPluginsFromConfigXML(args) {
    //Install plugins that are listed on config.xml
    var projectRoot = cordova_util.cdProjectRoot();
    var configPath = cordova_util.projectConfig(projectRoot);
    var cfg = new ConfigParser(configPath);
    var plugins_dir = path.join(projectRoot, 'plugins');

    // Get all configured plugins
    var plugins = cfg.getPluginIdList();
    if (0 === plugins.length) {
        return Q.all('No config.xml plugins to install');
    }

    // CB-9560 : Run `plugin add` serially, one plugin after another
    // We need to wait for the plugin and its dependencies to be installed
    // before installing the next root plugin otherwise we can have common
    // plugin dependencies installed twice which throws a nasty error.
    return promiseutil.Q_chainmap_graceful(plugins, function(featureId) {
        var pluginPath = path.join(plugins_dir, featureId);
        if (fs.existsSync(pluginPath)) {
            // Plugin already exists
            return Q();
        }
        events.emit('log', 'Discovered plugin "' + featureId + '" in config.xml. Installing to the project');
        var pluginEntry = cfg.getPlugin(featureId);

        // Install from given URL if defined or using a plugin id. If spec isn't a valid version or version range,
        // assume it is the location to install from.
        var pluginSpec = pluginEntry.spec;
        var installFrom = semver.validRange(pluginSpec, true) ? pluginEntry.name + '@' + pluginSpec : pluginSpec;

        // Add feature preferences as CLI variables if have any
        var options = {
            cli_variables: pluginEntry.variables,
            searchpath: args.searchpath
        };
        return plugin('add', installFrom, options);
    });
}<|endoftext|>


<commit_before>/*
 Copyright 2013 Massimo Foti (massimo@massimocorner.com)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
/* global luga */

if(typeof(luga) === "undefined"){
	throw("Unable to find luga.js");
}

(function(){
	"use strict";

	luga.namespace("luga.csi");

	luga.csi.CONST = {
		NODE_SELECTOR: "div[data-luga-csi]",
		URL_ATTRIBUTE: "data-luga-csi",
		AFTER_ATTRIBUTE: "data-luga-after",
		MESSAGES: {
			FILE_NOT_FOUND: "luga.csi failed to retrieve text from: {0}"
		}
	};

	/**
	 * Client-side Include widget
	 *
	 * @param options.rootNode:          Root node for widget (DOM reference). Required
	 * @param options.url:               Url to be included. Optional. Default to the value of the "data-luga-csi" attribute inside rootNode
	 * @param options.success:           Function that will be invoked once the url is successfully fetched. Optional, default to the internal "onSuccess" method
	 * @param options.after  :           Function that will be invoked once the include is successfully performed.
	 *                                   It will be called with the handler(rootNode, url, response) signature. Optional, it can be set using the "data-luga-after" attribute
	 * @param options.error:             Function that will be invoked if the url request fails. Optional, default to the internal "onError" method
	 * @param options.xhrTimeout:        Timeout for XHR call. Optional
	 */
	luga.csi.Include = function(options){
		var self = this;

		this.init = function(){
			jQuery.ajax({
				url: self.config.url,
				timeout: self.config.XHR_TIMEOUT,
				success: function(response, textStatus, jqXHR){
					self.config.success.apply(null, [response, textStatus, jqXHR]);
					var afterHandler = luga.utils.stringToFunction(self.config.after);
					if(afterHandler){
						afterHandler.apply(null, [self.config.rootNode, self.config.url, response]);
					}
				},
				error: function(jqXHR, textStatus, errorThrown){
					self.config.error.apply(null, [jqXHR, textStatus, errorThrown]);
				}
			});
		};

		this.onSuccess = function(response, textStatus, jqXHR){
			jQuery(self.config.rootNode).html(response);
		};

		this.onError = function(qXHR, textStatus, errorThrown){
			throw(luga.utils.formatString(luga.csi.CONST.MESSAGES.FILE_NOT_FOUND, [self.config.url]));
		};

		this.config = {
			url: jQuery(options.rootNode).attr(luga.csi.CONST.URL_ATTRIBUTE),
			after: jQuery(options.rootNode).attr(luga.csi.CONST.AFTER_ATTRIBUTE),
			success: this.onSuccess,
			error: this.onError,
			xhrTimeout: 5000
		};
		luga.merge(this.config, options);
	};

	luga.csi.loadIncludes = function(){
		jQuery(luga.csi.CONST.NODE_SELECTOR).each(function(index, item){
			var includeObj = new luga.csi.Include({rootNode: item});
			includeObj.init();
		});
	};

	jQuery(document).ready(function(){
		luga.csi.loadIncludes();
	});

}());<commit_msg>Added version<commit_after>/*
 Copyright 2013 Massimo Foti (massimo@massimocorner.com)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
/* global luga */

if(typeof(luga) === "undefined"){
	throw("Unable to find luga.js");
}

(function(){
	"use strict";

	luga.namespace("luga.csi");

	luga.csi.version = 0.8;

	luga.csi.CONST = {
		NODE_SELECTOR: "div[data-luga-csi]",
		URL_ATTRIBUTE: "data-luga-csi",
		AFTER_ATTRIBUTE: "data-luga-after",
		MESSAGES: {
			FILE_NOT_FOUND: "luga.csi failed to retrieve text from: {0}"
		}
	};

	/**
	 * Client-side Include widget
	 *
	 * @param options.rootNode:          Root node for widget (DOM reference). Required
	 * @param options.url:               Url to be included. Optional. Default to the value of the "data-luga-csi" attribute inside rootNode
	 * @param options.success:           Function that will be invoked once the url is successfully fetched. Optional, default to the internal "onSuccess" method
	 * @param options.after  :           Function that will be invoked once the include is successfully performed.
	 *                                   It will be called with the handler(rootNode, url, response) signature. Optional, it can be set using the "data-luga-after" attribute
	 * @param options.error:             Function that will be invoked if the url request fails. Optional, default to the internal "onError" method
	 * @param options.xhrTimeout:        Timeout for XHR call. Optional
	 */
	luga.csi.Include = function(options){
		var self = this;

		this.init = function(){
			jQuery.ajax({
				url: self.config.url,
				timeout: self.config.XHR_TIMEOUT,
				success: function(response, textStatus, jqXHR){
					self.config.success.apply(null, [response, textStatus, jqXHR]);
					var afterHandler = luga.utils.stringToFunction(self.config.after);
					if(afterHandler){
						afterHandler.apply(null, [self.config.rootNode, self.config.url, response]);
					}
				},
				error: function(jqXHR, textStatus, errorThrown){
					self.config.error.apply(null, [jqXHR, textStatus, errorThrown]);
				}
			});
		};

		this.onSuccess = function(response, textStatus, jqXHR){
			jQuery(self.config.rootNode).html(response);
		};

		this.onError = function(qXHR, textStatus, errorThrown){
			throw(luga.utils.formatString(luga.csi.CONST.MESSAGES.FILE_NOT_FOUND, [self.config.url]));
		};

		this.config = {
			url: jQuery(options.rootNode).attr(luga.csi.CONST.URL_ATTRIBUTE),
			after: jQuery(options.rootNode).attr(luga.csi.CONST.AFTER_ATTRIBUTE),
			success: this.onSuccess,
			error: this.onError,
			xhrTimeout: 5000
		};
		luga.merge(this.config, options);
	};

	luga.csi.loadIncludes = function(){
		jQuery(luga.csi.CONST.NODE_SELECTOR).each(function(index, item){
			var includeObj = new luga.csi.Include({rootNode: item});
			includeObj.init();
		});
	};

	jQuery(document).ready(function(){
		luga.csi.loadIncludes();
	});

}());<|endoftext|>


<commit_before>const program = require('commander');

program
    .version('0.0.1')
    .option('-p, --port <port>', 'specify the websocket port to listen to [9872]', 9872)
    .parse(process.argv);

const io = require('socket.io'),
      winston = require('winston'),
      models = require('./models');

winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});

const PORT = program.port;

winston.info('Unichat registrar service');
winston.info('Connecting to database...');

models.sequelize.sync().then( () => {
    winston.info('Listening on port ' + PORT);
    const socket = io.listen(PORT);
});
<commit_msg>Add addUser function<commit_after>const program = require('commander');

program
    .version('0.0.1')
    .option('-p, --port <port>', 'specify the websocket port to listen to [9872]', 9872)
    .parse(process.argv);

const io = require('socket.io'),
      winston = require('winston'),
      models = require('./models');

winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});

const PORT = program.port;

winston.info('Unichat registrar service');
winston.info('Connecting to database...');

const addUser = (user) => {
    models.User.create(user).then(() => {
        winston.debug('User ' + user.username + ' has been created.');
    }).catch((e) => {
        if (e.name == 'SequelizeValidationError') {
            if (e.message.startsWith("notNull Violation")) {
                winston.error(user.username + ': Please fill all necessary fields.');
            }
            else if (e.message.startsWith("Validation error: Validation isEmail failed")) {
                winston.error(user.username + ': Invalid email given.');
            }
            else if (e.message.startsWith("Password confirmation")) {
                winston.error(user.username + ': Passwords don\'t match');
            }
            else if (e.message.startsWith("Password should be at least 6 characters")) {
                winston.error(user.username + ': ' + e.message);
            }
            else {
                throw e;
            }
        }
        else if (e.name == 'SequelizeUniqueConstraintError') {
            winston.error(user.email + ': Email already exists.');
        }
        else {
            throw e;
        }
    });
};

models.sequelize.sync().then( () => {
    winston.info('Listening on port ' + PORT);
    const socket = io.listen(PORT);
});
<|endoftext|>


<commit_before>module('lively.morphic.tests.Connectors').requires('lively.morphic.tests.Morphic', 'lively.morphic.Connectors').toRun(function() {

lively.morphic.tests.MorphTests.subclass('lively.morphic.tests.ConnectorTest',
'assertion', {
    assertMorphIsDisconnectedFromConnector: function(morph, connector, idxOfControlPoint) {
        var ctrlPt = connector.getControlPoints()[idxOfControlPoint],
            prevCtrlPtPos = ctrlPt.getGlobalPos(),
            morphStartPos = morph.getPosition();
        try {
            morph.moveBy(pt(10,10))
            var currentCtrlPtPos = ctrlPt.getGlobalPos();
            this.assertEquals(prevCtrlPtPos, currentCtrlPtPos, 'when morph moved connector moved also');
            this.assertEquals(0, morph.attributeConnections.length, "morph has attributeConnections");

            this.assert(!ctrlPt.connectedMagnet, 'control point still has a magnet')
        } finally {
            morph.setPosition(morphStartPos);
        }
    },
    assertConnectorMovesWithMorph: function(morph, connector, idxOfControlPoint) {
        var ctrlPt = connector.getControlPoints()[idxOfControlPoint],
            prevCtrlPtPos = ctrlPt.getGlobalPos(),
            morphStartPos = morph.getPosition();
        try {
            morph.moveBy(pt(10,10))
            var currentCtrlPtPos = ctrlPt.getGlobalPos();
            this.assertEquals(prevCtrlPtPos.addXY(10,10), currentCtrlPtPos, 'morph did not move with connection')
            this.assert(ctrlPt.connectedMagnet, 'control point has no magnet')
        } finally {
            morph.setPosition(morphStartPos);
        }
    },

},
'testing', {
    test01getMagnets: function() {
        var morph = lively.morphic.Morph.makeRectangle(0,0, 20, 20);
        var magnet = morph.getMagnets()[0];
        this.assert(magnet instanceof lively.morphic.Magnet, "no magnet");
    },
    test02ConnectVertexControlPointToMorphMagnet: function() {
        var morph = lively.morphic.Morph.makeRectangle(0,0, 20, 20);
        morph.setPosition(pt(100,100))
        var magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line =  new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);

        this.assertIdentity(cp.getConnectedMagnet(), magnet)
        this.assertIdentity(magnet.getConnectedControlPoints()[0], cp);

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp did not move");

    },
    test03MoveMorphMovesControlPointOfConnector: function() {
        var morph = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line = new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);

        morph.moveBy(pt(10,10));

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp did not move");

        var owner = lively.morphic.Morph.makeRectangle(50,50, 50, 50);
        owner.addMorph(morph);
        this.world.addMorph(owner);
        owner.moveBy(pt(10,10));

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp when owner moveed did not move");
    },
    test04Disconnect: function() {
        var morph = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line = new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);
        cp.setConnectedMagnet(null);

        morph.moveBy(pt(10,10))
        this.assertMorphIsDisconnectedFromConnector(morph, line, 0)
    },
    test05InterfaceForVisualConnect: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);
        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        var connector = morph1.createConnectorTo(morph2);
        this.assertConnectorMovesWithMorph(morph1, connector, 0);
        this.assertConnectorMovesWithMorph(morph2, connector, 1);
    },
    test06InterfaceForVisualDisconnect: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);
        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        // move the first morph
        var connector = morph1.createConnectorTo(morph2);
        connector.disconnectFromMagnets();

        this.assertMorphIsDisconnectedFromConnector(morph1, connector, 0);
        this.assertMorphIsDisconnectedFromConnector(morph2, connector, 1);
    },
    test07ConnectionBuilderTest: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            connectionBuilder = morph1.getVisualBindingsBuilderFor('name');

        var openMenuWasCalledFor = null;
        connectionBuilder.openConnectToMenu = function(morph) { openMenuWasCalledFor = morph };
        this.assertEquals('name', connectionBuilder.label.textString);
        this.world.hands[0].grabMorph(connectionBuilder);
        this.world.hands[0].dropContentsOn(morph2, {stop: Functions.Null});

        this.assert(!morph2.submorphs.include(connectionBuilder), 'connection builder still there');
        this.assertIdentity(morph2, openMenuWasCalledFor, 'openMenu not working');
    },
    test08MagnetSetNearestMagnetToControlPoint: function() {

        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);

        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        var magnetSet = new lively.morphic.MagnetSet(this.world)
        this.assert(magnetSet.magnets.length >= 2)
        var line =  new lively.morphic.Path([pt(0,0), pt(100,100)]);

        var nearest = magnetSet.nearestMagnetsToControlPoint(line.getControlPoints()[1]);
        this.assertEquals(nearest.length, 1, "what points else")
        this.assertIdentity(nearest[0].morph, morph2, "wrong morph")
    },
});

lively.morphic.tests.ConnectorTest.subclass('lively.morphic.tests.VisualBindingsTest',
'testing', {
    test01ConnectMorphNameToText: function() {
        if (Config.noVisualConnect) {
            return;
        }
        var morph = new lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');
        this.world.addMorph(morph);
        this.world.addMorph(text);

        var con = lively.bindings.visualConnect(morph, 'name', text, 'textString');

        morph.setName('Foo');
        this.assertEquals('Foo', text.textString);

        this.assertConnectorMovesWithMorph(morph, con.getVisualConnector(), 0);
        this.assertConnectorMovesWithMorph(text, con.getVisualConnector(), 1);
    },
    test02GetListOfConnectionPoints: function() {
        var text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');

        var cPoints = text.getConnectionPoints();

        this.assert(Properties.own(cPoints).include('name'), 'name not in there')
        this.assert(Properties.own(cPoints).include('textString'), 'textString not in there')
    },
    test03GetListOfTargetConnectionPoints: function() {
        var text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');

        var cPoints = text.getTargetConnectionPoints();

        this.assert(Properties.own(cPoints).include('textString'), 'textString not in there')
    },
    test04DisconnectMorphNameToText: function() {
        if (Config.noVisualConnect) {
            return;
        }
        var morph = new lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');
        this.world.addMorph(morph);
        this.world.addMorph(text);

        var con = lively.bindings.visualConnect(morph, 'name', text, 'textString');
        con.visualDisconnect();

        morph.setName('Foo');
        this.assert('Foo' != text.textString, 'logical connection not disconnected');
        this.assertMorphIsDisconnectedFromConnector(morph, con.getVisualConnector(), 0)
    },

});

lively.morphic.tests.MorphTests.subclass('lively.morphic.tests.MagnetTest',
'testing', {
    test01getGlobalPosition: function() {
        var morph = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph)
        var magnet = new lively.morphic.Magnet(morph, pt(10,10));
        this.assertEquals(magnet.getPosition(), pt(10,10), "wrong position")
        this.assertEquals(magnet.getGlobalPosition(), pt(15,15), "wrong global position")
    },
    test02CachedGlobalPosition: function() {
        var morph = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph)
        var magnet = new lively.morphic.Magnet(morph, pt(10,10));
        this.assert(magnet.getGlobalPosition(), magnet.getCachedGlobalPosition(), "cache");
        magnet.resetCachedGlobalPosition()
        this.assert(!magnet.cachedGlobalPosition, "cache is empty");
    },
    test03MagnetSet: function() {
        var magnetSet = new lively.morphic.MagnetSet()
        var morph1 = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph1)

        var morph2 = lively.morphic.Morph.makeRectangle(50,50, 20, 20);
        this.world.addMorph(morph2)

        magnetSet.gatherMagnetsIn(this.world);

        this.assertIdentity(magnetSet.nearestMagnetsTo(pt(5,5))[0].morph, morph1, "first wrong")
        this.assertIdentity(magnetSet.nearestMagnetsTo(pt(50,50))[0].morph, morph2, 'second wrong')
    },
    test04RelativeMagnet: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(5,5, 20, 20);

        var relativeMagnet = new lively.morphic.RelativeMagnet(morph1, pt(0,0));

        relativeMagnet.setPosition(pt(10,10));
        morph1.setExtent(pt(40,40))
        this.assertEquals(relativeMagnet.getPosition(), pt(20,20))
    },

});

}) // end of module
<commit_msg>jenslincke, visual connect config, part2<commit_after>module('lively.morphic.tests.Connectors').requires('lively.morphic.tests.Morphic', 'lively.morphic.Connectors').toRun(function() {

lively.morphic.tests.MorphTests.subclass('lively.morphic.tests.ConnectorTest',
'assertion', {
    assertMorphIsDisconnectedFromConnector: function(morph, connector, idxOfControlPoint) {
        var ctrlPt = connector.getControlPoints()[idxOfControlPoint],
            prevCtrlPtPos = ctrlPt.getGlobalPos(),
            morphStartPos = morph.getPosition();
        try {
            morph.moveBy(pt(10,10))
            var currentCtrlPtPos = ctrlPt.getGlobalPos();
            this.assertEquals(prevCtrlPtPos, currentCtrlPtPos, 'when morph moved connector moved also');
            this.assertEquals(0, morph.attributeConnections.length, "morph has attributeConnections");

            this.assert(!ctrlPt.connectedMagnet, 'control point still has a magnet')
        } finally {
            morph.setPosition(morphStartPos);
        }
    },
    assertConnectorMovesWithMorph: function(morph, connector, idxOfControlPoint) {
        var ctrlPt = connector.getControlPoints()[idxOfControlPoint],
            prevCtrlPtPos = ctrlPt.getGlobalPos(),
            morphStartPos = morph.getPosition();
        try {
            morph.moveBy(pt(10,10))
            var currentCtrlPtPos = ctrlPt.getGlobalPos();
            this.assertEquals(prevCtrlPtPos.addXY(10,10), currentCtrlPtPos, 'morph did not move with connection')
            this.assert(ctrlPt.connectedMagnet, 'control point has no magnet')
        } finally {
            morph.setPosition(morphStartPos);
        }
    },

},
'testing', {
    test01getMagnets: function() {
        var morph = lively.morphic.Morph.makeRectangle(0,0, 20, 20);
        var magnet = morph.getMagnets()[0];
        this.assert(magnet instanceof lively.morphic.Magnet, "no magnet");
    },
    test02ConnectVertexControlPointToMorphMagnet: function() {
        var morph = lively.morphic.Morph.makeRectangle(0,0, 20, 20);
        morph.setPosition(pt(100,100))
        var magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line =  new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);

        this.assertIdentity(cp.getConnectedMagnet(), magnet)
        this.assertIdentity(magnet.getConnectedControlPoints()[0], cp);

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp did not move");

    },
    test03MoveMorphMovesControlPointOfConnector: function() {
        var morph = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line = new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);

        morph.moveBy(pt(10,10));

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp did not move");

        var owner = lively.morphic.Morph.makeRectangle(50,50, 50, 50);
        owner.addMorph(morph);
        this.world.addMorph(owner);
        owner.moveBy(pt(10,10));

        this.assertEquals(cp.getGlobalPos(), magnet.getGlobalPosition(), "cp when owner moveed did not move");
    },
    test04Disconnect: function() {
        var morph = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            magnet = morph.getMagnets()[0];
        this.world.addMorph(morph);

        var line = new lively.morphic.Path([pt(0,0), pt(20,100)])
        this.world.addMorph(line);

        var cp = line.getControlPoints()[0];
        cp.setConnectedMagnet(magnet);
        cp.setConnectedMagnet(null);

        morph.moveBy(pt(10,10))
        this.assertMorphIsDisconnectedFromConnector(morph, line, 0)
    },
    test05InterfaceForVisualConnect: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);
        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        var connector = morph1.createConnectorTo(morph2);
        this.assertConnectorMovesWithMorph(morph1, connector, 0);
        this.assertConnectorMovesWithMorph(morph2, connector, 1);
    },
    test06InterfaceForVisualDisconnect: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);
        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        // move the first morph
        var connector = morph1.createConnectorTo(morph2);
        connector.disconnectFromMagnets();

        this.assertMorphIsDisconnectedFromConnector(morph1, connector, 0);
        this.assertMorphIsDisconnectedFromConnector(morph2, connector, 1);
    },
    test07ConnectionBuilderTest: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20),
            connectionBuilder = morph1.getVisualBindingsBuilderFor('name');

        var openMenuWasCalledFor = null;
        connectionBuilder.openConnectToMenu = function(morph) { openMenuWasCalledFor = morph };
        this.assertEquals('name', connectionBuilder.label.textString);
        this.world.hands[0].grabMorph(connectionBuilder);
        this.world.hands[0].dropContentsOn(morph2, {stop: Functions.Null});

        this.assert(!morph2.submorphs.include(connectionBuilder), 'connection builder still there');
        this.assertIdentity(morph2, openMenuWasCalledFor, 'openMenu not working');
    },
    test08MagnetSetNearestMagnetToControlPoint: function() {

        var morph1 = lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            morph2 = lively.morphic.Morph.makeRectangle(100,100, 20, 20);

        this.world.addMorph(morph1);
        this.world.addMorph(morph2);

        var magnetSet = new lively.morphic.MagnetSet(this.world)
        this.assert(magnetSet.magnets.length >= 2)
        var line =  new lively.morphic.Path([pt(0,0), pt(100,100)]);

        var nearest = magnetSet.nearestMagnetsToControlPoint(line.getControlPoints()[1]);
        this.assertEquals(nearest.length, 1, "what points else")
        this.assertIdentity(nearest[0].morph, morph2, "wrong morph")
    },
});

lively.morphic.tests.ConnectorTest.subclass('lively.morphic.tests.VisualBindingsTest',
'testing', {
    test01ConnectMorphNameToText: function() {
        if (!Config.visualConnectEnabled) {
            return;
        }
        var morph = new lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');
        this.world.addMorph(morph);
        this.world.addMorph(text);

        var con = lively.bindings.visualConnect(morph, 'name', text, 'textString');

        morph.setName('Foo');
        this.assertEquals('Foo', text.textString);

        this.assertConnectorMovesWithMorph(morph, con.getVisualConnector(), 0);
        this.assertConnectorMovesWithMorph(text, con.getVisualConnector(), 1);
    },
    test02GetListOfConnectionPoints: function() {
        var text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');

        var cPoints = text.getConnectionPoints();

        this.assert(Properties.own(cPoints).include('name'), 'name not in there')
        this.assert(Properties.own(cPoints).include('textString'), 'textString not in there')
    },
    test03GetListOfTargetConnectionPoints: function() {
        var text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');

        var cPoints = text.getTargetConnectionPoints();

        this.assert(Properties.own(cPoints).include('textString'), 'textString not in there')
    },
    test04DisconnectMorphNameToText: function() {
        if (Config.noVisualConnect) {
            return;
        }
        var morph = new lively.morphic.Morph.makeRectangle(0,0, 20, 20),
            text = new lively.morphic.Text(new Rectangle(100,0,100,20), '');
        this.world.addMorph(morph);
        this.world.addMorph(text);

        var con = lively.bindings.visualConnect(morph, 'name', text, 'textString');
        con.visualDisconnect();

        morph.setName('Foo');
        this.assert('Foo' != text.textString, 'logical connection not disconnected');
        this.assertMorphIsDisconnectedFromConnector(morph, con.getVisualConnector(), 0)
    },

});

lively.morphic.tests.MorphTests.subclass('lively.morphic.tests.MagnetTest',
'testing', {
    test01getGlobalPosition: function() {
        var morph = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph)
        var magnet = new lively.morphic.Magnet(morph, pt(10,10));
        this.assertEquals(magnet.getPosition(), pt(10,10), "wrong position")
        this.assertEquals(magnet.getGlobalPosition(), pt(15,15), "wrong global position")
    },
    test02CachedGlobalPosition: function() {
        var morph = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph)
        var magnet = new lively.morphic.Magnet(morph, pt(10,10));
        this.assert(magnet.getGlobalPosition(), magnet.getCachedGlobalPosition(), "cache");
        magnet.resetCachedGlobalPosition()
        this.assert(!magnet.cachedGlobalPosition, "cache is empty");
    },
    test03MagnetSet: function() {
        var magnetSet = new lively.morphic.MagnetSet()
        var morph1 = lively.morphic.Morph.makeRectangle(5,5, 20, 20);
        this.world.addMorph(morph1)

        var morph2 = lively.morphic.Morph.makeRectangle(50,50, 20, 20);
        this.world.addMorph(morph2)

        magnetSet.gatherMagnetsIn(this.world);

        this.assertIdentity(magnetSet.nearestMagnetsTo(pt(5,5))[0].morph, morph1, "first wrong")
        this.assertIdentity(magnetSet.nearestMagnetsTo(pt(50,50))[0].morph, morph2, 'second wrong')
    },
    test04RelativeMagnet: function() {
        var morph1 = lively.morphic.Morph.makeRectangle(5,5, 20, 20);

        var relativeMagnet = new lively.morphic.RelativeMagnet(morph1, pt(0,0));

        relativeMagnet.setPosition(pt(10,10));
        morph1.setExtent(pt(40,40))
        this.assertEquals(relativeMagnet.getPosition(), pt(20,20))
    },

});

}) // end of module
<|endoftext|>


<commit_before>var pubsub = require('./pubsub.njs');
var atob = require('atob');
var lcd = require('./lcd.js');

var BEPPE_TOPIC = "projects/potent-poetry-86911/topics/beppe";
var ANNA_TOPIC = "projects/potent-poetry-86911/topics/anna";
var BEPPE_SUB = "projects/potent-poetry-86911/subscriptions/beppe";
var ANNA_SUB = "projects/potent-poetry-86911/subscriptions/anna";

// npm instal johnny-five galileo-io

var five = require("johnny-five");
var Edison = require("galileo-io");
var board = new five.Board({
	io : new Edison()
});

var parseee = null;

function go() {
	var SERVICE_ACCOUNT = '835550676211-5cd1go92306lp54ej68hguiibtaf58a6@developer.gserviceaccount.com';
	var PEM_PATH = '../p12/key.pem';

	pubsub.auth(PEM_PATH, SERVICE_ACCOUNT, function() {
		pubsub.pub("Anna pronta", ANNA_TOPIC);

		pubsub.sub(ANNA_SUB, parseee);
	});
}

board.on("ready", function() {
	var servo = new five.Servo(6);
	var raiseMutex = 0;

	function raiseArm() {
		servo.min();
		console.log("Raising Arm");
	}

	function lowerArm() {
		servo.to(84);
		console.log("Lowering Arm");
		if (raiseMutex) {
			console.log("Raise mutex released");
			raiseMutex = 0;
		}
	}

	lowerArm();

	function raiseArmForDuration(duration) {
		if (!raiseMutex) {
			console.log("Raise mutex set");
			raiseArm();
			raiseMutex = 1;
			setTimeout(function() {
				lowerArm();
			}, duration);
		} else {
			console.log("Mutex is set: not raising arm");
		}
	}

	function parse(msg) {
		var clearData = atob(msg.message.data);
		var stack = null;
		try {
			stack = JSON.parse(clearData);
		} catch (e) {
			console.log('JSON.parse failed');
		}

		if (stack !== null && stack.length > 0) {
			var popped = stack.pop();

			if (popped.color) {
				lcd.setColor(popped.color, popped.duration || 1000);
			}

			if (popped.arm) {
				// arm
				console.log("arm");
				raiseArmForDuration(popped.duration || 1000);
			}

			if (popped.buzzer) {
				// buzzer popped.duration || 1000
				console.log("buzzer");
			}

			// CHANGE TO NEXT Edison TOPIC
			pubsub.pub(JSON.stringify(stack), ANNA_TOPIC);
		}
	}

	parseee = parse;

	go();

});<commit_msg>avoid seg fault<commit_after>var pubsub = require('./pubsub.njs');
var atob = require('atob');
var lcd = require('./lcd.js');

var BEPPE_TOPIC = "projects/potent-poetry-86911/topics/beppe";
var ANNA_TOPIC = "projects/potent-poetry-86911/topics/anna";
var BEPPE_SUB = "projects/potent-poetry-86911/subscriptions/beppe";
var ANNA_SUB = "projects/potent-poetry-86911/subscriptions/anna";

// npm instal johnny-five galileo-io

var five = require("johnny-five");
var Edison = require("galileo-io");
var board = new five.Board({
	io : new Edison()
});

function go(parse) {
	var SERVICE_ACCOUNT = '835550676211-5cd1go92306lp54ej68hguiibtaf58a6@developer.gserviceaccount.com';
	var PEM_PATH = '../p12/key.pem';

	pubsub.auth(PEM_PATH, SERVICE_ACCOUNT, function() {
		pubsub.pub("Anna pronta", ANNA_TOPIC);

		pubsub.sub(ANNA_SUB, parse);
	});
}

board.on("ready", function() {
	var servo = new five.Servo(6);
	var raiseMutex = 0;

	function raiseArm() {
		servo.min();
		console.log("Raising Arm");
	}

	function lowerArm() {
		servo.to(84);
		console.log("Lowering Arm");
		if (raiseMutex) {
			console.log("Raise mutex released");
			raiseMutex = 0;
		}
	}

	lowerArm();

	function raiseArmForDuration(duration) {
		if (!raiseMutex) {
			console.log("Raise mutex set");
			raiseArm();
			raiseMutex = 1;
			setTimeout(function() {
				lowerArm();
			}, duration);
		} else {
			console.log("Mutex is set: not raising arm");
		}
	}

	function parse(msg) {
		var clearData = atob(msg.message.data);
		var stack = null;
		try {
			stack = JSON.parse(clearData);
		} catch (e) {
			console.log('JSON.parse failed');
		}

		if (stack !== null && stack.length > 0) {
			var popped = stack.pop();

			if (popped.color) {
				lcd.setColor(popped.color, popped.duration || 1000);
			}

			if (popped.arm) {
				// arm
				console.log("arm");
				raiseArmForDuration(popped.duration || 1000);
			}

			if (popped.buzzer) {
				// buzzer popped.duration || 1000
				console.log("buzzer");
			}

			// CHANGE TO NEXT Edison TOPIC
			pubsub.pub(JSON.stringify(stack), ANNA_TOPIC);
		}
	}

	go(parse);

});<|endoftext|>