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

var table = $('#example').DataTable();

$('.chosen_select_left').each(function(i, obj) {
    var attrName = $(obj).find(":selected").text();
    var number = $(obj).data('number');
    var value = $(obj).data('value-'+number);
    var temp = new Array();
    if (typeof(value) != "undefined"){ temp = value.split(","); }
    selected = $.trim(attrName);

        $.ajax({
            url : "/style/getAttributeValue",
            type : "post",
            dataType:"text",
            data : {
                'selected' : selected,
            },
            success: function (result){
                $('#loading').css('display','none');

                var employeeData = JSON.parse(result);
                var optionString = '';
                for(i = 0; employeeData.length >i; i++){

                    $.each(temp, function(key, value) {

                        if(value == employeeData[i]){
                            selected = 'selected';
                            return false;
                        }else{
                            selected = '';
                        }
                    });
                        optionString += "<option "+selected+" >"+employeeData[i]+"</option>";

                }
                var className = '#select-right-' + number;
                $(className).append( optionString).trigger("chosen:updated");
            }
        });

});
//lay ve het cac select hien tai
//for cac select -> lay ve option dang duoc chon ->

$('.chosen_select_right').on('change', function(evt, params) {

     var number = $(this).closest('form').find('.top_right_attName .chosen_select_left').attr('data-number');
     if(params.selected == 'all'){
        $('.chosen_select_right#select-right-'+number+' option').removeAttr('selected');
        $(this).val('all');
        $('.chosen_select_right#select-right-'+number).trigger('chosen:updated');
     }else{
        $('.chosen_select_right#select-right-'+number+' option.all').removeAttr('selected');
        $('.chosen_select_right#select-right-'+number).trigger('chosen:updated');
     }

});

$('.chosen_select_left').change(function(){
    var number = $(this).data('number');
    $('#loading').css('display','block');
    $(".chosen_select_right#select-right-"+number+" option").remove();
    selected = $(this).val();
        $.ajax({
            url : "/style/getAttributeValue",
            type : "post",
            dataType:"text",
            data : {
                'selected' : selected,
            },
            success: function (result){
                $('#loading').css('display','none');
                var employeeData = JSON.parse(result);
                var className = '#select-right-' + number;
                var optionString = '<option class="all" value="all">All</option>';

                for(i = 0; employeeData.length >i; i++){
                    optionString += "<option>"+employeeData[i]+"</option>";
                }
                $(className).append( optionString ).trigger("chosen:updated");
            }
        });
    // }else{
    //     var brand_store = $('#brand-store option');
    //     brand_list = [];

    //     for(i=0; brand_store.length>i;i++ ){
    //         brand_list.push(brand_store[i].value);
    //     }

    //     var className = '#select-right-' + number;
    //     var optionString = '';
    //     for(i = 0; brand_list.length >i; i++){
    //         optionString += "<option>"+brand_list[i]+"</option>";
    //     }
    //     $(className).append( optionString ).trigger("chosen:updated");
    //     //console.log(brand_list);
    //     //console.log(brand_list);
    // }
});
//form add new
    $(function () {
        $('form#add-new').bind('submit', function () {
            form = $(this).serialize();
            $.ajax({
            type: 'post',
            url: '/style/styledefination',
            data : {
                'form' : form,
            },
            success: function (result) {
              if(result == 1){
                alert('Created');
                location.reload();
              }else{
                alert('has error');
              }

            }
          });
          return false;
        });
    });

//form update

$(function () {
    $('form.style-update').bind('submit', function (event) {
        var action = $(this).find("input[type=submit]:focus").attr('data-action');
        var form = $(this).serialize();
        if(action == 'update'){
            $.ajax({
                type: 'post',
                url: '/style/updatestyledefination',
                data : {
                    'form' : form,
                },
                success: function (result) {
                if(result == 1){
                    alert('Update Success');
                    location.reload();
                }else{
                    alert('has error');
                }

                }
              });
        }else if(action == 'delete'){

             $.ajax({
                type: 'post',
                url: '/style/deletestyledefination',
                data : {
                    'form' : form,
                },
                success: function (result) {
                //alert(result);
                if(result == 1){
                    alert('Delete Success');
                    location.reload();
                }else{
                    alert('has error');
                }

                }
              });

        }
        return false;
    });
});

    $(".chosen_select_left").chosen();
    $(".chosen_select_right").chosen();

    $('#idNewsLetter').click(function() {

    	var $email = $('#idNewsLetterInput'); //change form to id or containment selector
    	var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
    	if ($email.val() == '' || !re.test($email.val()))
        {
    		myalert('alert_idNewsLetterInput3','type_missing','Ooops!','','OK','Please enter valid email address.',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
        }
        else
        {
            $("#loading-div-background").show();
            $.ajax({
                url: "/index/newsletter",
                type: 'POST',
                data: { newsLetterInput: $('#idNewsLetterInput').val()  },
                dataType: 'json',
                success: function (result)
                {
                    // alert(result.status);
                    if (result.status == 'success')
                    {
                    	$('#idNewsLetterInput').val('');
                    	myalert('alert_idNewsLetterInput1','type_success','Success','','OK','You have been successfully added to our newsletter.',function(){$('#alert_idNewsLetterInput1').foundation('reveal','close'); });
                    }
                    else if (result.status == 'success1')
                    {
                        myalert('alert_idNewsLetterInput3','type_missing','Ooops!','','OK','This email is already registered.',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
                    }
                    else
                    {
                    	 myalert('alert_idNewsLetterInput2', 'type_cancel','Internal Server Error', 'Please contact site administrator.','','',function(){$('#alert_idNewsLetterInput2').foundation('reveal','close'); });
                    }
                     $("#loading-div-background").hide();
                }
            });
        }

    });

    // $(".my_delete_yes").click(function(){
    //     $del_style = $(this).attr("data-delete");
    //     alert($del_style);
    //     $.ajax({
    //         url: "style/deletestyle",
    //         type: "POST",
    //         data: { del_style : $del_style },
    //         dataType: "html",
    //         success: function ()
    //         {
    //               // alert(result);
    //         }
    //     });
    // });

    $(".sb_create_style").click(function(){
        $(this).parents(".style_page").find("#top_left").animate({ left: "+=50", height: "toggle" }, 1000, function() {});
    });

});

$(document).on("click", ".my_delete_yes", function(){
    del_style = $(this).attr("data-delete2");
    // $('[data-delete='+del_style+']').parents('tr').remove();
    table.row( $('[data-delete='+del_style+']').parents('tr')).remove().draw();
    // alert(del_style);
    $.ajax({
        url: "style/deletestyle",
        type: "POST",
        data: { del_style : del_style },
        dataType: "test",
        success: function ()
        {
              // alert(result);
            // $('[data-delete='+del_style+']').parents('tr').remove();
        }
    });
    // location.reload();
});

