<commit_before>/*
    This file is part of rhizi, a collaborative knowledge graph editor.
    Copyright (C) 2014-2015  Rhizi

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict"

/**
 * model utility functions: - convert from/to client/backend data
 * representations
 */
define([ 'jquery', 'model/diff' ], function($, model_diff) {

    function __sanitize_label__write(label_str){
        var ret = label_str[0].toUpperCase() +
                  label_str.substring(1).toLowerCase();
        return ret;
    }

    function __sanitize_label__read(label_str){
        return label_str.toLowerCase();
    }

    /**
     * read by adapting from backend format
     */
    function adapt_format_read_node(n_raw) {
        var ret;

        ret = $.extend({
            // type:
            // - discard all but first label
            // - adjust to lowercase
            'type' : __sanitize_label__read(n_raw['__label_set'][0]),
            'state' : 'perm',
        }, n_raw);

        delete ret.__label_set;

        return ret;
    }

    /**
     * write by adapting to backend format
     */
    function adapt_format_write_node(n_raw) {
        var ret = $.extend({
        }, n_raw);

        ret['__label_set'] = [__sanitize_label__write(n_raw.type)];

        delete ret.state;
        delete ret.status
        delete ret.type;

        return ret
    }

    /**
     * read by adapting from backend format
     */
    function adapt_format_read_link_ptr(l_raw) {
        var ret;

        ret = $.extend({
            'state' : 'perm',
        }, l_raw);

        ret['name'] = __sanitize_label__read(ret['__type'][0]);
        delete ret.__type;

        return ret;
    }

    /**
     * write by adapting to backend format
     */
    function adapt_format_write_link(l_raw) {
        var ret = $.extend({
            '__src_id' : l_raw.source.id,
            '__dst_id' : l_raw.target.id,
        }, l_raw);

        ret['__type'] = [__sanitize_label__write(l_raw.__type)];

        delete ret.__dst;
        delete ret.__src;
        delete ret.source; // introduced by d3 accessor methods
        delete ret.state;
        delete ret.status;
        delete ret.target;
        delete ret.name;

        return ret;
    }

    /**
     * write adapt diff from node set, link set. sets may be passed by reference
     * as they are cloned
     */
    function adapt_format_write_diff__topo(n_set, l_set) {

        var new_n_set = $.extend([], n_set);
        var new_l_set = $.extend([], l_set);

        new_n_set = $.map(new_n_set, function(n, _) {
            return adapt_format_write_node(n);
        })

        new_l_set = $.map(new_l_set, function(l, _) {
            return adapt_format_write_link(l);
        })

        var topo_diff = new model_diff.new_topo_diff({
            node_set_add : new_n_set,
            link_set_add : new_l_set
        });
        return topo_diff;
    }

    /**
     * read adapt attr_diff from backend format
     */
    function adapt_format_read_diff__attr(diff_spec) {
        var attr_diff = new model_diff.new_attr_diff();
        attr_diff.id_to_node_map = diff_spec['__type_node'];
        attr_diff.id_to_link_map = diff_spec['__type_link'];
        return attr_diff;
    }

    return {
        adapt_format_read_node : adapt_format_read_node,
        adapt_format_read_link_ptr : adapt_format_read_link_ptr,
        adapt_format_write_node : adapt_format_write_node,
        adapt_format_write_link : adapt_format_write_link,

        adapt_format_write_diff__topo : adapt_format_write_diff__topo,
        adapt_format_read_diff__attr : adapt_format_read_diff__attr,
    }
});
<commit_msg>client/model/util: add missing semicolons<commit_after>/*
    This file is part of rhizi, a collaborative knowledge graph editor.
    Copyright (C) 2014-2015  Rhizi

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

/**
 * model utility functions: - convert from/to client/backend data
 * representations
 */
define([ 'jquery', 'model/diff' ], function($, model_diff) {

    function __sanitize_label__write(label_str){
        var ret = label_str[0].toUpperCase() +
                  label_str.substring(1).toLowerCase();
        return ret;
    }

    function __sanitize_label__read(label_str){
        return label_str.toLowerCase();
    }

    /**
     * read by adapting from backend format
     */
    function adapt_format_read_node(n_raw) {
        var ret;

        ret = $.extend({
            // type:
            // - discard all but first label
            // - adjust to lowercase
            'type' : __sanitize_label__read(n_raw['__label_set'][0]),
            'state' : 'perm',
        }, n_raw);

        delete ret.__label_set;

        return ret;
    }

    /**
     * write by adapting to backend format
     */
    function adapt_format_write_node(n_raw) {
        var ret = $.extend({
        }, n_raw);

        ret['__label_set'] = [__sanitize_label__write(n_raw.type)];

        delete ret.state;
        delete ret.status;
        delete ret.type;

        return ret;
    }

    /**
     * read by adapting from backend format
     */
    function adapt_format_read_link_ptr(l_raw) {
        var ret;

        ret = $.extend({
            'state' : 'perm',
        }, l_raw);

        ret['name'] = __sanitize_label__read(ret['__type'][0]);
        delete ret.__type;

        return ret;
    }

    /**
     * write by adapting to backend format
     */
    function adapt_format_write_link(l_raw) {
        var ret = $.extend({
            '__src_id' : l_raw.source.id,
            '__dst_id' : l_raw.target.id,
        }, l_raw);

        ret['__type'] = [__sanitize_label__write(l_raw.__type)];

        delete ret.__dst;
        delete ret.__src;
        delete ret.source; // introduced by d3 accessor methods
        delete ret.state;
        delete ret.status;
        delete ret.target;
        delete ret.name;

        return ret;
    }

    /**
     * write adapt diff from node set, link set. sets may be passed by reference
     * as they are cloned
     */
    function adapt_format_write_diff__topo(n_set, l_set) {

        var new_n_set = $.extend([], n_set);
        var new_l_set = $.extend([], l_set);

        new_n_set = $.map(new_n_set, function(n, _) {
            return adapt_format_write_node(n);
        });

        new_l_set = $.map(new_l_set, function(l, _) {
            return adapt_format_write_link(l);
        });

        var topo_diff = new model_diff.new_topo_diff({
            node_set_add : new_n_set,
            link_set_add : new_l_set
        });
        return topo_diff;
    }

    /**
     * read adapt attr_diff from backend format
     */
    function adapt_format_read_diff__attr(diff_spec) {
        var attr_diff = new model_diff.new_attr_diff();
        attr_diff.id_to_node_map = diff_spec['__type_node'];
        attr_diff.id_to_link_map = diff_spec['__type_link'];
        return attr_diff;
    }

    return {
        adapt_format_read_node : adapt_format_read_node,
        adapt_format_read_link_ptr : adapt_format_read_link_ptr,
        adapt_format_write_node : adapt_format_write_node,
        adapt_format_write_link : adapt_format_write_link,

        adapt_format_write_diff__topo : adapt_format_write_diff__topo,
        adapt_format_read_diff__attr : adapt_format_read_diff__attr,
    };
});
<|endoftext|>


<commit_before>'use strict';

// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
	// Init module configuration options
	var applicationModuleName = 'mean';
	var applicationModuleVendorDependencies = ['ngResource', 'ui.router', 'ui.bootstrap', 'ui.utils'];

	// Add a new vertical module
	var registerModule = function(moduleName, dependencies) {
		// Create angular module
		angular.module(moduleName, dependencies || []);

		// Add the module to the AngularJS configuration file
		angular.module(applicationModuleName).requires.push(moduleName);
	};

	return {
		applicationModuleName: applicationModuleName,
		applicationModuleVendorDependencies: applicationModuleVendorDependencies,
		registerModule: registerModule
	};
})();<commit_msg>‘bt-ford.socket-io’<commit_after>'use strict';

// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
	// Init module configuration options
	var applicationModuleName = 'mean';
	//add socket dependency here
	var applicationModuleVendorDependencies = ['ngResource', 'ngCookies',  'ngAnimate',  'ngTouch',  'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils', 'btford.socket-io'];

	// Add a new vertical module
	var registerModule = function(moduleName, dependencies) {
		// Create angular module
		angular.module(moduleName, dependencies || []);

		// Add the module to the AngularJS configuration file
		angular.module(applicationModuleName).requires.push(moduleName);
	};

	return {
		applicationModuleName: applicationModuleName,
		applicationModuleVendorDependencies: applicationModuleVendorDependencies,
		registerModule: registerModule
	};
})();<|endoftext|>


<commit_before>'use strict';

// This is a very simple interface
// Used to fire up gulp task in your local project
var Promise = require('bluebird');
var runner = require('../utils/runner');
var cb = require('../utils/callback');
var lookupRootPath = require('../utils/lookup-root');

function lookup (configFileName) {
  var currentPath = process.cwd();

  return new Promise(function (resolve, reject) {
    lookupRootPath(currentPath, configFileName, function (err, rootCwd) {
      if (err) {
        reject(err);
      }
      if (!rootCwd) {
        var customErr = '[-Error:]  This project may not be created by \'Ember-Rocks\'\n' +
          '[-Error:]  Or you are not in the project root directory. Try: `pwd`\n' +
          '[-Helper:] To create an \'Ember-Rocks\' project. Try: `em new myApp`';
        reject(customErr);
      }
      resolve(rootCwd);
    });
  });
}

function execCommand (command, opts) {
  switch (command) {
    case 'serve':
    case 's':
      runner(cb, 'serve', opts);
      break;

    case 'build':
    case 'b':
      runner(cb, 'release', opts);
      break;

    case 'test':
    case 't':
      runner(cb, 'test', opts);
      break;

    case 'mobile':
    case 'm':
      runner(cb, 'releaseMobile', opts);
      break;

    default:
      runner(cb, 'default', opts);
  }
}

var commands = function (options) {
  var command = process.argv.slice(2)[0] || options.parent.rawArgs[2];
  var configFileName = 'gulpfile.js';

  lookup(configFileName)
    .then(function (rootCwd) {
      // based on the return value, root cwd assigned to `LiftOff` setting
      var cwd = rootCwd || process.cwd();
      var opts = {
        cwd:        cwd,
        configPath: cwd + '/' + configFileName
      };
      execCommand(command, opts);
    })
    .catch(function (err) {
      console.log(err);
    });
};

module.exports = commands;
<commit_msg>make commands.js based on functional programming principle<commit_after>'use strict';

// This is a very simple interface
// Used to fire up gulp task in your local project
var Promise = require('bluebird');
var runner = require('../utils/runner');
var cb = require('../utils/callback');
var lookupRootPath = require('../utils/lookup-root');

function lookup (configFileName) {
  var currentPath = process.cwd();

  return new Promise(function (resolve, reject) {
    lookupRootPath(currentPath, configFileName, function (err, rootCwd) {
      if (err) {
        reject(err);
      }
      if (!rootCwd) {
        var customErr = '[-Error:]  This project may not be created by \'Ember-Rocks\'\n' +
          '[-Error:]  Or you are not in the project root directory. Try: `pwd`\n' +
          '[-Helper:] To create an \'Ember-Rocks\' project. Try: `em new myApp`';
        reject(customErr);
      }
      resolve(rootCwd);
    });
  });
}

function execCommand (command, opts) {
  switch (command) {
    case 'serve':
    case 's':
      runner(cb, 'serve', opts);
      break;

    case 'build':
    case 'b':
      runner(cb, 'release', opts);
      break;

    case 'test':
    case 't':
      runner(cb, 'test', opts);
      break;

    case 'mobile':
    case 'm':
      runner(cb, 'releaseMobile', opts);
      break;

    default:
      runner(cb, 'default', opts);
  }
}

function commands(options) {
  var command = process.argv.slice(2)[0] || options.parent.rawArgs[2];
  var configFileName = 'gulpfile.js';

  lookup(configFileName)
    .then(function (rootCwd) {
      // based on the return value, root cwd assigned to `LiftOff` setting
      var cwd = rootCwd || process.cwd();
      var opts = {
        cwd:        cwd,
        configPath: cwd + '/' + configFileName
      };
      execCommand(command, opts);
    })
    .catch(function (err) {
      console.log(err);
    });
}

module.exports = commands;
<|endoftext|>


<commit_before>/* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';

import type { ChildrenArray } from '../types';
import { Touchable } from './';
import { colorHashFromName } from '../utils/color';

export const initialsFromName = (name: string) =>
  (name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join('');

const styles = StyleSheet.create({
  frame: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: 'white',
  },
});

type Props = {
  name: string,
  size: number,
  shape?: string,
  children?: ChildrenArray<*>,
  onPress?: () => void,
};

export default class TextAvatar extends PureComponent<Props> {
  props: Props;

  render() {
    const { children, name, size, shape, onPress } = this.props;

    const frameSize = {
      height: size,
      width: size,
      borderRadius:
        shape === 'rounded' ? size / 8 : shape === 'circle' ? size / 2 : shape === 'square' ? 0 : 0,
      backgroundColor: colorHashFromName(name),
    };
    const textSize = {
      fontSize: size / 3,
    };

    return (
      <Touchable onPress={onPress}>
        <View style={[styles.frame, frameSize]}>
          <Text style={[styles.text, textSize]}>{initialsFromName(name)}</Text>
          {children}
        </View>
      </Touchable>
    );
  }
}
<commit_msg>jsdoc: Document TextAvatar component.<commit_after>/* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';

import type { ChildrenArray } from '../types';
import { Touchable } from './';
import { colorHashFromName } from '../utils/color';

export const initialsFromName = (name: string) =>
  (name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join('');

const styles = StyleSheet.create({
  frame: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: 'white',
  },
});

type Props = {
  name: string,
  size: number,
  shape?: string,
  children?: ChildrenArray<*>,
  onPress?: () => void,
};

/**
 * Renders a text avatar based on user initials and a color
 * calculated as a hash from their name.
 *
 * @prop name - User's full name to extract initials from.
 * @prop size - Sets width and height in pixels.
 * @prop shape - One of 'square', 'rounded', 'circle'.
 * @prop children - If provided, will render inside the component body.
 * @prop onPress - Event fired on pressing the component.
 */
export default class TextAvatar extends PureComponent<Props> {
  props: Props;

  render() {
    const { children, name, size, shape, onPress } = this.props;

    const frameSize = {
      height: size,
      width: size,
      borderRadius:
        shape === 'rounded' ? size / 8 : shape === 'circle' ? size / 2 : shape === 'square' ? 0 : 0,
      backgroundColor: colorHashFromName(name),
    };
    const textSize = {
      fontSize: size / 3,
    };

    return (
      <Touchable onPress={onPress}>
        <View style={[styles.frame, frameSize]}>
          <Text style={[styles.text, textSize]}>{initialsFromName(name)}</Text>
          {children}
        </View>
      </Touchable>
    );
  }
}
<|endoftext|>


