<commit_before>'use strict'

import React from 'react'
import { connect } from 'react-redux'

import { updateSelected } from '../actions'

import BarChart from './main-figure-bar-chart'
import BarChartHorizontal from './main-figure-bar-chart-horizontal'

const MainFigure = React.createClass({
  propTypes: {
    selected: React.PropTypes.string,
    mapData: React.PropTypes.object,
    dispatch: React.PropTypes.func
  },
  _getHighestValue: (zipProps) => {
    let values = [zipProps.students_gradeKto5, zipProps.students_grade6to8,
                  zipProps.students_grade9to12, zipProps.slots_gradeKto5,
                  zipProps.slots_grade6to8, zipProps.slots_grade9to12]
    return Math.max.apply(null, values.map((value) => parseInt(value)))
  },

  _deselectZip: function () {
    this.props.dispatch(updateSelected(''))
  },

  render: function () {
    const zipCode = this.props.selected
    const zipProps = this.props.mapData.features.find((feature) => {
      return feature.properties.zip_code === zipCode
    }).properties
    const highVal = this._getHighestValue(zipProps)
    const studentsKTo5 = zipProps.students_gradeKto5
    const slotsKTo5 = zipProps.slots_gradeKto5
    const students6To8 = zipProps.students_grade6to8
    const slots6To8 = zipProps.slots_grade6to8
    const students9To12 = zipProps.students_grade9to12
    const slots9To12 = zipProps.slots_grade9to12
    return (

            Back to All Areas

              Supply and demand for {zipProps.zip_code}

$??,???

Median Income

                {zipProps['families_below_poverty (percentage)']}%

Families Below Poverty

                {zipProps.schoolage_children.toLocaleString()}

Total School Aged Children

                {zipProps.dropout_factories}

Dropout Factories

                {zipProps.feeder_schools}

Feeder Schools

All Grade Levels

5

 After-school programs

                <BarChart
                  students={45}
                  studentPercent={90}
                  slots={70}
                  slotPercent={45}
                  zipCode={'20001'}
                />

Grades K-5

            <BarChartHorizontal
                students={45}
                studentPercent={90}
                slots={70}
                slotPercent={45}
                zipCode={'20001'}
              />

Grades 6-8

            <BarChartHorizontal
                students={45}
                studentPercent={90}
                slots={70}
                slotPercent={45}
                zipCode={'20001'}
              />

Grades 9-12

            <BarChartHorizontal
                students={45}
                studentPercent={90}
                slots={70}
                slotPercent={45}
                zipCode={'20001'}
              />

Grades K-12

            <BarChartHorizontal
                students={45}
                studentPercent={90}
                slots={70}
                slotPercent={45}
                zipCode={'20001'}
              />

              <BarChart
                students={studentsKTo5}
                studentPercent={studentsKTo5 / highVal * 100}
                slots={slotsKTo5}
                slotPercent={slotsKTo5 / highVal * 100}
                zipCode={zipCode}
              />

              <BarChart
                students={students6To8}
                studentPercent={students6To8 / highVal * 100}
                slots={slots6To8}
                slotPercent={slots6To8 / highVal * 100}
                zipCode={zipCode}
              />

              <BarChart
                students={students9To12}
                studentPercent={students9To12 / highVal * 100}
                slots={slots9To12}
                slotPercent={slots9To12 / highVal * 100}
                zipCode={zipCode}
              />

    )
  }
})

function mapStateToProps (state) {
  return {
    selected: state.selected
  }
}

export default connect(mapStateToProps)(MainFigure)
<commit_msg>Resolve conflicts<commit_after>'use strict'

import React from 'react'
import { connect } from 'react-redux'

import { updateSelected } from '../actions'

import BarChart from './main-figure-bar-chart'
import BarChartHorizontal from './main-figure-bar-chart-horizontal'

const MainFigure = React.createClass({
  propTypes: {
    selected: React.PropTypes.string,
    mapData: React.PropTypes.object,
    dispatch: React.PropTypes.func
  },
  _getHighestValue: (zipProps) => {
    let values = [zipProps.students_gradeKto5, zipProps.students_grade6to8,
                  zipProps.students_grade9to12, zipProps.slots_gradeKto5,
                  zipProps.slots_grade6to8, zipProps.slots_grade9to12]
    return Math.max.apply(null, values.map((value) => parseInt(value)))
  },

  _deselectZip: function () {
    this.props.dispatch(updateSelected(''))
  },

  render: function () {
    const zipCode = this.props.selected
    const zipProps = this.props.mapData.features.find((feature) => {
      return feature.properties.zip_code === zipCode
    }).properties
    const highVal = this._getHighestValue(zipProps)
    const studentsKTo5 = zipProps.students_gradeKto5
    const slotsKTo5 = zipProps.slots_gradeKto5
    const students6To8 = zipProps.students_grade6to8
    const slots6To8 = zipProps.slots_grade6to8
    const students9To12 = zipProps.students_grade9to12
    const slots9To12 = zipProps.slots_grade9to12
    const studentsKTo12 = zipProps.students_gradeKto12
    const slotsKTo12 = zipProps.slots_gradeKto12
    return (

            Back to All Areas

              Supply and demand for {zipProps.zip_code}

$??,???

Median Income

                {zipProps['families_below_poverty (percentage)']}%

Families Below Poverty

                {zipProps.schoolage_children.toLocaleString()}

Total School Aged Children

                {zipProps.dropout_factories}

Dropout Factories

                {zipProps.feeder_schools}

Feeder Schools

All Grade Levels

5

 After-school programs

                <BarChart
                  students={45}
                  studentPercent={90}
                  slots={70}
                  slotPercent={45}
                  zipCode={'20001'}
                />

Grades K-5

            <BarChartHorizontal
              students={studentsKTo5}
              studentPercent={studentsKTo5 / highVal * 100}
              slots={slotsKTo5}
              slotPercent={slotsKTo5 / highVal * 100}
              zipCode={zipCode}
              />

Grades 6-8

            <BarChartHorizontal
              students={students6To8}
              studentPercent={students6To8 / highVal * 100}
              slots={slots6To8}
              slotPercent={slots6To8 / highVal * 100}
              zipCode={zipCode}
              />

Grades 9-12

            <BarChartHorizontal
              students={students9To12}
              studentPercent={students9To12 / highVal * 100}
              slots={slots9To12}
              slotPercent={slots9To12 / highVal * 100}
              zipCode={zipCode}
              />

Grades K-12

            <BarChartHorizontal
              students={studentsKTo12}
              studentPercent={studentsKTo12 / highVal * 100}
              slots={slotsKTo12}
              slotPercent={slotsKTo12 / highVal * 100}
              zipCode={zipCode}
              />

    )
  }
})

function mapStateToProps (state) {
  return {
    selected: state.selected
  }
}

export default connect(mapStateToProps)(MainFigure)
<|endoftext|>


<commit_before>function drawGraph(graph, divId) {
  console.log(graph);
  $("#"+divId).empty();
  var width = 750,
      height = 450;

  var color = d3.scale.category10();

  var force = d3.layout.force()
    .charge(-1000)
    .linkDistance(100)
    .size([width, height]);

  var drag = d3.behavior.drag()
      .origin(function(d) { return d; })
      .on("dragstart", dragstarted)
      .on("drag", dragged)
      .on("dragend", dragended);

  var svg = d3.select("#"+divId).append("svg")
    .attr("width", width)
    .attr("height", height);
  var vis = svg
    .append('svg:g')
    .call(d3.behavior.zoom()
       .scaleExtent([0.1,10])
       .on("zoom", rescale)
    );

  vis.append('svg:rect')
    .attr('width', width)
    .attr('height', height)
    .style('opacity', '0.0');

  function rescale() {
    trans=d3.event.translate;
    scale=d3.event.scale;

    vis.attr("transform",
      "translate(" + trans + ")"
      + " scale(" + scale + ")");
  }
  force
      .nodes(graph.nodes)
      .links(graph.edges)
      .start();

  var link = vis.selectAll(".link")
      .data(graph.edges)
      .enter().append("line")
        .attr("class", "link")
        .attr("opacity", function(d) { return d.value; })
        .style("stroke-width", function(d) { return Math.sqrt(10); })
        .style("stroke", "#888") //function(d) { return color(d.group); });
  link.append("svg:title")
      .text(function(d) { return JSON.stringify(d.description, null, '\t'); });

  var node = vis.selectAll("circle.node")
        .data(graph.nodes)
        .enter().append("g")
        .attr("class", "node")
        .call(drag);
      //CIRCLE
      node.append("svg:circle")
        .attr("r", function(d) { return 10; })
        .attr("fill", function(d) { return color(d.group); })
        .attr("opacity", function(d) { return d.value; })
        .attr("class", function(d) { return "nodeGroup" + d.group; })
        .append("svg:title")
        .text(function(d) { return JSON.stringify(d.description, null, '\t'); });

      //TEXT
      node.append("text")
        .text(function(d, i) { return d.name; })
        .attr("x",    function(d) { return 10*d.value + 5; })
        .attr("y",            function(d) { return 10*d.value + 5; })
        .attr("font-family",  "Bree Serif")
        .attr("font-size",    function(d) {  return  "1em"; })
        .attr("text-anchor",  function(d) { return  "beginning";})
        .attr("class", "nodeLabel");

  force.on("tick", function(e) {
    node.attr("transform", function(d, i) {
          return "translate(" + d.x + "," + d.y + ")";
      });
     link.attr("x1", function(d)   { return d.source.x; })
         .attr("y1", function(d)   { return d.source.y; })
         .attr("x2", function(d)   { return d.target.x; })
         .attr("y2", function(d)   { return d.target.y; })
  });

  force.start();

  function dragstarted(d) {
    d3.event.sourceEvent.stopPropagation();
    d3.select(this).classed("dragging", true);
    force.start();
  }

  function dragged(d) {
    d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
  }

  function dragended(d) {
    d3.select(this).classed("dragging", false);
  }
}

function animate(divId, maxFrames) {
  var currentSelection = 0;
  $('#'+divId + ' #frame0').removeClass('hide');

  $('#'+divId + 'prev').on('click', function () {
    if(currentSelection > 0) {
      currentSelection -= 1;
      changeFrame(currentSelection + 1, currentSelection);
    } else {
      currentSelection = maxFrames - 1;
      changeFrame(0, currentSelection);
    }
  })
  $('#'+divId + 'next').on('click', function () {
    if(currentSelection < maxFrames - 1) {
      currentSelection += 1;
      changeFrame(currentSelection - 1, currentSelection);
    } else {
      currentSelection = 0;
      changeFrame(maxFrames-1, currentSelection);
    }
  })

  function changeFrame(oldSel, newSel) {
    $('#'+divId + ' #frame' + oldSel).addClass('hide');
    $('#'+divId + ' #frame' + newSel).removeClass('hide');
  }
}