$(document).on("click",".btn_delete_style", function(e){
    e.preventDefault();
    $(".my_cancel, .my_btn").css("display", "none");
    $(".my_delete_yes, .my_delete_no").css("display", "block");
    var x = $(this).attr("data-delete");
    $('.my_delete_yes').attr("data-delete2",x);
    // var that = $(this),
    // tableRow = that.parents('.test_id');
    // alert(tableRow.index());
    // $(".my_delete_yes").attr("data-index",tableRow.index());
    myalert('alert_idNewsLetterInput3','type_remove','Ooops!','','OK','Do you want to delete or not?',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
});
$(document).on( 'click', '.delete_style', function () {
        table.row( $(".btn_delete_style").parents('tr') ).remove().draw();
    } );<commit_msg>remove alert test<commit_after>$(document).ready(function() {

var table = $('#example').DataTable();

$('.chosen_select_left').each(function(i, obj) {
    var attrName = $(obj).find(":selected").text();
    var number = $(obj).data('number');
    var value = $(obj).data('value-'+number);
    var temp = new Array();
    if (typeof(value) != "undefined"){ temp = value.split(","); }
    selected = $.trim(attrName);

        $.ajax({
            url : "/style/getAttributeValue",
            type : "post",
            dataType:"text",
            data : {
                'selected' : selected,
            },
            success: function (result){
                $('#loading').css('display','none');

                var employeeData = JSON.parse(result);
                var optionString = '';
                for(i = 0; employeeData.length >i; i++){

                    $.each(temp, function(key, value) {

                        if(value == employeeData[i]){
                            selected = 'selected';
                            return false;
                        }else{
                            selected = '';
                        }
                    });
                        optionString += "<option "+selected+" >"+employeeData[i]+"</option>";

                }
                var className = '#select-right-' + number;
                $(className).append( optionString).trigger("chosen:updated");
            }
        });

});
//lay ve het cac select hien tai
//for cac select -> lay ve option dang duoc chon ->

$('.chosen_select_right').on('change', function(evt, params) {

     var number = $(this).closest('form').find('.top_right_attName .chosen_select_left').attr('data-number');
     if(params.selected == 'all'){
        $('.chosen_select_right#select-right-'+number+' option').removeAttr('selected');
        $(this).val('all');
        $('.chosen_select_right#select-right-'+number).trigger('chosen:updated');
     }else{
        $('.chosen_select_right#select-right-'+number+' option.all').removeAttr('selected');
        $('.chosen_select_right#select-right-'+number).trigger('chosen:updated');
     }

});

$('.chosen_select_left').change(function(){
    var number = $(this).data('number');
    $('#loading').css('display','block');
    $(".chosen_select_right#select-right-"+number+" option").remove();
    selected = $(this).val();
        $.ajax({
            url : "/style/getAttributeValue",
            type : "post",
            dataType:"text",
            data : {
                'selected' : selected,
            },
            success: function (result){
                $('#loading').css('display','none');
                var employeeData = JSON.parse(result);
                var className = '#select-right-' + number;
                var optionString = '<option class="all" value="all">All</option>';

                for(i = 0; employeeData.length >i; i++){
                    optionString += "<option>"+employeeData[i]+"</option>";
                }
                $(className).append( optionString ).trigger("chosen:updated");
            }
        });
    // }else{
    //     var brand_store = $('#brand-store option');
    //     brand_list = [];

    //     for(i=0; brand_store.length>i;i++ ){
    //         brand_list.push(brand_store[i].value);
    //     }

    //     var className = '#select-right-' + number;
    //     var optionString = '';
    //     for(i = 0; brand_list.length >i; i++){
    //         optionString += "<option>"+brand_list[i]+"</option>";
    //     }
    //     $(className).append( optionString ).trigger("chosen:updated");
    //     //console.log(brand_list);
    //     //console.log(brand_list);
    // }
});
//form add new
    $(function () {
        $('form#add-new').bind('submit', function () {
            form = $(this).serialize();
            $.ajax({
            type: 'post',
            url: '/style/styledefination',
            data : {
                'form' : form,
            },
            success: function (result) {
              if(result == 1){
                // alert('Created');
                location.reload();
              }else{
                alert('has error');
              }

            }
          });
          return false;
        });
    });

//form update

$(function () {
    $('form.style-update').bind('submit', function (event) {
        var action = $(this).find("input[type=submit]:focus").attr('data-action');
        var form = $(this).serialize();
        if(action == 'update'){
            $.ajax({
                type: 'post',
                url: '/style/updatestyledefination',
                data : {
                    'form' : form,
                },
                success: function (result) {
                if(result == 1){
                    // alert('Update Success');
                    location.reload();
                }else{
                    alert('has error');
                }

                }
              });
        }else if(action == 'delete'){

             $.ajax({
                type: 'post',
                url: '/style/deletestyledefination',
                data : {
                    'form' : form,
                },
                success: function (result) {
                //alert(result);
                if(result == 1){
                    // alert('Delete Success');
                    location.reload();
                }else{
                    alert('has error');
                }

                }
              });

        }
        return false;
    });
});

    $(".chosen_select_left").chosen();
    $(".chosen_select_right").chosen();

    $('#idNewsLetter').click(function() {

    	var $email = $('#idNewsLetterInput'); //change form to id or containment selector
    	var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
    	if ($email.val() == '' || !re.test($email.val()))
        {
    		myalert('alert_idNewsLetterInput3','type_missing','Ooops!','','OK','Please enter valid email address.',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
        }
        else
        {
            $("#loading-div-background").show();
            $.ajax({
                url: "/index/newsletter",
                type: 'POST',
                data: { newsLetterInput: $('#idNewsLetterInput').val()  },
                dataType: 'json',
                success: function (result)
                {
                    // alert(result.status);
                    if (result.status == 'success')
                    {
                    	$('#idNewsLetterInput').val('');
                    	myalert('alert_idNewsLetterInput1','type_success','Success','','OK','You have been successfully added to our newsletter.',function(){$('#alert_idNewsLetterInput1').foundation('reveal','close'); });
                    }
                    else if (result.status == 'success1')
                    {
                        myalert('alert_idNewsLetterInput3','type_missing','Ooops!','','OK','This email is already registered.',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
                    }
                    else
                    {
                    	 myalert('alert_idNewsLetterInput2', 'type_cancel','Internal Server Error', 'Please contact site administrator.','','',function(){$('#alert_idNewsLetterInput2').foundation('reveal','close'); });
                    }
                     $("#loading-div-background").hide();
                }
            });
        }

    });

    // $(".my_delete_yes").click(function(){
    //     $del_style = $(this).attr("data-delete");
    //     alert($del_style);
    //     $.ajax({
    //         url: "style/deletestyle",
    //         type: "POST",
    //         data: { del_style : $del_style },
    //         dataType: "html",
    //         success: function ()
    //         {
    //               // alert(result);
    //         }
    //     });
    // });

    $(".sb_create_style").click(function(){
        $(this).parents(".style_page").find("#top_left").animate({ left: "+=50", height: "toggle" }, 1000, function() {});
    });

});

$(document).on("click", ".my_delete_yes", function(){
    del_style = $(this).attr("data-delete2");
    // $('[data-delete='+del_style+']').parents('tr').remove();
    table.row( $('[data-delete='+del_style+']').parents('tr')).remove().draw();
    // alert(del_style);
    $.ajax({
        url: "style/deletestyle",
        type: "POST",
        data: { del_style : del_style },
        dataType: "test",
        success: function ()
        {
              // alert(result);
            // $('[data-delete='+del_style+']').parents('tr').remove();
        }
    });
    // location.reload();
});

$(document).on("click",".btn_delete_style", function(e){
    e.preventDefault();
    $(".my_cancel, .my_btn").css("display", "none");
    $(".my_delete_yes, .my_delete_no").css("display", "block");
    var x = $(this).attr("data-delete");
    $('.my_delete_yes').attr("data-delete2",x);
    // var that = $(this),
    // tableRow = that.parents('.test_id');
    // alert(tableRow.index());
    // $(".my_delete_yes").attr("data-index",tableRow.index());
    myalert('alert_idNewsLetterInput3','type_remove','Ooops!','','OK','Do you want to delete or not?',function(){$('#alert_idNewsLetterInput3').foundation('reveal','close'); });
});
$(document).on( 'click', '.delete_style', function () {
        table.row( $(".btn_delete_style").parents('tr') ).remove().draw();
    } );<|endoftext|>


<commit_before>import React from 'react';
import actions from '../actions/ipsumActions.js';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { renderChart } from '../D3graphTemplate';
import { Panel, Grid, Row, Col, PageHeader, Button, Image} from 'react-bootstrap';
import request from '../util/restHelpers';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import barGraph from './BarGraph';
import _ from 'underscore';
import MyAppHistory from './MyAppHistory';
import Select from 'react-select';

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lineGraphRoute: null,
      resizefunc: null,
      loading: false
    };
  }

  getAndGraphTodaysData(){
    this.setState({loading: true}, () => {
      // call 24 hr bar graph data and render
      request.post('/getStats/serverTotalsForApp', {
        appid: this.props.state.appSelection.id,
        hours: 24
      }, (err, data) => {
        if (err) {console.log('ERROR', err); return; }
        var data = JSON.parse(data.text);
        var output = [];
        Object.keys(data).forEach((serverId) => {
          output.push({
            value: data[serverId].statValue,
            label: data[serverId].hostname,
            id: Number(serverId)
          });
        });

        // for relative server load bar graph
        this.props.dispatch(actions.CHANGE_APP_SERVER_TOTALS(output));
        this.setState({loading: false}, () => {
          barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => {
            return -obj.value;
          }));
        });
      });

    });

    //For routes line Graph
    this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE('/Total'));
    var appId = this.props.state.appSelection.id;
    this.setState({loading: true}, () => {

      request.post('/getStats/app',
        {appId: appId, hours: 24}, //TODO figure out how to keep track of desired hours, have user settings/config in store?
        (err, res) => {
          this.setState({loading: false})
          if (err) { console.log("Error getting Server Data", err); }
          this.props.dispatch(actions.ADD_SERVER_DATA(res.body));
          this.setState({lineGraphRoute: this.props.state.graphData[0].route});
          renderChart('lineGraph', this.props.state.graphData[0].data);
      });

      this.setState({resizefunc: this.resizedb()}, () => {
        window.addEventListener('resize', this.state.resizefunc);
      })

    })
  }

  componentDidMount() {
    this.getAndGraphTodaysData();
  }

  resizedb() {
    var redraw = function() {
      // linegraph
      this.updateGraph({value: this.state.lineGraphRoute});
      // horizontal bar graph
      barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => {
        return -obj.value;
      }));
    }
    return _.debounce(redraw.bind(this), 500)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.state.resizefunc);
  }

  updateGraph(value) {
    !value ? null :
    this.setState({lineGraphRoute: value.value});
    this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE("/" + value.value));
    d3.select('#lineGraph > svg').remove();
    renderChart('lineGraph', _.findWhere(this.props.state.graphData, {route: value.value}).data);
  }

  tableLinkForm(cell) {
    return (
      <Link to="/myServer">

          {_.findWhere(this.props.state.servers, {id: cell}).active}

      </Link>
      );
  }

  goToServer(cell) {
    this.props.dispatch(actions.ADD_SERVER_SELECTION(_.findWhere(this.props.state.servers, {id: cell})));
  }

  enumFormatter(cell, row, enumObject) {
    return enumObject(cell);
  }

  render() {
    var sortedServerTotals = _.sortBy(this.props.state.appServerTotals, (obj) => {
        return -obj.value;
      });
    var statusData = sortedServerTotals.map((total, idx) => {
      return {
        label: total.label,
        status: _.findWhere(this.props.state.servers, {id: total.id}).active,
        id: total.id
      }
    })
    var lineGraphOptions = this.props.state.graphData.map((graph) => {return {label: '/'+graph.route, value: graph.route}})

    return (
       <Grid>
        <Row><Col xs={12} md={12}>
          <PageHeader>
            {this.props.state.appSelection.appname} at a glance
          </PageHeader>
        </Col></Row>

        <Row className='serverStatContainer'>

          <Col xs={12} lg={12} >

What{'\''}s Happening

              <Button onClick={this.getAndGraphTodaysData.bind(this)} bsStyle='primary'>Refresh</Button>

            <Panel header={
Routes
} >
            <Grid fluid>
            <Row>
            <Col xs={12} lg={12}>

            {this.state.loading ?

 :

                <Select
                  value={this.state.lineGraphRoute}
                  multi={false}
                  options={lineGraphOptions}
                  onChange={this.updateGraph.bind(this)}
                  />

Hits Per Hour Today

for {this.props.state.lineGraphTitle == '/Total' ? 'all monitored routes' : {this.props.state.lineGraphTitle}}

Hours Ago

            }
            </Col>
            </Row>
            </Grid>
            </Panel>
          </Col>

        </Row>
        <Row>
          <Col xs={12} md={12}>
            <Panel header={
Server Information
}>
              <Grid fluid>
              <Row>
                <Col xs={12} md={6}>

Relative load (24 hr)

                {this.state.loading ?

 :

                }
                </Col>

                <Col xs={12} md={6}>

Status

                <BootstrapTable ref='table' data={statusData} striped={true} hover={true} >
                  <TableHeaderColumn isKey={true} dataField="label" dataAlign="center">Hostname</TableHeaderColumn>
                  <TableHeaderColumn dataAlign="center" dataField="id" dataFormat={this.enumFormatter} formatExtraData={this.tableLinkForm.bind(this)}>See Stats</TableHeaderColumn>
                </BootstrapTable>

              </Col>
              </Row>
              </Grid>
            </Panel>
          </Col>
        </Row>
        <MyAppHistory />
      </Grid>
    )
  }
}