<commit_before>$(document).ready(function(){
  setTimeout(showRetryButton, 15000);

  $('#radiusvalue').on('change', function(){
     if (circle) { circle.setRadius(parseInt($('#radiusvalue select').val())); }
  });

  $(document).on('updatedlocation', function(){
     if (circle) { circle.setCenter(current_location); }
     if (youmarker) { youmarker.setPosition(current_location); }

     var location = clToPosition();
     $.ajax({
       url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + location.coords.latitude + ',' + location.coords.longitude + '&sensor=false',
       method: 'get',
       dataType: 'json'
     }).done(function(data) {
        $('#locationsign').text((!current_location) ? 'Please, enable your location settings' : 'You are located in ' + data.results[6].formatted_address)
     });

  });

  $('#retrybutton').click(function(event){
    event.preventDefault();
    location.reload(true);
  });

  $(document).on('updatedlocation.showselectors', function(){
    $(document).off('.showselectors');
    $('#locationmsg').slideUp().
      fadeOut({complete: function(){$('#cscselectors').slideDown().fadeIn();}});
  });

  $('#autonotify').change(function() {
     if(this.checked) {
       circle.setMap(map);
       circle.setRadius(parseInt($('#radiusvalue select').val()));

       $('#autonotifyform').fadeIn();
       current_timer_id = setTimeout(autoNotification, 10000);
     } else {
       circle.setMap(null);
       $('#autonotifyform').fadeOut();
       if ( current_timer_id !== null ) {
         clearTimeout(current_timer_id);
         current_timer_id = null;
       }
     }
  });

  $('#autoupdate').change(function() {
     if(this.checked) {
       current_auto_update_timer_id = setTimeout(autoUpdateCars, 30000);
     } else {
       if ( current_auto_update_timer_id !== null ) {
         clearTimeout(current_auto_update_timer_id);
         current_auto_update_timer_id = null;
       }
     }
  });

  $('.sltcsc').click(function(event) {
    csc = $(this).data('csc');
    event.preventDefault();
    $('#mainhowto').slideUp().
      fadeOut({ complete: function(){
                  $('#mainmap').slideDown().fadeIn();
                  setUpMap(clToPosition());
                }});
  });
});
<commit_msg>moved the location request to be done only once<commit_after>$(document).ready(function(){
  setTimeout(showRetryButton, 15000);

  $('#radiusvalue').on('change', function(){
     if (circle) { circle.setRadius(parseInt($('#radiusvalue select').val())); }
  });

  $(document).on('updatedlocation', function(){
     if (circle) { circle.setCenter(current_location); }
     if (youmarker) { youmarker.setPosition(current_location); }
  });

  $('#retrybutton').click(function(event){
    event.preventDefault();
    location.reload(true);
  });

  $(document).on('updatedlocation.showselectors', function(){
    $(document).off('.showselectors');
    $('#locationmsg').slideUp().
      fadeOut({complete: function(){$('#cscselectors').slideDown().fadeIn();}});

     var location = clToPosition();
     $.ajax({
       url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + location.coords.latitude + ',' + location.coords.longitude + '&sensor=false',
       method: 'get',
       dataType: 'json'
     }).done(function(data) {
        $('#locationsign').text('You are located in ' + data.results[6].formatted_address);
     }).fail(function(){
        $('#locationsign').text('Please, enable your location settings');
     });
  });

  $('#autonotify').change(function() {
     if(this.checked) {
       circle.setMap(map);
       circle.setRadius(parseInt($('#radiusvalue select').val()));

       $('#autonotifyform').fadeIn();
       current_timer_id = setTimeout(autoNotification, 10000);
     } else {
       circle.setMap(null);
       $('#autonotifyform').fadeOut();
       if ( current_timer_id !== null ) {
         clearTimeout(current_timer_id);
         current_timer_id = null;
       }
     }
  });

  $('#autoupdate').change(function() {
     if(this.checked) {
       current_auto_update_timer_id = setTimeout(autoUpdateCars, 30000);
     } else {
       if ( current_auto_update_timer_id !== null ) {
         clearTimeout(current_auto_update_timer_id);
         current_auto_update_timer_id = null;
       }
     }
  });

  $('.sltcsc').click(function(event) {
    csc = $(this).data('csc');
    event.preventDefault();
    $('#mainhowto').slideUp().
      fadeOut({ complete: function(){
                  $('#mainmap').slideDown().fadeIn();
                  setUpMap(clToPosition());
                }});
  });
});
<|endoftext|>


<commit_before>
var RUNPL = true;
var dbg_parts = [];

function strJoin (sep, str_coll) {
    if (str_coll.length == 0) {
        return "";
    } else {
        var l = str_coll.length-1;
        x = str_coll.slice(0,l).reduce(
            function (S, s) {return S + s + sep;}, "");
        return x + str_coll[l];
    }
}

function taskOptions(task, tool) {
    var opts = task.option_value_assignments;
    //console.log(opts);
    var options =
        _.pairs(_.omit(opts, _.filter(_.keys(opts),
                                      function(k) {return !opts[k];})));
    options = _.flatten(tool.inputs_named ?
                        options :
                        _.map(options, function (pair) {
                            return (typeof pair[1] == "boolean") ?
                                pair[0] :
                                pair[1];
                        }));

    options = tool.flags_have_value ?
        options :
        _.filter(options, function(x) {return !(typeof x == "boolean");});

    return strJoin(" ", options);
}

function inputURL(input, pl_graph, pipeline) {
    if ('pipeline_input_id' in input) {
        var pi_obj = {pipeline_input_id: input.pipeline_input_id};
        return _.find(pl_graph, pi_obj).data_URL;
    } else {
        // A task is input (i.e., its output is input)
        // Set run flag to false as task as input => no explicit run.
	var pltask = pipeline.getTask(input.task_id);
	if (!pltask.in_display) {
            pltask.runit = false;
	};
        var pl_graph_tsk_obj = _.find(pl_graph, {task_id: input.task_id});
        return encodeURIComponent(pl_graph_tsk_obj.task_URL);
    }
}

function taskInputs(task, pl_graph, pipeline) {
    var inputs = task.input_src_assignments["-in"];
    return _.map(inputs,
                 function(input) {
                     return inputURL(input, pl_graph, pipeline);
                 });
}

function constructTaskRunMap (task, pl_graph, pipeline) {
    var tool = _.find(pipeline.tools, {id: task.tool_id});

    var service_URL = tool.service_URL;
    var ws_service;
    var ws_URL;

    if (!tool.ws_URL) {
        var x = service_URL.split(":")[1].split("/?");
        ws_service = "ws:" + x[0];
        ws_URL = ws_service + "/?" + x[1];
        tool.ws_URL = ws_URL;
        tool.ws_service = ws_service;
    } else {
        ws_URL = tool.ws_URL;
        ws_service = tool.ws_service;
    };

    var param_loc = tool.param_loc;
    var input_sep = tool.inputs_named ? " -in " : " ";

    var options = taskOptions(task,tool);
    var inputs = taskInputs(task, pl_graph, pipeline);
    var prefix = service_URL;
    var ws_prefix = ws_URL;
    var suffix = "";

    if (param_loc == "after-input") {
        suffix = " " + options;;
    } else {
        prefix = strJoin(" ", _.flatten([service_URL, options]));
        ws_prefix = strJoin(" ", _.flatten([ws_URL, options]));
    };

    url =  encodeURI(prefix +
                     strJoin(input_sep, [""].concat(inputs)) +
                     suffix);
    wsurl = encodeURI(ws_prefix +
                      strJoin(input_sep, [""].concat(inputs)) +
                      suffix);

    task.task_URL = url;
    task.task_ws_URL = wsurl;

    return {id: task.task_id,
            http_service: service_URL, http_url: url,
            ws_service: ws_service, ws_url: wsurl};
}

