<commit_before>$(document).ready(function(){
		draw();
});

//function draw
function draw() {
	//triangle 1
	var x11 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y11 = Math.floor(Math.random() * (200 - 100 + 10)) + 10
		var x12 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y12 = Math.floor(Math.random() * (200 - 100 + 10)) + 10

		//triangle 2
		var x21 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y21 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		var x22 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y22 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		//triangle 3
		var x31 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y31 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		var x32 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y32 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		//triangle 4
		var x41 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y41 = Math.floor(Math.random() * (700 - 650 + 10)) + 20
		var x42 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y42 = Math.floor(Math.random() * (700 - 650 + 10)) + 20

    var maxAngle = 0;
    var maxAngleAnswer = "";
    var minAngle = 360;
    var minAngleAnswer = "";
    //calculate angle A
    var A12 = Math.sqrt(Math.pow((x11 - 100), 2) + Math.pow((y11 - 15), 2));
	var A13 = Math.sqrt(Math.pow((x11 - x12), 2) + Math.pow((y11 - y12), 2));
	var A23 = Math.sqrt(Math.pow((100 - x12), 2) + Math.pow((15 - y12), 2));
	var resultDegreeA = Math.acos(((Math.pow(A12, 2)) + (Math.pow(A13, 2)) - (Math.pow(A23, 2))) / (2 * A12 * A13)) * 180 / Math.PI;

	document.getElementById('A').innerHTML = "A = " + (resultDegreeA.toFixed(2))

    if(resultDegreeA > maxAngle){
        maxAngleAnswer = "A"
        maxAngle = resultDegreeA
    }

    if(resultDegreeA < minAngle){
        minAngleAnswer = "A"
        minAngle = resultDegreeA
    }

    //calculate angle B

    var B12 = Math.sqrt(Math.pow((x21 - 300), 2) + Math.pow((y21 - 50), 2));
	var B13 = Math.sqrt(Math.pow((x21 - x22), 2) + Math.pow((y21 - y22), 2));
	var B23 = Math.sqrt(Math.pow((300 - x22), 2) + Math.pow((50 - y22), 2));
	var resultDegreeB = Math.acos(((Math.pow(B12, 2)) + (Math.pow(B13, 2)) - (Math.pow(B23, 2))) / (2 * B12 * B13)) * 180 / Math.PI;

	document.getElementById('B').innerHTML = "B = " + (resultDegreeB.toFixed(2))

    if(resultDegreeB > maxAngle){
        maxAngleAnswer = "B"
        maxAngle = resultDegreeB
    }

    if(resultDegreeB < minAngle){
        minAngleAnswer = "B"
        minAngle = resultDegreeB
    }

		//calculate angle C

		var C12 = Math.sqrt(Math.pow((x31 - 500), 2) + Math.pow((y31 - 50), 2));
	var C13 = Math.sqrt(Math.pow((x31 - x32), 2) + Math.pow((y31 - y32), 2));
	var C23 = Math.sqrt(Math.pow((500 - x32), 2) + Math.pow((50 - y32), 2));
	var resultDegreeC = Math.acos(((Math.pow(C12, 2)) + (Math.pow(C13, 2)) - (Math.pow(C23, 2))) / (2 * C12 * C13)) * 180 / Math.PI;

	document.getElementById('C').innerHTML = "C = " + (resultDegreeC.toFixed(2))

    if(resultDegreeC > maxAngle){
        maxAngleAnswer = "C"
        maxAngle = resultDegreeC
    }

    if(resultDegreeC < minAngle){
        minAngleAnswer = "C"
        minAngle = resultDegreeC
    }

		//calculate angle D

    var D12 = Math.sqrt(Math.pow((x41 - 700), 2) + Math.pow((y41 - 50), 2));
	var D13 = Math.sqrt(Math.pow((x41 - x42), 2) + Math.pow((y41 - y42), 2));
	var D23 = Math.sqrt(Math.pow((700 - x42), 2) + Math.pow((50 - y42), 2));
	var resultDegreeD = Math.acos(((Math.pow(D12, 2)) + (Math.pow(D13, 2)) - (Math.pow(D23, 2))) / (2 * D12 * D13)) * 180 / Math.PI;

	document.getElementById('D').innerHTML = "D = " + (resultDegreeD.toFixed(2))

    if(resultDegreeD > maxAngle){
        maxAngleAnswer = "D"
        maxAngle = resultDegreeD
    }

    if(resultDegreeD < minAngle){
        minAngleAnswer = "D"
        minAngle = resultDegreeD
    }

    var canvas = document.getElementById('canvas');
	if (canvas.getContext) {
		var ctx = canvas.getContext('2d');

		ctx.beginPath();
		ctx.moveTo(250, 0);
		ctx.lineTo(250, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(450, 0);
		ctx.lineTo(450, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(650, 0);
		ctx.lineTo(650, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(100, 15);
		ctx.lineTo(x11, y11);
		ctx.lineTo(x12, y12);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(300, 50);
		ctx.lineTo(x21, y21);
		ctx.lineTo(x22, y22);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(500, 50);
		ctx.lineTo(x31, y31);
		ctx.lineTo(x32, y32);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(700, 50);
		ctx.lineTo(x41, y41);
		ctx.lineTo(x42, y42);
		ctx.stroke();

	}

    var choices = ["A", "B", "C", "D"]
    var choiceToDegree = {};
    choiceToDegree["A"] = resultDegreeA
    choiceToDegree["B"] = resultDegreeB
    choiceToDegree["C"] = resultDegreeC
    choiceToDegree["D"] = resultDegreeD

    var indexToRemove1 = choices.indexOf(maxAngleAnswer)
    choices.splice(indexToRemove1, 1)
    var indexToRemove2 = choices.indexOf(minAngleAnswer)
        choices.splice(indexToRemove2, 1)

    var answer1;
    var answer2;
    var answer3;
    var answer4;

    var correctAnswer;
    if(choiceToDegree[choices[0]] < choiceToDegree[choices[1]]){
        correctAnswer = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer1 = choices[0] +"< "+ minAngleAnswer + "< " + choices[1] + "< " +maxAngleAnswer
        answer2 = choices[0] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[1]
        answer3 = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[0] + "< " + maxAngleAnswer + "< " + choices[1]
    }
    else{
        correctAnswer = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer1 = choices[1] +"< "+ minAngleAnswer + "< " + choices[0] + "< " +maxAngleAnswer
        answer2 = choices[1] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[0]
        answer3 = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[1] + "< " + maxAngleAnswer + "< " + choices[0]
    }

    var answers = [answer1, answer2, answer3, answer4]
    var shuffledAnswers = shuffle(answers)

    createAnswers(shuffledAnswers, correctAnswer);

}

 // Creates a list of the answer choices as radio inputs
function createAnswers(answers, correctanswer) {
    var radioList = $('
');
    var item;
    var input = '';
    for (var i = 0; i < answers.length; i++) {
      item = $('
');
      input = '<input type="radio" name="answer" value=' + i + ' onclick="checkAnswer();"/>';
      input += answers[i];
      item.append(input);
      radioList.append(item);
    }
    $("#choices").append(radioList);

    var correctAnswer = '
' +"Correct Answer is "+ correctanswer + "
"
    $("#choices").append(correctAnswer);
}

function checkAnswer()

	{
	var selections = document.getElementsByName("answers");
	for (var i=0; i < selections.length; i++)
		{
		if(selections[i].checked)
			{
			alert ("u picked" +selections[i].value+"radio button.");
			}
		}
	}

//Implementation of the Fisher Yates Shuffle Algorithm
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

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

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

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

  return array;
}

///////////////////Sort array//////////////////////

 var array = [5,7,8,2,3,1,6];
 var temp;
 function sort(array) {
 	for(var i=0; i<array.length; i++) {
 		for (var j=0; j<array.length; j++) {
 			if (array[i] < array[j] && i!=j) {
 				temp = array[j];
 				array[j] = array[i];
 				array[i] = temp;

 			}

 		}
 	}
 	return array;
 }

 var sortedArray = sort(array);
document.getElementById('results').innerHTML += sortedArray;

function showAnswer() {
	var x = document.getElementById('showResult');
	if (x.style.display === 'none') {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';
 	}
}
<commit_msg>Update angles.js<commit_after>$(document).ready(function(){
		draw();
});

//function draw
function draw() {
	//triangle 1
	var x11 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y11 = Math.floor(Math.random() * (200 - 100 + 10)) + 10
		var x12 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y12 = Math.floor(Math.random() * (200 - 100 + 10)) + 10

		//triangle 2
		var x21 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y21 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		var x22 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y22 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		//triangle 3
		var x31 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y31 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		var x32 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y32 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		//triangle 4
		var x41 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y41 = Math.floor(Math.random() * (700 - 650 + 10)) + 20
		var x42 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y42 = Math.floor(Math.random() * (700 - 650 + 10)) + 20

    var maxAngle = 0;
    var maxAngleAnswer = "";
    var minAngle = 360;
    var minAngleAnswer = "";
    //calculate angle A
    var A12 = Math.sqrt(Math.pow((x11 - 100), 2) + Math.pow((y11 - 15), 2));
	var A13 = Math.sqrt(Math.pow((x11 - x12), 2) + Math.pow((y11 - y12), 2));
	var A23 = Math.sqrt(Math.pow((100 - x12), 2) + Math.pow((15 - y12), 2));
	var resultDegreeA = Math.acos(((Math.pow(A12, 2)) + (Math.pow(A13, 2)) - (Math.pow(A23, 2))) / (2 * A12 * A13)) * 180 / Math.PI;

	document.getElementById('A').innerHTML = "A = " + (resultDegreeA.toFixed(2))

    if(resultDegreeA > maxAngle){
        maxAngleAnswer = "A"
        maxAngle = resultDegreeA
    }

    if(resultDegreeA < minAngle){
        minAngleAnswer = "A"
        minAngle = resultDegreeA
    }

    //calculate angle B

    var B12 = Math.sqrt(Math.pow((x21 - 300), 2) + Math.pow((y21 - 50), 2));
	var B13 = Math.sqrt(Math.pow((x21 - x22), 2) + Math.pow((y21 - y22), 2));
	var B23 = Math.sqrt(Math.pow((300 - x22), 2) + Math.pow((50 - y22), 2));
	var resultDegreeB = Math.acos(((Math.pow(B12, 2)) + (Math.pow(B13, 2)) - (Math.pow(B23, 2))) / (2 * B12 * B13)) * 180 / Math.PI;

	document.getElementById('B').innerHTML = "B = " + (resultDegreeB.toFixed(2))

    if(resultDegreeB > maxAngle){
        maxAngleAnswer = "B"
        maxAngle = resultDegreeB
    }

    if(resultDegreeB < minAngle){
        minAngleAnswer = "B"
        minAngle = resultDegreeB
    }

		//calculate angle C

		var C12 = Math.sqrt(Math.pow((x31 - 500), 2) + Math.pow((y31 - 50), 2));
	var C13 = Math.sqrt(Math.pow((x31 - x32), 2) + Math.pow((y31 - y32), 2));
	var C23 = Math.sqrt(Math.pow((500 - x32), 2) + Math.pow((50 - y32), 2));
	var resultDegreeC = Math.acos(((Math.pow(C12, 2)) + (Math.pow(C13, 2)) - (Math.pow(C23, 2))) / (2 * C12 * C13)) * 180 / Math.PI;

	document.getElementById('C').innerHTML = "C = " + (resultDegreeC.toFixed(2))

    if(resultDegreeC > maxAngle){
        maxAngleAnswer = "C"
        maxAngle = resultDegreeC
    }

    if(resultDegreeC < minAngle){
        minAngleAnswer = "C"
        minAngle = resultDegreeC
    }

		//calculate angle D

    var D12 = Math.sqrt(Math.pow((x41 - 700), 2) + Math.pow((y41 - 50), 2));
	var D13 = Math.sqrt(Math.pow((x41 - x42), 2) + Math.pow((y41 - y42), 2));
	var D23 = Math.sqrt(Math.pow((700 - x42), 2) + Math.pow((50 - y42), 2));
	var resultDegreeD = Math.acos(((Math.pow(D12, 2)) + (Math.pow(D13, 2)) - (Math.pow(D23, 2))) / (2 * D12 * D13)) * 180 / Math.PI;

	document.getElementById('D').innerHTML = "D = " + (resultDegreeD.toFixed(2))

    if(resultDegreeD > maxAngle){
        maxAngleAnswer = "D"
        maxAngle = resultDegreeD
    }

    if(resultDegreeD < minAngle){
        minAngleAnswer = "D"
        minAngle = resultDegreeD
    }

    var canvas = document.getElementById('canvas');
	if (canvas.getContext) {
		var ctx = canvas.getContext('2d');

		ctx.beginPath();
		ctx.moveTo(250, 0);
		ctx.lineTo(250, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(450, 0);
		ctx.lineTo(450, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(650, 0);
		ctx.lineTo(650, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(100, 15);
		ctx.lineTo(x11, y11);
		ctx.lineTo(x12, y12);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(300, 50);
		ctx.lineTo(x21, y21);
		ctx.lineTo(x22, y22);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(500, 50);
		ctx.lineTo(x31, y31);
		ctx.lineTo(x32, y32);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(700, 50);
		ctx.lineTo(x41, y41);
		ctx.lineTo(x42, y42);
		ctx.stroke();

	}

    var choices = ["A", "B", "C", "D"]
    var choiceToDegree = {};
    choiceToDegree["A"] = resultDegreeA
    choiceToDegree["B"] = resultDegreeB
    choiceToDegree["C"] = resultDegreeC
    choiceToDegree["D"] = resultDegreeD

    var indexToRemove1 = choices.indexOf(maxAngleAnswer)
    choices.splice(indexToRemove1, 1)
    var indexToRemove2 = choices.indexOf(minAngleAnswer)
        choices.splice(indexToRemove2, 1)

    var answer1;
    var answer2;
    var answer3;
    var answer4;

    var correctAnswer;
    if(choiceToDegree[choices[0]] < choiceToDegree[choices[1]]){
        correctAnswer = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer1 = choices[0] +"< "+ minAngleAnswer + "< " + choices[1] + "< " +maxAngleAnswer
        answer2 = choices[0] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[1]
        answer3 = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[0] + "< " + maxAngleAnswer + "< " + choices[1]
    }
    else{
        correctAnswer = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer1 = choices[1] +"< "+ minAngleAnswer + "< " + choices[0] + "< " +maxAngleAnswer
        answer2 = choices[1] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[0]
        answer3 = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[1] + "< " + maxAngleAnswer + "< " + choices[0]
    }

    var answers = [answer1, answer2, answer3, answer4]
    var shuffledAnswers = shuffle(answers)

    createAnswers(shuffledAnswers, correctAnswer);

}

 // Creates a list of the answer choices as radio inputs
function createAnswers(answers, correctanswer) {
    var radioList = $('
');
    var item;
    var input = '';
    for (var i = 0; i < answers.length; i++) {
      item = $('
');
      input = '<input type="radio" name="answer" value=' + i + ' onclick="checkAnswer();"/>';
      input += answers[i];
      item.append(input);
      radioList.append(item);
    }
    $("#choices").append(radioList);

    var correctAnswer = '
' +"Correct Answer is "+ correctanswer + "
"
    $("#choices").append(correctAnswer);
}

function checkAnswer()

	{
	var selections = document.getElementsByName("choices");
	for (var i=0; i < selections.length; i++)
		{
		if(selections[i].checked)
			{
			alert ("u picked" +selections[i].value+"radio button.");
			}
		}
	}

//Implementation of the Fisher Yates Shuffle Algorithm
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

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

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

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

  return array;
}

///////////////////Sort array//////////////////////

 var array = [5,7,8,2,3,1,6];
 var temp;
 function sort(array) {
 	for(var i=0; i<array.length; i++) {
 		for (var j=0; j<array.length; j++) {
 			if (array[i] < array[j] && i!=j) {
 				temp = array[j];
 				array[j] = array[i];
 				array[i] = temp;

 			}

 		}
 	}
 	return array;
 }

 var sortedArray = sort(array);
document.getElementById('results').innerHTML += sortedArray;

function showAnswer() {
	var x = document.getElementById('showResult');
	if (x.style.display === 'none') {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';
 	}
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016-present Tuan Le.
 *
 * Licensed under the MIT License.
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/mit-license.html
 *
 * 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.
 *
 *------------------------------------------------------------------------
 *
 * @module CoverImage
 * @description - Cover image component.
 *
 * @author Tuan Le (tuan.t.lei@gmail.com)
 *
 * @flow
 */
'use strict'; // eslint-disable-line

import React from 'react';

import ReactNative from 'react-native'; // eslint-disable-line

import PropTypes from 'prop-types';

import {
    DefaultTheme,
    DefaultThemeContext
} from '../../themes/default-theme';

const {
    Dimensions,
    ImageBackground
} = ReactNative;

const DEVICE_WIDTH = Dimensions.get(`window`).width;
const DEVICE_HEIGHT = Dimensions.get(`window`).height;

const DEFAULT_DROP_SHADOW_STYLE = {
    shadowColor: `#000000`,
    shadowRadius: 2,
    shadowOpacity: 0.3,
    shadowOffset: {
        width: 0,
        height: 1
    }
};

const DEFAULT_COVER_IMAGE_STYLE = {
    flexDirection: `column`,
    justifyContent: `center`,
    alignItems: `center`,
    maxWidth: DEVICE_WIDTH,
    maxHeight: DEVICE_HEIGHT
};

const CoverImage = (props) => {
    const {
        exclusions,
        shade,
        width,
        height,
        corner,
        margin,
        resizeMode,
        dropShadowed,
        source,
        defaultSource,
        style,
        children
    } = props;
    let contentChildren = null;

    if (React.Children.count(children) > 0) {
        contentChildren = React.Children.toArray(React.Children.map(children, (child) => {
            if (child !== null) {
                const inheritedProps = Array.isArray(exclusions) ? Object.entries({
                    shade
                }).filter(([
                    propName,
                    prop // eslint-disable-line
                ]) => exclusions.every((exclusion) => propName !== exclusion)).reduce((_inheritedProps, [ propName, prop ]) => {
                    _inheritedProps[propName] = prop;
                    return _inheritedProps;
                }, {}) : {
                    shade
                };
                return React.cloneElement(child, inheritedProps);
            }
            return null;
        }));
    }

    return (
        <DefaultThemeContext.Consumer>
            {
                (context = {
                    Theme: DefaultTheme
                }) => {
                    const {
                        Theme
                    } = context;
                    const size = Math.min(width, height);
                    const nullMargin = {
                        margin: null,
                        marginTop: null,
                        marginBottom: null,
                        marginLeft: null,
                        marginRight: null,
                        marginHorizontal: null,
                        marginVertical: null
                    };
                    const nullBorderRadius = {
                        borderTopLeftRadius: null,
                        borderTopRightRadius: null,
                        borderBottomLeftRadius: null,
                        borderBottomRightRadius: null
                    };
                    let dropShadow;
                    let themedBorderRadius;
                    let themedCorner;
                    let themedMargin;

                    if (typeof corner === `string`) {
                        if (corner === `themed`) {
                            if (typeof Theme.image.cover.corner === `string` && Theme.image.corner.cover.hasOwnProperty(Theme.image.cover.corner)) {
                                themedCorner = Theme.image.corner.cover[Theme.image.cover.corner];
                            } else {
                                themedCorner = Theme.image.cover.corner;
                            }
                        } else if (Theme.image.corner.cover.hasOwnProperty(corner)) {
                            themedCorner = Theme.image.corner.cover[corner];
                        } else {
                            themedCorner = 0;
                        }
                    } else {
                        themedCorner = corner;
                    }
                    if (typeof themedCorner === `number`) {
                        themedBorderRadius = {
                            ...nullBorderRadius,
                            borderRadius: Math.floor(themedCorner * size)
                        };
                    } else if (typeof themedCorner === `object`) {
                        themedBorderRadius = Object.entries(themedCorner).reduce((_themedBorderRadius, [ key, value ]) => {
                            let _borderRadius = nullBorderRadius;

                            _borderRadius[`border${key.charAt(0).toUpperCase()}${key.slice(1)}Radius`] = Math.floor(size * value);

                            _themedBorderRadius = {
                                ..._themedBorderRadius,
                                ..._borderRadius
                            };
                            return _themedBorderRadius;
                        }, nullBorderRadius);
                    }

                    if (typeof margin === `string`) {
                        if (margin === `themed`) {
                            if (typeof Theme.image.cover.margin === `string` && Theme.image.margin.cover.hasOwnProperty(Theme.image.cover.margin)) {
                                themedMargin = Theme.image.margin.cover[Theme.image.cover.margin];
                            } else {
                                themedMargin = Theme.image.cover.margin;
                            }
                        } else if (Theme.image.margin.cover.hasOwnProperty(margin)) {
                            themedMargin = Theme.image.margin.cover[margin];
                        } else {
                            themedMargin = 0;
                        }
                    } else {
                        themedMargin = margin;
                    }
                    if (typeof themedMargin === `number`) {
                        themedMargin = {
                            ...nullMargin,
                            margin: themedMargin
                        };
                    } else if (typeof themedMargin === `object`) {
                        themedMargin = Object.entries(themedMargin).reduce((_themedMargin, [ key, value ]) => {
                            let _margin = nullMargin;

                            _margin[`margin${key.charAt(0).toUpperCase()}${key.slice(1)}`] = value;
                            _themedMargin = {
                                ..._themedMargin,
                                ..._margin
                            };
                            return _themedMargin;
                        }, nullMargin);
                    }

                    if ((typeof dropShadowed === `boolean` && dropShadowed) || (dropShadowed === `themed` && Theme.image.cover.dropShadowed)) {
                        dropShadow = DEFAULT_DROP_SHADOW_STYLE;
                    } else {
                        dropShadow = {
                            ...DEFAULT_DROP_SHADOW_STYLE,
                            shadowRadius: 0,
                            shadowOpacity: 0,
                            shadowOffset: {
                                width: 0,
                                height: 0
                            }
                        };
                    }
                    return (
                        <ImageBackground
                            style = {{
                                ...DEFAULT_COVER_IMAGE_STYLE,
                                ...dropShadow,
                                width,
                                height,
                                ...themedMargin,
                                ...themedBorderRadius,
                                ...(typeof style === `object` ? style : {})
                            }}
                            imageStyle = {{
                                ...themedBorderRadius
                            }}
                            source = {
                                typeof source === `string` ? {
                                    uri: source,
                                    cache: `only-if-cached`
                                } : source
                            }
                            defaultSource = {
                                typeof source === `string` ? {
                                    uri: defaultSource
                                } : defaultSource
                            }
                            resizeMode = { resizeMode }
                        >
                            {
                                contentChildren
                            }
                        </ImageBackground>
                    );
                }
            }
        </DefaultThemeContext.Consumer>
    );
};

const ImageURISourcePropType = PropTypes.shape({
    uri: PropTypes.string,
    bundle: PropTypes.string,
    method: PropTypes.string,
    headers: PropTypes.objectOf(PropTypes.string),
    body: PropTypes.string,
    cache: PropTypes.oneOf([
        `default`,
        `reload`,
        `force-cache`,
        `only-if-cached`
    ]),
    width: PropTypes.number,
    height: PropTypes.number,
    scale: PropTypes.number
});

CoverImage.propTypes = {
    exclusions: PropTypes.arrayOf(PropTypes.string),
    room: PropTypes.oneOf([
        `none`,
        `content-left`, `content-middle`, `content-right`,
        `content-bottom`, `content-top`,
        `media`, `activity-indicator`
    ]),
    shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]),
    width: PropTypes.number,
    height: PropTypes.number,
    corner: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
        PropTypes.shape({
            topLeft: PropTypes.number,
            topRight: PropTypes.number,
            bottomLeft: PropTypes.number,
            bottomRight: PropTypes.number
        })
    ]),
    margin: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
        PropTypes.shape({
            top: PropTypes.number,
            bottom: PropTypes.number,
            left: PropTypes.number,
            right: PropTypes.number,
            horizontal: PropTypes.number,
            vertical: PropTypes.number
        })
    ]),
    resizeMode: PropTypes.oneOf([ `cover`, `contain`, `stretch`, `repeat`, `center` ]),
    dropShadowed: PropTypes.oneOfType([
        PropTypes.bool,
        PropTypes.string
    ]),
    source: PropTypes.oneOfType([
        () => null,
        PropTypes.string,
        PropTypes.number,
        ImageURISourcePropType,
        PropTypes.arrayOf(ImageURISourcePropType)
    ]),
    defaultSource: PropTypes.oneOfType([
        () => null,
        PropTypes.string,
        PropTypes.number,
        ImageURISourcePropType,
        PropTypes.arrayOf(ImageURISourcePropType)
    ])
};

CoverImage.defaultProps = {
    exclusions: [ `` ],
    room: `none`,
    shade: `themed`,
    width: 0,
    height: 0,
    corner: `themed`,
    margin: `themed`,
    resizeMode: `contain`,
    dropShadowed: `themed`,
    source: null,
    defaultSource: null
};

export default CoverImage;
<commit_msg>Changed corner theme implementations. Code cleanups<commit_after>/**
 * Copyright 2016-present Tuan Le.
 *
 * Licensed under the MIT License.
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/mit-license.html
 *
 * 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.
 *
 *------------------------------------------------------------------------
 *
 * @module CoverImage
 * @description - Cover image component.
 *
 * @author Tuan Le (tuan.t.lei@gmail.com)
 *
 * @flow
 */
'use strict'; // eslint-disable-line

import React from 'react';

import ReactNative from 'react-native'; // eslint-disable-line

import PropTypes from 'prop-types';

import {
    DefaultTheme,
    DefaultThemeContext
} from '../../themes/default-theme';

const {
    Dimensions,
    ImageBackground
} = ReactNative;

const DEVICE_WIDTH = Dimensions.get(`window`).width;
const DEVICE_HEIGHT = Dimensions.get(`window`).height;

const DEFAULT_DROP_SHADOW_STYLE = {
    shadowColor: `#000000`,
    shadowRadius: 1,
    shadowOpacity: 0.25,
    shadowOffset: {
        width: 1,
        height: 2
    }
};

const DEFAULT_COVER_IMAGE_STYLE = {
    flexDirection: `column`,
    justifyContent: `center`,
    alignItems: `center`,
    maxWidth: DEVICE_WIDTH,
    maxHeight: DEVICE_HEIGHT
};

const CoverImage = (props) => {
    const {
        exclusions,
        shade,
        width,
        height,
        corner,
        margin,
        resizeMode,
        dropShadowed,
        source,
        defaultSource,
        style,
        children
    } = props;
    let contentChildren = null;

    if (React.Children.count(children) > 0) {
        contentChildren = React.Children.toArray(React.Children.map(children, (child) => {
            if (child !== null) {
                const inheritedProps = Array.isArray(exclusions) ? Object.entries({
                    shade
                }).filter(([
                    propName,
                    prop // eslint-disable-line
                ]) => exclusions.every((exclusion) => propName !== exclusion)).reduce((_inheritedProps, [ propName, prop ]) => {
                    _inheritedProps[propName] = prop;
                    return _inheritedProps;
                }, {}) : {
                    shade
                };
                return React.cloneElement(child, inheritedProps);
            }
            return null;
        }));
    }

    return (
        <DefaultThemeContext.Consumer>
            {
                (context = {
                    Theme: DefaultTheme
                }) => {
                    const {
                        Theme
                    } = context;
                    const nullMargin = {
                        margin: null,
                        marginTop: null,
                        marginBottom: null,
                        marginLeft: null,
                        marginRight: null,
                        marginHorizontal: null,
                        marginVertical: null
                    };
                    const nullBorderRadius = {
                        borderTopLeftRadius: null,
                        borderTopRightRadius: null,
                        borderBottomLeftRadius: null,
                        borderBottomRightRadius: null
                    };
                    let dropShadow;
                    let themedBorderRadius;
                    let themedCorner;
                    let themedMargin;

                    if (typeof corner === `string`) {
                        if (corner === `themed`) {
                            if (typeof Theme.image.cover.corner === `string` && Theme.image.corner.cover.hasOwnProperty(Theme.image.cover.corner)) {
                                themedCorner = Theme.image.corner.cover[Theme.image.cover.corner];
                            } else {
                                themedCorner = Theme.image.cover.corner;
                            }
                        } else if (Theme.image.corner.cover.hasOwnProperty(corner)) {
                            themedCorner = Theme.image.corner.cover[corner];
                        } else {
                            themedCorner = 0;
                        }
                    } else {
                        themedCorner = corner;
                    }
                    if (typeof themedCorner === `number`) {
                        themedBorderRadius = {
                            borderRadius: themedCorner
                        };
                    } else if (typeof themedCorner === `object`) {
                        themedBorderRadius = Object.entries(themedCorner).reduce((_themedBorderRadius, [ key, value ]) => {
                            let _borderRadius = nullBorderRadius;

                            _borderRadius[`border${key.charAt(0).toUpperCase()}${key.slice(1)}Radius`] = value;

                            _themedBorderRadius = {
                                ..._themedBorderRadius,
                                ..._borderRadius
                            };
                            return _themedBorderRadius;
                        }, nullBorderRadius);
                    }

                    if (typeof margin === `string`) {
                        if (margin === `themed`) {
                            if (typeof Theme.image.cover.margin === `string` && Theme.image.margin.cover.hasOwnProperty(Theme.image.cover.margin)) {
                                themedMargin = Theme.image.margin.cover[Theme.image.cover.margin];
                            } else {
                                themedMargin = Theme.image.cover.margin;
                            }
                        } else if (Theme.image.margin.cover.hasOwnProperty(margin)) {
                            themedMargin = Theme.image.margin.cover[margin];
                        } else {
                            themedMargin = 0;
                        }
                    } else {
                        themedMargin = margin;
                    }
                    if (typeof themedMargin === `number`) {
                        themedMargin = {
                            ...nullMargin,
                            margin: themedMargin
                        };
                    } else if (typeof themedMargin === `object`) {
                        themedMargin = Object.entries(themedMargin).reduce((_themedMargin, [ key, value ]) => {
                            let _margin = nullMargin;

                            _margin[`margin${key.charAt(0).toUpperCase()}${key.slice(1)}`] = value;
                            _themedMargin = {
                                ..._themedMargin,
                                ..._margin
                            };
                            return _themedMargin;
                        }, nullMargin);
                    }

                    if ((typeof dropShadowed === `boolean` && dropShadowed) || (dropShadowed === `themed` && Theme.image.cover.dropShadowed)) {
                        dropShadow = DEFAULT_DROP_SHADOW_STYLE;
                    } else {
                        dropShadow = {
                            ...DEFAULT_DROP_SHADOW_STYLE,
                            shadowRadius: 0,
                            shadowOpacity: 0,
                            shadowOffset: {
                                width: 0,
                                height: 0
                            }
                        };
                    }
                    return (
                        <ImageBackground
                            style = {{
                                ...DEFAULT_COVER_IMAGE_STYLE,
                                ...dropShadow,
                                width,
                                height,
                                ...themedMargin,
                                ...themedBorderRadius,
                                ...(typeof style === `object` ? style : {})
                            }}
                            imageStyle = {{
                                ...themedBorderRadius
                            }}
                            source = {
                                typeof source === `string` ? {
                                    uri: source,
                                    cache: `only-if-cached`
                                } : source
                            }
                            defaultSource = {
                                typeof source === `string` ? {
                                    uri: defaultSource
                                } : defaultSource
                            }
                            resizeMode = { resizeMode }
                        >
                            {
                                contentChildren
                            }
                        </ImageBackground>
                    );
                }
            }
        </DefaultThemeContext.Consumer>
    );
};

const ImageURISourcePropType = PropTypes.shape({
    uri: PropTypes.string,
    bundle: PropTypes.string,
    method: PropTypes.string,
    headers: PropTypes.objectOf(PropTypes.string),
    body: PropTypes.string,
    cache: PropTypes.oneOf([
        `default`,
        `reload`,
        `force-cache`,
        `only-if-cached`
    ]),
    width: PropTypes.number,
    height: PropTypes.number,
    scale: PropTypes.number
});

CoverImage.propTypes = {
    exclusions: PropTypes.arrayOf(PropTypes.string),
    room: PropTypes.oneOf([
        `none`,
        `content-left`, `content-middle`, `content-right`,
        `content-bottom`, `content-top`,
        `media`, `activity-indicator`
    ]),
    shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]),
    width: PropTypes.number,
    height: PropTypes.number,
    corner: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
        PropTypes.shape({
            topLeft: PropTypes.number,
            topRight: PropTypes.number,
            bottomLeft: PropTypes.number,
            bottomRight: PropTypes.number
        })
    ]),
    margin: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
        PropTypes.shape({
            top: PropTypes.number,
            bottom: PropTypes.number,
            left: PropTypes.number,
            right: PropTypes.number,
            horizontal: PropTypes.number,
            vertical: PropTypes.number
        })
    ]),
    resizeMode: PropTypes.oneOf([ `cover`, `contain`, `stretch`, `repeat`, `center` ]),
    dropShadowed: PropTypes.oneOfType([
        PropTypes.bool,
        PropTypes.string
    ]),
    source: PropTypes.oneOfType([
        () => null,
        PropTypes.string,
        PropTypes.number,
        ImageURISourcePropType,
        PropTypes.arrayOf(ImageURISourcePropType)
    ]),
    defaultSource: PropTypes.oneOfType([
        () => null,
        PropTypes.string,
        PropTypes.number,
        ImageURISourcePropType,
        PropTypes.arrayOf(ImageURISourcePropType)
    ])
};