MyApp = connect(state => ({ state: state }))(MyApp);
export default MyApp
<commit_msg>fix loading gif<commit_after>import React from 'react';
import actions from '../actions/ipsumActions.js';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { renderChart } from '../D3graphTemplate';
import { Panel, Grid, Row, Col, PageHeader, Button, Image} from 'react-bootstrap';
import request from '../util/restHelpers';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import barGraph from './BarGraph';
import _ from 'underscore';
import MyAppHistory from './MyAppHistory';
import Select from 'react-select';

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lineGraphRoute: null,
      resizefunc: null,
      loading1: false,
      loading2: false
    };
  }

  getAndGraphTodaysData(){
    this.setState({loading1: true}, () => {
      // call 24 hr bar graph data and render
      request.post('/getStats/serverTotalsForApp', {
        appid: this.props.state.appSelection.id,
        hours: 24
      }, (err, data) => {
        if (err) {console.log('ERROR', err); return; }
        var data = JSON.parse(data.text);
        var output = [];
        Object.keys(data).forEach((serverId) => {
          output.push({
            value: data[serverId].statValue,
            label: data[serverId].hostname,
            id: Number(serverId)
          });
        });

        // for relative server load bar graph
        this.props.dispatch(actions.CHANGE_APP_SERVER_TOTALS(output));
        this.setState({loading1: false}, () => {
          barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => {
            return -obj.value;
          }));
        });
      });

    });

    //For routes line Graph
    this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE('/Total'));
    var appId = this.props.state.appSelection.id;
    this.setState({loading2: true}, () => {

      request.post('/getStats/app',
        {appId: appId, hours: 24}, //TODO figure out how to keep track of desired hours, have user settings/config in store?
        (err, res) => {
          this.setState({loading2: false})
          if (err) { console.log("Error getting Server Data", err); }
          this.props.dispatch(actions.ADD_SERVER_DATA(res.body));
          this.setState({lineGraphRoute: this.props.state.graphData[0].route});
          renderChart('lineGraph', this.props.state.graphData[0].data);
      });

      this.setState({resizefunc: this.resizedb()}, () => {
        window.addEventListener('resize', this.state.resizefunc);
      })

    })
  }

  componentDidMount() {
    this.getAndGraphTodaysData();
  }

  resizedb() {
    var redraw = function() {
      // linegraph
      this.updateGraph({value: this.state.lineGraphRoute});
      // horizontal bar graph
      barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => {
        return -obj.value;
      }));
    }
    return _.debounce(redraw.bind(this), 500)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.state.resizefunc);
  }

  updateGraph(value) {
    !value ? null :
    this.setState({lineGraphRoute: value.value});
    this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE("/" + value.value));
    d3.select('#lineGraph > svg').remove();
    renderChart('lineGraph', _.findWhere(this.props.state.graphData, {route: value.value}).data);
  }

  tableLinkForm(cell) {
    return (
      <Link to="/myServer">

          {_.findWhere(this.props.state.servers, {id: cell}).active}

      </Link>
      );
  }

  goToServer(cell) {
    this.props.dispatch(actions.ADD_SERVER_SELECTION(_.findWhere(this.props.state.servers, {id: cell})));
  }

  enumFormatter(cell, row, enumObject) {
    return enumObject(cell);
  }

  render() {
    var sortedServerTotals = _.sortBy(this.props.state.appServerTotals, (obj) => {
        return -obj.value;
      });
    var statusData = sortedServerTotals.map((total, idx) => {
      return {
        label: total.label,
        status: _.findWhere(this.props.state.servers, {id: total.id}).active,
        id: total.id
      }
    })
    var lineGraphOptions = this.props.state.graphData.map((graph) => {return {label: '/'+graph.route, value: graph.route}})

    return (
       <Grid>
        <Row><Col xs={12} md={12}>
          <PageHeader>
            {this.props.state.appSelection.appname} at a glance
          </PageHeader>
        </Col></Row>

        <Row className='serverStatContainer'>

          <Col xs={12} lg={12} >

What{'\''}s Happening

              <Button onClick={this.getAndGraphTodaysData.bind(this)} bsStyle='primary'>Refresh</Button>

            <Panel header={
Routes
} >
            <Grid fluid>
            <Row>
            <Col xs={12} lg={12}>

            {this.state.loading2 ?

 :

                <Select
                  value={this.state.lineGraphRoute}
                  multi={false}
                  options={lineGraphOptions}
                  onChange={this.updateGraph.bind(this)}
                  />

Hits Per Hour Today

for {this.props.state.lineGraphTitle == '/Total' ? 'all monitored routes' : {this.props.state.lineGraphTitle}}

Hours Ago

            }
            </Col>
            </Row>
            </Grid>
            </Panel>
          </Col>

        </Row>
        <Row>
          <Col xs={12} md={12}>
            <Panel header={
Server Information
}>
              <Grid fluid>
              <Row>
                <Col xs={12} md={6}>

Relative load (24 hr)

                {this.state.loading1 ?

 :

                }
                </Col>

                <Col xs={12} md={6}>

Status

                <BootstrapTable ref='table' data={statusData} striped={true} hover={true} >
                  <TableHeaderColumn isKey={true} dataField="label" dataAlign="center">Hostname</TableHeaderColumn>
                  <TableHeaderColumn dataAlign="center" dataField="id" dataFormat={this.enumFormatter} formatExtraData={this.tableLinkForm.bind(this)}>See Stats</TableHeaderColumn>
                </BootstrapTable>

              </Col>
              </Row>
              </Grid>
            </Panel>
          </Col>
        </Row>
        <MyAppHistory />
      </Grid>
    )
  }
}