function constructPipelineRunMaps (pipeline) {
    var pl_graph = pipeline.linearized_cfg_graph;
    var tasks = _.filter(pl_graph, function(cfg) {return ('task_id' in cfg);});
    var task_run_maps =
        _.map(tasks,
              function(task){
                  return constructTaskRunMap(task, pl_graph, pipeline);});
    return _.filter(task_run_maps,
                    function (tm) {
                        return pipeline.getTask(tm.id).runit;
                    });
}

function ajaxRunPipeline (url) {
    $.ajax(
        url,
        {complete: function(xhr, status) {
            console.log("STATUS: " + status);
            samData = xhr.responseText;
            $("#monitor").append("
"+xhr.responseText+"
");
        },
         dataType: "text"});
}

function wsRunPipeline (task_run_info) {
    var ws_service = task_run_info["ws_service"];
    var wsurl = task_run_info["ws_url"];
    var task_id = task_run_info["id"];
    var parts = [];
    var client = BinaryClient(ws_service);

    client.on('open', function() {
        var stream = client.createStream(
            {event: 'run', params: {'url': wsurl}});
        stream.on('data', function(data) {
            parts.push(data);
        });
        stream.on('end', function() {
            dbg_parts = parts;
            //console.log(parts);
            $("#monitor").append(strJoin("\n", parts));
            // visualize data
            visualizeData(parts, task_id);
            // console.log(parts);
        });
    });
}

function visualizeData(parts, task_id) {
  var data = JSON.parse(parts[0]);
  app.current_visualization_view.addCharts(data, task_id);
}

$(function(){

    _.extend(app, Backbone.Events);

    app.loadPipeline = function(pipeline) {
        app.stopListening(app.pipeline);
        app.pipeline = pipeline;
        app.global_view.showGraph(new GlobalGraph(app.pipeline));
        app.focusOn(app.pipeline.inputs);
        app.listenTo(app.pipeline, 'add:task', app.focusOn);
        app.listenTo(app.pipeline,
                     'change',
                     function() {
                         var pl_json =
                             LZString.compressToBase64(
                                 JSON.stringify(app.pipeline));
                         var xurl =
                             "edit_pipeline/" + encodeURIComponent(pl_json);

                         app.pipeline.pl_json = pl_json;
                         //console.log("NewURL = " + xurl);
                         //console.log(app.pipeline);
                         app.router.navigate(xurl);
                         if (app.pipeline.tasks.length > 0)
                           app.runPipeline(app.pipeline, pl_json);
                     });
    }

    app.focusOn = function(datum) {
        var graph = (datum instanceof Task) ?
            new FocalTaskGraph(datum) :
            new FocalPipelineInputsGraph(app.pipeline);
        app.focal_view.showGraph(graph);
        app.global_view.focusDatum(datum);
    }

    app.router = new (Backbone.Router.extend(
        {routes:
         {"": function() {
             app.router.navigate("new_pipeline", {trigger: true});},

          "new_pipeline": "new_pipeline",
          "edit_pipeline/:pipeline_json": "edit_pipeline"
         },

         new_pipeline: function() {
             app.loadPipeline(new Pipeline());},

         edit_pipeline: function(pipeline_json) {
             var pl = new Pipeline(
                 JSON.parse(LZString.decompressFromBase64(pipeline_json)));
             app.loadPipeline(pl);
             app.runPipeline(pl, undefined);
         }
        }));

    app.runPipeline = function (pipeline, pl_json) {
        //console.log("RunPL: " + pl_json);

        if (pl_json) {
            pl_cfg = JSON.parse(LZString.decompressFromBase64(pl_json));
            pipeline.linearized_cfg_graph =
                pipeline._constructDependencyGraph(
                    pl_cfg.inputs, pl_cfg.tasks);
        }; // else, this call from edit_pipeline and already set

        var task_maps = constructPipelineRunMaps(pipeline);
        console.log(task_maps);
        if (task_maps) {
            plmap = _.last(task_maps);
            pipeline.url = plmap["http_url"];
            pipeline.wsurl = plmap["ws_url"];
            pipeline.ws_service = plmap["ws_service"];
            console.log(pipeline.url);
            if (RUNPL) {
              _.each(task_maps, function(tm){wsRunPipeline(tm);})
            };
        };
    }

    app.tool_library = new ToolLibrary(_.cloneDeep(server_data.tool_configs));

    app.global_view = new GlobalView({el: $("#global")});
    app.focal_view = new FocalView({el: $("#focal")});
    app.current_visualization_view = new VisualizationView({el: $("#current-visualization")});
    app.current_visualization_view = new VisualizationView({el: $("#current-visualization")});
    app.first_visualization_view = new VisualizationView({el: $("#first-visualization")});
    app.second_visualization_view = new VisualizationView({el: $("#second-visualization")});

    Backbone.history.start({pushState: true});
});
<commit_msg>Remove duplicate line<commit_after>
var RUNPL = true;
var dbg_parts = [];

function strJoin (sep, str_coll) {
    if (str_coll.length == 0) {
        return "";
    } else {
        var l = str_coll.length-1;
        x = str_coll.slice(0,l).reduce(
            function (S, s) {return S + s + sep;}, "");
        return x + str_coll[l];
    }
}

function taskOptions(task, tool) {
    var opts = task.option_value_assignments;
    //console.log(opts);
    var options =
        _.pairs(_.omit(opts, _.filter(_.keys(opts),
                                      function(k) {return !opts[k];})));
    options = _.flatten(tool.inputs_named ?
                        options :
                        _.map(options, function (pair) {
                            return (typeof pair[1] == "boolean") ?
                                pair[0] :
                                pair[1];
                        }));

    options = tool.flags_have_value ?
        options :
        _.filter(options, function(x) {return !(typeof x == "boolean");});

    return strJoin(" ", options);
}

function inputURL(input, pl_graph, pipeline) {
    if ('pipeline_input_id' in input) {
        var pi_obj = {pipeline_input_id: input.pipeline_input_id};
        return _.find(pl_graph, pi_obj).data_URL;
    } else {
        // A task is input (i.e., its output is input)
        // Set run flag to false as task as input => no explicit run.
	var pltask = pipeline.getTask(input.task_id);
	if (!pltask.in_display) {
            pltask.runit = false;
	};
        var pl_graph_tsk_obj = _.find(pl_graph, {task_id: input.task_id});
        return encodeURIComponent(pl_graph_tsk_obj.task_URL);
    }
}

function taskInputs(task, pl_graph, pipeline) {
    var inputs = task.input_src_assignments["-in"];
    return _.map(inputs,
                 function(input) {
                     return inputURL(input, pl_graph, pipeline);
                 });
}

function constructTaskRunMap (task, pl_graph, pipeline) {
    var tool = _.find(pipeline.tools, {id: task.tool_id});

    var service_URL = tool.service_URL;
    var ws_service;
    var ws_URL;

    if (!tool.ws_URL) {
        var x = service_URL.split(":")[1].split("/?");
        ws_service = "ws:" + x[0];
        ws_URL = ws_service + "/?" + x[1];
        tool.ws_URL = ws_URL;
        tool.ws_service = ws_service;
    } else {
        ws_URL = tool.ws_URL;
        ws_service = tool.ws_service;
    };

    var param_loc = tool.param_loc;
    var input_sep = tool.inputs_named ? " -in " : " ";

    var options = taskOptions(task,tool);
    var inputs = taskInputs(task, pl_graph, pipeline);
    var prefix = service_URL;
    var ws_prefix = ws_URL;
    var suffix = "";

    if (param_loc == "after-input") {
        suffix = " " + options;;
    } else {
        prefix = strJoin(" ", _.flatten([service_URL, options]));
        ws_prefix = strJoin(" ", _.flatten([ws_URL, options]));
    };

    url =  encodeURI(prefix +
                     strJoin(input_sep, [""].concat(inputs)) +
                     suffix);
    wsurl = encodeURI(ws_prefix +
                      strJoin(input_sep, [""].concat(inputs)) +
                      suffix);

    task.task_URL = url;
    task.task_ws_URL = wsurl;

    return {id: task.task_id,
            http_service: service_URL, http_url: url,
            ws_service: ws_service, ws_url: wsurl};
}

function constructPipelineRunMaps (pipeline) {
    var pl_graph = pipeline.linearized_cfg_graph;
    var tasks = _.filter(pl_graph, function(cfg) {return ('task_id' in cfg);});
    var task_run_maps =
        _.map(tasks,
              function(task){
                  return constructTaskRunMap(task, pl_graph, pipeline);});
    return _.filter(task_run_maps,
                    function (tm) {
                        return pipeline.getTask(tm.id).runit;
                    });
}

function ajaxRunPipeline (url) {
    $.ajax(
        url,
        {complete: function(xhr, status) {
            console.log("STATUS: " + status);
            samData = xhr.responseText;
            $("#monitor").append("
"+xhr.responseText+"
");
        },
         dataType: "text"});
}

function wsRunPipeline (task_run_info) {
    var ws_service = task_run_info["ws_service"];
    var wsurl = task_run_info["ws_url"];
    var task_id = task_run_info["id"];
    var parts = [];
    var client = BinaryClient(ws_service);

    client.on('open', function() {
        var stream = client.createStream(
            {event: 'run', params: {'url': wsurl}});
        stream.on('data', function(data) {
            parts.push(data);
        });
        stream.on('end', function() {
            dbg_parts = parts;
            //console.log(parts);
            $("#monitor").append(strJoin("\n", parts));
            // visualize data
            visualizeData(parts, task_id);
            // console.log(parts);
        });
    });
}

function visualizeData(parts, task_id) {
  var data = JSON.parse(parts[0]);
  app.current_visualization_view.addCharts(data, task_id);
}

$(function(){

    _.extend(app, Backbone.Events);

    app.loadPipeline = function(pipeline) {
        app.stopListening(app.pipeline);
        app.pipeline = pipeline;
        app.global_view.showGraph(new GlobalGraph(app.pipeline));
        app.focusOn(app.pipeline.inputs);
        app.listenTo(app.pipeline, 'add:task', app.focusOn);
        app.listenTo(app.pipeline,
                     'change',
                     function() {
                         var pl_json =
                             LZString.compressToBase64(
                                 JSON.stringify(app.pipeline));
                         var xurl =
                             "edit_pipeline/" + encodeURIComponent(pl_json);

                         app.pipeline.pl_json = pl_json;
                         //console.log("NewURL = " + xurl);
                         //console.log(app.pipeline);
                         app.router.navigate(xurl);
                         if (app.pipeline.tasks.length > 0)
                           app.runPipeline(app.pipeline, pl_json);
                     });
    }

    app.focusOn = function(datum) {
        var graph = (datum instanceof Task) ?
            new FocalTaskGraph(datum) :
            new FocalPipelineInputsGraph(app.pipeline);
        app.focal_view.showGraph(graph);
        app.global_view.focusDatum(datum);
    }

    app.router = new (Backbone.Router.extend(
        {routes:
         {"": function() {
             app.router.navigate("new_pipeline", {trigger: true});},

          "new_pipeline": "new_pipeline",
          "edit_pipeline/:pipeline_json": "edit_pipeline"
         },

         new_pipeline: function() {
             app.loadPipeline(new Pipeline());},

         edit_pipeline: function(pipeline_json) {
             var pl = new Pipeline(
                 JSON.parse(LZString.decompressFromBase64(pipeline_json)));
             app.loadPipeline(pl);
             app.runPipeline(pl, undefined);
         }
        }));

    app.runPipeline = function (pipeline, pl_json) {
        //console.log("RunPL: " + pl_json);

        if (pl_json) {
            pl_cfg = JSON.parse(LZString.decompressFromBase64(pl_json));
            pipeline.linearized_cfg_graph =
                pipeline._constructDependencyGraph(
                    pl_cfg.inputs, pl_cfg.tasks);
        }; // else, this call from edit_pipeline and already set

        var task_maps = constructPipelineRunMaps(pipeline);
        console.log(task_maps);
        if (task_maps) {
            plmap = _.last(task_maps);
            pipeline.url = plmap["http_url"];
            pipeline.wsurl = plmap["ws_url"];
            pipeline.ws_service = plmap["ws_service"];
            console.log(pipeline.url);
            if (RUNPL) {
              _.each(task_maps, function(tm){wsRunPipeline(tm);})
            };
        };
    }

    app.tool_library = new ToolLibrary(_.cloneDeep(server_data.tool_configs));

    app.global_view = new GlobalView({el: $("#global")});
    app.focal_view = new FocalView({el: $("#focal")});
    app.current_visualization_view = new VisualizationView({el: $("#current-visualization")});
    app.first_visualization_view = new VisualizationView({el: $("#first-visualization")});
    app.second_visualization_view = new VisualizationView({el: $("#second-visualization")});

    Backbone.history.start({pushState: true});
});
<|endoftext|>


<commit_before>// Init
$(function() {

    // cookies
    if($.cookie('un') && $.cookie('key')){
        $('#un').val($.cookie('un')) === $.cookie('un');
        $('#key').val($.cookie('key')) === $.cookie('key');
    }

    //init JCSDL
    $('#jcsdl-edit').jcsdlGui({
        save : function(code) {

            // validate the DS creds
            validateCreds();

            $('#debug').val(code);
        },
        hideTargets : ['twitter.status', 'twitter.place', 'twitter.retweet', 'twitter.mention_ids', 'twitter.domains', 'twitter.in_reply_to_screen_name', 'twitter.links', 'twitter.user', 'twitter.retweeted',   'interaction', '2ch', 'lexisnexis', 'intensedebate', 'sinaweibo', 'tencentweibo', 'tumblr', 'facebook_page', 'googleplus','instagram', 'wordpress', 'wikipedia', 'yammer',  'imdb','facebook', '2channel', 'myspace', 'digg', 'amazon', 'blog', 'board', 'bitly', 'dailymotion', 'flickr', 'newscred', 'reddit', 'topix', 'video', 'youtube', 'imdb.author', 'imdb.type', 'imdb.contenttype', 'imdb.thread']
    });
});

/*
 * validateCreds
 */
function validateCreds(){

    var ds_user = $.trim($('#un').val());
    var ds_key  = $.trim($('#key').val());

    if(ds_user ==='' || ds_key === ''){
        alert('Please enter a DataSift username and API key.');
    } else {
        // set cookie
        $.cookie('un', ds_user, { expires: 60 });
        $.cookie('key', ds_key, { expires: 60 });
        console.log('DEBUG: saved cookies: ' + ds_user + '' + ds_key);
    }
};

/*
function updateContact (contact) {

    jQuery.ajax({
        type: "PUT",
        url: "http://localhost:49193/Contacts.svc/Update",
        contentType: "application/json; charset=utf-8",
        data: contact.toJsonString(),
        dataType: "json",
        success: function (data, status, jqXHR) {
            // do something
        },

        error: function (jqXHR, status) {
            // error handler

        }
    });
}

function getContacts () {

    jQuery.ajax({
        type: "GET",
        url: "http://localhost:49193/Contacts.svc/GetAll",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status, jqXHR) {
            // do something
        },

        error: function (jqXHR, status) {
            // error handler
        }
    });
}

 */
// get the promise object for this API
var dataPromise = getData();

// register a function to get called when the data is resolved
dataPromise.done(function(data){
    console.log("We got data: " + data);
    console.log("We got data: " + typeof(data));
    $('#debug').val(data);
});

// register the failure function
dataPromise.fail(function(ex){
    console.log("oops, some problem occured: " + ex);
});

// Note: we can have as many dataPromise.done(...) as we want.
dataPromise.done(function(data){
    //console.log("We asked it twice, we get it twice: " + data);
});

function getData(){
    // 1) create the jQuery Deferred object that will be used
    var deferred = $.Deferred();

    // ---- AJAX Call ---- //
    //XMLHttpRequest xhr = new XMLHttpRequest();
    xhr = new XMLHttpRequest();
    //void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
    xhr.open("POST","http://localhost:3000/api/compile",true);

    // register the event handler
    xhr.addEventListener('load',function(){
        if(xhr.status === 200){
            // 3.1) RESOLVE the DEFERRED (this will trigger all the done()...)
            deferred.resolve(xhr.response);
        }else{
            // 3.2) REJECT the DEFERRED (this will trigger all the fail()...)
            deferred.reject("HTTP error: " + xhr.status);
        }
    },false)

    // perform the work
    xhr.send('hello from the browser :)');
    // Note: could and should have used jQuery.ajax.
    // Note: jQuery.ajax return Promise, but it is always a good idea to wrap it
    //       with application semantic in another Deferred/Promise
    // ---- /AJAX Call ---- //

    // 2) return the promise of this deferred
    return deferred.promise();
}

<commit_msg>Debug function.<commit_after>var ds_user = '';
var ds_key = '';

// Init
$(function() {

    // cookies
    if($.cookie('un') && $.cookie('key')){
        $('#un').val($.cookie('un')) === $.cookie('un');
        $('#key').val($.cookie('key')) === $.cookie('key');
    }

    //init JCSDL
    $('#jcsdl-edit').jcsdlGui({
        save : function(code) {

            log('DEBUG: CSDL generated: ' + code);

            // validate the DS creds
            if(validateCreds() === true){
                // compile csdl
                doCompile(code);
            }
        },
        hideTargets : ['twitter.status', 'twitter.place', 'twitter.retweet', 'twitter.mention_ids', 'twitter.domains', 'twitter.in_reply_to_screen_name', 'twitter.links', 'twitter.user', 'twitter.retweeted',   'interaction', '2ch', 'lexisnexis', 'intensedebate', 'sinaweibo', 'tencentweibo', 'tumblr', 'facebook_page', 'googleplus','instagram', 'wordpress', 'wikipedia', 'yammer',  'imdb','facebook', '2channel', 'myspace', 'digg', 'amazon', 'blog', 'board', 'bitly', 'dailymotion', 'flickr', 'newscred', 'reddit', 'topix', 'video', 'youtube', 'imdb.author', 'imdb.type', 'imdb.contenttype', 'imdb.thread']
    });
});

/*
 * validateCreds
 *
 * @return boolean
 *
 */
function validateCreds(){

    ds_user = $.trim($('#un').val());
    ds_key  = $.trim($('#key').val());

    if(ds_user ==='' || ds_key === ''){
        alert('Please enter a DataSift username and API key.');
        return false;
    }

    // set cookie
    $.cookie('un', ds_user, { expires: 60 });
    $.cookie('key', ds_key, { expires: 60 });
    console.log('DEBUG: saved cookies: ' + ds_user + '' + ds_key);
    return true;
};

function doCompile (csdl) {

    log('DEBUG: Compiling CSDL...');

    jQuery.ajax({
        type: "POST",
        url: "http://localhost:3000/api/compile",
        contentType: "application/json; charset=utf-8",
        data: 'csdl='+encodeURIComponent(csdl),
        dataType: "json",
        headers: {
            "Authorization": ds_user + ':' + ds_key
        },
        success: function (data, status, jqXHR) {
            log('DEBUG: compile success - ' + JSON.stringify(jqXHR.responseJSON));
        },
        error: function (jqXHR, status) {
            log('ERROR: compile failed: ' + JSON.stringify(jqXHR.responseJSON));
        }
    });
}

function log(update){
    $('#debug').val($('#debug').val() + "\n\n" + update);
}

/*
function getContacts () {

    jQuery.ajax({
        type: "GET",
        url: "http://localhost:49193/Contacts.svc/GetAll",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status, jqXHR) {
            // do something
        },

        error: function (jqXHR, status) {
            // error handler
        }
    });
}

// get the promise object for this API
var dataPromise = getData();

// register a function to get called when the data is resolved
dataPromise.done(function(data){
    console.log("We got data: " + data);
    console.log("We got data: " + typeof(data));
    $('#debug').val(data);
});

// register the failure function
dataPromise.fail(function(ex){
    console.log("oops, some problem occured: " + ex);
});

// Note: we can have as many dataPromise.done(...) as we want.
dataPromise.done(function(data){
    //console.log("We asked it twice, we get it twice: " + data);
});

function getData(){
    // 1) create the jQuery Deferred object that will be used
    var deferred = $.Deferred();

    // ---- AJAX Call ---- //
    //XMLHttpRequest xhr = new XMLHttpRequest();
    xhr = new XMLHttpRequest();
    //void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
    xhr.open("POST","http://localhost:3000/api/compile",true);

    // register the event handler
    xhr.addEventListener('load',function(){
        if(xhr.status === 200){
            // 3.1) RESOLVE the DEFERRED (this will trigger all the done()...)
            deferred.resolve(xhr.response);
        }else{
            // 3.2) REJECT the DEFERRED (this will trigger all the fail()...)
            deferred.reject("HTTP error: " + xhr.status);
        }
    },false)

    // perform the work
    xhr.send('hello from the browser :)');
    // Note: could and should have used jQuery.ajax.
    // Note: jQuery.ajax return Promise, but it is always a good idea to wrap it
    //       with application semantic in another Deferred/Promise
    // ---- /AJAX Call ---- //

    // 2) return the promise of this deferred
    return deferred.promise();
}

 */<|endoftext|>


<commit_before>$(document).ready(function() {
  $("table").tablesorter();

  $(".tabs a").click(function() {
    var el = $(this);

    var rev = el.parent().parent().attr("data-rev");
    var revsTable = $("#revs-" + rev).hide();
    // switch tab
    $(".tabs li").removeClass("active");
    el.parent().addClass("active");

    if(el.text() == "matrix") {
      $.ajax({
          url: "/matrix/" + rev,
          type: "GET",
          dataType: "html",

          success: function(data) {
            revsTable.after(data);
          },

          error: function() {
            $("#error-message").slideDown();
            setTimeout(function() {
              $("#error-message").slideUp();
            }, 3000);
          },
      });
    } else {
      $("#matrix-" + rev).hide();
      $("#revs-" + rev).show();
    }
  });
});<commit_msg>JS fix.<commit_after>$(document).ready(function() {
  $("table").tablesorter();

  $(".tabs a").click(function() {
    var el = $(this);

    var rev = el.parent().parent().attr("data-rev");
    var matrixElement = $("#matrix-" + rev);
    var revElement = $("#revs-" + rev);

    // switch tab
    $(".tabs li").removeClass("active");
    el.parent().addClass("active");

    if(el.text() == "matrix") {
      revElement.hide();

      if(matrixElement.size() != 0) {
        console.log("showing existing element");
        matrixElement.show();
        return;
      }

      $.ajax({
          url: "/matrix/" + rev,
          type: "GET",
          dataType: "html",

          success: function(data) {
            revElement.after(data);
          },

          error: function() {
            $("#error-message").slideDown();
            setTimeout(function() {
              $("#error-message").slideUp();
            }, 3000);
          },
      });
    } else {
      matrixElement.hide();
      revElement.show();
    }
  });
});<|endoftext|>


<commit_before>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$('.dropdown-inverse li > a').click(function(e){
		    $('.status').text(this.innerHTML);
		});

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

		$scope.courts = [];

    $scope.initCourts = function(facId){
        console.log(facId);
        var url = '/courts/fac/'+facId;
        $http({method:'GET',url:url}).
            success(function(data,status){
                console.log(data);

            for(var x in data){
                $scope.courts.push(data[x]);

                 $('.courtBox').append(
                 	'
'+
                   	'
'+
							'
'+
								'
'+
      							''+
      							'
'+
        							'
'+
          								'
'+
                  							'
'+data[x].name+'
'+
                    					'
'+
                    				'
'+
                    			'
'+
                    			'
'+
                    				'
'+
                                    	'
'+
                                    		''+
                  						'
'+
                  					'
'+
                  				'
'+
		                  		'
'+
		                  			'
'+
		          						'
Availability
'+
		          						'
Time slots available
'+
		          					'
'+
		          				'
'+
	          				'
'+
	          			'
'+
	          		'
'+
          		'
');

                console.log(data[x].image);
            }
            console.log($scope.courts);
        });
    };

    console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
		$scope.court = {
			name: "",
			facId: "",
			image: "",
			id: ""
		}

 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];

		$scope.getCourts = function(){
			var path = '/courts/fac/' + $scope.court.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						$scope.courts =  data[0];
					}
				});
		}

		$scope.getCourt = function(){
			var path = '/courts/' + $scope.court.name;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var courtVals = data[0];
						$scope.court.name = courtVals.name;
						$scope.court.facId = courtVals.facId;
						$scope.court.image = courtVals.image;
					}
				});
		}

	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<commit_msg>angular<commit_after>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$('.dropdown-inverse li > a').click(function(e){
		    $('.status').text(this.innerHTML);
		});

		$(".dropdown-inverse li a").click( function() {
		    var yourText = $(this).text();
		});

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

		$scope.courts = [];

    $scope.initCourts = function(facId){
        console.log(facId);
        var url = '/courts/fac/'+facId;
        $http({method:'GET',url:url}).
            success(function(data,status){
                console.log(data);

            for(var x in data){
                $scope.courts.push(data[x]);

                 $('.courtBox').append(
                 	'
'+
                   	'
'+
							'
'+
								'
'+
      							''+
      							'
'+
        							'
'+
          								'
'+
                  							'
'+data[x].name+'
'+
                    					'
'+
                    				'
'+
                    			'
'+
                    			'
'+
                    				'
'+
                                    	'
'+
                                    		''+
                  						'
'+
                  					'
'+
                  				'
'+
		                  		'
'+
		                  			'
'+
		          						'
Availability
'+
		          						'
Time slots available
'+
		          					'
'+
		          				'
'+
	          				'
'+
	          			'
'+
	          		'
'+
          		'
');

                console.log(data[x].image);
            }
            console.log($scope.courts);
        });
    };

    console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
		$scope.court = {
			name: "",
			facId: "",
			image: "",
			id: ""
		}

 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];

		$scope.getCourts = function(){
			var path = '/courts/fac/' + $scope.court.facId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						$scope.courts =  data[0];
					}
				});
		}

		$scope.getCourt = function(){
			var path = '/courts/' + $scope.court.name;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var courtVals = data[0];
						$scope.court.name = courtVals.name;
						$scope.court.facId = courtVals.facId;
						$scope.court.image = courtVals.image;
					}
				});
		}

	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<|endoftext|>