CoverImage.defaultProps = {
    exclusions: [ `` ],
    room: `none`,
    shade: `themed`,
    width: 0,
    height: 0,
    corner: `themed`,
    margin: `themed`,
    resizeMode: `contain`,
    dropShadowed: `themed`,
    source: null,
    defaultSource: null
};

export default CoverImage;
<|endoftext|>


<commit_before>import React from 'react';
import {render} from 'react-dom';

import { Router, Route, IndexRoute, IndexRedirect, applyRouterMiddleware} from 'react-router';

let history;
if(typeof process !== "undefined" && process.env.NODE_ENV === "production") {
	history = require('react-router/lib/hashHistory');
} else {
	history = require('react-router/lib/browserHistory');
}
// console.log(typeof process !== "undefined" && process.env.NODE_ENV);

import App from './components/App';
// import Home from './components/Home';
// import Intro from './components/Intro';
// import WorkerTypes from './components/WorkerTypes';
// import Dedicated from './components/Dedicated';
// import DedicatedExample from './components/DedicatedExample';
// import Shared from './components/Shared';
// import SharedExample from './components/SharedExample';
// import WorkerScope from './components/WorkerScope';
// import InliningWorkers from './components/InliningWorkers';
// import Caveats from './components/Caveats';
// import About from './components/About';
// import Resources from './components/Resources';
import NotFound from './components/NotFound';