MyApp = connect(state => ({ state: state }))(MyApp);
export default MyApp
<|endoftext|>


<commit_before>$(function() {

	$.history.init(function(url) {
		if (url && (url.length > 1)) {
			$('html, body').animate({scrollTop:0}, 400, 'swing');

			$("#content_box").hide('slide', {direction: 'left'}, 'fast', function(e) {
				$.getScript(url + '.js', function(e) {
					// Animate height change?
					$("#index_hero").css("height", $("#content_box").height());

					$("#content_box").show('slide', {direction: 'right'}, 'fast');
				});
			});

		} else {
			$("#index_hero").css("height", 'inherit');
			$.getScript("/projects/heroes.js", function(e) {
				$("#index_hero").css("height", $("#content_box").height());
			});
		}
	},{ unescape: "/" });

	$('a.project_link').live('click', function(e) {
		var url = $(this).attr('href');
		url = url.replace(/^.*#/, '');
		$.history.load(url);

		e.preventDefault();
	});

	$('#header h1 a').click(function(e) {
		$.history.load('');
		e.preventDefault();
	});

});
<commit_msg>Heroes banner to only animate in after initial page load.<commit_after>$(function() {
	var loaded = false;

	$.history.init(function(url) {
		if (url == '' && loaded) url = '/projects/heroes';

		if (url && (url.length > 1)) {
			$('html, body').animate({scrollTop:0}, 400, 'swing');

			$("#content_box").hide('slide', {direction: 'left'}, 'fast', function(e) {
				$.getScript(url + '.js', function(e) {
					// Animate height change?
					$("#index_hero").css("height", $("#content_box").height());

					$("#content_box").show('slide', {direction: 'right'}, 'fast');
				});
			});

		} else {
			$("#index_hero").css("height", 'inherit');
			$.getScript("/projects/heroes.js", function(e) {
				$("#index_hero").css("height", $("#content_box").height());
			});
			loaded = true;
		}
	},{ unescape: "/" });

	$('a.project_link').live('click', function(e) {
		var url = $(this).attr('href');
		url = url.replace(/^.*#/, '');
		$.history.load(url);

		e.preventDefault();
	});

	$('#header h1 a').click(function(e) {
		$.history.load('');
		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>if (window.console) {
    console.log("Welcome to your Play application's JavaScript!");
}

$( document ).ready(function() {

    $(".table_link, .lens_link").on("click", function() {
        var table = $(this).html();
        var query = "SELECT * FROM "+table+";";

        $("#query_textarea").val(query);
        $("#query_btn").trigger("click");
    });

    $(".db_link").on("click", function() {
        var db = $(this).html();
        var curr = $("#curr_db").html().trim();

        if(db.valueOf() !== curr.valueOf()) {
            $("#db_field").val(db);
            $("#query_textarea").val("");
            $("#query_btn").trigger("click");
        }
    });

    $("#create_database").on("click", function() {
        var db = prompt("Please enter a name for the new database", "awesomedb");
        var existing_dbs = new Array();

        if(!db.match(/^\w+$/))
            alert("That is not a valid name, please try again");

        db += ".db";

        $(".db_link").each(function() {
            existing_dbs.push($(this).html());
        });

        if($.inArray(db, existing_dbs) != -1) {
            alert("A database with the name "+db+" already exists");
        }
        else {
            $("#create_db_field").val(db);
            $("#create_db_form").submit();
        }
    });

    $("#result_table").colResizable( {
        liveDrag: true,
        minWidth: 20
    });

    $("#about_btn").on("click", function() {
        $("#about").toggle(100);
    });

    $("#upload").on("click", function() {
        $("#drop_area").toggle(100);
    });

    $(".close_btn").on("click", function() {
        $(this).parent().hide(100);
    });

    $(".non_deterministic_cell").one("click", function(e) {
        $(this).tooltipster({
            animation: 'grow',
            delay: 10,
            contentAsHTML: 'true',
            functionInit: function(origin, content) {

                    var col_index = origin.prevAll().length;
            		var col = origin.parents('table').find('th').eq(col_index).text();
                    var row = origin.parent().children(".rowid_col").html();
                    var query = $("#query_textarea").val().replace(";","");
                    var db = $("#db_field").val();

                    var bounds = [];
                    var variance;
                    var conf_int = [];
                    var causes = [];

                    var fault = false;

                    var data_params_query = 'queryjson?query=SELECT BOUNDS('+col
                                            +'), VAR('+col+'), CONFIDENCE('+col+') FROM ('+query
                                            +') AS TEMP WHERE ROWID = '+row+';&db='+db;

                    var vgterms_query = 'queryjson?query=EXPLAIN '+query+';&db='+db;

                    if (content == null) {

                        $.when(
                            $.get(data_params_query, function (res) {
                                if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                    fault = true;
                                }
                                else {
                                    bounds[0] = res.data[0][1];
                                    bounds[1] = res.data[0][2];
                                    variance = res.data[0][3];
                                    var confStr = res.data[0][4];
                                    var confVal = confStr.split(" - ");
                                    conf_int[0] = confVal[0].substring(1);
                                    conf_int[1] = confVal[1].substring(0, confVal[1].length-1);
                                }
                            }),
                            $.get(vgterms_query, function (res) {
                                if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                    fault = true;
                                }
                                else {
                                    causes = extractCauses(res.result, col_index);
                                }
                            })
                        ).then( function() {
                            if(fault) {
                                origin.tooltipster('content', 'Something went wrong!');
                            }
                            else {
                                var tooltip_template = '
'+
                                                      '
'+
                                                          '
'+
                                                              'Bounds	'+
                                                              ''+ parseFloat(bounds[0]).toFixed(2) +' - '+ parseFloat(bounds[1]).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'Variance	'+
                                                              ''+ parseFloat(variance).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'Confidence Interval	'+
                                                              ''+ parseFloat(conf_int[0]).toFixed(2) + ' - '+ parseFloat(conf_int[1]).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'VG Terms	'+
                                                              '
'+ listify(causes) +'
	'+
                                                          '
'+
                                                      '
'+
                                                  '
';
                                origin.tooltipster('content', tooltip_template);
                            }
                        });

                        // this returned string will overwrite the content of the tooltip for the time being
                        return 'Loading...';
                    }
                    else {
                        // return nothing : the initialization continues normally with its content unchanged.
                    }
                },
            theme: 'tooltipster-shadow',
            position: 'bottom',
            minWidth: 350,
            maxWidth: 350,
            trigger: 'click',
        });

        $(this).click();
    });

    $(".non_deterministic_row").one("click", function(e) {
        $(this).tooltipster({
            animation: 'grow',
            delay: 10,
            functionInit: function(origin, content) {

                var row = origin.children(".rowid_col").html();
                var query = $("#query_textarea").val().replace(";","");
                var db = $("#db_field").val();

                var prob;
                var causes = [];

                var fault = false;

                var prob_query = 'queryjson?query=SELECT PROB() FROM ('+query+') AS TEMP WHERE ROWID = '+row+';&db='+db;
                var vgterms_query = 'queryjson?query=EXPLAIN '+query+';&db='+db;

                if (content == null) {
                    $.when(
                        $.get(prob_query, function (res) {
                            if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                fault = true;
                            }
                            else {
                                prob = res.data[0][1];
                            }
                        }),
                        $.get(vgterms_query, function (res) {
                            if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                fault = true;
                            }
                            else {
                                causes = extractCauses(res.result, -1);
                                // -1 will indicate __MIMIR_CONDITION
                            }
                        })
                    ).then( function() {
                        if(fault) {
                            origin.tooltipster('content', 'Something went wrong!');
                        }
                        else {
                            var tooltip_template = '
'+
                                                  '
'+
                                                      '
'+
                                                          'Confidence	'+
                                                          ''+prob+'	'+
                                                      '
'+
                                                      '
'+
                                                          'VG Terms	'+
                                                          '
'+ listify(causes) +'
	'+
                                                      '
'+
                                                  '
'+
                                              '
';
                            origin.tooltipster('content', tooltip_template);
                        }
                    });

                    // this returned string will overwrite the content of the tooltip for the time being
                    return 'Loading...';
                }
                else {
                    // return nothing : the initialization continues normally with its content unchanged.
                }
            },
            contentAsHTML: 'true',
            theme: 'tooltipster-shadow',
            position: 'top-right',
            minWidth: 200,
            maxWidth: 350,
            trigger: 'click',
        });

        $(this).click();
    });

    Dropzone.options.myAwesomeDropzone = {
      maxFilesize: 100000, // MB
      acceptedFiles: ".csv",
      addRemoveLinks: true,
      init: function() {
        this.on('success', function () {
            var acceptedFiles = [];
            this.getAcceptedFiles().forEach(function (element, index, array) {
                acceptedFiles.push(element.name.replace(/\.csv/i, ""));
            });
            var listedFiles = [];
            $(".table_link").each( function() {
                listedFiles.push( $(this).html() );
            });
            acceptedFiles.forEach(function (element, index, array) {
                var i;
                var found = false;
                for(i= 0; i<listedFiles.length; i++) {
                    if(element.toUpperCase() === listedFiles[i].toUpperCase()) {
                        found = true;
                        break;
                    }
                }

                if(!found) {
                    $("#tables_header").after('
'+element+'
');
                }
            });
        });
        this.on("error", function() {
            var span = $("span[data-dz-errormessage]");
            span.html("There is no table with this name in the current database!");
        });
      }
    };

});

function listify(causes) {
    var i;
    var result = '';
    for(i = 0; i<causes.length; i++) {
        result += '
'+ causes[i] +'
'
    }

    return result;
}

function extractCauses(queryExplanation, col_index) {

    var optimizedQuery = queryExplanation.split(/--- Optimized Query ---/i)[1];

    var pos = 0;
    var project = /PROJECT/i.exec(optimizedQuery);
    if(project) {
        pos = project.index + "PROJECT".length;
    }

    var projectArgs = getArguments(optimizedQuery, pos, "[", "]");

    if(col_index == -1) {
        return findVGTerms(projectArgs[projectArgs.length-1][1]);
    } else {
        return findVGTerms(projectArgs[col_index-1][1]);
    }
}

function getArguments(str, pos, opening, closing) {

    var braces = 0;
    var i = pos;

    do {
        if(str.charAt(i) === opening) braces++;
        else if(str.charAt(i) === closing) braces--;
        i++;
    } while(braces > 0 && i < str.length);

    if(braces != 0) {
        throw new Error('Mis-formed arguments');
    }

    var argsString = str.substring(pos+1, i-1);
    var args = argsString.split(",");
    var argsMap = new Array(args.length);

    args.forEach(function (currentValue, index, array) {
        var arg = currentValue.split("<=");
        argsMap[index] = [arg[0].trim(), arg[1].trim()];
    });

    return argsMap;
}

function findVGTerms(str) {
    var re = /{{([^}]*)}}/img;
    var causes = [];
    var match;

    while(match = re.exec(str)) {
        causes.push(match[1]);
    }

    return causes;
}<commit_msg>Stable commit with working CSV import and data metric explains<commit_after>if (window.console) {
    console.log("Welcome to your Play application's JavaScript!");
}

$( document ).ready(function() {

    $(".table_link, .lens_link").on("click", function() {
        var table = $(this).html();
        var query = "SELECT * FROM "+table+";";

        $("#query_textarea").val(query);
        $("#query_btn").trigger("click");
    });

    $(".db_link").on("click", function() {
        var db = $(this).html();
        var curr = $("#curr_db").html().trim();

        if(db.valueOf() !== curr.valueOf()) {
            $("#db_field").val(db);
            $("#query_textarea").val("");
            $("#query_btn").trigger("click");
        }
    });

    $("#create_database").on("click", function() {
        var db = prompt("Please enter a name for the new database", "awesomedb");
        var existing_dbs = new Array();

        if(!db.match(/^\w+$/))
            alert("That is not a valid name, please try again");

        db += ".db";

        $(".db_link").each(function() {
            existing_dbs.push($(this).html());
        });

        if($.inArray(db, existing_dbs) != -1) {
            alert("A database with the name "+db+" already exists");
        }
        else {
            $("#create_db_field").val(db);
            $("#create_db_form").submit();
        }
    });

    $("#result_table").colResizable( {
        liveDrag: true,
        minWidth: 20
    });

    $("#about_btn").on("click", function() {
        $("#about").toggle(100);
    });

    $("#upload").on("click", function() {
        $("#drop_area").toggle(100);
    });

    $(".close_btn").on("click", function() {
        $(this).parent().hide(100);
    });

    $(".non_deterministic_cell").one("click", function(e) {
        $(this).tooltipster({
            animation: 'grow',
            delay: 10,
            contentAsHTML: 'true',
            functionInit: function(origin, content) {

                    var col_index = origin.prevAll().length;
            		var col = origin.parents('table').find('th').eq(col_index).text();
                    var row = origin.parent().children(".rowid_col").html();
                    var query = $("#query_textarea").val().replace(";","");
                    var db = $("#db_field").val();

                    var bounds = [];
                    var variance;
                    var conf_int = [];
                    var causes = [];

                    var fault = false;

                    var data_params_query = 'queryjson?query=SELECT BOUNDS('+col
                                            +'), VAR('+col+'), CONFIDENCE('+col+') FROM ('+query
                                            +') AS TEMP WHERE ROWID = '+row+';&db='+db;

                    var vgterms_query = 'queryjson?query=EXPLAIN '+query+';&db='+db;

                    if (content == null) {

                        $.when(
                            $.get(data_params_query, function (res) {
                                if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                    fault = true;
                                }
                                else {
                                    bounds[0] = res.data[0][1];
                                    bounds[1] = res.data[0][2];
                                    variance = res.data[0][3];
                                    var confStr = res.data[0][4];
                                    var confVal = confStr.split(" - ");
                                    conf_int[0] = confVal[0].substring(1);
                                    conf_int[1] = confVal[1].substring(0, confVal[1].length-1);
                                }
                            }),
                            $.get(vgterms_query, function (res) {
                                if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                    fault = true;
                                }
                                else {
                                    causes = extractCauses(res.result, col_index);
                                }
                            })
                        ).then( function() {
                            if(fault) {
                                origin.tooltipster('content', 'Something went wrong!');
                            }
                            else {
                                var tooltip_template = '
'+
                                                      '
'+
                                                          '
'+
                                                              'Bounds	'+
                                                              ''+ parseFloat(bounds[0]).toFixed(2) +' - '+ parseFloat(bounds[1]).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'Variance	'+
                                                              ''+ parseFloat(variance).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'Confidence Interval	'+
                                                              ''+ parseFloat(conf_int[0]).toFixed(2) + ' - '+ parseFloat(conf_int[1]).toFixed(2) +'	'+
                                                          '
'+
                                                          '
'+
                                                              'VG Terms	'+
                                                              '
'+ listify(causes) +'
	'+
                                                          '
'+
                                                      '
'+
                                                  '
';
                                origin.tooltipster('content', tooltip_template);
                            }
                        });

                        // this returned string will overwrite the content of the tooltip for the time being
                        return 'Loading...';
                    }
                    else {
                        // return nothing : the initialization continues normally with its content unchanged.
                    }
                },
            theme: 'tooltipster-shadow',
            position: 'bottom',
            minWidth: 350,
            maxWidth: 350,
            trigger: 'click',
        });

        $(this).click();
    });

    $(".non_deterministic_row").one("click", function(e) {
        $(this).tooltipster({
            animation: 'grow',
            delay: 10,
            functionInit: function(origin, content) {

                var row = origin.children(".rowid_col").html();
                var query = $("#query_textarea").val().replace(";","");
                var db = $("#db_field").val();

                var prob;
                var causes = [];

                var fault = false;

                var prob_query = 'queryjson?query=SELECT PROB() FROM ('+query+') AS TEMP WHERE ROWID = '+row+';&db='+db;
                var vgterms_query = 'queryjson?query=EXPLAIN '+query+';&db='+db;

                if (content == null) {
                    $.when(
                        $.get(prob_query, function (res) {
                            if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                fault = true;
                            }
                            else {
                                prob = res.data[0][1];
                            }
                        }),
                        $.get(vgterms_query, function (res) {
                            if(res.hasOwnProperty('result') && res.result.startsWith("Command Ignored")) {
                                fault = true;
                            }
                            else {
                                causes = extractCauses(res.result, -1);
                                // -1 will indicate __MIMIR_CONDITION
                            }
                        })
                    ).then( function() {
                        if(fault) {
                            origin.tooltipster('content', 'Something went wrong!');
                        }
                        else {
                            var tooltip_template = '
'+
                                                  '
'+
                                                      '
'+
                                                          'Confidence	'+
                                                          ''+prob+'	'+
                                                      '
'+
                                                      '
'+
                                                          'VG Terms	'+
                                                          '
'+ listify(causes) +'
	'+
                                                      '
'+
                                                  '
'+
                                              '
';
                            origin.tooltipster('content', tooltip_template);
                        }
                    });

                    // this returned string will overwrite the content of the tooltip for the time being
                    return 'Loading...';
                }
                else {
                    // return nothing : the initialization continues normally with its content unchanged.
                }
            },
            contentAsHTML: 'true',
            theme: 'tooltipster-shadow',
            position: 'top-right',
            minWidth: 200,
            maxWidth: 350,
            trigger: 'click',
        });

        $(this).click();
    });

    Dropzone.options.myAwesomeDropzone = {
      maxFilesize: 100000, // MB
      acceptedFiles: ".csv",
      addRemoveLinks: true,
      init: function() {
        this.on('success', function () {
            var acceptedFiles = [];
            this.getAcceptedFiles().forEach(function (element, index, array) {
                acceptedFiles.push(element.name.replace(/\.csv/i, ""));
            });
            var listedFiles = [];
            $(".table_link").each( function() {
                listedFiles.push( $(this).html() );
            });
            acceptedFiles.forEach(function (element, index, array) {
                var i;
                var found = false;
                for(i= 0; i<listedFiles.length; i++) {
                    if(element.toUpperCase() === listedFiles[i].toUpperCase()) {
                        found = true;
                        break;
                    }
                }

                if(!found) {
                    $("#tables_header").after('
'+element+'
');
                }
            });
        });
        this.on("error", function() {
            var span = $("span[data-dz-errormessage]");
            span.html("There is no table with this name in the current database!");
        });
      }
    };

});