function drawVectors(vectors, divId) {
  console.log(vectors);
  $("#"+divId).empty();
  var width = 600,
      height = 450;

  var color = d3.scale.category10();

  var drag = d3.behavior.drag()
      .origin(function(d) { return d; })
      .on("dragstart", dragstarted)
      .on("drag", dragged)
      .on("dragend", dragended);

  var svg = d3.select("#"+divId).append("svg")
    .attr("width", width)
    .attr("height", height);
  var vis = svg
    .append('svg:g')
    .call(d3.behavior.zoom()
       .scaleExtent([0.1,10])
       .on("zoom", rescale)
    );

  vis.append('svg:rect')
    .attr('width', width)
    .attr('height', height)
    .style('opacity', '0.0');

  function rescale() {
    trans=d3.event.translate;
    scale=d3.event.scale;

    vis.attr("transform",
      "translate(" + trans + ")"
      + " scale(" + scale + ")");
  }

  var node = vis.selectAll("circle.node")
        .data(vectors)
        .enter().append("g")
        .attr("class", "node")
        .call(drag);
      //CIRCLE
      node.append("svg:circle")
        .attr("r", function(d) { return 5; })
        .attr("cx", function(d) { return 25 + d._3[0]*(width-50); })
        .attr("cy", function(d) { return 25 + d._3[1]*(height-50); })
        .attr("fill", function(d) { return color(d._1); })
        .attr("class", function(d) { return "nodeGroup" + d._1; })
        .append("svg:title")
        .text(function(d) { return JSON.stringify(d._2, null, '\t'); });

      //TEXT
//      node.append("text")
//        .text(function(d, i) { return d.name; })
//        .attr("x",    function(d) { return 10*d.value + 5; })
//        .attr("y",            function(d) { return 10*d.value + 5; })
//        .attr("font-family",  "Bree Serif")
//        .attr("font-size",    function(d) {  return  "1em"; })
//        .attr("text-anchor",  function(d) { return  "beginning";})
//        .attr("class", "nodeLabel");

//  force.on("tick", function(e) {
//    node.attr("transform", function(d, i) {
//          return "translate(" + d.x + "," + d.y + ")";
//      });
//  });

  function dragstarted(d) {
    d3.event.sourceEvent.stopPropagation();
    d3.select(this).classed("dragging", true);
    force.start();
  }

  function dragged(d) {
    d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
  }

  function dragended(d) {
    d3.select(this).classed("dragging", false);
  }
}<commit_msg>update d3utils from htmlgen<commit_after>function drawGraph(graph, divId) {
  console.log(graph);
  $("#"+divId).empty();
  var width = 750,
      height = 450;

  var color = d3.scale.category10();

  var force = d3.layout.force()
    .charge(-1000)
    .linkDistance(100)
    .size([width, height]);

  var drag = d3.behavior.drag()
      .origin(function(d) { return d; })
      .on("dragstart", dragstarted)
      .on("drag", dragged)
      .on("dragend", dragended);

  var svg = d3.select("#"+divId).append("svg")
    .attr("width", width)
    .attr("height", height);
  var vis = svg
    .append('svg:g')
    .call(d3.behavior.zoom()
       .scaleExtent([0.1,10])
       .on("zoom", rescale)
    );

  vis.append('svg:rect')
    .attr('width', width)
    .attr('height', height)
    .style('opacity', '0.0');

  function rescale() {
    trans=d3.event.translate;
    scale=d3.event.scale;

    vis.attr("transform",
      "translate(" + trans + ")"
      + " scale(" + scale + ")");
  }
  force
      .nodes(graph.nodes)
      .links(graph.edges)
      .start();

  var link = vis.selectAll(".link")
      .data(graph.edges)
      .enter().append("line")
        .attr("class", "link")
        .attr("opacity", function(d) { return d.value; })
        .style("stroke-width", function(d) { return Math.sqrt(10); })
        .style("stroke", "#888") //function(d) { return color(d.group); });
  link.append("svg:title")
      .text(function(d) { return JSON.stringify(d.description, null, '\t'); });

  var node = vis.selectAll("circle.node")
        .data(graph.nodes)
        .enter().append("g")
        .attr("class", "node")
        .call(drag);
      //CIRCLE
      node.append("svg:circle")
        .attr("r", function(d) { return 10; })
        .attr("fill", function(d) { return color(d.group); })
        .attr("opacity", function(d) { return d.value; })
        .attr("class", function(d) { return "nodeGroup" + d.group; })
        .append("svg:title")
        .text(function(d) { return JSON.stringify(d.description, null, '\t'); });

      //TEXT
      node.append("text")
        .text(function(d, i) { return d.name; })
        .attr("x",    function(d) { return 10*d.value + 5; })
        .attr("y",            function(d) { return 10*d.value + 5; })
        .attr("font-family",  "Bree Serif")
        .attr("font-size",    function(d) {  return  "1em"; })
        .attr("text-anchor",  function(d) { return  "beginning";})
        .attr("class", "nodeLabel");

  force.on("tick", function(e) {
    node.attr("transform", function(d, i) {
          return "translate(" + d.x + "," + d.y + ")";
      });
     link.attr("x1", function(d)   { return d.source.x; })
         .attr("y1", function(d)   { return d.source.y; })
         .attr("x2", function(d)   { return d.target.x; })
         .attr("y2", function(d)   { return d.target.y; })
  });

  force.start();

  function dragstarted(d) {
    d3.event.sourceEvent.stopPropagation();
    d3.select(this).classed("dragging", true);
    force.start();
  }

  function dragged(d) {
    d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
  }

  function dragended(d) {
    d3.select(this).classed("dragging", false);
  }
}

function animate(divId, maxFrames) {
  var currentSelection = 0;
  $('#'+divId + ' #frame0').removeClass('hide');

  $('#'+divId + 'prev').on('click', function () {
    if(currentSelection > 0) {
      currentSelection -= 1;
      changeFrame(currentSelection + 1, currentSelection);
    } else {
      currentSelection = maxFrames - 1;
      changeFrame(0, currentSelection);
    }
  })
  $('#'+divId + 'next').on('click', function () {
    if(currentSelection < maxFrames - 1) {
      currentSelection += 1;
      changeFrame(currentSelection - 1, currentSelection);
    } else {
      currentSelection = 0;
      changeFrame(maxFrames-1, currentSelection);
    }
  })

  function changeFrame(oldSel, newSel) {
    $('#'+divId + ' #frame' + oldSel).addClass('hide');
    $('#'+divId + ' #frame' + newSel).removeClass('hide');
  }
}

function drawVectors(vectors, divId) {
  console.log(vectors);
  $("#"+divId).empty();
  var width = 600,
      height = 450;
  var margin = 50;

  var color = d3.scale.category10();

  var zoom = d3.behavior.zoom()
      .scaleExtent([1, 10])
      .on("zoom", zoomed);

  var svg = d3.select("#"+divId).append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("g")
      .attr("transform", "translate(" + 0 + "," + 0 + ")")
      .call(zoom);

  var rect = svg.append("rect")
      .attr("width", width)
      .attr("height", height)
      .style("fill", "none")
      .style("pointer-events", "all");

  var vis = svg.append("g");

  var node = vis.append("g")
    .attr("class", "nodes")
    .selectAll(".node")
    .data(vectors)
    .enter().append("g")
    .attr("class", "node")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

  //CIRCLE
  node.append("circle")
    .attr("r", function(d) { return 5; })
    .attr("cx", function(d) { return margin + d._3[0]*(width-2*margin); })
    .attr("cy", function(d) { return margin + d._3[1]*(height-2*margin); })
    .attr("fill", function(d) { return color(d._1); })
    .attr("class", function(d) { return "nodeGroup" + d._1; })
    .append("svg:title")
    .text(function(d) { return JSON.stringify(d._2, null, '\t'); });

  //TEXT
  node.append("text")
    .text(function(d) { return JSON.stringify(d._2, null, '\t'); })
    .attr("x", function(d) { return margin + d._3[0]*(width-2*margin); })
    .attr("y", function(d) { return margin + d._3[1]*(height-2*margin); })
    .attr("class", function(d) { return "nodeGroup" + d._1; })
    .attr("font-family",  "Bree Serif")
    .attr("font-size",    function(d) {  return  "1em"; });

  function zoomed() {
    vis.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
  }
}<|endoftext|>


<commit_before>import React, { Component } from 'react';

import Article from './Article';

export default class Main extends Component {

	constructor(props) {
		super(props);

		this.state = {
			articles: [
				{
					id: 1,
					title: 'Title 1'
				}, {
					id: 2,
					title: 'Title 2'
				}, {
					id: 3,
					title: 'Title 3'
				}
			]
		}
	}

	render() {
		return (

				{this.state.articles.map(function(article, index) {
					return (

					);
				})}

		);
	}
}<commit_msg>try update state using this.setState()<commit_after>import React, { Component } from 'react';

import Article from './Article';

export default class Main extends Component {

	constructor(props) {
		super(props);

		this.state = {
			articles: [
				{
					id: 1,
					title: 'Title 1'
				}, {
					id: 2,
					title: 'Title 2'
				}, {
					id: 3,
					title: 'Title 3'
				}
			]
		}

		setTimeout(() => {
			this.setState({
				articles: this.state.articles.concat([{
					id: 4,
					title: 'Title 4'
				}])
			});
		}, 2000);
	}

	render() {
		return (

				{this.state.articles.map(function(article, index) {
					return (

					);
				})}

		);
	}
}<|endoftext|>


<commit_before>
import { MenuItem, MenuItems } from '../../imports/api/menuItem.js';

import { Order, Orders, orderItem } from '../../imports/api/order.js';

var orderArray = [];
var itemArray = [];

var mItemID = 1;

function createOrderItem(mItemID, mPriority, mMenuItemID, mSpecialRequests) {
    return new orderItem({
        "itemID": mItemID,
        "priority": mPriority,
        "menuItemID": mMenuItemID,
        "specialRequests": mSpecialRequests
    });
};

Template.waiter.events({
    'click .Appetizers' () {
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("appMenu").className = "displayAll";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');
    },
    'click .Entrees' () {
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayAll";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone"
        $('.menu-active').removeClass('menu-active');
    },
    'click .FloorPlan' () {
        document.getElementById("floorPlan").className = "displayAll";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');
    },
    'click .Desserts' () {
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayAll";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');

    },
    'click .placeOrder' () {
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayAll";
        $('.menu-active').removeClass('menu-active');

        for (i = 0; i < orderArray.length; i++) {
            itemArray.push(MenuItems.findOne({ itemID: orderArray[i].itemID }));
            console.log(MenuItems.findOne({ itemID: orderArray[i].itemID }).itemName);
        }
        Template.waiter.__helpers.get('selected')();

        // Create new order with orderID as the highest orderID in collection + 1
        new Order({
            orderID: Order.findOne({}, { sort: {orderID: -1}}) + 1,
            waiterID: 69,
            orderItems: orderArray,
            timePlaced: new Date()
        }).placeOrder();

		orderArray = [];
    },
    'click .drinkicon' () {
        console.log("hello")
        $('.ui.modal')
            .modal('show')
        ;
    },
});

Template.menuCards.events({
    'click .ui.bottom.attached.button'() {
        orderArray.push(createOrderItem(mItemID, 2, this.itemID, "NONE"));
        console.log(orderArray);
    },

});

Template.waiter.helpers({
    drinks() {
        return MenuItems.find({mealType: 0});
    },
	apps() {
        return MenuItems.find({mealType: 1});
    },
    entrees() {
        return MenuItems.find({mealType: 2});
    },
    desserts() {
        return MenuItems.find({mealType: 3});

    },
    selected: function() {
        return _.map(Object, function(itemID, itemName, itemDescription, mealType, itemPrice, cookTime){
            return {
                itemid: itemID,
                name : itemName,
                desc: itemDescription,
                type: mealType,
                price: itemPrice,
                timeCook: cookTime,
            }
        })

    },
});

/*
		for (i = 0; i < orderArray.length; i++) {
			itemArray.push(MenuItems.findOne({ itemID: orderArray[i].itemID }));
			console.log(MenuItems.findOne({ itemID: orderArray[i].itemID }));
		}
		return itemArray;
*/<commit_msg>fixed raj<commit_after>import { MenuItem, MenuItems } from '../../imports/api/menuItem.js';
import { Order, Orders, orderItem } from '../../imports/api/order.js';

var orderArray = [];
var itemArray = [];

var mItemID = 1;

function createOrderItem(mItemID, mPriority, mMenuItemID, mSpecialRequests) {
    return new orderItem({
        "itemID": mItemID,
        "priority": mPriority,
        "menuItemID": mMenuItemID,
        "specialRequests": mSpecialRequests
    });
};