<commit_before>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.put();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			var changed = false;
			$scope.userGetPath = '/users/' + $scope.user.fbUserId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = JSON.parse(data);
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

						/*if(localStorage.phone.length){
							if(localStorage.phone != userVals.phone){
								$scope.user.phone = localStorage.phone;
								changed = true;
							} else {
								$scope.user.phone = userVals.phone;
							}
						} else {
							$scope.user.phone = userVals.phone;
						}

						if(changed) {
							$scope.put();
						}*/

					} else {
						$scope.put();
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', function($scope){
 		$scope.facilities = [
 			{
				name: 'Richards Building - BYU',
				hours: '6 am-10 pm Mon-Sat',
				phone: '(801) 422-3644',
				images: "../assets/rb.jpg"

			},
			{
				name: '24 Hour Fitness',
				hours: '6 am-12 pm Mon-Sat',
				phone: '(801) 224-2096',
				images: "../assets/24Hour.jpg"

			},
			{
					name: 'Orem Recreation Center',
					hours: '5 am-10 pm Mon-Fri 7 am-7 pm Sat',
					phone: '(801) 852-6600',
					images: "../assets/OremRec.jpg"

				},
				{
					name: 'Provo Recreation Center',
					hours: '5 am-10 pm Mon-Fri 7 am-8 pm Sat',
					phone: '(801) 229-7154',
					images: "../assets/ProvoRec.jpg"

				}

		];

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Falcon Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Shark Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Courgar Court',
				image: "../assets/rb.jpg"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','12 pm','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();

// var myApp = angular.module('SportScheduler',[])
//    .config(function($routeProvider) {
//        $routeProvider
//                .when('/homePage', {templateUrl: "views/homePage.html", controller: "homeCtrl"})
//                .when('/login', {templateUrl: "views/login.html", controller: "loginCtrl"})
//                .when('/project/:projectId', {templateUrl: "views/project.html", controller: "projectCtrl"})
//                .when('/editproject/:projectId', {templateUrl: "views/editproject.html", controller: "editProjectCtrl"})
//                .otherwise({redirectTo: '/home'});
//    });<commit_msg>editted court controller<commit_after>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.put();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			var changed = false;
			$scope.userGetPath = '/users/' + $scope.user.fbUserId;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = JSON.parse(data);
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = userVals.phone;

						/*if(localStorage.phone.length){
							if(localStorage.phone != userVals.phone){
								$scope.user.phone = localStorage.phone;
								changed = true;
							} else {
								$scope.user.phone = userVals.phone;
							}
						} else {
							$scope.user.phone = userVals.phone;
						}

						if(changed) {
							$scope.put();
						}*/

					} else {
						$scope.put();
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', function($scope){
 		$scope.facilities = [
 			{
				name: 'Richards Building - BYU',
				hours: '6 am-10 pm Mon-Sat',
				phone: '(801) 422-3644',
				images: "../assets/rb.jpg"

			},
			{
				name: '24 Hour Fitness',
				hours: '6 am-12 pm Mon-Sat',
				phone: '(801) 224-2096',
				images: "../assets/24Hour.jpg"

			},
			{
					name: 'Orem Recreation Center',
					hours: '5 am-10 pm Mon-Fri 7 am-7 pm Sat',
					phone: '(801) 852-6600',
					images: "../assets/OremRec.jpg"

				},
				{
					name: 'Provo Recreation Center',
					hours: '5 am-10 pm Mon-Fri 7 am-8 pm Sat',
					phone: '(801) 229-7154',
					images: "../assets/ProvoRec.jpg"

				}

		];

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Falcon Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Shark Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Courgar Court',
				image: "../assets/rb.jpg"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();

// var myApp = angular.module('SportScheduler',[])
//    .config(function($routeProvider) {
//        $routeProvider
//                .when('/homePage', {templateUrl: "views/homePage.html", controller: "homeCtrl"})
//                .when('/login', {templateUrl: "views/login.html", controller: "loginCtrl"})
//                .when('/project/:projectId', {templateUrl: "views/project.html", controller: "projectCtrl"})
//                .when('/editproject/:projectId', {templateUrl: "views/editproject.html", controller: "editProjectCtrl"})
//                .otherwise({redirectTo: '/home'});
//    });<|endoftext|>


<commit_before>$(document).ready(function() {
    $.getJSON('js/messages.json', function(obj) {
        $messages = obj[document.documentElement.lang];
        $table = $('#main').DataTable({
            'columns': [
                { 'data': 'title' },
                { 'data': 'title_ruby' },
                { 'data': 'volume' },
                { 'data': 'authors' },
                { 'data': 'isbn' },
                { 'data': 'jpno' },
                { 'data': 'published_date' },
                { 'data': 'ndl_url' },
            ],
            'columnDefs': [
                { 'visible': false, 'targets': 1 },
                { 'visible': false, 'targets': 5 },
                { 'visible': false, 'targets': 7 },
            ],
            'order': [[ 0, 'asc' ], [ 6, 'asc' ]],
            'lengthMenu': [ 10, 20, 30, 50, 100, 200 ],
            'displayLength': 100,
            'scrollY': true,
            'deferRender': true,
            'ajax': 'list',
            'rowCallback': function(row, data, index) {
                $('td:eq(0)', row).html('' + data.title + '');
            },
            'drawCallback': function(settings) {
                $('.pagination').append('
' + $messages.delete.label + '
');
            },
        });

        if (typeof customFunc == 'function') customFunc();
    });

    $.notifyDefaults({
        'placement': {
            'from': 'bottom',
            'align': 'right',
        },
        'mouse_over': 'pause',
    });

    $('#main tbody').on('click', 'tr', function() {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            $('#main_delete').addClass('disabled');
            $('#delete').attr('onclick', 'return false;');
        } else {
            $table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');

            if ($table.row('.selected').data() != null) {
                $('#main_delete').removeClass('disabled');
                $('#delete').attr('onclick', 'deleteBook(); return false;');
            }
        }
    });

    $('#register').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            'url': $form.attr('action'),
            'type': $form.attr('method'),
            'data': $form.serialize(),
            'success': function(result) {
                $.notify($messages.add.success, { 'type': 'success' });
                $table.ajax.reload(null, false);
                $form[0].reset();
            },
            'error': function(result) {
                var f = {
                    404: function() { $.notify($messages.not_exist, { 'type': 'warning' }); },
                    409: function() { $.notify($messages.add.failure, { 'type': 'danger' }); },
                    422: function() { validateError(result.responseJSON.code[0]); },
                };
                f[result.status]();
            },
        });
    });
});