function listify(causes) {
    var i;
    var result = '';
    for(i = 0; i<causes.length; i++) {
        result += '
'+ causes[i] +'
'
    }

    return result;
}

function extractCauses(queryExplanation, col_index) {

    var optimizedQuery = queryExplanation.split(/--- Optimized Query ---/i)[1];

    var pos = 0;
    var project = /PROJECT/i.exec(optimizedQuery);
    if(project) {
        pos = project.index + "PROJECT".length;
    }

    var projectArgs = getArguments(optimizedQuery, pos, "[", "]");

    if(col_index == -1) {
        return findVGTerms(projectArgs[projectArgs.length-1][1]);
    } else {
        return findVGTerms(projectArgs[col_index-1][1]);
    }
}

function getArguments(str, pos, opening, closing) {

    var braces = 0;
    var i = pos;

    do {
        if(str.charAt(i) === opening) braces++;
        else if(str.charAt(i) === closing) braces--;
        i++;
    } while(braces > 0 && i < str.length);

    if(braces != 0) {
        throw new Error('Mis-formed arguments');
    }

    var argsString = str.substring(pos+1, i-1);
    var args = argsString.split(",");
    var argsMap = new Array(args.length);

    args.forEach(function (currentValue, index, array) {
        var arg = currentValue.split("<=");
        argsMap[index] = [arg[0].trim(), arg[1].trim()];
    });

    return argsMap;
}