Template.waiter.events({
    'click .Appetizers' () {
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("appMenu").className = "displayAll";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');
    },
    'click .Entrees' () {
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayAll";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone"
        $('.menu-active').removeClass('menu-active');
    },
    'click .FloorPlan' () {
        document.getElementById("floorPlan").className = "displayAll";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');
    },
    'click .Desserts' () {
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayAll";
        document.getElementById("placeOrderMenu").className = "displayNone";
        $('.menu-active').removeClass('menu-active');

    },
    'click .placeOrder' () {
        document.getElementById("floorPlan").className = "displayNone";
        document.getElementById("entreeMenu").className = "displayNone";
        document.getElementById("appMenu").className = "displayNone";
        document.getElementById("dessertsMenu").className = "displayNone";
        document.getElementById("placeOrderMenu").className = "displayAll";
        $('.menu-active').removeClass('menu-active');

        // Create new order with orderID as the highest orderID in collection + 1
        new Order({
            orderID: Order.findOne({}, { sort: {orderID: -1}}).orderID + 1,
            waiterID: 69,
            orderItems: orderArray,
            timePlaced: new Date()
        }).placeOrder();
//

        Template.waiter.__helpers.get('selected')();

        orderArray = [];
    },
    'click .drinkicon' () {
        console.log("hello")
        $('.ui.modal')
            .modal('show')
        ;
    },
});

Template.menuCards.events({
    'click .ui.bottom.attached.button'() {
        orderArray.push(createOrderItem(mItemID, 2, this.itemID, "NONE"));
        console.log(orderArray);
    },

});

Template.waiter.helpers({
    drinks() {
        return MenuItems.find({mealType: 0});
    },
    apps() {
        return MenuItems.find({mealType: 1});
    },
    entrees() {
        return MenuItems.find({mealType: 2});
    },
    desserts() {
        console.log(MenuItems.find({mealType: 3}));
        return MenuItems.find({mealType: 3});

    },
    selected() {
        console.log("Item array" + itemArray);
        return itemArray;
    },
});

/*
 for (i = 0; i < orderArray.length; i++) {
 itemArray.push(MenuItems.findOne({ itemID: orderArray[i].itemID }));
 console.log(MenuItems.findOne({ itemID: orderArray[i].itemID }));
 }
 return itemArray;
 */<|endoftext|>


<commit_before>var gulp = require('gulp');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var jade = require('gulp-jade');
var plato = require('gulp-plato');
var espower = require('gulp-espower');
var karma = require('karma').server;

gulp.task('jade', function () {
    return gulp.src('./src/views/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('typescript', function () {
    return gulp.src('./src/scripts/**/*.ts')
        .pipe(tslint())
        .pipe(tslint.report('verbose'))
        .pipe(ts({
            declarationFiles: true,
            target: 'es5'
        })
        .pipe(gulp.dest('./dist/scripts/')));
});

// Generate complexity analysis reports
gulp.task('analyze', function () {
    return gulp.src('./dist/scripts/*.js')
        .pipe(plato('./report', {
            jshint: {
                options: {
                    strict: true
                }
            },
            complexity: {
                trycatch: true
            }
        }));
});

gulp.task('test', function (done) {
    gulp.src('./test/scripts/*.js')
        .pipe(espower())
        .pipe(gulp.dest('./test/scripts/espower'));

    return karma.start({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done);
});

// Copy all files in "src" directory
gulp.task('copy', function () {
    gulp.src([
        'src/**/*',
        '!src/**/*.html',
        '!src/**/*.css',
    ])
    .pipe(gulp.dest('dist/'));
});

// Copy all files in "bower_components" directory
gulp.task('components', function () {
    gulp.src([
        'bower_components/**/*'
    ])
    .pipe(gulp.dest('dist/bower_components/'));
});

gulp.task('default', function () {
});
<commit_msg>Add comments<commit_after>'use strict';

var gulp = require('gulp');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var jade = require('gulp-jade');
var plato = require('gulp-plato');
var espower = require('gulp-espower');
var karma = require('karma').server;

// Compile jade
gulp.task('jade', function () {
    return gulp.src('./src/views/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./dist/'));
});

// Compile and Lint TypeScript
gulp.task('typescript', function () {
    return gulp.src('./src/scripts/**/*.ts')
        .pipe(tslint())
        .pipe(tslint.report('verbose'))
        .pipe(ts({
            declarationFiles: true,
            target: 'es5'
        })
        .pipe(gulp.dest('./dist/scripts/')));
});

// Generate complexity analysis reports
gulp.task('analyze', function () {
    return gulp.src('./dist/scripts/*.js')
        .pipe(plato('./report', {
            jshint: {
                options: {
                    strict: true
                }
            },
            complexity: {
                trycatch: true
            }
        }));
});

// Test scripts
gulp.task('test', function (done) {
    gulp.src('./test/scripts/*.js')
        .pipe(espower())
        .pipe(gulp.dest('./test/scripts/espower'));

    karma.start({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done);
});

// Copy all files in "src" directory
gulp.task('copy', function () {
    gulp.src([
        'src/**/*',
        '!src/**/*.html',
        '!src/**/*.css',
    ])
    .pipe(gulp.dest('dist/'));
});

// Copy all files in "bower_components" directory
gulp.task('components', function () {
    gulp.src([
        'bower_components/**/*'
    ])
    .pipe(gulp.dest('dist/bower_components/'));
});

gulp.task('default', function () {
});
<|endoftext|>


<commit_before>import React from 'react';

import PropTypes from 'prop-types';
import {
  Animated,
  Dimensions,
  Easing,
  Modal,
  Platform,
  StatusBar,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
  ViewPropTypes,
} from 'react-native';

const STATES = {
  HIDDEN: 'HIDDEN',
  ANIMATING: 'ANIMATING',
  SHOWN: 'SHOWN',
};

const ANIMATION_DURATION = 300;
const EASING = Easing.bezier(0.4, 0, 0.2, 1);
const SCREEN_INDENT = 8;

class Menu extends React.Component {
  _container = null;

  state = {
    menuState: STATES.HIDDEN,

    top: 0,
    left: 0,

    menuWidth: 0,
    menuHeight: 0,

    buttonWidth: 0,
    buttonHeight: 0,

    menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
    opacityAnimation: new Animated.Value(0),
  };

  _setContainerRef = ref => {
    this._container = ref;
  };

  // Start menu animation
  _onMenuLayout = e => {
    if (this.state.menuState === STATES.ANIMATING) {
      return;
    }

    const { width, height } = e.nativeEvent.layout;

    this.setState(
      {
        menuState: STATES.ANIMATING,
        menuWidth: width,
        menuHeight: height,
      },
      () => {
        Animated.parallel([
          Animated.timing(this.state.menuSizeAnimation, {
            toValue: { x: width, y: height },
            duration: ANIMATION_DURATION,
            easing: EASING,
          }),
          Animated.timing(this.state.opacityAnimation, {
            toValue: 1,
            duration: ANIMATION_DURATION,
            easing: EASING,
          }),
        ]).start();
      },
    );
  };

  // Save button width and height for menu layout
  _onButtonLayout = e => {
    const { width, height } = e.nativeEvent.layout;
    this.setState({ buttonWidth: width, buttonHeight: height });
  };

  _onDismiss = () => {
    if (this.props.onHidden) {
      this.props.onHidden();
    }
  };

  show = () => {
    this._container.measureInWindow((x, y) => {
      const top = Math.max(SCREEN_INDENT, y);
      const left = Math.max(SCREEN_INDENT, x);
      this.setState({ menuState: STATES.SHOWN, top, left });
    });
  };

  hide = () => {
    Animated.timing(this.state.opacityAnimation, {
      toValue: 0,
      duration: ANIMATION_DURATION,
      easing: EASING,
    }).start(() => {
      // Reset state
      this.setState(
        {
          menuState: STATES.HIDDEN,
          menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
          opacityAnimation: new Animated.Value(0),
        },
        () => {
          // Invoke onHidden callback if defined
          if (Platform.OS !== 'ios' && this.props.onHidden) {
            this.props.onHidden();
          }
        },
      );
    });
  };

  render() {
    const dimensions = Dimensions.get('window');
    const { width: windowWidth } = dimensions;
    const windowHeight = dimensions.height - (StatusBar.currentHeight || 0);

    const {
      menuSizeAnimation,
      menuWidth,
      menuHeight,
      buttonWidth,
      buttonHeight,
      opacityAnimation,
    } = this.state;
    const menuSize = {
      width: menuSizeAnimation.x,
      height: menuSizeAnimation.y,
    };

    // Adjust position of menu
    let { left, top } = this.state;
    const transforms = [];

    // Flip by X axis if menu hits right screen border
    if (left > windowWidth - menuWidth - SCREEN_INDENT) {
      transforms.push({
        translateX: Animated.multiply(menuSizeAnimation.x, -1),
      });

      left = Math.min(windowWidth - SCREEN_INDENT, left + buttonWidth);
    }

    // Flip by Y axis if menu hits bottom screen border
    if (top > windowHeight - menuHeight - SCREEN_INDENT) {
      transforms.push({
        translateY: Animated.multiply(menuSizeAnimation.y, -1),
      });

      top = windowHeight - SCREEN_INDENT;
      top = Math.min(windowHeight - SCREEN_INDENT, top + buttonHeight);
    }

    const shadowMenuContainerStyle = {
      opacity: opacityAnimation,
      transform: transforms,
      left,
      top,
    };

    const { menuState } = this.state;
    const animationStarted = menuState === STATES.ANIMATING;
    const modalVisible = menuState === STATES.SHOWN || animationStarted;

    const { testID, button, style, children } = this.props;

    return (
      <View ref={this._setContainerRef} collapsable={false} testID={testID}>
        <View onLayout={this._onButtonLayout}>{button}</View>

        <Modal
          visible={modalVisible}
          onRequestClose={this.hide}
          supportedOrientations={[
            'portrait',
            'portrait-upside-down',
            'landscape',
            'landscape-left',
            'landscape-right',
          ]}
          transparent
          onDismiss={this._onDismiss}
        >
          <TouchableWithoutFeedback onPress={this.hide}>
            <View style={StyleSheet.absoluteFill}>
              <Animated.View
                onLayout={this._onMenuLayout}
                style={[
                  styles.shadowMenuContainer,
                  shadowMenuContainerStyle,
                  style,
                ]}
              >
                <Animated.View
                  style={[styles.menuContainer, animationStarted && menuSize]}
                >
                  {children}
                </Animated.View>
              </Animated.View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </View>
    );
  }
}

Menu.propTypes = {
  button: PropTypes.node.isRequired,
  children: PropTypes.node.isRequired,
  onHidden: PropTypes.func,
  style: ViewPropTypes.style,
  testID: ViewPropTypes.testID,
};

const styles = StyleSheet.create({
  shadowMenuContainer: {
    position: 'absolute',
    backgroundColor: 'white',
    borderRadius: 4,
    opacity: 0,

    // Shadow
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.14,
        shadowRadius: 2,
      },
      android: {
        elevation: 8,
      },
    }),
  },
  menuContainer: {
    overflow: 'hidden',
  },
});