// TODO maybe change browserHistory to hashHitory when deploying

import useScroll from 'react-router-scroll/lib/useScroll';

// render((
// 	<Router history={history} render={applyRouterMiddleware(useScroll())}>
// 		<Route path="/" component={App}>
// 			<IndexRoute component={Home}/>
// 			<Route path="intro" component={Intro}/>
// 			<Route path="worker_types" component={WorkerTypes}/>
// 			<Route path="dedicated_worker">
// 				<IndexRoute component={Dedicated}/>
// 				<Route path="example" component={DedicatedExample}/>
// 			</Route>
// 			<Route path="shared_worker">
// 				<IndexRoute component={Shared}/>
// 				<Route path="example" component={SharedExample}/>
// 			</Route>
// 			<Route path="worker_scope" component={WorkerScope}/>
// 			<Route path="inlining_workers" component={InliningWorkers}/>
// 			<Route path="caveats" component={Caveats}/>
// 			<Route path="resources" component={Resources}/>
// 			<Route path="about" component={About} MyProp="UPPER"/>
// 			<Route path="*" component={NotFound}/>
// 		</Route>
// 	</Router>
// ),
// document.getElementById("app"));

import routes from './helpers/routemap';
console.log("First Route:", routes[0]);

render((
	<Router history={history} render={applyRouterMiddleware(useScroll())}>
		<Route path="/" component={App}>
			{/* <IndexRedirect to="/home"/> */}
			{/* <IndexRoute path={"/"} component={Home}/> */}
			{/* <Route path="../" component={Home}/> */}
			{routes}
			<Route path="*" component={NotFound}/>
		</Route>
	</Router>
),
document.getElementById("app"));
<commit_msg>refactor(routing): Simpler route passing to root route<commit_after>import React from 'react';
import {render} from 'react-dom';