function findVGTerms(str) {
    var re = /{{([^}]*)}}/img;
    var causes = [];
    var match;

    while(match = re.exec(str)) {
        causes.push(match[1]);
    }

    return causes;
}<|endoftext|>


<commit_before>"use strict";
var template = _.template(
    $( ".songs-template" ).html()
);
var isLoggedin = true;
var userOnArticleReq = function(feature, featureValue, articleid, url, fillSongTemplate) {
    var dataValue;
    dataValue = {
        song_id : articleid,
    };
    dataValue[feature] = featureValue;
    var request = $.ajax({
        url: "/"+url+"/",
        method: "POST",
        data: dataValue
    });
    request.done(function( msg ) {
      console.log(feature+"success");
      fillSongTemplate();
      var gr = new Grudio();
    });

    request.fail(function( jqXHR, textStatus ) {
      console.log( "Request failed: " + textStatus );
      fillSongTemplate();
      var gr = new Grudio();
    });
};

var Grudio = function() {
    this.songsList = $('.song-list');
    this.songs = $(this.songsList).children('.song-item');
    console.log(this.songs);
    this.songInteractionInit();
};
Grudio.prototype.songInteractionInit = function() {
    var self;
    self = this;
    console.log(this.songs);
    this.songs.each(function() {
        self.selectUpvoteButton.call(this, self.upvoted, self.fillSongTemplate.bind(self));
        self.selectDownvoteButton.call(this, self.downvoted);
    });
};
Grudio.prototype.selectUpvoteButton = function(upvoted, fillSongTemplate) {
    var self, upvoteButton, songid, isUpvoted;

    self = this;
    upvoteButton = $(this).find('.upvote');
    songid = $(upvoteButton).data('songid');

    isUpvoted = parseInt($(upvoteButton).data('isupvoted'));
    this.boolUpvote = false;
    if(isUpvoted) {
        $(upvoteButton).addClass('active');
        this.boolUpvote = true;
    }
    $(upvoteButton).on('click', function() {
        upvoted.call(self, upvoteButton, songid, fillSongTemplate);
    });
};
Grudio.prototype.upvoted = function(upvoteButton, songid, fillSongTemplate) {
    if(!isLoggedin) {
        console.log("show login");
    } else {
        if(!this.boolUpvote) {
            $(upvoteButton).addClass('active');
            this.boolUpvote = true;
            userOnArticleReq('upvote', 1, songid, 'togglefeature', fillSongTemplate);
        } else {
            $(upvoteButton).removeClass('active');
            userOnArticleReq('upvote', 0, songid, 'togglefeature', fillSongTemplate);
            this.boolUpvote = false;
        }
    }
};
Grudio.prototype.selectDownvoteButton = function(downvoted) {
    var downvoteButton, songid, isDownvoted, self;

    self = this;

    downvoteButton = $(this).find('.downvote');
    songid = $(downvoteButton).data('songid');

    isDownvoted = parseInt($(downvoteButton).data('downvoted'));
    this.boolDownvote = false;
    if(isDownvoted) {
        $(downvoteButton).addClass('active');
        this.boolDownvote = true;
    }

    $(downvoteButton).on('click', function() {
        downvoted.call(self, downvoteButton, songid);
    });
};
Grudio.prototype.downvoted = function(downvoteButton, songid) {
    if(!isLoggedin) {
        console.log("show login");
    } else {
        if(!this.boolDownvote) {
            $(downvoteButton).addClass('active');
            this.boolDownvote = true;
            userOnArticleReq('downvote', 1, songid, 'togglefeature');
        } else {
            $(downvoteButton).removeClass('active');
            userOnArticleReq('downvote', 0, songid, 'togglefeature');
            this.boolDownvote = false;
        }
    }
};
Grudio.prototype.fillSongTemplate = function() {
    var self = this;
    $(this.songsList).html(template);
    console.log('html in progress');
};