export default Menu;
<commit_msg>Setting accessible={false} on outer layer makes child views accessible. (#57)<commit_after>import React from 'react';

import PropTypes from 'prop-types';
import {
  Animated,
  Dimensions,
  Easing,
  Modal,
  Platform,
  StatusBar,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
  ViewPropTypes,
} from 'react-native';

const STATES = {
  HIDDEN: 'HIDDEN',
  ANIMATING: 'ANIMATING',
  SHOWN: 'SHOWN',
};

const ANIMATION_DURATION = 300;
const EASING = Easing.bezier(0.4, 0, 0.2, 1);
const SCREEN_INDENT = 8;

class Menu extends React.Component {
  _container = null;

  state = {
    menuState: STATES.HIDDEN,

    top: 0,
    left: 0,

    menuWidth: 0,
    menuHeight: 0,

    buttonWidth: 0,
    buttonHeight: 0,

    menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
    opacityAnimation: new Animated.Value(0),
  };

  _setContainerRef = ref => {
    this._container = ref;
  };

  // Start menu animation
  _onMenuLayout = e => {
    if (this.state.menuState === STATES.ANIMATING) {
      return;
    }

    const { width, height } = e.nativeEvent.layout;

    this.setState(
      {
        menuState: STATES.ANIMATING,
        menuWidth: width,
        menuHeight: height,
      },
      () => {
        Animated.parallel([
          Animated.timing(this.state.menuSizeAnimation, {
            toValue: { x: width, y: height },
            duration: ANIMATION_DURATION,
            easing: EASING,
          }),
          Animated.timing(this.state.opacityAnimation, {
            toValue: 1,
            duration: ANIMATION_DURATION,
            easing: EASING,
          }),
        ]).start();
      },
    );
  };

  // Save button width and height for menu layout
  _onButtonLayout = e => {
    const { width, height } = e.nativeEvent.layout;
    this.setState({ buttonWidth: width, buttonHeight: height });
  };

  _onDismiss = () => {
    if (this.props.onHidden) {
      this.props.onHidden();
    }
  };

  show = () => {
    this._container.measureInWindow((x, y) => {
      const top = Math.max(SCREEN_INDENT, y);
      const left = Math.max(SCREEN_INDENT, x);
      this.setState({ menuState: STATES.SHOWN, top, left });
    });
  };

  hide = () => {
    Animated.timing(this.state.opacityAnimation, {
      toValue: 0,
      duration: ANIMATION_DURATION,
      easing: EASING,
    }).start(() => {
      // Reset state
      this.setState(
        {
          menuState: STATES.HIDDEN,
          menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
          opacityAnimation: new Animated.Value(0),
        },
        () => {
          // Invoke onHidden callback if defined
          if (Platform.OS !== 'ios' && this.props.onHidden) {
            this.props.onHidden();
          }
        },
      );
    });
  };

  render() {
    const dimensions = Dimensions.get('window');
    const { width: windowWidth } = dimensions;
    const windowHeight = dimensions.height - (StatusBar.currentHeight || 0);

    const {
      menuSizeAnimation,
      menuWidth,
      menuHeight,
      buttonWidth,
      buttonHeight,
      opacityAnimation,
    } = this.state;
    const menuSize = {
      width: menuSizeAnimation.x,
      height: menuSizeAnimation.y,
    };

    // Adjust position of menu
    let { left, top } = this.state;
    const transforms = [];

    // Flip by X axis if menu hits right screen border
    if (left > windowWidth - menuWidth - SCREEN_INDENT) {
      transforms.push({
        translateX: Animated.multiply(menuSizeAnimation.x, -1),
      });

      left = Math.min(windowWidth - SCREEN_INDENT, left + buttonWidth);
    }

    // Flip by Y axis if menu hits bottom screen border
    if (top > windowHeight - menuHeight - SCREEN_INDENT) {
      transforms.push({
        translateY: Animated.multiply(menuSizeAnimation.y, -1),
      });

      top = windowHeight - SCREEN_INDENT;
      top = Math.min(windowHeight - SCREEN_INDENT, top + buttonHeight);
    }

    const shadowMenuContainerStyle = {
      opacity: opacityAnimation,
      transform: transforms,
      left,
      top,
    };

    const { menuState } = this.state;
    const animationStarted = menuState === STATES.ANIMATING;
    const modalVisible = menuState === STATES.SHOWN || animationStarted;

    const { testID, button, style, children } = this.props;

    return (
      <View ref={this._setContainerRef} collapsable={false} testID={testID}>
        <View onLayout={this._onButtonLayout}>{button}</View>

        <Modal
          visible={modalVisible}
          onRequestClose={this.hide}
          supportedOrientations={[
            'portrait',
            'portrait-upside-down',
            'landscape',
            'landscape-left',
            'landscape-right',
          ]}
          transparent
          onDismiss={this._onDismiss}
        >
          <TouchableWithoutFeedback onPress={this.hide} accessible={false}>
            <View style={StyleSheet.absoluteFill}>
              <Animated.View
                onLayout={this._onMenuLayout}
                style={[
                  styles.shadowMenuContainer,
                  shadowMenuContainerStyle,
                  style,
                ]}
              >
                <Animated.View
                  style={[styles.menuContainer, animationStarted && menuSize]}
                >
                  {children}
                </Animated.View>
              </Animated.View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </View>
    );
  }
}

Menu.propTypes = {
  button: PropTypes.node.isRequired,
  children: PropTypes.node.isRequired,
  onHidden: PropTypes.func,
  style: ViewPropTypes.style,
  testID: ViewPropTypes.testID,
};

const styles = StyleSheet.create({
  shadowMenuContainer: {
    position: 'absolute',
    backgroundColor: 'white',
    borderRadius: 4,
    opacity: 0,

    // Shadow
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.14,
        shadowRadius: 2,
      },
      android: {
        elevation: 8,
      },
    }),
  },
  menuContainer: {
    overflow: 'hidden',
  },
});

export default Menu;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import DropZone from 'react-dropzone'
import map from 'lodash/map'
import Button from '../../components/button'
import List from '../../components/list'
import {StudentSummary} from '../../modules/student/student-summary'
import {initStudent} from '../../redux/students/actions/init-student'
import withRouter from 'react-router/lib/withRouter'
import {connect} from 'react-redux'
import debug from 'debug'
const log = debug('web:react')

import './method-upload.scss'

class UploadFileScreen extends React.Component {
	static propTypes = {
		dispatch: PropTypes.func.isRequired,
		router: PropTypes.object.isRequired,
	}

	state = {
		files: [],
		students: [],
	}

	handleFileDrop = files => {
		log(files)
		files = files.map(f => ({
			name: f.name,
			size: f.size,
			data: new Promise((resolve, reject) => {
				let reader = new FileReader()
				reader.onload = ev => resolve(ev.target.result)
				reader.onerror = reader.onabort = reject
				reader.readAsText(f)
			}),
		}))
		this.setState({files})
		this.convertFilesToStudents(files)
	}

	handleOpenPicker = () => {
		this.dropzone.open()
	}

	convertOneFile = file => {
		file.data
			.then(data => {
				let parsed
				try {
					parsed = JSON.parse(data)
				} catch (err) {
					const msg = err.message
					return {
						name: file.name,
						error: `could not parse "${data}" because "${msg}"`,
					}
				}

				let converted
				try {
					converted = initStudent(parsed)
				} catch (err) {
					return {name: file.name, error: err.message}
				}

				return converted
			})
			.then(student => {
				this.setState({
					students: this.state.students.concat(student),
				})
			})
	}

	convertFilesToStudents = files => {
		this.setState({students: []})
		files.forEach(this.convertOneFile)
	}

	handleImportStudents = () => {
		this.state.students.forEach(this.props.dispatch)
		this.props.router.push('/')
	}

	render() {
		let {students} = this.state
		let files = this.state.files.slice(students.length)

		return (

Upload a File

				<DropZone
					ref={el => (this.dropzone = el)}
					accept=".gbstudent,.json,.gb-student"
					onDrop={this.handleFileDrop}
					multiple
					disablePreview
					className="upload-dropzone"
					activeClassName="canDrop"
					rejectClassName="canDrop" // HTML doesn't give us filenames until we drop, so it can't tell if it'll be accepted until the drop happens
				>

						Just drop some students here, or click to select some to
						upload.

				</DropZone>

				<List type="plain" className="upload-results">
					{// eslint-disable-next-line no-confusing-arrow
					map(
						students,
						stu =>
							stu.payload ? (

									<StudentSummary
										student={stu.payload}
										showMessage={false}
										showAvatar={false}
										randomizeHello
									/>

							) : (

									{stu.name} returned the error "
									{stu.error}
									"

							),
					)}
					{map(files, file =>
{file.name}
)}
				</List>

				<Button onClick={this.handleImportStudents}>
					Import Students
				</Button>

		)
	}
}

let mapDispatch = dispatch => ({dispatch})

export default connect(
	undefined,
	mapDispatch,
)(withRouter(UploadFileScreen))
<commit_msg>clean up some processes in UploadStudentFile<commit_after>import React from 'react'
import PropTypes from 'prop-types'

import DropZone from 'react-dropzone'
import map from 'lodash/map'
import Button from '../../components/button'
import List from '../../components/list'
import {StudentSummary} from '../../modules/student/student-summary'
import {initStudent} from '../../redux/students/actions/init-student'
import withRouter from 'react-router/lib/withRouter'
import {connect} from 'react-redux'
import debug from 'debug'
const log = debug('web:react')

import './method-upload.scss'

class UploadFileScreen extends React.Component {
	static propTypes = {
		dispatch: PropTypes.func.isRequired,
		router: PropTypes.object.isRequired,
	}

	state = {
		files: [],
		actions [],
	}

	handleFileDrop = files => {
		log(files)
		files = files.map(f => ({
			name: f.name,
			size: f.size,
			data: new Promise((resolve, reject) => {
				let reader = new FileReader()
				reader.onload = ev => resolve(ev.target.result)
				reader.onerror = reader.onabort = reject
				reader.readAsText(f)
			}),
		}))
		this.setState(() => ({files}), () => this.convertFilesToStudents(files))
	}

	handleOpenPicker = () => {
		this.dropzone.open()
	}

	convertOneFile = async file => {
		let data = await file.data

		let parsed
		try {
			parsed = JSON.parse(data)
		} catch (err) {
			const msg = err.message
			parsed = {
				name: file.name,
				error: `could not parse "${data}" because "${msg}"`,
			}
		}

		let converted
		try {
			converted = initStudent(parsed)
		} catch (err) {
			converted = {name: file.name, error: err.message}
		}

		this.setState((state) => ({actions: [...state.actions, converted]}))
	}

	convertFilesToStudents = files => {
		this.setState(() => ({actions: []}), files.forEach(this.convertOneFile))
	}

	handleImportStudents = () => {
		this.state.actions.forEach(this.props.dispatch)
		this.props.router.push('/')
	}

	render() {
		let {actions} = this.state
		let files = this.state.files.slice(actions.length)

		return (

Upload a File

				<DropZone
					ref={el => (this.dropzone = el)}
					accept=".gbstudent,.json,.gb-student"
					onDrop={this.handleFileDrop}
					multiple={true}
					disablePreview={true}
					className="upload-dropzone"
					activeClassName="canDrop"
					rejectClassName="canDrop" // HTML doesn't give us filenames until we drop, so it can't tell if it'll be accepted until the drop happens
				>

						Just drop some students here, or click to select some to
						upload.

				</DropZone>

				<List type="plain" className="upload-results">
					{// eslint-disable-next-line no-confusing-arrow
					map(
						actions,
						stu =>
							stu.payload ? (

									<StudentSummary
										student={stu.payload}
										showMessage={false}
										showAvatar={false}
										randomizeHello
									/>

							) : (

									{stu.name} returned the error "
									{stu.error}
									"

							),
					)}
					{map(files, file =>
{file.name}
)}
				</List>

				<Button onClick={this.handleImportStudents}>
					Import Students
				</Button>

		)
	}
}

let mapDispatch = dispatch => ({dispatch})

export default connect(
	undefined,
	mapDispatch,
)(withRouter(UploadFileScreen))
<|endoftext|>


<commit_before>import GroupCtrl from '../controllers/GroupCtr'

const GroupRoutes = (router) => {
    router.route('/group')
      .post(GroupCtrl.createGroup);

    router.route('/group/:id/user')
      .post(GroupCtrl.addUserToGroup)
      .get(GroupCtrl.retrieveGroupUsers);

}