import { Router, Route, applyRouterMiddleware} from 'react-router';

let history;
if(typeof process !== "undefined" && process.env.NODE_ENV === "production") {
	history = require('react-router/lib/hashHistory');
} else {
	history = require('react-router/lib/browserHistory');
}
// console.log(typeof process !== "undefined" && process.env.NODE_ENV);

import App from './components/App';
import NotFound from './components/NotFound';

// TODO maybe change browserHistory to hashHitory when deploying

import useScroll from 'react-router-scroll/lib/useScroll';

import routes from './helpers/routemap';

render((
	<Router history={history} render={applyRouterMiddleware(useScroll())}>
		<Route path="/" component={App} children={routes}/>
		<Route path="*" component={NotFound}/>
	</Router>
),
document.getElementById("app"));
<|endoftext|>


<commit_before>// ========================================================================
// Copyright (c) 2008-2009, Metaweb Technologies, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB
// TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ========================================================================

/*
**  Rendering the spreadsheet back to the user
*/

function onDisplayOutputScreen() {
    setTimeout(checkLogin,0);
    setTimeout(displaySpreadsheet,0);
    setTimeout(prepareTriples,0);
}
function onHideOutputScreen() {
    if (spreadsheetRendererYielder)
        spreadsheetRendererYielder.cancel();
    if (tripleGetterYielder)
        tripleGetterYielder.cancel();
    $("#outputSpreadSheet")[0].value = "";
}