var gr = new Grudio();<commit_msg>template downvote update features<commit_after>"use strict";
var template = _.template(
    $( ".songs-template" ).html()
);
var isLoggedin = true;
var userOnArticleReq = function(feature, featureValue, articleid, url, fillSongTemplate) {
    var dataValue;
    dataValue = {
        song_id : articleid,
    };
    dataValue[feature] = featureValue;
    var request = $.ajax({
        url: "/"+url+"/",
        method: "POST",
        data: dataValue
    });
    request.done(function( msg ) {
      console.log(feature+"success");
      fillSongTemplate();
      var gr = new Grudio();
    });

    request.fail(function( jqXHR, textStatus ) {
      console.log( "Request failed: " + textStatus );
      fillSongTemplate();
      var gr = new Grudio();
    });
};

var Grudio = function() {
    this.songsList = $('.song-list');
    this.songs = $(this.songsList).children('.song-item');
    console.log(this.songs);
    this.songInteractionInit();
};
Grudio.prototype.songInteractionInit = function() {
    var self;
    self = this;
    console.log(this.songs);
    this.songs.each(function() {
        self.selectUpvoteButton.call(this, self.upvoted, self.fillSongTemplate.bind(self));
        self.selectDownvoteButton.call(this, self.downvoted, self.fillSongTemplate.bind(self));
    });
};
Grudio.prototype.selectUpvoteButton = function(upvoted, fillSongTemplate) {
    var self, upvoteButton, songid, isUpvoted;

    self = this;
    upvoteButton = $(this).find('.upvote');
    songid = $(upvoteButton).data('songid');

    isUpvoted = parseInt($(upvoteButton).data('isupvoted'));
    this.boolUpvote = false;
    if(isUpvoted) {
        $(upvoteButton).addClass('active');
        this.boolUpvote = true;
    }
    $(upvoteButton).on('click', function() {
        upvoted.call(self, upvoteButton, songid, fillSongTemplate);
    });
};
Grudio.prototype.upvoted = function(upvoteButton, songid, fillSongTemplate) {
    if(!isLoggedin) {
        console.log("show login");
    } else {
        if(!this.boolUpvote) {
            $(upvoteButton).addClass('active');
            this.boolUpvote = true;
            userOnArticleReq('upvote', 1, songid, 'togglefeature', fillSongTemplate);
        } else {
            $(upvoteButton).removeClass('active');
            userOnArticleReq('upvote', 0, songid, 'togglefeature', fillSongTemplate);
            this.boolUpvote = false;
        }
    }
};
Grudio.prototype.selectDownvoteButton = function(downvoted, fillSongTemplate) {
    var downvoteButton, songid, isDownvoted, self;

    self = this;

    downvoteButton = $(this).find('.downvote');
    songid = $(downvoteButton).data('songid');

    isDownvoted = parseInt($(downvoteButton).data('downvoted'));
    this.boolDownvote = false;
    if(isDownvoted) {
        $(downvoteButton).addClass('active');
        this.boolDownvote = true;
    }

    $(downvoteButton).on('click', function() {
        downvoted.call(self, downvoteButton, songid, fillSongTemplate);
    });
};
Grudio.prototype.downvoted = function(downvoteButton, songid, fillSongTemplate) {
    if(!isLoggedin) {
        console.log("show login");
    } else {
        if(!this.boolDownvote) {
            $(downvoteButton).addClass('active');
            this.boolDownvote = true;
            userOnArticleReq('downvote', 1, songid, 'togglefeature', fillSongTemplate);
        } else {
            $(downvoteButton).removeClass('active');
            userOnArticleReq('downvote', 0, songid, 'togglefeature', fillSongTemplate);
            this.boolDownvote = false;
        }
    }
};
Grudio.prototype.fillSongTemplate = function() {
    var self = this;
    $(this.songsList).html(template);
    console.log('html in progress');
};

var gr = new Grudio();<|endoftext|>


<commit_before>$.fn.extend({
  animateCSS: function (name) {
    return this.addClass('animated ' + name).one('animationend', function () {
      $(this).removeClass('animated ' + name);
    });
  }
});