export default GroupRoutes;
<commit_msg>refactor: Post group/:id/user<commit_after>import GroupCtrl from '../controllers/GroupCtr'
import Auth from '../middleware/Auth'

const GroupRoutes = (router) => {
    router.route('/group')
      .post(GroupCtrl.createGroup);

    router.route('/group/:id/user')
      .post( GroupCtrl.addUserToGroup)
      .get(GroupCtrl.retrieveGroupUsers);

}

export default GroupRoutes;
<|endoftext|>


<commit_before>/**
 * Parallax layer class
 *
 * Create a new jcparallax layer within the given viewport with the target element.
 *
 * @requires jcparallax.js
 * @requires jcp-viewport.js
 *
 * @param {Viewport} viewport jcparallax.Viewport object responsible for animating this layer
 * @param {jQuery}   el       target layer element for animation
 * @param {object}   options  options for this layer. Same as the Viewport options - @see jcp-viewport.js
 */
(function($) {

jcparallax.Layer = function(viewport, el, options)
{
	// setup instance options
	this.viewport = viewport;
	this.element = el;
	this.options = jcparallax.Viewport._inferMovementRanges(options);

	// store animation event handler to be called by our Viewport
	if ($.isFunction(this.options.animHandler)) {
		this.animHandler = this.options.animHandler;
	} else {
		this.animHandler = jcparallax.Layer.animHandlers[this.options.animHandler];
	}

	// compute movement range
	this._updateMovementRange(this.options.movementRangeX, this.options.movementRangeY);
};

$.extend(jcparallax.Layer.prototype, {

	// cached layer coordinates for speeding up animation
	minX : null,
	minY : null,
	rangeX : null,
	rangeY : null,

	// previous CSS attributes of the layer
	prevFrameCss : {},

	/**
	 * Refreshes the cached coordinates of the layer after some external DOM manipulation
	 */
	refreshCoords : function()
	{
		if (!$.isArray(this.options.movementRangeX) || !$.isArray(this.options.movementRangeY)) {
			this._updateMovementRange(this.options.movementRangeX, this.options.movementRangeY);
		}
	},

	/**
	 * Redraw the layer, given new input values
	 * @return true if the layer needed re-rendering
	 */
	redraw : function(xVal, yVal)
	{
		var newCss = this.animHandler.call(this, xVal, yVal);

		if (this._cssChanged(newCss)) {
			this.prevFrameCss = newCss;
			this.element.css(newCss);
			return true;
		}

		return false;
	},

	_updateMovementRange : function(xRangeOrCb, yRangeOrCb)
	{
		var xRange, yRange;

		if ($.isArray(xRangeOrCb)) {
			xRange = xRangeOrCb;
		} else {
			xRange = this._calculateMovementRange(xRangeOrCb);
		}
		if ($.isArray(yRangeOrCb)) {
			yRange = yRangeOrCb;
		} else {
			yRange = this._calculateMovementRange(yRangeOrCb);
		}

		this.minX = parseFloat(xRange[0]);
		this.rangeX = parseFloat(xRange[1] - xRange[0]);
		this.minY = parseFloat(yRange[0]);
		this.rangeY = parseFloat(yRange[1] - yRange[0]);
	},

	_calculateMovementRange : function(rangeCallback)
	{
		if (!$.isFunction(rangeCallback)) {
			rangeCallback = jcparallax.Layer.rangeCalculators[rangeCallback];
		}

		return rangeCallback.call(this, this.element, this.viewport);
	},

	_cssChanged : function(newCss)
	{
		for (var i in newCss) {
			if (this.prevFrameCss[i] === undefined || this.prevFrameCss[i] != newCss[i]) {
				return true;
			}
		}
		return false;
	}
});

//------------------------------------------------------------------------------
// Layer animation handlers
//------------------------------------------------------------------------------

jcparallax.Layer.animHandlers = {

	position : function(xVal, yVal)
	{
		return {
			left : this.minX + (xVal * this.rangeX),
			top : this.minY + (yVal * this.rangeY),
		};
	},

	padding : function(xVal, yVal)
	{

	},

	margins : function(xVal, yVal)
	{

	},

	background : function(xVal, yVal)
	{
		return {
			'background-position' : (this.minX + (xVal * this.rangeX)) + 'px ' + (this.minY + (yVal * this.rangeY)) + 'px',
		};
	},

	stretch : function(xVal, yVal)
	{

	},

	textShadow : function(xVal, yVal)
	{

	},

	opacity : function(xVal, yVal)
	{

	}
};

//------------------------------------------------------------------------------
// Automatic layer movement range calculation callbacks
//------------------------------------------------------------------------------

jcparallax.Layer.rangeCalculators = {

	width : function(el, vp)
	{
		return [0, vp.sizeX - el.width()];
	},

	height : function(el, vp)
	{
		return [vp.sizeY - el.height(), 0];
	},

	scrollWidth : function(el, vp)
	{
		return [-(el.get(0).scrollWidth - vp.sizeX), 0];
	},

	scrollHeight : function(el, vp)
	{
		return [0, el.get(0).scrollHeight - vp.sizeY];
	},

	fontSize : function(el, vp)
	{
		return [0, el.css('font-size')];
	},

	lineHeight : function(el, vp)
	{
		return [el.css('line-height'), 0];
	},

	opacity : function(el, vp)
	{
		return [0, el.css('opacity') || 1];
	}
};

})(jQuery);
<commit_msg>added range handlers to read an explicit range of movement from data attributes easily<commit_after>/**
 * Parallax layer class
 *
 * Create a new jcparallax layer within the given viewport with the target element.
 *
 * @requires jcparallax.js
 * @requires jcp-viewport.js
 *
 * @param {Viewport} viewport jcparallax.Viewport object responsible for animating this layer
 * @param {jQuery}   el       target layer element for animation
 * @param {object}   options  options for this layer. Same as the Viewport options - @see jcp-viewport.js
 */
(function($) {

jcparallax.Layer = function(viewport, el, options)
{
	// setup instance options
	this.viewport = viewport;
	this.element = el;
	this.options = jcparallax.Viewport._inferMovementRanges(options);

	// store animation event handler to be called by our Viewport
	if ($.isFunction(this.options.animHandler)) {
		this.animHandler = this.options.animHandler;
	} else {
		this.animHandler = jcparallax.Layer.animHandlers[this.options.animHandler];
	}

	// compute movement range
	this._updateMovementRange(this.options.movementRangeX, this.options.movementRangeY);
};

$.extend(jcparallax.Layer.prototype, {

	// cached layer coordinates for speeding up animation
	minX : null,
	minY : null,
	rangeX : null,
	rangeY : null,

	// previous CSS attributes of the layer
	prevFrameCss : {},

	/**
	 * Refreshes the cached coordinates of the layer after some external DOM manipulation
	 */
	refreshCoords : function()
	{
		if (!$.isArray(this.options.movementRangeX) || !$.isArray(this.options.movementRangeY)) {
			this._updateMovementRange(this.options.movementRangeX, this.options.movementRangeY);
		}
	},

	/**
	 * Redraw the layer, given new input values
	 * @return true if the layer needed re-rendering
	 */
	redraw : function(xVal, yVal)
	{
		var newCss = this.animHandler.call(this, xVal, yVal);

		if (this._cssChanged(newCss)) {
			this.prevFrameCss = newCss;
			this.element.css(newCss);
			return true;
		}

		return false;
	},

	_updateMovementRange : function(xRangeOrCb, yRangeOrCb)
	{
		var xRange, yRange;

		if ($.isArray(xRangeOrCb)) {
			xRange = xRangeOrCb;
		} else {
			xRange = this._calculateMovementRange(xRangeOrCb);
		}
		if ($.isArray(yRangeOrCb)) {
			yRange = yRangeOrCb;
		} else {
			yRange = this._calculateMovementRange(yRangeOrCb);
		}

		this.minX = parseFloat(xRange[0]);
		this.rangeX = parseFloat(xRange[1] - xRange[0]);
		this.minY = parseFloat(yRange[0]);
		this.rangeY = parseFloat(yRange[1] - yRange[0]);
	},

	_calculateMovementRange : function(rangeCallback)
	{
		if (!$.isFunction(rangeCallback)) {
			rangeCallback = jcparallax.Layer.rangeCalculators[rangeCallback];
		}

		return rangeCallback.call(this, this.element, this.viewport);
	},

	_cssChanged : function(newCss)
	{
		for (var i in newCss) {
			if (this.prevFrameCss[i] === undefined || this.prevFrameCss[i] != newCss[i]) {
				return true;
			}
		}
		return false;
	}
});

//------------------------------------------------------------------------------
// Layer animation handlers
//------------------------------------------------------------------------------

jcparallax.Layer.animHandlers = {

	position : function(xVal, yVal)
	{
		return {
			left : this.minX + (xVal * this.rangeX),
			top : this.minY + (yVal * this.rangeY),
		};
	},

	padding : function(xVal, yVal)
	{

	},

	margins : function(xVal, yVal)
	{

	},

	background : function(xVal, yVal)
	{
		return {
			'background-position' : (this.minX + (xVal * this.rangeX)) + 'px ' + (this.minY + (yVal * this.rangeY)) + 'px',
		};
	},

	stretch : function(xVal, yVal)
	{

	},

	textShadow : function(xVal, yVal)
	{

	},

	opacity : function(xVal, yVal)
	{

	}
};

//------------------------------------------------------------------------------
// Automatic layer movement range calculation callbacks
//------------------------------------------------------------------------------

jcparallax.Layer.rangeCalculators = {

	width : function(el, vp)
	{
		return [0, vp.sizeX - el.width()];
	},

	height : function(el, vp)
	{
		return [vp.sizeY - el.height(), 0];
	},

	scrollWidth : function(el, vp)
	{
		return [-(el.get(0).scrollWidth - vp.sizeX), 0];
	},

	scrollHeight : function(el, vp)
	{
		return [0, el.get(0).scrollHeight - vp.sizeY];
	},

	fontSize : function(el, vp)
	{
		return [0, el.css('font-size')];
	},

	lineHeight : function(el, vp)
	{
		return [el.css('line-height'), 0];
	},

	opacity : function(el, vp)
	{
		return [0, el.css('opacity') || 1];
	},

	dataRangeX : function(el, vp) 	// reads data attribute 'jcp-xrange'
	{
		return el.data('jcp-xrange').split(',');
	},

	dataRangeY : function(el, vp)  	// reads data attribute 'jcp-yrange'
	{
		return el.data('jcp-yrange').split(',');
	}
};

})(jQuery);
<|endoftext|>


<commit_before>import {SelectionState} from './selection.state';

export class SingleSelectionState extends SelectionState {
	constructor(model) {
		super(model);

		this.item = null;
	}

	entries() {
		return this.item ? [this.item] : [];
	}

	selectCore(item, state) {
		if (state) {
			this.item = item;
		}
		else {
			this.item = null;
		}
	}

	stateCore(item) {
		return this.item && this.key(item) === this.key(this.item);
	}

	clearCore() {
		this.item = null;
	}
}<commit_msg>fixed statecore of single selection<commit_after>import {SelectionState} from './selection.state';

export class SingleSelectionState extends SelectionState {
	constructor(model) {
		super(model);

		this.item = null;
	}

	entries() {
		return this.item ? [this.item] : [];
	}

	selectCore(item, state) {
		if (state) {
			this.item = item;
		}
		else {
			this.item = null;
		}
	}

	stateCore(item) {
		return this.item !== null && this.key(item) === this.key(this.item);
	}

	clearCore() {
		this.item = null;
	}
}<|endoftext|>


<commit_before>import { getLocalSettings } from '../utils/settings';
import { GET } from '../utils/http';
// import $ from 'jquery';
/* eslint-disable new-cap */