function encodeLine(arr) {
    var values = [];
    for(var i = 0; i < headers.length; i++){
        var val = arr[i];
        if (typeof val == "undefined")
            values.push("");
        else if (!val.match(/(\t|\"|\n)/))
            values.push(arr[i])
        else {
            val = val.replace(/"/g, '""');
            values.push('"' + val + '"');
        }
    }
    return values.join("\t");
}

//Like getChainedProperty, only it preserves array placement
function getChainedPropertyPreservingPlace(entity, prop) {
    var slots = [entity];
    $.each(prop.split(":"), function(_,part) {
        var newSlots = [];
        $.each(slots, function(_,slot) {
            if (!slot || !slot[part])
                newSlots.push(undefined);
            else
                newSlots = newSlots.concat($.makeArray(slot && slot[part]))
        })
        slots = newSlots;
    });
    if (slots === []) return undefined;
    return slots;
}

function encodeRow(row) {
    var lines = [[]];
    for (var i = 0; i < headers.length; i++){
        var val = getChainedPropertyPreservingPlace(row, headers[i]);
        if ($.isArray(val)) {
            for (var j = 0; j < val.length; j++) {
                if (lines[j] == undefined) lines[j] = [];
                lines[j][i] = textValue(val[j]);
            }
        }
        else
            lines[0][i] = textValue(val);
    }
    return $.map(lines,encodeLine);
}

function displaySpreadsheet() {
    $("#outputSpreadSheet")[0].value = "One moment, rendering...";

    renderSpreadsheet(function(spreadsheet) {
        $("#outputSpreadSheet")[0].value = spreadsheet;
    })
}

var spreadsheetRendererYielder;
function renderSpreadsheet(onComplete) {
    var lines = [];
    lines.push(encodeLine(headers));
    spreadsheetRendererYielder = new Yielder();
    politeEach(rows, function(idx, row) {
        lines = lines.concat(encodeRow(row));
    },
    function() {
        onComplete(lines.join("\n"));
    }, spreadsheetRendererYielder);
}

function prepareTriples() {
    getTriples(entities, function(triples) {
        politeMap(triples,function(val){return JSON.stringify(val)},
            function(encodedTriples) {
                var tripleString = encodedTriples.join("\n");
                $(".triplesDisplay").html(tripleString);
                $(".triple_count").html(encodedTriples.length);
                $('#payload')[0].value = tripleString;
            }
        );
    });
}

var tripleGetterYielder;
function getTriples(entities, callback) {
    tripleGetterYielder = new Yielder();
    function isValidID(id) {
        if ($.isArray(id))
            id = id[0];
        return id !== undefined && $.trim(id) !== "";
    }
    function getID(entity) {
        if (entity.id === "None")
            return "$entity" + entity['/rec_ui/id'];
        return entity.id;
    }
    function getValue(property, stringValue) {
        var expectedType = freebase.getPropMetadata(property).expected_type.id;
        if (Arr.contains(["/type/int","/type/float"], expectedType))
            return Number($.trim(stringValue));
        if (expectedType === "/type/boolean"){
            var lowerValue = $.trim(stringValue.toLowerCase());
            if (lowerValue === "true")
                return true;
            if (lowerValue === "false")
                return false;
            return undefined;
        }
        return stringValue;
    }
    function cvtObject(cvt) {
        var result = {};
        var props = cvt['/rec_ui/cvt_props'];
        var empty = true;
        var type = $.makeArray(cvt['/type/object/type'])[0];
        for (var i = 0; i < props.length; i++){
            var predicate = props[i];
            if (predicate.indexOf(type) != 0){
                warn("bad predicate " + predicate + " in CVT with type" + type);
                continue;
            }
            var value = cvt[predicate];
            var outputPredicate = predicate.replace(type + "/","");
            if (isValueProperty(predicate)) {
                value = getValue(predicate, value);
                if (value){
                    result[outputPredicate] = value
                    empty = false;
                }
            }
            else {
                if (value['/rec_ui/toplevel_entity'])
                    continue;
                var id = getID(value);
                if (id){
                    result[outputPredicate] = id;
                    empty = false;
                }
            }
        }
        if (empty)
            return undefined;
        return result;
    }

    var triples = [];
    politeEach(entities, function(_,subject) {
        if (!subject || !isValidID(subject.id) || subject.isCVT())
            return;

        /* Assert each type and all included types exactly once */
        var types = new Set();
        $.each($.makeArray(subject['/type/object/type']), function(_, type){
            types.add(type);
            var metadata = freebase.getTypeMetadata(type);
            if (metadata)
                types.addAll(metadata["/freebase/type_hints/included_types"]);
        });
        $.each(types.getAll(), function(_,type) {
            if (type)
                triples.push({s:getID(subject), p:"/type/object/type",o:type});
        })

        /* If the subject is new to Freebase, give it a name as well */
        if (subject.id === "None"){
            $.each($.makeArray(subject["/type/object/name"]), function(_, name) {
                if (name)
                    triples.push({s:getID(subject),p:"/type/object/name",o:name});
            });
        }

        /* Assert each of the top level mql properties */
        var mqlProps = Arr.unique(Arr.filter($.map(subject['/rec_ui/headers'], function(val){return val.split(":")[0]}), isMqlProp));
        $.each(mqlProps, function(_, predicate) {

            $.each($.makeArray(subject[predicate]), function(_, object) {
                if (isValueProperty(predicate)) {
                    triples.push({s:getID(subject), p:predicate, o:getValue(predicate, object)});
                    return;
                }

                if (object['/rec_ui/is_cvt']){
                    if (!(object['/rec_ui/parent']['/rec_ui/id'] === subject['/rec_ui/id']))
                        return; //only create cvt once, from the 'root' of the parent
                    var cvtTripleObject = cvtObject(object);
                    if (cvtTripleObject)
                        triples.push({s:getID(subject),p:predicate,o:cvtTripleObject});
                }

                if  (!isValidID(object.id))
                    return;

                triples.push({s:getID(subject),p:predicate,o:getID(object)});
            })
        });
    }, function() {callback(triples)}, tripleGetterYielder);
}

function checkLogin() {
    $(".uploadLogin").hide();
    $(".uploadForm").hide();
    $.ajax({
        url:"http://data.labs.freebase.com/freeq/spreadsheet/",
        type:"GET",
        complete:function(response){
            if (!response || !response.status){
                error(response);
                return;
            }
            if (response.status === 200){
                $(".uploadLogin").hide();
                $(".uploadForm").show();
            }
            else if (response.status === 401){
                $(".uploadLogin").show();
                $(".uploadForm").hide();
            }
            else
                error(response);
        }});
}
<commit_msg>Fixed getValue where the value is sometimes an array rather than string<commit_after>// ========================================================================
// Copyright (c) 2008-2009, Metaweb Technologies, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB
// TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ========================================================================

/*
**  Rendering the spreadsheet back to the user
*/

function onDisplayOutputScreen() {
    setTimeout(checkLogin,0);
    setTimeout(displaySpreadsheet,0);
    setTimeout(prepareTriples,0);
}
function onHideOutputScreen() {
    if (spreadsheetRendererYielder)
        spreadsheetRendererYielder.cancel();
    if (tripleGetterYielder)
        tripleGetterYielder.cancel();
    $("#outputSpreadSheet")[0].value = "";
}

function encodeLine(arr) {
    var values = [];
    for(var i = 0; i < headers.length; i++){
        var val = arr[i];
        if (typeof val == "undefined")
            values.push("");
        else if (!val.match(/(\t|\"|\n)/))
            values.push(arr[i])
        else {
            val = val.replace(/"/g, '""');
            values.push('"' + val + '"');
        }
    }
    return values.join("\t");
}

//Like getChainedProperty, only it preserves array placement
function getChainedPropertyPreservingPlace(entity, prop) {
    var slots = [entity];
    $.each(prop.split(":"), function(_,part) {
        var newSlots = [];
        $.each(slots, function(_,slot) {
            if (!slot || !slot[part])
                newSlots.push(undefined);
            else
                newSlots = newSlots.concat($.makeArray(slot && slot[part]))
        })
        slots = newSlots;
    });
    if (slots === []) return undefined;
    return slots;
}

function encodeRow(row) {
    var lines = [[]];
    for (var i = 0; i < headers.length; i++){
        var val = getChainedPropertyPreservingPlace(row, headers[i]);
        if ($.isArray(val)) {
            for (var j = 0; j < val.length; j++) {
                if (lines[j] == undefined) lines[j] = [];
                lines[j][i] = textValue(val[j]);
            }
        }
        else
            lines[0][i] = textValue(val);
    }
    return $.map(lines,encodeLine);
}

function displaySpreadsheet() {
    $("#outputSpreadSheet")[0].value = "One moment, rendering...";

    renderSpreadsheet(function(spreadsheet) {
        $("#outputSpreadSheet")[0].value = spreadsheet;
    })
}

var spreadsheetRendererYielder;
function renderSpreadsheet(onComplete) {
    var lines = [];
    lines.push(encodeLine(headers));
    spreadsheetRendererYielder = new Yielder();
    politeEach(rows, function(idx, row) {
        lines = lines.concat(encodeRow(row));
    },
    function() {
        onComplete(lines.join("\n"));
    }, spreadsheetRendererYielder);
}

function prepareTriples() {
    getTriples(entities, function(triples) {
        politeMap(triples,function(val){return JSON.stringify(val)},
            function(encodedTriples) {
                var tripleString = encodedTriples.join("\n");
                $(".triplesDisplay").html(tripleString);
                $(".triple_count").html(encodedTriples.length);
                $('#payload')[0].value = tripleString;
            }
        );
    });
}

var tripleGetterYielder;
function getTriples(entities, callback) {
    tripleGetterYielder = new Yielder();
    function isValidID(id) {
        if ($.isArray(id))
            id = id[0];
        return id !== undefined && $.trim(id) !== "";
    }
    function getID(entity) {
        if (entity.id === "None")
            return "$entity" + entity['/rec_ui/id'];
        return entity.id;
    }
    function getValue(property, value) {
        if (getType(value) === "array") {
            if (value.length === 1)
                return getValue(property, value[0]);
            return $.map(value, function(val){return getValue(property, val)});
        }
        var stringValue = value;
        var expectedType = freebase.getPropMetadata(property).expected_type.id;
        if (Arr.contains(["/type/int","/type/float"], expectedType))
            return Number($.trim(stringValue));
        if (expectedType === "/type/boolean"){
            var lowerValue = $.trim(stringValue.toLowerCase());
            if (lowerValue === "true")
                return true;
            if (lowerValue === "false")
                return false;
            return undefined;
        }
        return stringValue;
    }
    function cvtObject(cvt) {
        var result = {};
        var props = cvt['/rec_ui/cvt_props'];
        var empty = true;
        var type = $.makeArray(cvt['/type/object/type'])[0];
        for (var i = 0; i < props.length; i++){
            var predicate = props[i];
            if (predicate.indexOf(type) != 0){
                warn("bad predicate " + predicate + " in CVT with type" + type);
                continue;
            }
            var value = cvt[predicate];
            var outputPredicate = predicate.replace(type + "/","");
            if (isValueProperty(predicate)) {
                value = getValue(predicate, value);
                if (value){
                    result[outputPredicate] = value
                    empty = false;
                }
            }
            else {
                if (value['/rec_ui/toplevel_entity'])
                    continue;
                var id = getID(value);
                if (id){
                    result[outputPredicate] = id;
                    empty = false;
                }
            }
        }
        if (empty)
            return undefined;
        return result;
    }

    var triples = [];
    politeEach(entities, function(_,subject) {
        if (!subject || !isValidID(subject.id) || subject.isCVT())
            return;

        /* Assert each type and all included types exactly once */
        var types = new Set();
        $.each($.makeArray(subject['/type/object/type']), function(_, type){
            types.add(type);
            var metadata = freebase.getTypeMetadata(type);
            if (metadata)
                types.addAll(metadata["/freebase/type_hints/included_types"]);
        });
        $.each(types.getAll(), function(_,type) {
            if (type)
                triples.push({s:getID(subject), p:"/type/object/type",o:type});
        })

        /* If the subject is new to Freebase, give it a name as well */
        if (subject.id === "None"){
            $.each($.makeArray(subject["/type/object/name"]), function(_, name) {
                if (name)
                    triples.push({s:getID(subject),p:"/type/object/name",o:name});
            });
        }

        /* Assert each of the top level mql properties */
        var mqlProps = Arr.unique(Arr.filter($.map(subject['/rec_ui/headers'], function(val){return val.split(":")[0]}), isMqlProp));
        $.each(mqlProps, function(_, predicate) {

            $.each($.makeArray(subject[predicate]), function(_, object) {
                if (isValueProperty(predicate)) {
                    triples.push({s:getID(subject), p:predicate, o:getValue(predicate, object)});
                    return;
                }

                if (object['/rec_ui/is_cvt']){
                    if (!(object['/rec_ui/parent']['/rec_ui/id'] === subject['/rec_ui/id']))
                        return; //only create cvt once, from the 'root' of the parent
                    var cvtTripleObject = cvtObject(object);
                    if (cvtTripleObject)
                        triples.push({s:getID(subject),p:predicate,o:cvtTripleObject});
                }

                if  (!isValidID(object.id))
                    return;

                triples.push({s:getID(subject),p:predicate,o:getID(object)});
            })
        });
    }, function() {callback(triples)}, tripleGetterYielder);
}

function checkLogin() {
    $(".uploadLogin").hide();
    $(".uploadForm").hide();
    $.ajax({
        url:"http://data.labs.freebase.com/freeq/spreadsheet/",
        type:"GET",
        complete:function(response){
            if (!response || !response.status){
                error(response);
                return;
            }
            if (response.status === 200){
                $(".uploadLogin").hide();
                $(".uploadForm").show();
            }
            else if (response.status === 401){
                $(".uploadLogin").show();
                $(".uploadForm").hide();
            }
            else
                error(response);
        }});
}
<|endoftext|>


<commit_before>var generators = require('yeoman-generator');
var readFile = require('html-wiring');
var makeDir = require('mkdirp');

module.exports = generators.Base.extend({

    prompting: function () {
        return this.prompt([{
            type    : 'input',
            name    : 'appName',
            message : 'Your project name',
            default : this.appname // Default to current folder name
        }, {
            type: 'input',
            name: 'baseUrl',
            message: 'Choose the base URL for the Application Under Test',
            default: 'http://localhost:3000'
        }]).then(function (answers) {
            this.appName = answers.appName;
            this.baseUrl = answers.baseUrl;
            this.log('app name', answers.appName);
            this.log('baseUrl', answers.baseUrl);
        }.bind(this));
    },

    writing: {
        app: function() {
            //Avoid https://github.com/npm/npm/issues/1862 - npm renames .gitignore to .npmignore
            this.fs.move('_gitignore', '.gitignore');
            makeDir.mkdirp('tests/e2e/example/pageobjects');
            makeDir.mkdirp('tests/e2e/example/specs');
            makeDir.mkdirp('tests/e2e/helpers');
            makeDir.mkdirp('src/js');
        },

        projectfiles: function() {
            this.copy(
                'conf.js',
                'tests/e2e/conf.js'
            );
            this.copy(
                'example.spec.js',
                'tests/e2e/example/specs/example.spec.js'
            );
            this.copy(
                'example.page.js',
                'tests/e2e/example/pageobjects/example.page.js'
            );
            this.copy(
                'html-select.helper.js',
                'tests/e2e/helpers/html-select.helper.js'
            );
            this.copy(
                'wait-plugin.js',
                'src/js/wait-plugin.js'
            );
            this.template('package.json');
            this.copy('README.md');
            this.copy('Gruntfile.js');
            this.copy('.gitignore');
        }
    },

    install: function() {

        console.log('method install just ran');
        this.config.save();
        var self = this;
        this.installDependencies({
            bower: false,
            skipInstall: this.options['skip-install'],
            callback: function() {
                this.spawnCommand('grunt', ['install']);
                var readme = readFile.readFileAsString('README.md');
                self.log('Done! Now follow these steps:');
                self.log(readme);
                self.log('You can read these instructions in README.md');
            }.bind(this)
        });
    }
});

<commit_msg>Avoid npm issue 1862 npm renames .gitignore to .npmignore<commit_after>var generators = require('yeoman-generator');
var readFile = require('html-wiring');
var makeDir = require('mkdirp');

module.exports = generators.Base.extend({

    prompting: function () {
        return this.prompt([{
            type    : 'input',
            name    : 'appName',
            message : 'Your project name',
            default : this.appname // Default to current folder name
        }, {
            type: 'input',
            name: 'baseUrl',
            message: 'Choose the base URL for the Application Under Test',
            default: 'http://localhost:3000'
        }]).then(function (answers) {
            this.appName = answers.appName;
            this.baseUrl = answers.baseUrl;
            this.log('app name', answers.appName);
            this.log('baseUrl', answers.baseUrl);
        }.bind(this));
    },

    writing: {
        app: function() {
            makeDir.mkdirp('tests/e2e/example/pageobjects');
            makeDir.mkdirp('tests/e2e/example/specs');
            makeDir.mkdirp('tests/e2e/helpers');
            makeDir.mkdirp('src/js');
        },

        projectfiles: function() {
            this.copy(
                'conf.js',
                'tests/e2e/conf.js'
            );
            this.copy(
                'example.spec.js',
                'tests/e2e/example/specs/example.spec.js'
            );
            this.copy(
                'example.page.js',
                'tests/e2e/example/pageobjects/example.page.js'
            );
            this.copy(
                'html-select.helper.js',
                'tests/e2e/helpers/html-select.helper.js'
            );
            this.copy(
                'wait-plugin.js',
                'src/js/wait-plugin.js'
            );
            this.template('package.json');
            this.copy('README.md');
            this.copy('Gruntfile.js');
            //Avoid https://github.com/npm/npm/issues/1862 - npm renames .gitignore to .npmignore
            this.copy(
                '_gitignore',
                '.gitignore'
            );
        }
    },

    install: function() {

        console.log('method install just ran');
        this.config.save();
        var self = this;
        this.installDependencies({
            bower: false,
            skipInstall: this.options['skip-install'],
            callback: function() {
                this.spawnCommand('grunt', ['install']);
                var readme = readFile.readFileAsString('README.md');
                self.log('Done! Now follow these steps:');
                self.log(readme);
                self.log('You can read these instructions in README.md');
            }.bind(this)
        });
    }
});

<|endoftext|>


<commit_before>const members = [
  {
    username: 'fforres',
    image: 'fforres.jpg',
    twitter: 'fforres'
  },
  {
    username: 'Xabadu',
    image: 'xabadu.jpg',
    twitter: 'xabadu'
  },
  {
    username: 'DMaster69',
    image: 'dmaster.jpg',
    twitter: 'DMaster69'
  },
  {
    username: 'cristofer-dev',
    image: 'cristofer.jpg',
    twitter: 'cristofer_dev'
  },
  {
    username: 'L0rdKras',
    image: 'lordkras.jpg',
    twitter: 'L0rdKras'
  },
  {
    username: 'luchosrock',
    image: 'luchosrock.jpg',
    twitter: 'luismairiu'
  },
  {
    username: 'enBonnet',
    image: 'bonnet.jpg',
    twitter: 'enBonnet'
  },
  {
    username: 'carolina',
    image: 'carolina.jpg',
    github: 'carolina-pinzon'
  },
  {
    username: 'max',
    image: 'creedarky.jpg',
    twitter: 'creedarky'
  }
];

export default members;
<commit_msg>Remove Xabadu from orgs (#128)<commit_after>const members = [
  {
    username: 'fforres',
    image: 'fforres.jpg',
    twitter: 'fforres'
  },
  {
    username: 'DMaster69',
    image: 'dmaster.jpg',
    twitter: 'DMaster69'
  },
  {
    username: 'cristofer-dev',
    image: 'cristofer.jpg',
    twitter: 'cristofer_dev'
  },
  {
    username: 'L0rdKras',
    image: 'lordkras.jpg',
    twitter: 'L0rdKras'
  },
  {
    username: 'luchosrock',
    image: 'luchosrock.jpg',
    twitter: 'luismairiu'
  },
  {
    username: 'enBonnet',
    image: 'bonnet.jpg',
    twitter: 'enBonnet'
  },
  {
    username: 'carolina',
    image: 'carolina.jpg',
    github: 'carolina-pinzon'
  },
  {
    username: 'max',
    image: 'creedarky.jpg',
    twitter: 'creedarky'
  }
];

export default members;
<|endoftext|>


<commit_before>function makeData() {
  "use strict";

  var data1 = [{team: "Team A", earnings: 400000, quarter: "q1"}, {team: "Team A", earnings: -300000, quarter: "q2"}, {team: "Team A", earnings: 600000, quarter: "q3"}, {team: "Team A", earnings: -100000, quarter: "q4"}];
  var data2 = [{team: "Team B", earnings: 200000, quarter: "q1"}, {team: "Team B", earnings: 300000, quarter: "q2"}, {team: "Team B", earnings: 500000, quarter: "q3"}, {team: "Team B", earnings: 400000, quarter: "q4"}];
  var data3 = [{team: "Team C", earnings: -200000, quarter: "q1"}, {team: "Team C", earnings: 0, quarter: "q2"}, {team: "Team C", earnings: -100000, quarter: "q3"}, {team: "Team C", earnings: 300000, quarter: "q4"}];
  var data4 = [{team: "Team D", earnings: -15000, quarter: "q1"}, {team: "Team D", earnings: -23000, quarter: "q2"}, {team: "Team D", earnings: 200000, quarter: "q3"}, {team: "Team D", earnings: -1300000, quarter: "q4"}];
  var data5 = [{team: "Team E", earnings: 90000, quarter: "q1"}, {team: "Team E", earnings: 170000, quarter: "q2"}, {team: "Team E", earnings: 50000, quarter: "q3"}, {team: "Team E", earnings: 300000, quarter: "q4"}];

  return [data1, data2, data3, data4, data5];
}

function run(div, data, Plottable) {
  "use strict";

  var svg = div.append("svg").attr("height", 800);

  var xScale1 = new Plottable.Scale.Ordinal();
  var yScale1 = new Plottable.Scale.Linear();
  var xScale2 = new Plottable.Scale.Linear();
  var yScale2 = new Plottable.Scale.Ordinal();

  var colorScale = new Plottable.Scale.Color();

  var xAxis1 = new Plottable.Axis.Category(xScale1, "bottom");
  var yAxis1 = new Plottable.Axis.Numeric(yScale1, "left");
  var xAxis2 = new Plottable.Axis.Numeric(xScale2, "bottom");
  var yAxis2 = new Plottable.Axis.Category(yScale2, "left");

  var legend = new Plottable.Component.HorizontalLegend(colorScale);
    legend.xAlign("center");

  var title = new Plottable.Component.TitleLabel("Sample Net Earnings by Teams");

  var verticalPlot = new Plottable.Plot.StackedBar(xScale1, yScale1, true)
    .project("x", "quarter", xScale1)
    .project("y", "earnings", yScale1)
    .project("fill", "team", colorScale)
    .addDataset("d1", data[0])
    .addDataset("d2", data[1])
    .addDataset("d3", data[2])
    .addDataset("d4", data[3])
    .addDataset("d5", data[4]);

  var horizontalPlot = new Plottable.Plot.StackedBar(xScale2, yScale2, false)
    .project("x", "earnings", xScale2)
    .project("y", "quarter", yScale2)
    .project("fill", "team", colorScale)
    .addDataset("d1", data[0])
    .addDataset("d2", data[1])
    .addDataset("d3", data[2])
    .addDataset("d4", data[3])
    .addDataset("d5", data[4]);

  var chart1 = new Plottable.Component.Table([
    [yAxis1, verticalPlot], [null, xAxis1]
    ]);

  var chart2 = new Plottable.Component.Table([
    [yAxis2, horizontalPlot], [null, xAxis2]
    ]);

  var finalchart = new Plottable.Component.Table([
    [title],
    [legend],
    [chart1],
    [chart2]
    ]);

  finalchart.renderTo(svg);
}
<commit_msg>changes after Brandon's comments<commit_after>function makeData() {
  "use strict";

  var data1 = [{team: "Team A", earnings: 400000, quarter: "q1"}, {team: "Team A", earnings: -300000, quarter: "q2"}, {team: "Team A", earnings: 600000, quarter: "q3"}, {team: "Team A", earnings: -100000, quarter: "q4"}];
  var data2 = [{team: "Team B", earnings: 200000, quarter: "q1"}, {team: "Team B", earnings: 300000, quarter: "q2"}, {team: "Team B", earnings: 500000, quarter: "q3"}, {team: "Team B", earnings: 400000, quarter: "q4"}];
  var data3 = [{team: "Team C", earnings: -200000, quarter: "q1"}, {team: "Team C", earnings: 0, quarter: "q2"}, {team: "Team C", earnings: -100000, quarter: "q3"}, {team: "Team C", earnings: 300000, quarter: "q4"}];
  var data4 = [{team: "Team D", earnings: -15000, quarter: "q1"}, {team: "Team D", earnings: -23000, quarter: "q2"}, {team: "Team D", earnings: 200000, quarter: "q3"}, {team: "Team D", earnings: -1300000, quarter: "q4"}];
  var data5 = [{team: "Team E", earnings: 90000, quarter: "q1"}, {team: "Team E", earnings: 170000, quarter: "q2"}, {team: "Team E", earnings: 50000, quarter: "q3"}, {team: "Team E", earnings: 300000, quarter: "q4"}];

  return [data1, data2, data3, data4, data5];
}

function run(div, data, Plottable) {
  "use strict";

  var svg = div.append("svg").attr("height", 800);

  var xScale1 = new Plottable.Scale.Ordinal();
  var yScale1 = new Plottable.Scale.Linear();
  var xScale2 = new Plottable.Scale.Linear();
  var yScale2 = new Plottable.Scale.Ordinal();

  var colorScale = new Plottable.Scale.Color();

  var xAxis1 = new Plottable.Axis.Category(xScale1, "bottom");
  var yAxis1 = new Plottable.Axis.Numeric(yScale1, "left");
  var xAxis2 = new Plottable.Axis.Numeric(xScale2, "bottom");
  var yAxis2 = new Plottable.Axis.Category(yScale2, "left");

  var legend = new Plottable.Component.HorizontalLegend(colorScale);
  legend.xAlign("center");

  var title = new Plottable.Component.TitleLabel("Sample Net Earnings by Teams");

  var verticalPlot = new Plottable.Plot.StackedBar(xScale1, yScale1, true)
    .project("x", "quarter", xScale1)
    .project("y", "earnings", yScale1)
    .project("fill", "team", colorScale)
    .addDataset("d1", data[0])
    .addDataset("d2", data[1])
    .addDataset("d3", data[2])
    .addDataset("d4", data[3])
    .addDataset("d5", data[4]);

  var horizontalPlot = new Plottable.Plot.StackedBar(xScale2, yScale2, false)
    .project("x", "earnings", xScale2)
    .project("y", "quarter", yScale2)
    .project("fill", "team", colorScale)
    .addDataset("d1", data[0])
    .addDataset("d2", data[1])
    .addDataset("d3", data[2])
    .addDataset("d4", data[3])
    .addDataset("d5", data[4]);

  var chart1 = new Plottable.Component.Table([
    [yAxis1, verticalPlot], [null, xAxis1]
    ]);

  var chart2 = new Plottable.Component.Table([
    [yAxis2, horizontalPlot], [null, xAxis2]
    ]);

  var finalchart = new Plottable.Component.Table([
    [title],
    [legend],
    [chart1],
    [chart2]
    ]);

  finalchart.renderTo(svg);
}
<|endoftext|>


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

var Attributes = require('./attributes')

// packet class
var Packet = function (method, type, attrs) {
  this.method = method
  this.type = type
  this.attrs = attrs || new Attributes()
  this.tid = this._getTransactionId()
}

// packet header length
Packet.HEADER_LENGTH = 20
// STUN magic cookie
Packet.MAGIC_COOKIE = 0x2112A442 // fixed
// max transaction ID (32bit)
Packet.TID_MAX = Math.pow(2, 32)
// message types
Packet.TYPE = {
  REQUEST: 0x0000,
  INDICATION: 0x0010,
  SUCCESS_RESPONSE: 0x0100,
  ERROR_RESPONSE: 0x0110
}
// STUN method
Packet.METHOD = {}
Packet.METHOD.BINDING = 0x0001

// encode packet
Packet.prototype.encode = function () {
  var attrsBuffer = this.attrs.encode(Packet.MAGIC_COOKIE, this.tid)
  var attrsLength = attrsBuffer.length
  // check if we need to include a message integrity attribute
  var messageIntegrity = this.getAttribute(Attributes.MESSAGE_INTEGRITY)
  if (messageIntegrity) {
    attrsLength += 24 // size of the message-integrity attribute
  }
  // encode header buffer
  var headerBuffer = this._encodeHeader(attrsLength)
  // create packet buffer
  var packetBuffer = Buffer.concat([headerBuffer, attrsBuffer])
  // append message integrity attribute if requested
  if (messageIntegrity) {
    var messageIntegrityBuffer = messageIntegrity.encode(packetBuffer)
    packetBuffer = Buffer.concat([packetBuffer, messageIntegrityBuffer])
  }
  return packetBuffer
}

// decode packet
Packet.decode = function (buffer) {
  if (!Packet._isStunPacket(buffer)) {
    winston.debug('[libstun] this is not a STUN packet')
    return
  }

  var headerBytes = buffer.slice(0, Packet.HEADER_LENGTH)
  var header = Packet._decodeHeader(headerBytes)

  if (header.magic !== Packet.MAGIC_COOKIE) {
    var incorrectMagicCookieError = 'magic cookie field has incorrect value'
    winston.error('[libstun] ' + incorrectMagicCookieError)
    throw new Error(incorrectMagicCookieError)
  }

  var attrsBytes = buffer.slice(Packet.HEADER_LENGTH, buffer.length)
  var attrs = Attributes.decode(attrsBytes, headerBytes)

  var packet = new Packet(header.method, header.type, attrs)
  packet.tid = header.tid

  return packet
}

// get attribute
Packet.prototype.getAttribute = function (type) {
  return this.attrs.get(type)
}

// encode packet header
Packet.prototype._encodeHeader = function (length) {
  var type = this.method | this.type
  var encodedHeader = new Buffer(Packet.HEADER_LENGTH)
  encodedHeader.writeUInt16BE((type & 0x3fff), 0)
  encodedHeader.writeUInt16BE(length, 2)
  encodedHeader.writeUInt32BE(Packet.MAGIC_COOKIE, 4)
  encodedHeader.writeUInt32BE(0, 8)
  encodedHeader.writeUInt32BE(0, 12)
  encodedHeader.writeUInt32BE(this.tid, 16)

  return encodedHeader
}

// decode packet header
Packet._decodeHeader = function (buffer) {
  var header = {}
  var methodType = buffer.readUInt16BE(0)
  header.length = buffer.readUInt16BE(2)
  header.magic = buffer.readUInt32BE(4)
  header.tid = buffer.readUInt32BE(16)
  header.type = (methodType & 0x0110)
  header.method = (methodType & 0xFEEF)
  return header
}

// check if this is a STUN packet (starts with 0b00)
Packet._isStunPacket = function (buffer) {
  var block = buffer.readUInt8(0)
  var bit1 = containsFlag(block, 0x80)
  var bit2 = containsFlag(block, 0x40)
  return (!bit1 && !bit2)
}

// generate tansaction ID
Packet.prototype._getTransactionId = function () {
  return (Math.random() * Packet.TID_MAX)
}

function containsFlag (number, flag) {
  return (number & flag) === flag
}

module.exports = Packet
<commit_msg>checking method and type before constructing new packet<commit_after>var winston = require('winston')

var Attributes = require('./attributes')

// packet class
var Packet = function (method, type, attrs) {
  if (!containsValue(Packet.METHOD, method)) {
    var methodError = '[libstun] invalid packet method attribute'
    winston.error(methodError)
    throw new Error(methodError)
  }
  if (!containsValue(Packet.TYPE, type)) {
    var typeError = '[libstun] invalid packet type attribute'
    winston.error(typeError)
    throw new Error(typeError)
  }

  this.method = method
  this.type = type
  this.attrs = attrs || new Attributes()
  this.tid = this._getTransactionId()
}

// packet header length
Packet.HEADER_LENGTH = 20
// STUN magic cookie
Packet.MAGIC_COOKIE = 0x2112A442 // fixed
// max transaction ID (32bit)
Packet.TID_MAX = Math.pow(2, 32)
// message types
Packet.TYPE = {
  REQUEST: 0x0000,
  INDICATION: 0x0010,
  SUCCESS_RESPONSE: 0x0100,
  ERROR_RESPONSE: 0x0110
}
// STUN method
Packet.METHOD = {}
Packet.METHOD.BINDING = 0x0001

// encode packet
Packet.prototype.encode = function () {
  var attrsBuffer = this.attrs.encode(Packet.MAGIC_COOKIE, this.tid)
  var attrsLength = attrsBuffer.length
  // check if we need to include a message integrity attribute
  var messageIntegrity = this.getAttribute(Attributes.MESSAGE_INTEGRITY)
  if (messageIntegrity) {
    attrsLength += 24 // size of the message-integrity attribute
  }
  // encode header buffer
  var headerBuffer = this._encodeHeader(attrsLength)
  // create packet buffer
  var packetBuffer = Buffer.concat([headerBuffer, attrsBuffer])
  // append message integrity attribute if requested
  if (messageIntegrity) {
    var messageIntegrityBuffer = messageIntegrity.encode(packetBuffer)
    packetBuffer = Buffer.concat([packetBuffer, messageIntegrityBuffer])
  }
  return packetBuffer
}

// decode packet
Packet.decode = function (buffer) {
  if (!Packet._isStunPacket(buffer)) {
    winston.debug('[libstun] this is not a STUN packet')
    return
  }

  var headerBytes = buffer.slice(0, Packet.HEADER_LENGTH)
  var header = Packet._decodeHeader(headerBytes)

  if (header.magic !== Packet.MAGIC_COOKIE) {
    var incorrectMagicCookieError = 'magic cookie field has incorrect value'
    winston.error('[libstun] ' + incorrectMagicCookieError)
    throw new Error(incorrectMagicCookieError)
  }

  var attrsBytes = buffer.slice(Packet.HEADER_LENGTH, buffer.length)
  var attrs = Attributes.decode(attrsBytes, headerBytes)

  var packet = new Packet(header.method, header.type, attrs)
  packet.tid = header.tid

  return packet
}

// get attribute
Packet.prototype.getAttribute = function (type) {
  return this.attrs.get(type)
}

// encode packet header
Packet.prototype._encodeHeader = function (length) {
  var type = this.method | this.type
  var encodedHeader = new Buffer(Packet.HEADER_LENGTH)
  encodedHeader.writeUInt16BE((type & 0x3fff), 0)
  encodedHeader.writeUInt16BE(length, 2)
  encodedHeader.writeUInt32BE(Packet.MAGIC_COOKIE, 4)
  encodedHeader.writeUInt32BE(0, 8)
  encodedHeader.writeUInt32BE(0, 12)
  encodedHeader.writeUInt32BE(this.tid, 16)

  return encodedHeader
}

// decode packet header
Packet._decodeHeader = function (buffer) {
  var header = {}
  var methodType = buffer.readUInt16BE(0)
  header.length = buffer.readUInt16BE(2)
  header.magic = buffer.readUInt32BE(4)
  header.tid = buffer.readUInt32BE(16)
  header.type = (methodType & 0x0110)
  header.method = (methodType & 0xFEEF)
  return header
}

// check if this is a STUN packet (starts with 0b00)
Packet._isStunPacket = function (buffer) {
  var block = buffer.readUInt8(0)
  var bit1 = containsFlag(block, 0x80)
  var bit2 = containsFlag(block, 0x40)
  return (!bit1 && !bit2)
}

// generate tansaction ID
Packet.prototype._getTransactionId = function () {
  return (Math.random() * Packet.TID_MAX)
}

// utils
function containsFlag (number, flag) {
  return (number & flag) === flag
}

function containsValue (object, value) {
  var result = false
  Object.keys(object).forEach(function (key) {
    if (object[key] === value) {
      result = true
    }
  })
  return result
}

module.exports = Packet
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import formatTime from '../../helpers/formatTime'

export default class AudioProgressBar extends Component {
  constructor(props) {
    super(props)
    this.handleSeek = this.handleSeek.bind(this)
  }

  componentDidMount() {
    const forceUpdate = () => { this.forceUpdate.call(this) }

    this.props.audio.on('load', forceUpdate)
    this.props.audio.on('seek', forceUpdate)
    this.props.audio.on('play', () => {
      this.timer = setInterval(forceUpdate, 1000)
    })
    this.props.audio.on('pause', () => clearInterval(this.timer))
    this.props.audio.on('stop', () => clearInterval(this.timer))
  }

  handleSeek(event) {
    const coords  = this.refs.seekBar.getClientRects()[0]
    const clickX = event.pageX - coords.left
    const percent = clickX / (coords.right - coords.left)

    const seekPosition = this.props.audio.duration() * percent
    this.props.audio.seek(seekPosition)
  }

  render() {
    const { audio } = this.props
    const position = audio.seek()
    const duration = audio.duration()
    const percentage = `${(position / duration) * 100}%`

    let progressText, progressStyle
    if (this.props.audio.state() === 'loading') {
      progressText = 'Loading...'
      progressStyle = { display: 'none' }
    } else {
      progressText = `${formatTime(position)} / ${formatTime(duration)}`
      progressStyle = { width: percentage }
    }

    return (

{progressText}

{progressText}

    )
  }
}
<commit_msg>Increase speed of progress-bar updates<commit_after>import React, { Component } from 'react'
import formatTime from '../../helpers/formatTime'

export default class AudioProgressBar extends Component {
  constructor(props) {
    super(props)
    this.handleSeek = this.handleSeek.bind(this)
  }

  componentDidMount() {
    const forceUpdate = () => { this.forceUpdate.call(this) }

    this.props.audio.on('load', forceUpdate)
    this.props.audio.on('seek', forceUpdate)
    this.props.audio.on('play', () => {
      this.timer = setInterval(forceUpdate, 500)
    })
    this.props.audio.on('pause', () => clearInterval(this.timer))
    this.props.audio.on('stop', () => clearInterval(this.timer))
  }

  handleSeek(event) {
    const coords  = this.refs.seekBar.getClientRects()[0]
    const clickX = event.pageX - coords.left
    const percent = clickX / (coords.right - coords.left)

    const seekPosition = this.props.audio.duration() * percent
    this.props.audio.seek(seekPosition)
  }

  render() {
    const { audio } = this.props
    const position = audio.seek()
    const duration = audio.duration()
    const percentage = `${(position / duration) * 100}%`

    let progressText, progressStyle
    if (this.props.audio.state() === 'loading') {
      progressText = 'Loading...'
      progressStyle = { display: 'none' }
    } else {
      progressText = `${formatTime(position)} / ${formatTime(duration)}`
      progressStyle = { width: percentage }
    }

    return (

{progressText}

{progressText}

    )
  }
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var fs = require('fs');
var url = require('url');

var BuymilkGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Buymilk generator!'));

    var prompts = [{
      type: 'input',
      name: 'store_url',
      message: 'What is your store URL?',
      default: 'http://example.buycraft.net/'
    }];

    this.prompt(prompts, function (props) {
      this.store_url = url.parse(props.store_url);

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('app');
    this.mkdir('app/templates');

    var store_url = this.store_url;

    this.fetch(this.store_url.href, 'app', function() {
        var indexHtml = fs.readFileSync('app/' + store_url.hostname)
                          .toString()
                          .replace(/\/assets/g, store_url.href + "assets") // Replace assets with store ones
                          .replace(/theme\/style\?cache=\d+/g, 'styles/main.css'); // Inject our custom css appropriately.
        fs.writeFileSync('app/index.html', indexHtml);
        fs.unlink('app/' + store_url.hostname);
    });

    this.template('_package.json', 'package.json');
    this.template('_Gulpfile.js', 'Gulpfile.js');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
  },

  method3: function() {
    console.log('This is a deep deep test');
  }
});

module.exports = BuymilkGenerator;
<commit_msg>Add build testing.<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var fs = require('fs');
var url = require('url');

var BuymilkGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Buymilk generator!'));

    var prompts = [{
      type: 'input',
      name: 'store_url',
      message: 'What is your store URL?',
      default: 'http://example.buycraft.net/'
    }];

    this.prompt(prompts, function (props) {
      try {
        this.store_url = url.parse(props.store_url);
      } catch(e) {
          done(e);
      }

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('app');
    this.mkdir('app/templates');

    var store_url = this.store_url;

    this.fetch(this.store_url.href, 'app', function() {
        var indexHtml = fs.readFileSync('app/' + store_url.hostname)
                          .toString()
                          .replace(/\/assets/g, store_url.href + "assets") // Replace assets with store ones
                          .replace(/theme\/style\?cache=\d+/g, 'styles/main.css'); // Inject our custom css appropriately.
        fs.writeFileSync('app/index.html', indexHtml);
        fs.unlink('app/' + store_url.hostname);
    });

    this.template('_package.json', 'package.json');
    this.template('_Gulpfile.js', 'Gulpfile.js');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
  },

  method3: function() {
    console.log('This is a deep deep test');
  }
});

module.exports = BuymilkGenerator;
<|endoftext|>