var Main = {
  results: [],
  step: 0,

  init: function init () {
    this
      .shuffle()
      .setDom()
      .listen()
      .showHome();

    return this;
  },

  reset: function reset () {
    this.results = [];
    this.showHome();

    return this;
  },

  shuffle: function shuffleAnswers () {
    $('.page__question').shuffle().each(function () {
      $(this).find('.answer').shuffle();
    });

    return this;
  },

  setDom: function setDom () {
    _.extend(this, {
      $pages: $('.page'),
      $questions: $('.page__question'),
      $answers: $('.answer'),

      $preComputing: $('#js-pre-computing'),
      $postComputing: $('#js-post-computing')
    });

    return this;
  },

  listen: function listen () {
    var self = this;

    this.$answers
      .off('click.answer')
      .on('click.answer', this.selectAnswer.bind(this));

    $('#js-start')
      .off('click.start')
      .on('click.start', function (event) {
        event.preventDefault();
        self.showAuth();
      });

    $('#js-skip')
      .off('click.skip')
      .on('click.skip', function (event) {
        event.preventDefault();
        self.initQuiz();
      });

    PubSub.subscribe('user:register', function (label, user) {
      self.initQuiz();
    });

    return this;
  },

  initQuiz: function initQuiz () {
    var total = 3,
        duration = 1800;

    this.showPage(this.$preComputing.index());

    setTimeout(function () {
      this.showQuestion(0);
    }.bind(this), duration);

    return this;
  },

  getState: function getState () {
    return {
      step: this.step,
      results: this.results
    };
  },

  selectAnswer: function selectAnswer (event) {
    var self = this,
        $answer = $(event.target).closest('.answer');

    this.setAnswer($answer.data('value'));

    $answer
      .addClass('answer--isSelected')
      .addClass('animated tada')
      .one('animationend', function () {
        self.nextQuestion();
      })
      .siblings()
      .removeClass('answer--isSelected')
      .addClass('animated bounceOut');

    return this;
  },

  setAnswer: function setAnswer (value) {
    this.results[this.step] = parseInt(value, 10);
    return this;
  },

  showPage: function showPage (index) {
    this.step = index;
    this.$pages.hide().eq(index).show();
    return this;
  },

  nextPage: function nextPage () {
    this.showPage(this.step + 1);
    return this;
  },

  showHome: function showHome () {
    this.showPage(0);
    return this;
  },

  showAuth: function showAuth () {
    this.showPage(1);
    return this;
  },

  showQuestion: function showQuestion (index) {
    var $question = this.$pages.filter('.page__question').eq(index),
        $answers = $question.find('.answer');

    this.showPage($question.index());

    $answers
      .css('animation-delay', function () {
        return $(this).index() * .25 + 's';
      })
      .animateCSS('flipInY')
      .last()
      .one('animationend', function () {
        $answers.css('animation-delay', '0s');
      });

    return this;
  },

  nextQuestion: function nextQuestion () {
    var step = this.step,
        $questions = this.$pages.filter('.page__question');

    if (step < $questions.length)
      this.showQuestion(step - $questions.first().index() + 1);
    else
      this.nextPage();

    return this;
  },

  showResult: function showResult () {
    this.showPage(this.$pages.length);
    return this;
  }
};

Main.init();
<commit_msg>No reset yet<commit_after>$.fn.extend({
  animateCSS: function (name) {
    return this.addClass('animated ' + name).one('animationend', function () {
      $(this).removeClass('animated ' + name);
    });
  }
});

var Main = {
  results: [],
  step: 0,

  init: function init () {
    this
      .shuffle()
      .setDom()
      .listen()
      .showHome();

    return this;
  },

  shuffle: function shuffleAnswers () {
    $('.page__question').shuffle().each(function () {
      $(this).find('.answer').shuffle();
    });

    return this;
  },

  setDom: function setDom () {
    _.extend(this, {
      $pages: $('.page'),
      $questions: $('.page__question'),
      $answers: $('.answer'),

      $preComputing: $('#js-pre-computing'),
      $postComputing: $('#js-post-computing')
    });

    return this;
  },

  listen: function listen () {
    var self = this;

    this.$answers
      .off('click.answer')
      .on('click.answer', this.selectAnswer.bind(this));

    $('#js-start')
      .off('click.start')
      .on('click.start', function (event) {
        event.preventDefault();
        self.showAuth();
      });

    $('#js-skip')
      .off('click.skip')
      .on('click.skip', function (event) {
        event.preventDefault();
        self.initQuiz();
      });

    PubSub.subscribe('user:register', function (label, user) {
      self.initQuiz();
    });

    return this;
  },

  initQuiz: function initQuiz () {
    var total = 3,
        duration = 1800;

    this.showPage(this.$preComputing.index());

    setTimeout(function () {
      this.showQuestion(0);
    }.bind(this), duration);

    return this;
  },

  getState: function getState () {
    return {
      step: this.step,
      results: this.results
    };
  },

  selectAnswer: function selectAnswer (event) {
    var self = this,
        $answer = $(event.target).closest('.answer');

    this.setAnswer($answer.data('value'));

    $answer
      .addClass('answer--isSelected')
      .addClass('animated tada')
      .one('animationend', function () {
        self.nextQuestion();
      })
      .siblings()
      .removeClass('answer--isSelected')
      .addClass('animated bounceOut');

    return this;
  },

  setAnswer: function setAnswer (value) {
    this.results[this.step] = parseInt(value, 10);
    return this;
  },

  showPage: function showPage (index) {
    this.step = index;
    this.$pages.hide().eq(index).show();
    return this;
  },

  nextPage: function nextPage () {
    this.showPage(this.step + 1);
    return this;
  },

  showHome: function showHome () {
    this.showPage(0);
    return this;
  },

  showAuth: function showAuth () {
    this.showPage(1);
    return this;
  },

  showQuestion: function showQuestion (index) {
    var $question = this.$pages.filter('.page__question').eq(index),
        $answers = $question.find('.answer');

    this.showPage($question.index());

    $answers
      .css('animation-delay', function () {
        return $(this).index() * .25 + 's';
      })
      .animateCSS('flipInY')
      .last()
      .one('animationend', function () {
        $answers.css('animation-delay', '0s');
      });

    return this;
  },

  nextQuestion: function nextQuestion () {
    var step = this.step,
        $questions = this.$pages.filter('.page__question');

    if (step < $questions.length)
      this.showQuestion(step - $questions.first().index() + 1);
    else
      this.nextPage();

    return this;
  },

  showResult: function showResult () {
    this.showPage(this.$pages.length);
    return this;
  }
};

Main.init();
<|endoftext|>


<commit_before>function initialize(coords) {
  var myLatlng = new google.maps.LatLng(coords[0][0],coords[0][1]);
  console.log(myLatlng);
  var mapOptions = {
    zoom: 13,
    center: myLatlng
  }

  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  displayRoute1walk(coords[0],coords[1]);
  displayRoutebike(coords[1],coords[2]);
  displayRoute2walk(coords[2],coords[3]);

}

  function displayRoute1walk(start,start_station) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(start[0],start[1]);

    var myLatlng2 = new google.maps.LatLng(start_station[0],start_station[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
      }
    });
  }

  function displayRoutebike(start_station, next_station) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(start_station[0],start_station[1]);

    var myLatlng2 = new google.maps.LatLng(next_station[0],next_station[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.BICYCLING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
      }
    });
  }

  function displayRoute2walk(next_station, destination) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(next_station[0],next_station[1]);

    var myLatlng2 = new google.maps.LatLng(destination[0],destination[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.WALKING
    };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
      }
    });
  }

  function renderMap(coords) {
    google.maps.event.addDomListener(window, 'load', initialize(coords));
  }
<commit_msg>change markers<commit_after>function initialize(coords) {
  var myLatlng = new google.maps.LatLng(coords[0][0],coords[0][1]);
  console.log(myLatlng);
  var mapOptions = {
    zoom: 13,
    center: myLatlng
  }

  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  displayRoute1walk(coords[0],coords[1]);
  displayRoutebike(coords[1],coords[2]);
  displayRoute2walk(coords[2],coords[3]);

}

  function displayRoute1walk(start,start_station) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(start[0],start[1]);

    var myLatlng2 = new google.maps.LatLng(start_station[0],start_station[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
      }
    });
  }

  function displayRoutebike(start_station, next_station) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(start_station[0],start_station[1]);

    var myLatlng2 = new google.maps.LatLng(next_station[0],next_station[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.BICYCLING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
        directionsDisplay.setOptions( {suppressMarkers: true})
      }
    });
  }

  function displayRoute2walk(next_station, destination) {
    var directionsService = new google.maps.DirectionsService();
    var myLatlng = new google.maps.LatLng(next_station[0],next_station[1]);

    var myLatlng2 = new google.maps.LatLng(destination[0],destination[1]);

    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(map);

    var request = {
      origin : myLatlng,
      destination : myLatlng2,
      travelMode : google.maps.TravelMode.WALKING
    };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions({ preserveViewport: true });
        directionsDisplay.setDirections(response);
      }
    });
  }

  function renderMap(coords) {
    google.maps.event.addDomListener(window, 'load', initialize(coords));
  }
<|endoftext|>