function addStyle(css, storeId) {
  try {
    const styleTag = document.createElement('style');
    styleTag.type = 'text/css';
    styleTag.id = storeId;
    styleTag.appendChild(document.createTextNode(css.replace(/@-moz-document.*{/g, '@media all {')));
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  } catch (e) {
    console.error(e);
  }
}

function checkAddStyle(userStyleUrl) {
  try {
    if (userStyleUrl === '') return;
    const userStyleId = userStyleUrl.match(/\/styles\/(\d+)\//)[1];
    const storeId = `voz_living_userstyle_${userStyleId}`;
    const oldCss = window.localStorage.getItem(storeId);
    if (oldCss !== null) {
      addStyle(oldCss, storeId);
      return;
    }
    GET(`https://userstyles.org/styles/${userStyleId}.css`, {
      credentials: 'same-origin',
    })
      .then((css) => {
        if (oldCss === null) {
          addStyle(css, storeId);
          window.localStorage.setItem(storeId, css);
        }
      });
  } catch (e) {
    console.error(e);
  }
}

export function UserStyle() {
  let isAdded = false;
  let uStyle = localStorage.getItem('userStyle');
  if (uStyle !== '') {
    uStyle = uStyle.split(',');
    setTimeout(() => {
      for (const eachStyle of uStyle) {
        checkAddStyle(eachStyle);
      }
    }, 50);
    isAdded = true;
  }
  getLocalSettings()
    .then((settings) => {
      let { userStyle } = settings;
      if (userStyle !== '' && !isAdded) {
        userStyle = userStyle.split(',');
        for (const eachStyle of userStyle) {
          checkAddStyle(eachStyle);
        }
      }
      localStorage.setItem('userStyle', userStyle);
    });
}
<commit_msg>[hot-fix] prevent undefined || null split<commit_after>import { getLocalSettings } from '../utils/settings';
import { GET } from '../utils/http';
// import $ from 'jquery';
/* eslint-disable new-cap */

function addStyle(css, storeId) {
  try {
    const styleTag = document.createElement('style');
    styleTag.type = 'text/css';
    styleTag.id = storeId;
    styleTag.appendChild(document.createTextNode(css.replace(/@-moz-document.*{/g, '@media all {')));
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  } catch (e) {
    console.error(e);
  }
}

function checkAddStyle(userStyleUrl) {
  try {
    if (userStyleUrl === '') return;
    const userStyleId = userStyleUrl.match(/\/styles\/(\d+)\//)[1];
    const storeId = `voz_living_userstyle_${userStyleId}`;
    const oldCss = window.localStorage.getItem(storeId);
    if (oldCss !== null) {
      addStyle(oldCss, storeId);
      return;
    }
    GET(`https://userstyles.org/styles/${userStyleId}.css`, {
      credentials: 'same-origin',
    })
      .then((css) => {
        if (oldCss === null) {
          addStyle(css, storeId);
          window.localStorage.setItem(storeId, css);
        }
      });
  } catch (e) {
    console.error(e);
  }
}

export function UserStyle() {
  let isAdded = false;
  let uStyle = localStorage.getItem('userStyle');
  if (uStyle && uStyle !== '') {
    uStyle = uStyle.split(',');
    setTimeout(() => {
      for (const eachStyle of uStyle) {
        checkAddStyle(eachStyle);
      }
    }, 50);
    isAdded = true;
  }
  getLocalSettings()
    .then((settings) => {
      let { userStyle } = settings;
      if (userStyle && userStyle !== '' && !isAdded) {
        userStyle = userStyle.split(',');
        for (const eachStyle of userStyle) {
          checkAddStyle(eachStyle);
        }
      }
      localStorage.setItem('userStyle', userStyle);
    });
}
<|endoftext|>


<commit_before>var charCreatorHelperGlobalVar;
var playersGlobalVar = [];
var easterEggEngineGlobalVar;
var simulationMode  = false;
var teamsGlobalVar = [];
var lastTeamIndex = -2; //each round starts at index + 2
window.onload = function() {
	$(this).scrollTop(0);
	loadNavbar();
	displayPotentialFighters();
}

//hide the teams and button. randomize the teams and reDescribe them to show new order.
//render AB in center, facing left team.
//then, render first team on left of AB, and second team on right of AB.
//then, pass first team to AB (upgrade her to have 'url params' from var as well as actual window location.)
//number to simulate is 10.
//when each session is done, need to call a callback in this file instead of printSTats or whatever (minor AB upgrade)
//callback should note if win (+1 to displayed score), or if grimDark crash (-1 to displayed score, AB flashes corrupt red.)  should also pass MVP value and title (wanna keep track of.)
//when done, callback to this page so it knows to start next team. AB faces right. repeat.
//when both teams done, compare scores, show winner, and strikethrough loser.
//queue up next 2.
//when done, erase all losers, and start again with new teams (teamsGlobalVar should be object[], not string[])
function startTournament(){
	$("#teams").hide();
	$("#roundTitle").css('display', 'inline-block');
	$("#team1").css('display', 'inline-block');
	$("#ab").css('display', 'inline-block');
	$("#team2").css('display', 'inline-block');
	//render team 1 and team2
	teamsGlobalVar = shuffle(teamsGlobalVar); //if these were svgs, could be animated???
	displayTeams();
	$("#tournamentButtonDiv").hide();
	startRound();
}

function startRound(){
	lastTeamIndex += 2;
	var team1 = teamsGlobalVar[lastTeamIndex]
	var team2 = teamsGlobalVar[lastTeamIndex+1]  //if no team 2, they win???
	var team1Title = "
"+ team1 + "
";
	var team2Title =  "
"+ team2 + "
";
	$("#roundTitle").html(team1Title +" vs " + team2Title);
	renderTeam(team1, $("#team1"));
	renderTeam(team2, $("#team2"));
	abLeft();
	console.log("TODO, do 10 rounds of team 1.")
	fight();
}

function doneWithRound(){
	alert("Done with round, now what???")
}

function fight(){
	var numSimulationsToDo = 10;
	var team = teamsGlobalVar[lastTeamIndex]
	if(team.numberSessions >= numSimulationsToDo) team = teamsGlobalVar[lastTeamIndex+1];
	if(team.numberSessions >= numSimulationsToDo) return doneWithRound();
	//var team2 = teamsGlobalVar[lastTeamIndex+1]  //if no team 2, they win???

	simulatedParamsGlobalVar = ""; //which session are we checking?
	alert("Hey, future, JR, don't forget to ALSo parse for easter egg fan oc players, not just STUCK players. probably wILL have to mod get url params to shove stuff into it ")
	startSession(aBCallBack);
}

//what will happen if scratch? Will it return here still?
//need to make sure scratched sessions don't count. (they get stat boost after all)
function aBCallBack(sessionSummary){
	alert(sessionSummary)
	var team = teamsGlobalVar[lastTeamIndex]
	if(team.numberSessions >= numSimulationsToDo) team = teamsGlobalVar[lastTeamIndex+1];
	team.numberSessions ++;
	if(sessionSummary.won) team.win ++;
	if(sessionSummary.crashedFromPlayerActions) team.crash;
	if(sessionSummary.mvp.power > team.mvp_score){
		team.mvp = sessionSummary.mvp.htmlTitle();
		team.mvp_scpre = sessionSummary.mvp.power;
	}
	fight();

}

function abLeft(){
	$("#avatar").attr("src", "images/guide_bot_turnways.png");
	$("#team1Title").css("color", "red");
	$("#team2Title").css("color", "black");
}

function abRight(){
	$("#avatar").attr("src", "images/guide_bot.png");
	$("#team2Title").css("color", "red");
	$("#team1Title").css("color", "black");
}

function renderTeam(team, div){
	var win = "# of Won Sessions: " + team.win
	var crash = "
 # of GrimDark Crash Sessions: " + team.crash
	var score = "
Score:  " + team.score();
	var mvp = "
MVP:  " + team.mvp_name + " with a power of: " + team.mvp_score;
	div.html("
" + win + crash + score + mvp + "
")
}

//all selected tiers will render example chars and a text explanation.handle up to ALL chosen.
//KnightStuck: randomly generated players that are forced to be Knights only.
//IF use rare session finder, will have to have params ALSO able to come internally, not just from url
//fighters chosen become a "bracket"
//do i want symbols for teams?
function displayPotentialFighters(){
	//tiers are EXACTLY the same name as the param, so can generate a "URL" of the right format, for AB to check.
	var fanTeams = ["reddit","tumblr","discord","creditsBuckaroos","ideasWranglers","patrons","patrons2","patrons3","canon","otherFandoms","creators"];
	var classTeams = ["KnightStuck", "SeerStuck","BardStuck","HeirStuck","MaidStuck","RogueStuck","PageStuck","ThiefStuck","SylphStuck","PrinceStuck","WitchStuck","MageStuck"];
	var aspectTeams = ["BloodStuck", "MindStuck","RageStuck","VoidStuck","TimeStuck","HeartStuck","BreathStuck","LightStuck","SpaceStuck","HopeStuck","LifeStuck","DoomStuck"];
	var teams = fanTeams.concat(classTeams);
	teams = teams.concat(aspectTeams);
	var html = "Choose Combatants!
<select multiple size = '" + teams.length + "' id = 'tiers' name='tier'>";
	for(var i = 0; i< teams.length; i++){
			html += '<option value="' + teams[i] +'">' + teams[i]+'</option>'
	}
	html += '</select>'
	$("#teams").append(html);
	wireUpTeamSelector();
}

function wireUpTeamSelector(){
	$("#teams").change(function() {
		teamsGlobalVar = [];
		$('#teams :selected').each(function(i, selected){
			teamsGlobalVar.push(new Team($(selected).text()));
		});
		displayTeams();
	});

}

function displayTeams(){
	//when teams are displayed, also make sure button to start tournament is displayed. Hides team selector, shows AB in middle, with current fighters on either sidebar
	//points go up with each won session, AB glitches red with each grim dark crash and a point is lost.
	//loser is crossed off from team description, and next pair go.
	var html = "";
	var divStart = "
";
	var divEnd = "
";
	for(var i = 0; i < teamsGlobalVar.length; i++){
		html += divStart + getTeamDescription(teamsGlobalVar[i]) + divEnd;
	}
	$("#descriptions").html(html);
	$("#tournamentButtonDiv").css('display', 'inline-block');
}

//when tournament starts up, drop down is set to none, and this is left most thing.
function getTeamDescription(team){
	console.log("~~~~~~~~~~~~~~~~~~TODO~~~~~~~~~~~~~~~ have icon for each category.");
	var stuck = team.name.split("Stuck");
	if(stuck.length == 2) return "
" +stuck[0] +"Stuck

 A random team of only  " + stuck[0] + " Players. (With Time/Space guaranteed)"

	return "
" + team + "

Players chosen randomly from the " + team + " fan OCs";

}

function Team(name){
	this.name = name;
	this.numberSessions = 0;
	this.win = 0;
	this.crash = 0;
	this.mvp_name = "";
	this.mvp_score = 0;

	this.score = function(){
		return this.win - this.crash;
	}

	this.toString = function(){
		return this.name;
	}
}
<commit_msg>fucking hell ab, i told you NOT to print stats out<commit_after>var charCreatorHelperGlobalVar;
var playersGlobalVar = [];
var easterEggEngineGlobalVar;
var simulationMode  = false;
var teamsGlobalVar = [];
var lastTeamIndex = -2; //each round starts at index + 2
window.onload = function() {
	$(this).scrollTop(0);
	loadNavbar();
	displayPotentialFighters();
}

//hide the teams and button. randomize the teams and reDescribe them to show new order.
//render AB in center, facing left team.
//then, render first team on left of AB, and second team on right of AB.
//then, pass first team to AB (upgrade her to have 'url params' from var as well as actual window location.)
//number to simulate is 10.
//when each session is done, need to call a callback in this file instead of printSTats or whatever (minor AB upgrade)
//callback should note if win (+1 to displayed score), or if grimDark crash (-1 to displayed score, AB flashes corrupt red.)  should also pass MVP value and title (wanna keep track of.)
//when done, callback to this page so it knows to start next team. AB faces right. repeat.
//when both teams done, compare scores, show winner, and strikethrough loser.
//queue up next 2.
//when done, erase all losers, and start again with new teams (teamsGlobalVar should be object[], not string[])
function startTournament(){
	$("#teams").hide();
	$("#roundTitle").css('display', 'inline-block');
	$("#team1").css('display', 'inline-block');
	$("#ab").css('display', 'inline-block');
	$("#team2").css('display', 'inline-block');
	//render team 1 and team2
	teamsGlobalVar = shuffle(teamsGlobalVar); //if these were svgs, could be animated???
	displayTeams();
	$("#tournamentButtonDiv").hide();
	startRound();
}

function startRound(){
	lastTeamIndex += 2;
	var team1 = teamsGlobalVar[lastTeamIndex]
	var team2 = teamsGlobalVar[lastTeamIndex+1]  //if no team 2, they win???
	var team1Title = "
"+ team1 + "
";
	var team2Title =  "
"+ team2 + "
";
	$("#roundTitle").html(team1Title +" vs " + team2Title);
	renderTeam(team1, $("#team1"));
	renderTeam(team2, $("#team2"));
	abLeft();
	console.log("TODO, do 10 rounds of team 1.")
	fight();
}

function doneWithRound(){
	alert("Done with round, now what???")
}

function fight(){
	var numSimulationsToDo = 10;
	var team = teamsGlobalVar[lastTeamIndex]
	if(team.numberSessions >= numSimulationsToDo) team = teamsGlobalVar[lastTeamIndex+1];
	if(team.numberSessions >= numSimulationsToDo) return doneWithRound();
	//var team2 = teamsGlobalVar[lastTeamIndex+1]  //if no team 2, they win???

	simulatedParamsGlobalVar = ""; //which session are we checking?
	alert("Hey, future, JR, don't forget to ALSo parse for easter egg fan oc players, not just STUCK players. probably wILL have to mod get url params to shove stuff into it ")
	console.log("crash code, which includes grim dark, causes stats to print out. damn. also: everything is crashing forever.")
	startSession(aBCallBack);
}

//what will happen if scratch? Will it return here still?
//need to make sure scratched sessions don't count. (they get stat boost after all)
function aBCallBack(sessionSummary){
	alert(sessionSummary)
	var team = teamsGlobalVar[lastTeamIndex]
	if(team.numberSessions >= numSimulationsToDo) team = teamsGlobalVar[lastTeamIndex+1];
	team.numberSessions ++;
	if(sessionSummary.won) team.win ++;
	if(sessionSummary.crashedFromPlayerActions) team.crash;
	if(sessionSummary.mvp.power > team.mvp_score){
		team.mvp = sessionSummary.mvp.htmlTitle();
		team.mvp_scpre = sessionSummary.mvp.power;
	}
	fight();

}

function abLeft(){
	$("#avatar").attr("src", "images/guide_bot_turnways.png");
	$("#team1Title").css("color", "red");
	$("#team2Title").css("color", "black");
}

function abRight(){
	$("#avatar").attr("src", "images/guide_bot.png");
	$("#team2Title").css("color", "red");
	$("#team1Title").css("color", "black");
}

function renderTeam(team, div){
	var win = "# of Won Sessions: " + team.win
	var crash = "
 # of GrimDark Crash Sessions: " + team.crash
	var score = "
Score:  " + team.score();
	var mvp = "
MVP:  " + team.mvp_name + " with a power of: " + team.mvp_score;
	div.html("
" + win + crash + score + mvp + "
")
}

//all selected tiers will render example chars and a text explanation.handle up to ALL chosen.
//KnightStuck: randomly generated players that are forced to be Knights only.
//IF use rare session finder, will have to have params ALSO able to come internally, not just from url
//fighters chosen become a "bracket"
//do i want symbols for teams?
function displayPotentialFighters(){
	//tiers are EXACTLY the same name as the param, so can generate a "URL" of the right format, for AB to check.
	var fanTeams = ["reddit","tumblr","discord","creditsBuckaroos","ideasWranglers","patrons","patrons2","patrons3","canon","otherFandoms","creators"];
	var classTeams = ["KnightStuck", "SeerStuck","BardStuck","HeirStuck","MaidStuck","RogueStuck","PageStuck","ThiefStuck","SylphStuck","PrinceStuck","WitchStuck","MageStuck"];
	var aspectTeams = ["BloodStuck", "MindStuck","RageStuck","VoidStuck","TimeStuck","HeartStuck","BreathStuck","LightStuck","SpaceStuck","HopeStuck","LifeStuck","DoomStuck"];
	var teams = fanTeams.concat(classTeams);
	teams = teams.concat(aspectTeams);
	var html = "Choose Combatants!
<select multiple size = '" + teams.length + "' id = 'tiers' name='tier'>";
	for(var i = 0; i< teams.length; i++){
			html += '<option value="' + teams[i] +'">' + teams[i]+'</option>'
	}
	html += '</select>'
	$("#teams").append(html);
	wireUpTeamSelector();
}

function wireUpTeamSelector(){
	$("#teams").change(function() {
		teamsGlobalVar = [];
		$('#teams :selected').each(function(i, selected){
			teamsGlobalVar.push(new Team($(selected).text()));
		});
		displayTeams();
	});

}

function displayTeams(){
	//when teams are displayed, also make sure button to start tournament is displayed. Hides team selector, shows AB in middle, with current fighters on either sidebar
	//points go up with each won session, AB glitches red with each grim dark crash and a point is lost.
	//loser is crossed off from team description, and next pair go.
	var html = "";
	var divStart = "
";
	var divEnd = "
";
	for(var i = 0; i < teamsGlobalVar.length; i++){
		html += divStart + getTeamDescription(teamsGlobalVar[i]) + divEnd;
	}
	$("#descriptions").html(html);
	$("#tournamentButtonDiv").css('display', 'inline-block');
}

//when tournament starts up, drop down is set to none, and this is left most thing.
function getTeamDescription(team){
	console.log("~~~~~~~~~~~~~~~~~~TODO~~~~~~~~~~~~~~~ have icon for each category.");
	var stuck = team.name.split("Stuck");
	if(stuck.length == 2) return "
" +stuck[0] +"Stuck

 A random team of only  " + stuck[0] + " Players. (With Time/Space guaranteed)"

	return "
" + team + "

Players chosen randomly from the " + team + " fan OCs";

}

function Team(name){
	this.name = name;
	this.numberSessions = 0;
	this.win = 0;
	this.crash = 0;
	this.mvp_name = "";
	this.mvp_score = 0;

	this.score = function(){
		return this.win - this.crash;
	}

	this.toString = function(){
		return this.name;
	}
}
<|endoftext|>


<commit_before>import { itemPoint } from '../../echarts-base'
import { getFormated, getStackMap } from '../../utils'

function getLineXAxis (args) {
  const { dimension, rows, xAxisName, axisVisible, xAxisType } = args
  return dimension.map((item, index) => ({
    type: xAxisType,
    nameLocation: 'middle',
    nameGap: 22,
    boundaryGap: false,
    name: xAxisName[index] || '',
    axisTick: { show: true, lineStyle: { color: '#eee' } },
    data: rows.map(row => row[item]),
    show: axisVisible
  }))
}

function getLineSeries (args) {
  const {
    rows,
    axisSite,
    metrics,
    area,
    stack,
    nullAddZero,
    labelMap,
    label,
    itemStyle,
    lineStyle,
    areaStyle,
    xAxisType,
    dimension
  } = args
  let series = []
  const dataTemp = {}
  const stackMap = stack && getStackMap(stack)
  metrics.forEach(item => { dataTemp[item] = [] })
  rows.forEach(row => {
    metrics.forEach(item => {
      let value = null
      if (row[item] != null) {
        value = row[item]
      } else if (nullAddZero) {
        value = 0
      }
      const dataItem = xAxisType === 'category'
        ? value
        : [row[dimension[0]], value]
      dataTemp[item].push(dataItem)
    })
  })
  metrics.forEach(item => {
    let seriesItem = {
      name: labelMap[item] != null ? labelMap[item] : item,
      type: 'line',
      data: dataTemp[item]
    }

    if (area) seriesItem.areaStyle = { normal: {} }
    if (axisSite.right) {
      seriesItem.yAxisIndex = ~axisSite.right.indexOf(item) ? 1 : 0
    }

    if (stack && stackMap[item]) seriesItem.stack = stackMap[item]

    if (label) seriesItem.label = label
    if (itemStyle) seriesItem.itemStyle = itemStyle
    if (lineStyle) seriesItem.lineStyle = lineStyle
    if (areaStyle) seriesItem.areaStyle = areaStyle

    series.push(seriesItem)
  })
  return series
}

function getLineYAxis (args) {
  const {
    yAxisName,
    yAxisType,
    axisVisible,
    scale,
    min,
    max,
    digit
  } = args
  const yAxisBase = {
    type: 'value',
    axisTick: {
      show: false
    },
    show: axisVisible
  }
  let yAxis = []
  for (let i = 0; i < 2; i++) {
    if (yAxisType[i]) {
      yAxis[i] = Object.assign({}, yAxisBase, {
        axisLabel: {
          formatter (val) {
            return getFormated(val, yAxisType[i], digit)
          }
        }
      })
    } else {
      yAxis[i] = Object.assign({}, yAxisBase)
    }
    yAxis[i].name = yAxisName[i] || ''
    yAxis[i].scale = scale[i] || false
    yAxis[i].min = min[i] || null
    yAxis[i].max = max[i] || null
  }
  return yAxis
}

function getLineTooltip (args) {
  const { axisSite, yAxisType, digit, labelMap, xAxisType, tooltipFormatter } = args
  const rightItems = axisSite.right || []
  const rightList = labelMap
    ? rightItems.map(item => {
      return labelMap[item] === undefined ? item : labelMap[item]
    })
    : rightItems
  return {
    trigger: 'axis',
    formatter (items) {
      if (tooltipFormatter) {
        return tooltipFormatter.apply(null, arguments)
      }
      let tpl = []
      const { name, axisValueLabel } = items[0]
      const title = name || axisValueLabel
      tpl.push(`${title}<br>`)
      items.forEach(item => {
        let showData = null
        const type = ~rightList.indexOf(item.seriesName)
          ? yAxisType[1]
          : yAxisType[0]
        const data = xAxisType === 'category'
          ? item.data
          : item.data[1]
        showData = getFormated(data, type, digit)
        tpl.push(itemPoint(item.color))
        tpl.push(`${item.seriesName}: ${showData}`)
        tpl.push('
')
      })
      return tpl.join('')
    }
  }
}

function getLegend (args) {
  const { metrics, legendName, labelMap } = args
  if (!legendName && !labelMap) return { data: metrics }
  const data = labelMap
    ? metrics.map(item => (labelMap[item] == null ? item : labelMap[item]))
    : metrics
  return {
    data,
    formatter (name) {
      return legendName[name] != null ? legendName[name] : name
    }
  }
}

export const line = (columns, rows, settings, extra) => {
  const {
    axisSite = {},
    yAxisType = ['normal', 'normal'],
    xAxisType = 'category',
    yAxisName = [],
    dimension = [columns[0]],
    xAxisName = [],
    axisVisible = true,
    area,
    stack,
    scale = [false, false],
    min = [null, null],
    max = [null, null],
    nullAddZero = false,
    digit = 2,
    legendName = {},
    labelMap = {},
    label,
    itemStyle,
    lineStyle,
    areaStyle
  } = settings
  const { tooltipVisible, legendVisible, tooltipFormatter } = extra
  let metrics = columns.slice()

  if (axisSite.left && axisSite.right) {
    metrics = axisSite.left.concat(axisSite.right)
  } else if (axisSite.left && !axisSite.right) {
    metrics = axisSite.left
  } else if (settings.metrics) {
    metrics = settings.metrics
  } else {
    metrics.splice(columns.indexOf(dimension[0]), 1)
  }

  const legend = legendVisible && getLegend({ metrics, legendName, labelMap })
  const tooltip = tooltipVisible && getLineTooltip({
    axisSite,
    yAxisType,
    digit,
    labelMap,
    xAxisType,
    tooltipFormatter
  })
  const xAxis = getLineXAxis({
    dimension,
    rows,
    xAxisName,
    axisVisible,
    xAxisType
  })
  const yAxis = getLineYAxis({
    yAxisName,
    yAxisType,
    axisVisible,
    scale,
    min,
    max,
    digit
  })
  const series = getLineSeries({
    rows,
    axisSite,
    metrics,
    area,
    stack,
    nullAddZero,
    labelMap,
    label,
    itemStyle,
    lineStyle,
    areaStyle,
    xAxisType,
    dimension
  })
  if (!xAxis || !series) return false

  let options = { legend, xAxis, series, yAxis, tooltip }
  return options
}
<commit_msg>fix(line): 移除返回 false<commit_after>import { itemPoint } from '../../echarts-base'
import { getFormated, getStackMap } from '../../utils'

function getLineXAxis (args) {
  const { dimension, rows, xAxisName, axisVisible, xAxisType } = args
  return dimension.map((item, index) => ({
    type: xAxisType,
    nameLocation: 'middle',
    nameGap: 22,
    boundaryGap: false,
    name: xAxisName[index] || '',
    axisTick: { show: true, lineStyle: { color: '#eee' } },
    data: rows.map(row => row[item]),
    show: axisVisible
  }))
}

function getLineSeries (args) {
  const {
    rows,
    axisSite,
    metrics,
    area,
    stack,
    nullAddZero,
    labelMap,
    label,
    itemStyle,
    lineStyle,
    areaStyle,
    xAxisType,
    dimension
  } = args
  let series = []
  const dataTemp = {}
  const stackMap = stack && getStackMap(stack)
  metrics.forEach(item => { dataTemp[item] = [] })
  rows.forEach(row => {
    metrics.forEach(item => {
      let value = null
      if (row[item] != null) {
        value = row[item]
      } else if (nullAddZero) {
        value = 0
      }
      const dataItem = xAxisType === 'category'
        ? value
        : [row[dimension[0]], value]
      dataTemp[item].push(dataItem)
    })
  })
  metrics.forEach(item => {
    let seriesItem = {
      name: labelMap[item] != null ? labelMap[item] : item,
      type: 'line',
      data: dataTemp[item]
    }

    if (area) seriesItem.areaStyle = { normal: {} }
    if (axisSite.right) {
      seriesItem.yAxisIndex = ~axisSite.right.indexOf(item) ? 1 : 0
    }

    if (stack && stackMap[item]) seriesItem.stack = stackMap[item]

    if (label) seriesItem.label = label
    if (itemStyle) seriesItem.itemStyle = itemStyle
    if (lineStyle) seriesItem.lineStyle = lineStyle
    if (areaStyle) seriesItem.areaStyle = areaStyle

    series.push(seriesItem)
  })
  return series
}

function getLineYAxis (args) {
  const {
    yAxisName,
    yAxisType,
    axisVisible,
    scale,
    min,
    max,
    digit
  } = args
  const yAxisBase = {
    type: 'value',
    axisTick: {
      show: false
    },
    show: axisVisible
  }
  let yAxis = []
  for (let i = 0; i < 2; i++) {
    if (yAxisType[i]) {
      yAxis[i] = Object.assign({}, yAxisBase, {
        axisLabel: {
          formatter (val) {
            return getFormated(val, yAxisType[i], digit)
          }
        }
      })
    } else {
      yAxis[i] = Object.assign({}, yAxisBase)
    }
    yAxis[i].name = yAxisName[i] || ''
    yAxis[i].scale = scale[i] || false
    yAxis[i].min = min[i] || null
    yAxis[i].max = max[i] || null
  }
  return yAxis
}

function getLineTooltip (args) {
  const { axisSite, yAxisType, digit, labelMap, xAxisType, tooltipFormatter } = args
  const rightItems = axisSite.right || []
  const rightList = labelMap
    ? rightItems.map(item => {
      return labelMap[item] === undefined ? item : labelMap[item]
    })
    : rightItems
  return {
    trigger: 'axis',
    formatter (items) {
      if (tooltipFormatter) {
        return tooltipFormatter.apply(null, arguments)
      }
      let tpl = []
      const { name, axisValueLabel } = items[0]
      const title = name || axisValueLabel
      tpl.push(`${title}<br>`)
      items.forEach(item => {
        let showData = null
        const type = ~rightList.indexOf(item.seriesName)
          ? yAxisType[1]
          : yAxisType[0]
        const data = xAxisType === 'category'
          ? item.data
          : item.data[1]
        showData = getFormated(data, type, digit)
        tpl.push(itemPoint(item.color))
        tpl.push(`${item.seriesName}: ${showData}`)
        tpl.push('
')
      })
      return tpl.join('')
    }
  }
}

function getLegend (args) {
  const { metrics, legendName, labelMap } = args
  if (!legendName && !labelMap) return { data: metrics }
  const data = labelMap
    ? metrics.map(item => (labelMap[item] == null ? item : labelMap[item]))
    : metrics
  return {
    data,
    formatter (name) {
      return legendName[name] != null ? legendName[name] : name
    }
  }
}

export const line = (columns, rows, settings, extra) => {
  const {
    axisSite = {},
    yAxisType = ['normal', 'normal'],
    xAxisType = 'category',
    yAxisName = [],
    dimension = [columns[0]],
    xAxisName = [],
    axisVisible = true,
    area,
    stack,
    scale = [false, false],
    min = [null, null],
    max = [null, null],
    nullAddZero = false,
    digit = 2,
    legendName = {},
    labelMap = {},
    label,
    itemStyle,
    lineStyle,
    areaStyle
  } = settings
  const { tooltipVisible, legendVisible, tooltipFormatter } = extra
  let metrics = columns.slice()

  if (axisSite.left && axisSite.right) {
    metrics = axisSite.left.concat(axisSite.right)
  } else if (axisSite.left && !axisSite.right) {
    metrics = axisSite.left
  } else if (settings.metrics) {
    metrics = settings.metrics
  } else {
    metrics.splice(columns.indexOf(dimension[0]), 1)
  }

  const legend = legendVisible && getLegend({ metrics, legendName, labelMap })
  const tooltip = tooltipVisible && getLineTooltip({
    axisSite,
    yAxisType,
    digit,
    labelMap,
    xAxisType,
    tooltipFormatter
  })
  const xAxis = getLineXAxis({
    dimension,
    rows,
    xAxisName,
    axisVisible,
    xAxisType
  })
  const yAxis = getLineYAxis({
    yAxisName,
    yAxisType,
    axisVisible,
    scale,
    min,
    max,
    digit
  })
  const series = getLineSeries({
    rows,
    axisSite,
    metrics,
    area,
    stack,
    nullAddZero,
    labelMap,
    label,
    itemStyle,
    lineStyle,
    areaStyle,
    xAxisType,
    dimension
  })
  let options = { legend, xAxis, series, yAxis, tooltip }
  return options
}
<|endoftext|>


<commit_before>var fs = require("fs");

var IS_VERBOSE = false;
const ERROR_NUM_ARGS = "Error: Number of arguments was invalid.";
const ERROR_FILEIO = "Error: Could not open the file specified. Does it exist, and do we have read access to it?";
const INFO_USAGE = "Usage: node interpret.js [-v | --verbose] <path-to-task>";
/*
 * Interprets a CSL task and translates to WebdriverIO.
 */
function main() {
  var data = readArgs(process.argv);
  if (!data)
    return; // Abandon ship!
  parse(data);
}

function readArgs(args) {
  // Usage: interpret.js [-v] <task>

  // Check number of args
  if (!args || args.length < 3 || args.length > 4) {
    console.error(ERROR_NUM_ARGS);
    console.error(INFO_USAGE);
    return;
  }

  // Check for verbose flag
  var flag = args.indexOf("--verbose");
  if (flag == -1)
    flag = args.indexOf("-v");
  if (flag != -1) {
    args.splice(flag, 1);
    if (args.length < 3) {
      console.error(ERROR_NUM_ARGS);
      console.error(INFO_USAGE);
      return;
    }

    VERBOSE_FLAG = true;
  }

  // Check if we can open file specified
  var data = "";
  try {
    data = fs.readFileSync(args[2]);
  } catch (err) {
    console.error(ERROR_FILEIO);
    return;
  }

  // If all goes well...
  return data;
}

/*
 * Parses file data as CSL and interprets as WebdriverIO code.
 */
function parse(data) {
}

if (require.main === module) {
  main();
}
<commit_msg>Start line-by-line process<commit_after>var fs = require("fs");

var IS_VERBOSE = false;
const ERROR_NUM_ARGS = "Error: Number of arguments was invalid.";
const ERROR_FILEIO = "Error: Could not open the file specified. Does it exist, and do we have read access to it?";
const ERROR_SYNTAX = "Error: Syntax error on line ";
const INFO_USAGE = "Usage: node interpret.js [-v | --verbose] <path-to-task>";
/*
 * Interprets a CSL task and translates to WebdriverIO.
 */
function main() {
  var data = readArgs(process.argv);
  if (!data)
    return; // Abandon ship!
  parse(data);
}

function readArgs(args) {
  // Usage: interpret.js [-v] <task>

  // Check number of args
  if (!args || args.length < 3 || args.length > 4) {
    console.error(ERROR_NUM_ARGS);
    console.error(INFO_USAGE);
    return;
  }

  // Check for verbose flag
  var flag = args.indexOf("--verbose");
  if (flag == -1)
    flag = args.indexOf("-v");
  if (flag != -1) {
    args.splice(flag, 1);
    if (args.length < 3) {
      console.error(ERROR_NUM_ARGS);
      console.error(INFO_USAGE);
      return;
    }

    VERBOSE_FLAG = true;
  }

  // Check if we can open file specified
  var data = "";
  try {
    data = fs.readFileSync(args[2]);
  } catch (err) {
    console.error(ERROR_FILEIO);
    return;
  }

  // If all goes well...
  return data;
}

/*
 * Parses file data as CSL and interprets as WebdriverIO code.
 */
function parse(data) {
  var lines = data.split('\n');
  var timeout = 30000;
  var output = [];
  if ("!timeout" in lines[0])
    // timeout = processTimeout()
  for (var i = 0; i < lines.length; i++) {
    // Process line-by-line
    try {
      output.push(processLine(lines[i]));
    } catch (err) {
      console.error(ERROR_SYNTAX + i);
      return;
    }
  }
}

function processTimeout(line) {

}

function processLine(line) {

}

if (require.main === module) {
  main();
}
<|endoftext|>


<commit_before>var check = function (node, file) {
};

exports.MethodDefinition =
exports.Property = function (node, parent, file) {
  if (node.kind === "set" && node.value.params.length !== 1) {
    throw file.errorWithNode(node.value, "Setters must have only one parameter");
  }
};
<commit_msg>remove unused check function<commit_after>exports.MethodDefinition =
exports.Property = function (node, parent, file) {
  if (node.kind === "set" && node.value.params.length !== 1) {
    throw file.errorWithNode(node.value, "Setters must have only one parameter");
  }
};
<|endoftext|>