function jumpZXingUrl() {
    var url = location.origin + '/create?code={CODE}&_token=' + document.head.querySelector('meta[name="csrf-token"]').content;
    location.href = 'http://zxing.appspot.com/scan?ret=' + escape(url);
}

function deleteBook() {
    if (window.confirm($messages.confirm)) {
        var bookId = $table.row('.selected').data().id;

        $.ajax({
            'url': 'delete',
            'type': 'POST',
            'data': {
                'id': bookId,
                '_token': document.head.querySelector('meta[name="csrf-token"]').content,
            },
            'success': function(result) {
                $table.row('.selected').remove().draw(false);
                $.notify($messages.delete.success, { 'type': 'success' });
            },
            'error': function(result) {
                var f = {
                    404: function() { $.notify($messages.delete.failure, { 'type': 'danger' }); },
                    422: function() { validateError(result.responseJSON.id[0]); },
                };
                f[result.status]();
            },
        });
    }
}

function validateError(message) {
    var $mes = $messages;
    $mes.invalid.message = '
' + message + '
';
    $.notify($mes.invalid, { 'type': 'warning' });
}
<commit_msg>Fix syntax<commit_after>$(document).ready(function() {
    $.getJSON('js/messages.json', function(obj) {
        $messages = obj[document.documentElement.lang];
        $table = $('#main').DataTable({
            'columns': [
                { 'data': 'title' },
                { 'data': 'title_ruby' },
                { 'data': 'volume' },
                { 'data': 'authors' },
                { 'data': 'isbn' },
                { 'data': 'jpno' },
                { 'data': 'published_date' },
                { 'data': 'ndl_url' },
            ],
            'columnDefs': [
                { 'visible': false, 'targets': 1 },
                { 'visible': false, 'targets': 5 },
                { 'visible': false, 'targets': 7 },
            ],
            'order': [[ 0, 'asc' ], [ 6, 'asc' ]],
            'lengthMenu': [ 10, 20, 30, 50, 100, 200 ],
            'displayLength': 100,
            'scrollY': true,
            'deferRender': true,
            'ajax': 'list',
            'rowCallback': function(row, data, index) {
                $('td:eq(0)', row).html('' + data.title + '');
            },
            'drawCallback': function(settings) {
                $('.pagination').append('
' + $messages.delete.label + '
');
            },
        });

        if (typeof customFunc == 'function') customFunc();
    });

    $.notifyDefaults({
        'placement': {
            'from': 'bottom',
            'align': 'right',
        },
        'mouse_over': 'pause',
    });

    $('#main tbody').on('click', 'tr', function() {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            $('#main_delete').addClass('disabled');
            $('#delete').attr('onclick', 'return false;');
        } else {
            $table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');

            if ($table.row('.selected').data() != null) {
                $('#main_delete').removeClass('disabled');
                $('#delete').attr('onclick', 'deleteBook(); return false;');
            }
        }
    });

    $('#register').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            'url': $form.attr('action'),
            'type': $form.attr('method'),
            'data': $form.serialize(),
            'success': function(result) {
                $.notify($messages.add.success, { 'type': 'success' });
                $table.ajax.reload(null, false);
                $form[0].reset();
            },
            'error': function(result) {
                var f = {
                    404: function() { $.notify($messages.not_exist, { 'type': 'warning' }); },
                    409: function() { $.notify($messages.add.failure, { 'type': 'danger' }); },
                    422: function() { validateError(result.responseJSON.code[0]); },
                };
                f[result.status]();
            },
        });
    });
});

function jumpZXingUrl() {
    var url = location.origin + '/create?code={CODE}&_token=' + document.head.querySelector('meta[name="csrf-token"]').content;
    location.href = 'http://zxing.appspot.com/scan?ret=' + escape(url);
}

function deleteBook() {
    if (window.confirm($messages.confirm)) {
        var bookId = $table.row('.selected').data().id;

        $.ajax({
            'url': 'delete',
            'type': 'POST',
            'data': {
                'id': bookId,
                '_token': document.head.querySelector('meta[name="csrf-token"]').content,
            },
            'success': function(result) {
                $table.row('.selected').remove().draw(false);
                $.notify($messages.delete.success, { 'type': 'success' });
            },
            'error': function(result) {
                var f = {
                    404: function() { $.notify($messages.delete.failure, { 'type': 'danger' }); },
                    422: function() { validateError(result.responseJSON.id[0]); },
                };
                f[result.status]();
            },
        });
    }
}

function validateError(message) {
    var $mes = $messages.invalid;
    $mes.message = '
' + message + '
';
    $.notify($mes, { 'type': 'warning' });
}
<|endoftext|>