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

  console.log('profile js linked!')

  // $('#itemList').click(function(event) {
  //   console.log(event.target)
  // })

    $.getJSON('/token')
      .done((data) => {
        console.log(data)
        const user_id = data.cookies.userId
        console.log(user_id)

        const jaxObj = {
          method: "GET",
          url: `/users/${user_id}`
        }
        $.ajax(jaxObj)
          .done((user) => {

            console.log(user)

            const username = user[0].username
            $('#username').text('Username: ' + username)
            const join = user[0].created_at
            const date = new Date(join)
            $('#joindate').text("joindate: " + (date.getMonth() +1) + '/' + new Date(join).getDate() + '/' + date.getFullYear())

          })
          .fail(($xhr) => {
            Materialize.toast($xhr.responseText, 3000);
          })
        })
      })

      $.getJSON('/token')
        .done((data) => {
          console.log(data)
          const user_id = data.cookies.userId
          console.log("we made it")

          const jaxObj = {
            method: "GET",
            url: `/items`
          }
          $.ajax(jaxObj)
            .done((items) => {
              console.log(items);
              for(const item of items){
                if (item.owner_id === user_id) {

                  const $card = $('<div>').addClass('card card-image');

                  const $cardContent = $('<div>').addClass('card-content black-text')
                  const $span = $('<span>').addClass('card-title')
                  $span.text(item.title)
                  const $pPrice = $('<p>')
                  $pPrice.text("$" + item.daily_price + " a day.")
                  const $p = $('<p>')
                  $p.text(item.desc)
                  const $img = $('<img>').attr({ src: item.img_url, alt: item.title, height: 80, width: 80 });

                  $card.append($img);
                  $cardContent.append($span)
                  $cardContent.append($pPrice)
                  $cardContent.append($p)
                  $card.append($cardContent)
                  $card.click(function() {
                    window.location.href = `/item.html?id=${item.id}`
                  })
                  let li = $('<li>')
                  li.append($card)
                  $('#itemList').append(li);

                  console.log(item)
                }
              }

            })
            .fail(($xhr) => {
              Materialize.toast($xhr.responseText, 3000);
            })
          })
<commit_msg>3pm wednesday<commit_after>$(document).ready(() => {

  console.log('profile js linked!')

  // $('#itemList').click(function(event) {
  //   console.log(event.target)
  // })

    $.getJSON('/token')
      .done((data) => {
        console.log(data)
        const user_id = data.cookies.userId
        console.log(user_id)

        const jaxObj = {
          method: "GET",
          url: `/users/${user_id}`
        }
        $.ajax(jaxObj)
          .done((user) => {

            console.log(user)

            const username = user[0].username
            $('#username').text('Username: ' + username)
            const join = user[0].created_at
            const date = new Date(join)
            $('#joindate').text("joindate: " + (date.getMonth() +1) + '/' + new Date(join).getDate() + '/' + date.getFullYear())

          })
          .fail(($xhr) => {
            Materialize.toast($xhr.responseText, 3000);
          })
        })
      })

      $.getJSON('/token')
        .done((data) => {
          console.log(data)
          const user_id = data.cookies.userId
          console.log("we made it")

          const jaxObj = {
            method: "GET",
            url: `/items`
          }
          $.ajax(jaxObj)
            .done((items) => {
              console.log(items);
              for(const item of items){
                if (item.owner_id === user_id) {

                  const $card = $('<div>').addClass('card card-image');

                  const $cardContent = $('<div>').addClass('card-content black-text')
                  const $span = $('<span>').addClass('card-title')
                  $span.text(item.title)
                  const $pPrice = $('<p>')
                  $pPrice.text("$" + item.daily_price + " a day.")
                  const $p = $('<p>')
                  $p.text(item.desc)
                  const $img = $('<img>').attr({ alt: item.title, height: 80, width: 80 });

                  $card.append($img);
                  $cardContent.append($span)
                  $cardContent.append($pPrice)
                  $cardContent.append($p)
                  $card.append($cardContent)
                  $card.click(function() {
                    window.location.href = `/item.html?id=${item.id}`
                  })
                  let li = $('<li>')
                  li.append($card)
                  $('#itemList').append(li);

                  console.log(item)
                }
              }

            })
            .fail(($xhr) => {
              Materialize.toast($xhr.responseText, 3000);
            })
          })
<|endoftext|>


<commit_before>/**
 * @class Utils provides a number of utility functions which are handy
 *        around the app.
 *
 * @property {Boolean} debugMode This boolean can be changed from true to
 *           false for production mode to speed up the app.
 *
 * @constructs
 */
var Utils = Utils || {};

Utils.debugMode = true;

Utils.couchUrl = "https://ilanguage.iriscouch.com/sapir-firstcorpus";
/**
 * The address of the TouchDB-Android database on the Android.
 */
Utils.touchUrl = "http://localhost:8888/db";

/**
 * The address of the PouchDB database on the browser.
 */
Utils.pouchUrl = "idb://db";

Utils.activityFeedCouchUrl = "http://trisapeace.iriscouch.com/activity_feed";
/**
 * The address of the TouchDB-Android database on the Android.
 */
Utils.activityFeedTouchUrl = "http://localhost:8888/activity_feed_db";

/**
 * The address of the PouchDB database on the browser.
 */
Utils.activityFeedPouchUrl = "idb://activity_feed_db";

/**
 * The url of the authentication server.
 */
Utils.authUrl = "https://ifield.fieldlinguist.com";//"https://localhost:3001";
/**
 * The parameters of the default couch server.
 */
Utils.defaultCouchConnection = function() {
  return {
    protocol : "https://",
    domain : "ilanguage.iriscouch.com",
    port : "443",
    corpusname : "sapir-firstcorpus"
  };
};
/**
 * A message for users if they need help which brings them to our contact us form
 */
Utils.contactUs = "Contact Us";

/**
 * Console logs out, if not on Internet Explorer. Only logs out if
 * debugMode is true.
 */
Utils.debug = function(message) {
	if(navigator.appName == 'Microsoft Internet Explorer') {
		return;
	}
	if(this.debugMode) {
		console.log(message);
	}
};

/**
 * Simple Pub/sub plugin to create a decoupled javascript app
 * http://answers.oreilly.com/topic/2190-two-examples-of-the-observer-pattern-in-javascript/
 *
 * How to use it:
var hub = {};
makePublisher(hub);

hub.subscribe(
  "probeCommand",
  function(arg) {
    debug("Receiving command " + arg);
  }, self);

hub.publish(
    "probeResponse",
"Command not valid.")

var right = document.getElementById("rightSideReading");
hub.unsubscribe('probeResponse', null, center);
hub.subscribe('probeResponse', function(arg) {
  debug("Putting probe's response in the right input field.");
  var cleanedMessage = arg.replace(/[^0-9]/g, "");
  debug("Cleaned message: " + arg + " to: " + cleanedMessage);
  right.value = cleanedMessage;
}, right);

hub.subscribe('changeLogo',function(arg){
  debug("Putting the logo from the user. This is the path: "+ arg);
  img.setAttribute("src",storage.getItem("userLogo"));
},img);
 *
 */

Utils.publisher = {
  subscribers : {
    any : []
  },
  subscribe : function(type, fn, context) {
    type = type || 'any';
    fn = typeof fn === "function" ? fn : context[fn];

    if (typeof this.subscribers[type] === "undefined") {
      this.subscribers[type] = [];
    }
    this.subscribers[type].push({
      fn : fn,
      context : context || this
    });
  },
  unsubscribe : function(type, fn, context) {
    this.visitSubscribers('unsubscribe', type, fn, context);
  },
  publish : function(type, publication) {
    this.visitSubscribers('publish', type, publication);
  },
  visitSubscribers : function(action, type, arg, context) {
    var pubtype = type || 'any', subscribers = this.subscribers[pubtype], i, max = subscribers ? subscribers.length
        : 0;

    for (i = 0; i < max; i += 1) {
      if (action === 'publish') {
        subscribers[i].fn.call(subscribers[i].context, arg);
      } else {
        if (subscribers[i].context === context) {
          subscribers.splice(i, 1);
          debug("Removed subscribers");

        } else {
          debug("Not removing subscriber" + i);

        }
      }
    }
  }
};
Utils.makePublisher = function(o) {
  var i;
  for (i in Utils.publisher) {
    if (Utils.publisher.hasOwnProperty(i)
        && typeof Utils.publisher[i] === "function") {
      o[i] = Utils.publisher[i];
    }
  }
  o.subscribers = {
    any : []
  };
};

/**
 * Detects whether we are running offline on an Android app.
 *
 * Note: to Android app developers, append this to your user agent string to
 * take advantage of the offline functionality of this app.
 *
 * @returns {Boolean} true if using offline Android
 */
Utils.androidApp = function() {
	return navigator.userAgent.indexOf("OfflineAndroidApp") > -1;
};

/**
 * Detects whether we are running offline in chrome extension.
 *
 * @returns {Boolean} true if using a Chrome Extension
 */
Utils.chromeApp = function() {
	return window.location.href.indexOf("chrome-extension") > -1;
};

/**
 * If not running offline on an android or in a chrome extension,
 * assume we are online.
 *
 * @returns {Boolean} true if not on offline Android or on a Chrome
 *          Extension
 */
Utils.onlineOnly = function() {
	return !this.androidApp() && !this.chromeApp();
};

Utils.hasClass = function(ele, cls) {
	return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};

Utils.addClass = function(ele, cls) {
	if(!this.hasClass(ele, cls))
		ele.className += " " + cls;
};

Utils.removeClass = function(ele, cls) {
	if(this.hasClass(ele, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)', 'g');
		ele.className = ele.className.replace(reg, ' ');
	}
};

<commit_msg>fixing typo in pubsub it wasnt using Utils namespace<commit_after>/**
 * @class Utils provides a number of utility functions which are handy
 *        around the app.
 *
 * @property {Boolean} debugMode This boolean can be changed from true to
 *           false for production mode to speed up the app.
 *
 * @constructs
 */
var Utils = Utils || {};

Utils.debugMode = true;

Utils.couchUrl = "https://ilanguage.iriscouch.com/sapir-firstcorpus";
/**
 * The address of the TouchDB-Android database on the Android.
 */
Utils.touchUrl = "http://localhost:8888/db";

/**
 * The address of the PouchDB database on the browser.
 */
Utils.pouchUrl = "idb://db";

Utils.activityFeedCouchUrl = "http://trisapeace.iriscouch.com/activity_feed";
/**
 * The address of the TouchDB-Android database on the Android.
 */
Utils.activityFeedTouchUrl = "http://localhost:8888/activity_feed_db";

/**
 * The address of the PouchDB database on the browser.
 */
Utils.activityFeedPouchUrl = "idb://activity_feed_db";

/**
 * The url of the authentication server.
 */
Utils.authUrl = "https://ifield.fieldlinguist.com";//"https://localhost:3001";
/**
 * The parameters of the default couch server.
 */
Utils.defaultCouchConnection = function() {
  return {
    protocol : "https://",
    domain : "ilanguage.iriscouch.com",
    port : "443",
    corpusname : "sapir-firstcorpus"
  };
};
/**
 * A message for users if they need help which brings them to our contact us form
 */
Utils.contactUs = "Contact Us";

/**
 * Console logs out, if not on Internet Explorer. Only logs out if
 * debugMode is true.
 */
Utils.debug = function(message) {
	if(navigator.appName == 'Microsoft Internet Explorer') {
		return;
	}
	if(this.debugMode) {
		console.log(message);
	}
};

/**
 * Simple Pub/sub plugin to create a decoupled javascript app
 * http://answers.oreilly.com/topic/2190-two-examples-of-the-observer-pattern-in-javascript/
 *
 * How to use it:
var hub = {};
makePublisher(hub);

hub.subscribe(
  "probeCommand",
  function(arg) {
    debug("Receiving command " + arg);
  }, self);

hub.publish(
    "probeResponse",
"Command not valid.")

var right = document.getElementById("rightSideReading");
hub.unsubscribe('probeResponse', null, center);
hub.subscribe('probeResponse', function(arg) {
  debug("Putting probe's response in the right input field.");
  var cleanedMessage = arg.replace(/[^0-9]/g, "");
  debug("Cleaned message: " + arg + " to: " + cleanedMessage);
  right.value = cleanedMessage;
}, right);

hub.subscribe('changeLogo',function(arg){
  debug("Putting the logo from the user. This is the path: "+ arg);
  img.setAttribute("src",storage.getItem("userLogo"));
},img);
 *
 */

Utils.publisher = {
  subscribers : {
    any : []
  },
  subscribe : function(type, fn, context) {
    type = type || 'any';
    fn = typeof fn === "function" ? fn : context[fn];

    if (typeof this.subscribers[type] === "undefined") {
      this.subscribers[type] = [];
    }
    this.subscribers[type].push({
      fn : fn,
      context : context || this
    });
  },
  unsubscribe : function(type, fn, context) {
    this.visitSubscribers('unsubscribe', type, fn, context);
  },
  publish : function(type, publication) {
    this.visitSubscribers('publish', type, publication);
  },
  visitSubscribers : function(action, type, arg, context) {
    var pubtype = type || 'any', subscribers = this.subscribers[pubtype], i, max = subscribers ? subscribers.length
        : 0;

    for (i = 0; i < max; i += 1) {
      if (action === 'publish') {
        subscribers[i].fn.call(subscribers[i].context, arg);
      } else {
        if (subscribers[i].context === context) {
          subscribers.splice(i, 1);
          Utils.debug("Removed subscribers");

        } else {
          Utils.debug("Not removing subscriber" + i);

        }
      }
    }
  }
};
Utils.makePublisher = function(o) {
  var i;
  for (i in Utils.publisher) {
    if (Utils.publisher.hasOwnProperty(i)
        && typeof Utils.publisher[i] === "function") {
      o[i] = Utils.publisher[i];
    }
  }
  o.subscribers = {
    any : []
  };
};

/**
 * Detects whether we are running offline on an Android app.
 *
 * Note: to Android app developers, append this to your user agent string to
 * take advantage of the offline functionality of this app.
 *
 * @returns {Boolean} true if using offline Android
 */
Utils.androidApp = function() {
	return navigator.userAgent.indexOf("OfflineAndroidApp") > -1;
};

/**
 * Detects whether we are running offline in chrome extension.
 *
 * @returns {Boolean} true if using a Chrome Extension
 */
Utils.chromeApp = function() {
	return window.location.href.indexOf("chrome-extension") > -1;
};

/**
 * If not running offline on an android or in a chrome extension,
 * assume we are online.
 *
 * @returns {Boolean} true if not on offline Android or on a Chrome
 *          Extension
 */
Utils.onlineOnly = function() {
	return !this.androidApp() && !this.chromeApp();
};

Utils.hasClass = function(ele, cls) {
	return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};

Utils.addClass = function(ele, cls) {
	if(!this.hasClass(ele, cls))
		ele.className += " " + cls;
};

Utils.removeClass = function(ele, cls) {
	if(this.hasClass(ele, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)', 'g');
		ele.className = ele.className.replace(reg, ' ');
	}
};

<|endoftext|>


<commit_before>if (typeof(RtStat) == "undefined") {
    RtStat = {};
}
RtStat.Monitoring = function (config) {
    var self = this;
    var columns = [];

    $('#edit-mode-btn').on('click', function () {
       $('body').toggleClass('edit-mode-off').toggleClass('edit-mode-on');
    });
    $('#add-col-btn').on('click', function () {
        var newCol = new RtStat.Monitoring.Column(columns.length);
        columns.push(newCol);
        $('#wrapper').append(newCol.getBlock());
        newCol.init();
    });
    $('#get-config-btn').click(function () {
        var txId = 'tx-' + RtStat.Monitoring.generateRandomString();

        var source = $("#config-dialog-template").html();
        var template = Handlebars.compile(source);
        $.modal($(template({
            title: 'Current config',
            textareaId: txId,
            needButton: false
        })));

        $('#' + txId).val(JSON.stringify(self.getCurrentConfig(), undefined, 2));
    });
    $('#setup-btn').click(function () {
        var txId = 'tx-' + RtStat.Monitoring.generateRandomString();
        var btnId = 'btn-' + RtStat.Monitoring.generateRandomString();

        var source = $("#config-dialog-template").html();
        var template = Handlebars.compile(source);
        var m = $.modal($(template({
            title: 'Setup from config',
            textareaId: txId,
            buttonId: btnId,
            needButton: true
        })));

        $('#' + btnId).click(function () {
            try {
                var newConfig = JSON.parse($('#' + txId).val());
            } catch (e) {
                console.error("JSON parsing error:", e);
                alert('JSON can not be parsed (perhaps it\'s not valid). Check developer console for details.');
                return;
            }
            self.setup(newConfig);
            m.close();
        });
    });

    var removeAllColumns = function () {
        for (var i in columns) {
            if (!columns.hasOwnProperty(i)) {
                continue;
            }
            columns[i].remove();
        }
    };

    this.setup = function (config) {
        removeAllColumns();

        for (var i = 0; i < config.columns.length; i++) {
            columns[i] = new RtStat.Monitoring.Column(i);
            $('#wrapper').append(columns[i].getBlock());
            columns[i].init();

            for (var j = 0; j < config.columns[i].servers.length; j++) {
                var serverConfig = config.columns[i].servers[j];
                var server = new RtStat.Monitoring.Server(serverConfig);
                columns[i].addServer(server);
            }
        }
    };

    this.getCurrentConfig = function () {
        var currentConfig = {columns: []};
        for (var i in columns) {
            if (!columns.hasOwnProperty(i)) {
                continue;
            }
            var colConfig = {
                servers: []
            };

            var servers = columns[i].getServers();
            for (var s in servers) {
                if (!servers.hasOwnProperty(s)) {
                    continue;
                }
                colConfig.servers.push(servers[s].getCurrentConfig());
            }

            currentConfig.columns.push(colConfig);
        }

        return currentConfig;
    };

    this.setup(config);
};

RtStat.Monitoring.generateRandomString = function () {
    return Math.floor((Math.random()) * Math.pow(10, 50)).toString(36);
};

RtStat.Monitoring.init = function (config) {
    var e = new RtStat.Monitoring(config);
};

RtStat.Monitoring.Column = function (index) {
    var self = this;
    var block = (function () {
        var source = $("#col-template").html();
        var template = Handlebars.compile(source);
        return $(template({colIndex: index}));
    })();

    var servers = [];

    this.getBlock = function () {
        return block;
    };

    this.remove = function () {
        for (var i = 0; i < servers.length; i++) {
            this.removeServer(servers[i]);
        }
        block.remove();
    };

    this.init = function () {
        $('#col-' + index + '-remove-btn').click(function () {
            self.remove();
        });
        $('#col-' + index + '-add-server-btn').click(function () {
            self.addServer(new RtStat.Monitoring.Server({
                id: RtStat.Monitoring.generateRandomString(),
                name: 'New Server',
                host: 'localhost',
                interval: 1.5,
                autoStart: false
            }));
        });
    };

    this.addServer = function (server) {
        block.find('.servers').append(server.getBlock());
        servers.push(server);
        server.init();

        block.find('.server-remove-btn').click(function () {
            self.removeServer(server);
        });
    };

    this.removeServer = function (server) {
        server.uninit();
        server.getBlock().remove();
        servers.splice(servers.indexOf(server));
    };

    this.getServers = function () {
        return servers.slice(0);
    };
};

RtStat.Monitoring.Server = function (initialConfig) {
    var self = this;

    var block = (function () {
        var source = $("#server-template").html();
        var template = Handlebars.compile(source);
        return block = $(template({server: initialConfig}));
    })();
    if (initialConfig.autoStart) {
        block.find('.auto-start').prop('checked', true);
    }

    this.getBlock = function () {
        return block;
    };

    var srvPref = function (id) {
        return "server-" + initialConfig.id + "-" + id;
    };
    var srvPref$ = function (id) {
        return "#" + srvPref(id);
    };

    var cpuStat = function (allCpus) {
        var typesCpu = [
            {key: 'user', color: "rgb(60,163,23)"},
            {key: 'system', color: "rgb(247,187,22)"},
            {key: 'iowait', color: "rgb(232,23,23)"}
        ];
        graphInfo(allCpus, typesCpu, 'processors', 'processors-cpuX-template', 'processors', 0.90, function (data) { return data.usage;},
            function (data, element) { return data[element.key];});
    };

    var memInfo = function (meminfo) {
        var typesMemory = [
            {key: 'apps', color: "rgb(33,145,29)"},
            {key: 'buffers', color: "rgb(160,20,0)"},
            {key: 'cached', color: "rgb(242,143,12)"},
            {key: 'swapCached', color: "rgb(232,23,23)"}
        ];
        graphInfo({memory: meminfo.memory}, typesMemory, '', '', '', 0.85, function (data) {return (data.apps + data.buffers) / data.total;},
            function (data, element) {return data[element.key] / data.total;});

        var typesSwap = [
            {key: 'used', color: "rgb(232,23,23)"}
        ];
        graphInfo({swap: meminfo.swap}, typesSwap, '', '', '', 0.10, function (data) {return data.used / data.total;},
            function (data, element) {return data[element.key] / data.total;});
    };

    var graphInfo = function (dataset, types, blockSelector, blockTemplateSelector, appendToSelector, warnLimit,
                        dataGetOverallUsageValueClb, dataGetElementUsageValueClb) {
        for (var key in dataset) {
            if (!dataset.hasOwnProperty(key)) {
                continue;
            }

            var data = dataset[key];

            var compiledBlockSelector = (blockSelector ? blockSelector + '-' : '') + key + '-canvas';
            var block = $(srvPref$(compiledBlockSelector));
            if (block.length < 1) {
                var template = Handlebars.compile($(srvPref$(blockTemplateSelector)).html());
                var newEl =  $(template({cpuId: key}));
                $(srvPref$(appendToSelector)).append(newEl);
                block = newEl.find(srvPref$(compiledBlockSelector));
            }

            var valueField = block.parent().find('span.value');
            if (valueField) {
                var value = dataGetOverallUsageValueClb(data);
                valueField.text(Math.round(value * 1000) / 10 + '%');
                if (value >= warnLimit) {
                    valueField.addClass('warning');
                }
                else {
                    valueField.removeClass('warning');
                }
            }

            var canvas = block.get(0);
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            var lastX = 0;
            var width = canvas.width;
            types.forEach(function (element) {
                var value = dataGetElementUsageValueClb(data, element);
                ctx.fillStyle = element.color;
                var segmentWidth = Math.round(value * width);
                if (segmentWidth > 1) {
                    ctx.fillRect(lastX + 1, 1, segmentWidth - 1, canvas.height - 2);
                    lastX += segmentWidth;
                }
            });
        }
    };

    var uptime = function (uptime) {
        for (var key in uptime) {
            if (!uptime.hasOwnProperty(key)) {
                continue;
            }
            $(srvPref$('uptime-' + key)).text(uptime[key]);
        }
        $(srvPref$('title')).html( '[ <small>' + uptime.la1 + '</small> ' + uptime.la5 + ' ]');
    };

    var processes = function (processes) {
        for (var key in processes) {
            if (!processes.hasOwnProperty(key)) {
                continue;
            }
            $(srvPref$('processes-' + key)).text(processes[key]);
        }
    };

    var statusBlock; // will be assigned later in init()
    var wantToBeConnected = false;
    var connecting = false;
    var client = new RtStat.WebSocketClient({
        onCmdCallback: function (cmd, args) {
            if (cmd == 'push') {
                if (args.length < 1) {
                    console.log('Error: push command without arguments');
                }
                var msg = args[0];
                var jsonResponce = JSON.parse(msg);
                cpuStat(jsonResponce.cpu_stat);
                memInfo(jsonResponce.meminfo);
                uptime(jsonResponce.uptime);
                processes(jsonResponce.processes);
            }
        },
        onOpenCallback: function () {
            connecting = false;
            statusBlock.text('Connected');
            var token = self.getToken();
            if (token) {
                client.authenticate(token);
            }
            setInterval();
            client.start();
        },
        onErrorCallback: function (data) {
            statusBlock.text('Error. Disconnecting...');
        },
        onCloseCallback: function () {
            if (wantToBeConnected) {
                statusBlock.text('Disconnected. Trying to connect...');
                setTimeout(function() {
                    if (wantToBeConnected) {
                        connect();
                    } else {
                        statusBlock.text('Disconnected');
                        connecting = false;
                    }
                }, self.getInterval() * 1000);
            } else {
                statusBlock.text('Disconnected');
                connecting = false;
            }
        }
    });

    var connect = function () {
        statusBlock.text('Connecting...');

        var wsUri = self.getHost();
        var hostMatch = wsUri.match(/^((ws|wss):\/\/)?([a-zA-Z0-9\-\.]{1,63})(:(\d{1,5}))?(\/.*)?$/i);
        if (hostMatch) {
            wsUri = hostMatch[3]; // host
            if (hostMatch[2]) { // protocol
                wsUri = hostMatch[1] + wsUri;
            } else {
                wsUri = 'ws://' + wsUri;
            }
            if (hostMatch[5]) { // port
                wsUri += ":" + hostMatch[5];
            } else {
                wsUri += ":8000";
            }
            if (hostMatch[6]) { // local part
                wsUri += hostMatch[6];
            } else {
                wsUri += "/";
            }
        } else {
            wsUri = "ws://localhost:8000/";
        }

        client.connect(wsUri);
    };

    var start = function () {
        if (connecting) {
            return;
        }
        if (client.isConnected()) {
            client.stop();
        }

        wantToBeConnected = true;
        connecting = true;
        connect();
    };
    var stop = function () {
        wantToBeConnected = false;
        if (client.isConnected()) {
            client.stop();
        }
        if (client.isConnected() || connecting) {
            client.disconnect();
        }
        statusBlock.text('Disconnected');
    };
    var setInterval = function () {
        client.setInterval(self.getInterval());
    };

    this.init = function () {
        $(srvPref$('start-btn')).on('click', start);
        $(srvPref$('stop-btn')).on('click', stop);
        $(srvPref$('interval-btn')).on('click', setInterval);
        $(srvPref$('options-btn')).on('click', function () {
            $(srvPref$('options')).toggle();
            var t = $(this);
            if (t.text() == 'Options') {
                t.text('Hide options');
            } else {
                t.text('Options');
            }
        });
        $(srvPref$('name-btn')).on('click', function () {
            var newName = prompt('Enter new server name', self.getName());
            self.setName(newName);
        });

        statusBlock = $(srvPref$('status'));

        if (initialConfig.autoStart) {
            start();
        }
    };

    this.uninit = function () {
        stop();
    };

    this.getName = function () {
        return $(srvPref$('name')).text();
    };
    this.setName = function (value) {
        $(srvPref$('name')).text(value);
    };

    this.getHost = function () {
        return $(srvPref$('host')).val();
    };
    this.setHost = function (value) {
        $(srvPref$('host')).val(value);
    };

    this.getInterval = function () {
        return parseFloat($(srvPref$('interval')).val());
    };
    this.setInterval = function (value) {
        $(srvPref$('interval')).val(value);
    };

    this.getToken = function () {
        return $(srvPref$('token')).val();
    };
    this.setToken = function (value) {
        $(srvPref$('token')).val(value);
    };

    this.getAutoStart = function () {
        return $(srvPref$('auto-start')).is(':checked');
    };
    this.setAutoStart = function (value) {
        $(srvPref$('auto-start')).attr('checked', 'checked');
    };

    this.getCurrentConfig = function () {
        return {
            id: initialConfig.id,
            name: this.getName(),
            host: this.getHost(),
            interval: this.getInterval(),
            autoStart: this.getAutoStart()
        };
    };
};<commit_msg>Monitoring client: fix forgotten token key in server current config<commit_after>if (typeof(RtStat) == "undefined") {
    RtStat = {};
}
RtStat.Monitoring = function (config) {
    var self = this;
    var columns = [];

    $('#edit-mode-btn').on('click', function () {
       $('body').toggleClass('edit-mode-off').toggleClass('edit-mode-on');
    });
    $('#add-col-btn').on('click', function () {
        var newCol = new RtStat.Monitoring.Column(columns.length);
        columns.push(newCol);
        $('#wrapper').append(newCol.getBlock());
        newCol.init();
    });
    $('#get-config-btn').click(function () {
        var txId = 'tx-' + RtStat.Monitoring.generateRandomString();

        var source = $("#config-dialog-template").html();
        var template = Handlebars.compile(source);
        $.modal($(template({
            title: 'Current config',
            textareaId: txId,
            needButton: false
        })));

        $('#' + txId).val(JSON.stringify(self.getCurrentConfig(), undefined, 2));
    });
    $('#setup-btn').click(function () {
        var txId = 'tx-' + RtStat.Monitoring.generateRandomString();
        var btnId = 'btn-' + RtStat.Monitoring.generateRandomString();

        var source = $("#config-dialog-template").html();
        var template = Handlebars.compile(source);
        var m = $.modal($(template({
            title: 'Setup from config',
            textareaId: txId,
            buttonId: btnId,
            needButton: true
        })));

        $('#' + btnId).click(function () {
            try {
                var newConfig = JSON.parse($('#' + txId).val());
            } catch (e) {
                console.error("JSON parsing error:", e);
                alert('JSON can not be parsed (perhaps it\'s not valid). Check developer console for details.');
                return;
            }
            self.setup(newConfig);
            m.close();
        });
    });

    var removeAllColumns = function () {
        for (var i in columns) {
            if (!columns.hasOwnProperty(i)) {
                continue;
            }
            columns[i].remove();
        }
    };

    this.setup = function (config) {
        removeAllColumns();

        for (var i = 0; i < config.columns.length; i++) {
            columns[i] = new RtStat.Monitoring.Column(i);
            $('#wrapper').append(columns[i].getBlock());
            columns[i].init();

            for (var j = 0; j < config.columns[i].servers.length; j++) {
                var serverConfig = config.columns[i].servers[j];
                var server = new RtStat.Monitoring.Server(serverConfig);
                columns[i].addServer(server);
            }
        }
    };

    this.getCurrentConfig = function () {
        var currentConfig = {columns: []};
        for (var i in columns) {
            if (!columns.hasOwnProperty(i)) {
                continue;
            }
            var colConfig = {
                servers: []
            };

            var servers = columns[i].getServers();
            for (var s in servers) {
                if (!servers.hasOwnProperty(s)) {
                    continue;
                }
                colConfig.servers.push(servers[s].getCurrentConfig());
            }

            currentConfig.columns.push(colConfig);
        }

        return currentConfig;
    };

    this.setup(config);
};

RtStat.Monitoring.generateRandomString = function () {
    return Math.floor((Math.random()) * Math.pow(10, 50)).toString(36);
};

RtStat.Monitoring.init = function (config) {
    var e = new RtStat.Monitoring(config);
};

RtStat.Monitoring.Column = function (index) {
    var self = this;
    var block = (function () {
        var source = $("#col-template").html();
        var template = Handlebars.compile(source);
        return $(template({colIndex: index}));
    })();

    var servers = [];

    this.getBlock = function () {
        return block;
    };

    this.remove = function () {
        for (var i = 0; i < servers.length; i++) {
            this.removeServer(servers[i]);
        }
        block.remove();
    };

    this.init = function () {
        $('#col-' + index + '-remove-btn').click(function () {
            self.remove();
        });
        $('#col-' + index + '-add-server-btn').click(function () {
            self.addServer(new RtStat.Monitoring.Server({
                id: RtStat.Monitoring.generateRandomString(),
                name: 'New Server',
                host: 'localhost',
                interval: 1.5,
                autoStart: false
            }));
        });
    };

    this.addServer = function (server) {
        block.find('.servers').append(server.getBlock());
        servers.push(server);
        server.init();

        block.find('.server-remove-btn').click(function () {
            self.removeServer(server);
        });
    };

    this.removeServer = function (server) {
        server.uninit();
        server.getBlock().remove();
        servers.splice(servers.indexOf(server));
    };

    this.getServers = function () {
        return servers.slice(0);
    };
};

RtStat.Monitoring.Server = function (initialConfig) {
    var self = this;

    var block = (function () {
        var source = $("#server-template").html();
        var template = Handlebars.compile(source);
        return block = $(template({server: initialConfig}));
    })();
    if (initialConfig.autoStart) {
        block.find('.auto-start').prop('checked', true);
    }

    this.getBlock = function () {
        return block;
    };

    var srvPref = function (id) {
        return "server-" + initialConfig.id + "-" + id;
    };
    var srvPref$ = function (id) {
        return "#" + srvPref(id);
    };

    var cpuStat = function (allCpus) {
        var typesCpu = [
            {key: 'user', color: "rgb(60,163,23)"},
            {key: 'system', color: "rgb(247,187,22)"},
            {key: 'iowait', color: "rgb(232,23,23)"}
        ];
        graphInfo(allCpus, typesCpu, 'processors', 'processors-cpuX-template', 'processors', 0.90, function (data) { return data.usage;},
            function (data, element) { return data[element.key];});
    };

    var memInfo = function (meminfo) {
        var typesMemory = [
            {key: 'apps', color: "rgb(33,145,29)"},
            {key: 'buffers', color: "rgb(160,20,0)"},
            {key: 'cached', color: "rgb(242,143,12)"},
            {key: 'swapCached', color: "rgb(232,23,23)"}
        ];
        graphInfo({memory: meminfo.memory}, typesMemory, '', '', '', 0.85, function (data) {return (data.apps + data.buffers) / data.total;},
            function (data, element) {return data[element.key] / data.total;});

        var typesSwap = [
            {key: 'used', color: "rgb(232,23,23)"}
        ];
        graphInfo({swap: meminfo.swap}, typesSwap, '', '', '', 0.10, function (data) {return data.used / data.total;},
            function (data, element) {return data[element.key] / data.total;});
    };

    var graphInfo = function (dataset, types, blockSelector, blockTemplateSelector, appendToSelector, warnLimit,
                        dataGetOverallUsageValueClb, dataGetElementUsageValueClb) {
        for (var key in dataset) {
            if (!dataset.hasOwnProperty(key)) {
                continue;
            }

            var data = dataset[key];

            var compiledBlockSelector = (blockSelector ? blockSelector + '-' : '') + key + '-canvas';
            var block = $(srvPref$(compiledBlockSelector));
            if (block.length < 1) {
                var template = Handlebars.compile($(srvPref$(blockTemplateSelector)).html());
                var newEl =  $(template({cpuId: key}));
                $(srvPref$(appendToSelector)).append(newEl);
                block = newEl.find(srvPref$(compiledBlockSelector));
            }

            var valueField = block.parent().find('span.value');
            if (valueField) {
                var value = dataGetOverallUsageValueClb(data);
                valueField.text(Math.round(value * 1000) / 10 + '%');
                if (value >= warnLimit) {
                    valueField.addClass('warning');
                }
                else {
                    valueField.removeClass('warning');
                }
            }

            var canvas = block.get(0);
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            var lastX = 0;
            var width = canvas.width;
            types.forEach(function (element) {
                var value = dataGetElementUsageValueClb(data, element);
                ctx.fillStyle = element.color;
                var segmentWidth = Math.round(value * width);
                if (segmentWidth > 1) {
                    ctx.fillRect(lastX + 1, 1, segmentWidth - 1, canvas.height - 2);
                    lastX += segmentWidth;
                }
            });
        }
    };

    var uptime = function (uptime) {
        for (var key in uptime) {
            if (!uptime.hasOwnProperty(key)) {
                continue;
            }
            $(srvPref$('uptime-' + key)).text(uptime[key]);
        }
        $(srvPref$('title')).html( '[ <small>' + uptime.la1 + '</small> ' + uptime.la5 + ' ]');
    };

    var processes = function (processes) {
        for (var key in processes) {
            if (!processes.hasOwnProperty(key)) {
                continue;
            }
            $(srvPref$('processes-' + key)).text(processes[key]);
        }
    };

    var statusBlock; // will be assigned later in init()
    var wantToBeConnected = false;
    var connecting = false;
    var client = new RtStat.WebSocketClient({
        onCmdCallback: function (cmd, args) {
            if (cmd == 'push') {
                if (args.length < 1) {
                    console.log('Error: push command without arguments');
                }
                var msg = args[0];
                var jsonResponce = JSON.parse(msg);
                cpuStat(jsonResponce.cpu_stat);
                memInfo(jsonResponce.meminfo);
                uptime(jsonResponce.uptime);
                processes(jsonResponce.processes);
            }
        },
        onOpenCallback: function () {
            connecting = false;
            statusBlock.text('Connected');
            var token = self.getToken();
            if (token) {
                client.authenticate(token);
            }
            setInterval();
            client.start();
        },
        onErrorCallback: function (data) {
            statusBlock.text('Error. Disconnecting...');
        },
        onCloseCallback: function () {
            if (wantToBeConnected) {
                statusBlock.text('Disconnected. Trying to connect...');
                setTimeout(function() {
                    if (wantToBeConnected) {
                        connect();
                    } else {
                        statusBlock.text('Disconnected');
                        connecting = false;
                    }
                }, self.getInterval() * 1000);
            } else {
                statusBlock.text('Disconnected');
                connecting = false;
            }
        }
    });

    var connect = function () {
        statusBlock.text('Connecting...');

        var wsUri = self.getHost();
        var hostMatch = wsUri.match(/^((ws|wss):\/\/)?([a-zA-Z0-9\-\.]{1,63})(:(\d{1,5}))?(\/.*)?$/i);
        if (hostMatch) {
            wsUri = hostMatch[3]; // host
            if (hostMatch[2]) { // protocol
                wsUri = hostMatch[1] + wsUri;
            } else {
                wsUri = 'ws://' + wsUri;
            }
            if (hostMatch[5]) { // port
                wsUri += ":" + hostMatch[5];
            } else {
                wsUri += ":8000";
            }
            if (hostMatch[6]) { // local part
                wsUri += hostMatch[6];
            } else {
                wsUri += "/";
            }
        } else {
            wsUri = "ws://localhost:8000/";
        }

        client.connect(wsUri);
    };

    var start = function () {
        if (connecting) {
            return;
        }
        if (client.isConnected()) {
            client.stop();
        }

        wantToBeConnected = true;
        connecting = true;
        connect();
    };
    var stop = function () {
        wantToBeConnected = false;
        if (client.isConnected()) {
            client.stop();
        }
        if (client.isConnected() || connecting) {
            client.disconnect();
        }
        statusBlock.text('Disconnected');
    };
    var setInterval = function () {
        client.setInterval(self.getInterval());
    };

    this.init = function () {
        $(srvPref$('start-btn')).on('click', start);
        $(srvPref$('stop-btn')).on('click', stop);
        $(srvPref$('interval-btn')).on('click', setInterval);
        $(srvPref$('options-btn')).on('click', function () {
            $(srvPref$('options')).toggle();
            var t = $(this);
            if (t.text() == 'Options') {
                t.text('Hide options');
            } else {
                t.text('Options');
            }
        });
        $(srvPref$('name-btn')).on('click', function () {
            var newName = prompt('Enter new server name', self.getName());
            self.setName(newName);
        });

        statusBlock = $(srvPref$('status'));

        if (initialConfig.autoStart) {
            start();
        }
    };

    this.uninit = function () {
        stop();
    };

    this.getName = function () {
        return $(srvPref$('name')).text();
    };
    this.setName = function (value) {
        $(srvPref$('name')).text(value);
    };

    this.getHost = function () {
        return $(srvPref$('host')).val();
    };
    this.setHost = function (value) {
        $(srvPref$('host')).val(value);
    };

    this.getInterval = function () {
        return parseFloat($(srvPref$('interval')).val());
    };
    this.setInterval = function (value) {
        $(srvPref$('interval')).val(value);
    };

    this.getToken = function () {
        return $(srvPref$('token')).val();
    };
    this.setToken = function (value) {
        $(srvPref$('token')).val(value);
    };

    this.getAutoStart = function () {
        return $(srvPref$('auto-start')).is(':checked');
    };
    this.setAutoStart = function (value) {
        $(srvPref$('auto-start')).attr('checked', 'checked');
    };

    this.getCurrentConfig = function () {
        var currentConfig = {
            id: initialConfig.id,
            name: this.getName(),
            host: this.getHost(),
            interval: this.getInterval(),
            autoStart: this.getAutoStart()
        };

        var token = this.getToken();
        if (token) {
            currentConfig.token = token;
        }

        return currentConfig;
    };
};<|endoftext|>


<commit_before>/* jshint indent: 4 */

(function($) {

    var utils = {

        onPage: function(regex, fn) {
          if (location.pathname.match(regex)) fn();
        },

        hasAnyRole: function(/*roles, cb*/) {
          var roles = [].slice.call(arguments, 0);
          var cb = roles.pop();
          for (var i = 0; i < arguments.length; i++) {
            if (ENV.current_user_roles.indexOf(arguments[i]) !== -1) {
              return cb(true);
            }
          }
          return cb(false);
        },

        isUser: function(id, cb) {
          cb(ENV.current_user_id == id);
        },

        onElementRendered: function(selector, cb, _attempts) {
          var el = $(selector);
          _attempts = ++_attempts || 1;
          if (el.length) return cb(el);
          if (_attempts == 60) return;
          setTimeout(function() {
            onElementRendered(selector, cb, _attempts);
          }, 250);
        }

    }

    // header rainbow
    $('#header').append('
');

    // help links
    var helpHtml = [
        '
',
        '<select class="sfu_help_links">',
        '<option value="">Help</option>',
        '<option value="https://canvas.sfu.ca/courses/14504">Help for Students</option>',
        '<option value="https://canvas.sfu.ca/courses/14686">Help for Instructors</option>',
        '
'
    ].join('');
    $('#topbar .logout').before(helpHtml);
    $('#topbar .sfu_help_links').on('change', function(ev) {
        if (this.value) {
            window.location = this.value;
        }
    });

    // sfu logo in footer
    $('footer').html('').show();

    // handle no-user case
    if ($('#header').hasClass('no-user')) {
        // add in a dummy #menu div
        $('#header-inner').append('

');
        // remove the register link
        $('#header.no-user a[href="/register"]').parent().remove()
    }

    // hijack Start New Course button (CANVAS-192)
    // first, cache the original event handler and disable it
    function hijackStartNewCourseButton() {
        if (!jQuery._data(document, "events")) {
            // bit of a hack for IE which seems to randomly not have the events
            // loaded by the time this script loads
            window.setTimeout(hijackStartNewCourseButton, 100);
        } else {
            var eventlist = jQuery._data( document, "events" ).click,
                targetSelector = '.element_toggler[aria-controls]',
                origHandler, e;
            // cache the handler
            for (var i = 0; i < eventlist.length; i++) {
                e = eventlist[i];
                if (e.selector === targetSelector) {
                    origHandler = e.handler;
                }
            }
            if (origHandler) {
                // remove the handler, and add our own
                $(document).off('click change', targetSelector).on('click change', targetSelector, function(event) {
                    if (this.id === 'start_new_course') {
                        event.stopImmediatePropagation();
                        window.location = '/sfu/course/new';
                    } else {
                        origHandler.call(this, event);
                    }
                });
            }
        }
    }
    $(document).ready(function() {
        hijackStartNewCourseButton();
    });

    // END CANVAS-192

    // FIX (temporary) for no-flash browsers to upload files using the Files tool
    var hasFlash = false;
    try {
        if (new ActiveXObject('ShockwaveFlash.ShockwaveFlash')) hasFlash = true;
    } catch(e) {
        if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
    }
    if (!hasFlash) {
        // remove the invisible element that is blocking the "Add File" link
        $('#swfupload_holder').hide();
    }
    // END no-flash upload FIX

    // Add copyright compliance notice under the Publish Course button
    utils.onPage(/^\/courses\/\d+$/, function() {
        // The Publish Course button ID attribute contains the course ID
        var $publishButton = $('#' + location.pathname.replace('/courses/', 'edit_course_'));
        var $readMoreLink = $('Read more.');
        var $disclaimer = $('').css('border', 'none');
        $("
I confirm that the use of copyright protected materials in this course complies with Canada's Copyright Act and SFU Policy R30.04 - Copyright Compliance and Administration.
")
            .append($readMoreLink)
            .insertAfter($publishButton);
        // Use a modal dialog to display the full disclaimer
        $('<form id="copyright_dialog" title="Copyright Disclaimer">')
            .attr('data-turn-into-dialog', '{"width":600,"height":500,"modal":true}')
            .append($disclaimer)
            .hide()
            .appendTo('body');
    });

    // CANVAS-244 1/2 Add enrollment term to course autocomplete
    utils.onPage(/accounts\/\d+(\/courses)?$/, function () {
        // Override the method that renders the autocomplete item
        var autocompleteData = $('#course_name').data('ui-autocomplete');
        if (autocompleteData) {
            autocompleteData._renderItem = function (ul, item) {
                return $('
')
                    .append('
' + item.label + '

' + item.term + '
')
                    .appendTo(ul);
            };
        }
    });
    // END CANVAS-244 1/2

    // Fixes for Import Content page only
    utils.onPage(/courses\/\d+\/content_migrations/, function() {
        // The fixes are for elements that are dynamically generated when a specific XHR call completes
        $(document).ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
            if (ajaxOptions.url && ajaxOptions.url.match(/users\/\d+\/manageable_courses/)) {
                // Alphabetize course drop-down list, by sorting <option>s inside each <optgroup>
                // NOTE: This is no longer needed when XHR results are pre-sorted by Canvas
                $('optgroup', $('#courseSelect')).each(function (i, termGroup) {
                    $('option', termGroup)
                        .sort(function (a, b) { return $(a).text().localeCompare($(b).text()); })
                        .appendTo(termGroup);
                });
                // END Alphabetize course drop-down list

                // CANVAS-244 2/2 Add enrollment term to course autocomplete
                // Override the method that renders the autocomplete item
                var autocompleteData = $('#courseSearchField').data('ui-autocomplete');
                if (autocompleteData) {
                    autocompleteData._renderItem = function (ul, item) {
                        return $('
')
                            .append('
' + item.label + '

' + item.term + '
')
                            .appendTo(ul);
                    };
                }
                // END CANVAS-244 2/2
            }
        });
    });

    // Fix for the new conversations page - toolbar renders underneath the rainbow bar
    utils.onPage(/conversations/, function() {
        // are we on the new conversations page?
        if (ENV.CONVERSATIONS && (ENV.CONVERSATIONS.ATTACHMENTS_FOLDER_ID && !ENV.hasOwnProperty('CONTEXT_ACTION_SOURCE'))) {
            jQuery('div#main').css('top', '92px');
        }
    });

    // CANVAS-246 Create button that links to the Start a New Ad Hoc Space form (only on these pages: / and /courses)
    utils.onPage(/^\/(courses)?$/, function () {
        // Add the button right after the existing Start a New Course button
        var addAdHocButton = function () {
            var $courseButton = $('#start_new_course');
            var $adhocButton = $courseButton.clone();
            $adhocButton
                .text('Start a New Ad Hoc Space')
                .attr('id', 'start_new_adhoc')
                .attr('aria-controls', 'new_adhoc_form')
                .insertAfter($courseButton)
                .on('click', function () {
                    window.location = '/sfu/adhoc/new';
                });
        }

        // If the button is not there yet, it's likely still being loaded in the sidebar.
        // Wait for it to complete, and then add the button. This is meant for the home page.
        if ($('#start_new_course').length == 0) {
            $(document).ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
                if (ajaxOptions.url && ajaxOptions.url.match(/dashboard-sidebar/)) {
                    addAdHocButton();
                }
            });
        } else {
            addAdHocButton();
        }
    });
    // END CANVAS-246
})(jQuery);

// google analytics
if (window.location.hostname && 'canvas.sfu.ca' === window.location.hostname) {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-36473171-1']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
}

<commit_msg>Remove CANVAS-244 JavaScript stopgap<commit_after>/* jshint indent: 4 */

(function($) {

    var utils = {

        onPage: function(regex, fn) {
          if (location.pathname.match(regex)) fn();
        },

        hasAnyRole: function(/*roles, cb*/) {
          var roles = [].slice.call(arguments, 0);
          var cb = roles.pop();
          for (var i = 0; i < arguments.length; i++) {
            if (ENV.current_user_roles.indexOf(arguments[i]) !== -1) {
              return cb(true);
            }
          }
          return cb(false);
        },

        isUser: function(id, cb) {
          cb(ENV.current_user_id == id);
        },

        onElementRendered: function(selector, cb, _attempts) {
          var el = $(selector);
          _attempts = ++_attempts || 1;
          if (el.length) return cb(el);
          if (_attempts == 60) return;
          setTimeout(function() {
            onElementRendered(selector, cb, _attempts);
          }, 250);
        }

    }

    // header rainbow
    $('#header').append('
');

    // help links
    var helpHtml = [
        '
',
        '<select class="sfu_help_links">',
        '<option value="">Help</option>',
        '<option value="https://canvas.sfu.ca/courses/14504">Help for Students</option>',
        '<option value="https://canvas.sfu.ca/courses/14686">Help for Instructors</option>',
        '
'
    ].join('');
    $('#topbar .logout').before(helpHtml);
    $('#topbar .sfu_help_links').on('change', function(ev) {
        if (this.value) {
            window.location = this.value;
        }
    });

    // sfu logo in footer
    $('footer').html('').show();

    // handle no-user case
    if ($('#header').hasClass('no-user')) {
        // add in a dummy #menu div
        $('#header-inner').append('

');
        // remove the register link
        $('#header.no-user a[href="/register"]').parent().remove()
    }

    // hijack Start New Course button (CANVAS-192)
    // first, cache the original event handler and disable it
    function hijackStartNewCourseButton() {
        if (!jQuery._data(document, "events")) {
            // bit of a hack for IE which seems to randomly not have the events
            // loaded by the time this script loads
            window.setTimeout(hijackStartNewCourseButton, 100);
        } else {
            var eventlist = jQuery._data( document, "events" ).click,
                targetSelector = '.element_toggler[aria-controls]',
                origHandler, e;
            // cache the handler
            for (var i = 0; i < eventlist.length; i++) {
                e = eventlist[i];
                if (e.selector === targetSelector) {
                    origHandler = e.handler;
                }
            }
            if (origHandler) {
                // remove the handler, and add our own
                $(document).off('click change', targetSelector).on('click change', targetSelector, function(event) {
                    if (this.id === 'start_new_course') {
                        event.stopImmediatePropagation();
                        window.location = '/sfu/course/new';
                    } else {
                        origHandler.call(this, event);
                    }
                });
            }
        }
    }
    $(document).ready(function() {
        hijackStartNewCourseButton();
    });

    // END CANVAS-192

    // FIX (temporary) for no-flash browsers to upload files using the Files tool
    var hasFlash = false;
    try {
        if (new ActiveXObject('ShockwaveFlash.ShockwaveFlash')) hasFlash = true;
    } catch(e) {
        if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
    }
    if (!hasFlash) {
        // remove the invisible element that is blocking the "Add File" link
        $('#swfupload_holder').hide();
    }
    // END no-flash upload FIX

    // Add copyright compliance notice under the Publish Course button
    utils.onPage(/^\/courses\/\d+$/, function() {
        // The Publish Course button ID attribute contains the course ID
        var $publishButton = $('#' + location.pathname.replace('/courses/', 'edit_course_'));
        var $readMoreLink = $('Read more.');
        var $disclaimer = $('').css('border', 'none');
        $("
I confirm that the use of copyright protected materials in this course complies with Canada's Copyright Act and SFU Policy R30.04 - Copyright Compliance and Administration.
")
            .append($readMoreLink)
            .insertAfter($publishButton);
        // Use a modal dialog to display the full disclaimer
        $('<form id="copyright_dialog" title="Copyright Disclaimer">')
            .attr('data-turn-into-dialog', '{"width":600,"height":500,"modal":true}')
            .append($disclaimer)
            .hide()
            .appendTo('body');
    });

    // Fixes for Import Content page only
    utils.onPage(/courses\/\d+\/content_migrations/, function() {
        // The fixes are for elements that are dynamically generated when a specific XHR call completes
        $(document).ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
            if (ajaxOptions.url && ajaxOptions.url.match(/users\/\d+\/manageable_courses/)) {
                // Alphabetize course drop-down list, by sorting <option>s inside each <optgroup>
                // NOTE: This is no longer needed when XHR results are pre-sorted by Canvas
                $('optgroup', $('#courseSelect')).each(function (i, termGroup) {
                    $('option', termGroup)
                        .sort(function (a, b) { return $(a).text().localeCompare($(b).text()); })
                        .appendTo(termGroup);
                });
                // END Alphabetize course drop-down list
            }
        });
    });

    // Fix for the new conversations page - toolbar renders underneath the rainbow bar
    utils.onPage(/conversations/, function() {
        // are we on the new conversations page?
        if (ENV.CONVERSATIONS && (ENV.CONVERSATIONS.ATTACHMENTS_FOLDER_ID && !ENV.hasOwnProperty('CONTEXT_ACTION_SOURCE'))) {
            jQuery('div#main').css('top', '92px');
        }
    });

    // CANVAS-246 Create button that links to the Start a New Ad Hoc Space form (only on these pages: / and /courses)
    utils.onPage(/^\/(courses)?$/, function () {
        // Add the button right after the existing Start a New Course button
        var addAdHocButton = function () {
            var $courseButton = $('#start_new_course');
            var $adhocButton = $courseButton.clone();
            $adhocButton
                .text('Start a New Ad Hoc Space')
                .attr('id', 'start_new_adhoc')
                .attr('aria-controls', 'new_adhoc_form')
                .insertAfter($courseButton)
                .on('click', function () {
                    window.location = '/sfu/adhoc/new';
                });
        }

        // If the button is not there yet, it's likely still being loaded in the sidebar.
        // Wait for it to complete, and then add the button. This is meant for the home page.
        if ($('#start_new_course').length == 0) {
            $(document).ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
                if (ajaxOptions.url && ajaxOptions.url.match(/dashboard-sidebar/)) {
                    addAdHocButton();
                }
            });
        } else {
            addAdHocButton();
        }
    });
    // END CANVAS-246
})(jQuery);

// google analytics
if (window.location.hostname && 'canvas.sfu.ca' === window.location.hostname) {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-36473171-1']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
}

<|endoftext|>


<commit_before>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Nav from './Nav';
import 'whatwg-fetch';

const API_URL = 'https://hotel-project-ajboyle.c9users.io/api/locations/';
//const API_URL = 'https://ajbhotelpage.herokuapp.com/api/locations/';
const API_HEADERS = {
    'Content-Type': 'application/json'
};

class App extends Component {
    constructor(){
        super();
        this.getHotelsSearch = this.getHotelsSearch.bind(this);
        this.getHotel = this.getHotel.bind(this);
        this.clearHotel = this.clearHotel.bind(this);
        this.clearHotelsSearch = this.clearHotelsSearch.bind(this);

        this.state = {
            hotel: [],
            hotelsSearch: [],
            city: "",
            checkin: "",
            checkout: "",
            showHotel: false
        };

    }
    getHotelsSearch(city, checkin, checkout){
        let urlRemainder = city + '/hotels?checkin=' + checkin + '&checkout=' + checkout;

        fetch(API_URL + urlRemainder, {headers: API_HEADERS})
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                hotelsSearch: responseData,
                city: city,
                checkin: checkin,
                checkout: checkout,

            });
        })
        .catch((error) => {
            console.log('Error fetching and parsing data hotels', error);
        });
    }
    getHotel(hotelId){
        fetch(API_URL + this.state.city + "/hotels/" + hotelId + "?checkin=" + this.state.checkin + "&checkout=" + this.state.checkout, {headers: API_HEADERS})
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                hotel: responseData,
                showHotel: true
            });
        })
        .catch((error) => {

            console.log('Error fetching and parsing data hotel ', error);
        });
    }
    sortPriceLow(){

    }
    clearHotel(){
        this.setState({
            hotel: []
        });
    }
    clearHotelsSearch(){
        this.setState({
            hotelsSearch: []
        });
    }
    render(){
        return(

HotelsLite.com

The Limited Choice in Hotels!

                <Nav taskCallbacks={{
                    getHotel: this.getHotel,
                    getHotelsSearch: this.getHotelsSearch,
                    clearHotel: this.clearHotel,
                    clearHotelsSearch: this.clearHotelsSearch }}

                    hotelData={{
                        hotel: this.state.hotel,
                        hotelsSearch: this.state.hotelsSearch,
                        city: this.state.city,
                        checkin: this.state.checkin,
                        checkout: this.state.checkout,
                        showHotel: this.state.showHotel
                    }}
                />

        );
    }
}

ReactDOM.render(<App />, document.getElementById("app"));<commit_msg>updated url<commit_after>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Nav from './Nav';
import 'whatwg-fetch';

//const API_URL = 'https://hotel-project-ajboyle.c9users.io/api/locations/';
const API_URL = 'https://ajbhotelpage.herokuapp.com/api/locations/';
const API_HEADERS = {
    'Content-Type': 'application/json'
};

class App extends Component {
    constructor(){
        super();
        this.getHotelsSearch = this.getHotelsSearch.bind(this);
        this.getHotel = this.getHotel.bind(this);
        this.clearHotel = this.clearHotel.bind(this);
        this.clearHotelsSearch = this.clearHotelsSearch.bind(this);

        this.state = {
            hotel: [],
            hotelsSearch: [],
            city: "",
            checkin: "",
            checkout: "",
            showHotel: false
        };

    }
    getHotelsSearch(city, checkin, checkout){
        let urlRemainder = city + '/hotels?checkin=' + checkin + '&checkout=' + checkout;

        fetch(API_URL + urlRemainder, {headers: API_HEADERS})
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                hotelsSearch: responseData,
                city: city,
                checkin: checkin,
                checkout: checkout,

            });
        })
        .catch((error) => {
            console.log('Error fetching and parsing data hotels', error);
        });
    }
    getHotel(hotelId){
        fetch(API_URL + this.state.city + "/hotels/" + hotelId + "?checkin=" + this.state.checkin + "&checkout=" + this.state.checkout, {headers: API_HEADERS})
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                hotel: responseData,
                showHotel: true
            });
        })
        .catch((error) => {

            console.log('Error fetching and parsing data hotel ', error);
        });
    }
    sortPriceLow(){

    }
    clearHotel(){
        this.setState({
            hotel: []
        });
    }
    clearHotelsSearch(){
        this.setState({
            hotelsSearch: []
        });
    }
    render(){
        return(

HotelsLite.com

The Limited Choice in Hotels!

                <Nav taskCallbacks={{
                    getHotel: this.getHotel,
                    getHotelsSearch: this.getHotelsSearch,
                    clearHotel: this.clearHotel,
                    clearHotelsSearch: this.clearHotelsSearch }}

                    hotelData={{
                        hotel: this.state.hotel,
                        hotelsSearch: this.state.hotelsSearch,
                        city: this.state.city,
                        checkin: this.state.checkin,
                        checkout: this.state.checkout,
                        showHotel: this.state.showHotel
                    }}
                />

        );
    }
}

ReactDOM.render(<App />, document.getElementById("app"));<|endoftext|>


<commit_before>import React, { useState } from "react";
import PubSub from 'pubsub-js'
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import Tooltip from '@material-ui/core/Tooltip';
import makeStyles from "@material-ui/core/styles/makeStyles";
import { Box, Link, Popover, Typography } from "@material-ui/core";

const useMenuStyles = makeStyles((theme) => ({
    menuButton: {
        marginLeft: theme.spacing(2),
    },
}));

export function ApplicationMenu() {
    const classes = useMenuStyles();
    const [menu, setMenu] = useState(null);
    const [anchorEl, setAnchorEl] = React.useState(null);

    const handleAbout = (event) => {
        setMenu(null);
        console.info(`Show About`)
        setAnchorEl(event.currentTarget);
    };

    const handleNewDiagram = (event) => {
        setMenu(null);
        console.info(`New Diagram`)

        var shouldDelete = confirm('Do you really want to clear the current diagram?') //eslint-disable-line
        if (shouldDelete) {
            PubSub.publish('diagram.NewDiagram')
        }
    };

    const handleCloseAbout = () => {
        console.info(`Hide About`)
        setAnchorEl(null);
    };

    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;

    return (
        <>
            <Tooltip title="Customize and control">
                <IconButton
                    edge="start"
                    className={classes.menuButton}
                    color="inherit"
                    onClick={e => setMenu(e.currentTarget)}
                >
                    <MenuIcon />
                </IconButton>
            </Tooltip>
            <Menu
                anchorEl={menu}
                keepMounted
                open={Boolean(menu)}
                onClose={() => setMenu(null)}
                PaperProps={{
                    // style: {
                    //     backgroundColor: "#333333"
                    // },
                }}
            >

                <MenuItem onClick={handleNewDiagram}>New Diagram</MenuItem>
                <MenuItem onClick={handleAbout}>About</MenuItem>

            </Menu>
            <Popover
                id={id}
                open={open}
                anchorEl={anchorEl}
                onClose={handleCloseAbout}
                anchorReference="anchorPosition"
                anchorPosition={{ top: 200, left: 400 }}
                anchorOrigin={{
                    vertical: 'center',
                    horizontal: 'center',
                }}
                transformOrigin={{
                    vertical: 'center',
                    horizontal: 'center',
                }}
            >
                <Box style={{ width: 400, height: 200, padding: 20 }}>
                    <Typography variant="h5">Dependinator</Typography>
                    <Typography >
                        Early preview of a tool for visualizing software architecture inspired by map tools for
                        navigation and the "<Link href="https://c4model.com" target="_blank">C4 Model</Link>"by Simon Brown.

                    </Typography>
                </Box>

            </Popover>
        </>
    )
}

<commit_msg>Start to implement print support<commit_after>import React, { useState } from "react";
import PubSub from 'pubsub-js'
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import Tooltip from '@material-ui/core/Tooltip';
import makeStyles from "@material-ui/core/styles/makeStyles";
import { Box, Link, Popover, Typography } from "@material-ui/core";

const useMenuStyles = makeStyles((theme) => ({
    menuButton: {
        marginLeft: theme.spacing(2),
    },
}));

export function ApplicationMenu() {
    const classes = useMenuStyles();
    const [menu, setMenu] = useState(null);
    const [anchorEl, setAnchorEl] = React.useState(null);

    const handleAbout = (event) => {
        setMenu(null);
        console.info(`Show About`)
        setAnchorEl(event.currentTarget);
    };

    const handleNewDiagram = (event) => {
        setMenu(null);
        console.info(`New Diagram`)

        var shouldDelete = confirm('Do you really want to clear the current diagram?') //eslint-disable-line
        if (shouldDelete) {
            PubSub.publish('diagram.NewDiagram')
        }
    };

    function ImagetoPrint(source) {
        return "\n" +
            " Text";
    }

    const handleExport = (event) => {
        console.log('export')
        setMenu(null);
        const tab = window.open("export:diagram", "_blank");
        tab.document.open();
        tab.document.write(ImagetoPrint());
    }

    const handleCloseAbout = () => {
        console.info(`Hide About`)
        setAnchorEl(null);
    };

    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;

    return (
        <>
            <Tooltip title="Customize and control">
                <IconButton
                    edge="start"
                    className={classes.menuButton}
                    color="inherit"
                    onClick={e => setMenu(e.currentTarget)}
                >
                    <MenuIcon />
                </IconButton>
            </Tooltip>
            <Menu
                anchorEl={menu}
                keepMounted
                open={Boolean(menu)}
                onClose={() => setMenu(null)}
                PaperProps={{
                    // style: {
                    //     backgroundColor: "#333333"
                    // },
                }}
            >

                <MenuItem onClick={handleNewDiagram}>New Diagram</MenuItem>
                <MenuItem onClick={handleExport}>Export Diagram</MenuItem>
                <MenuItem onClick={handleAbout}>About</MenuItem>

            </Menu>
            <Popover
                id={id}
                open={open}
                anchorEl={anchorEl}
                onClose={handleCloseAbout}
                anchorReference="anchorPosition"
                anchorPosition={{ top: 200, left: 400 }}
                anchorOrigin={{
                    vertical: 'center',
                    horizontal: 'center',
                }}
                transformOrigin={{
                    vertical: 'center',
                    horizontal: 'center',
                }}
            >
                <Box style={{ width: 400, height: 200, padding: 20 }}>
                    <Typography variant="h5">Dependinator</Typography>
                    <Typography >
                        Early preview of a tool for visualizing software architecture inspired by map tools for
                        navigation and the "<Link href="https://c4model.com" target="_blank">C4 Model</Link>"by Simon Brown.

                    </Typography>
                </Box>

            </Popover>
        </>
    )
}

<|endoftext|>


<commit_before>/*
 * File: app/view/CsnClusterForm.js
 *
 * This file was generated by Sencha Architect version 2.2.2.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 4.2.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 4.2.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('C.view.CsnClusterForm', {
	extend: 'Ext.form.Panel',

	bodyPadding: 10,
	title: 'My Form',

	initComponent: function() {
		var me = this;

		Ext.applyIf(me, {
			items: [
				{
					xtype: 'fieldcontainer',
					formBind: false,
					itemId: 'graphContainer',
					defaults: {
						labelWidth: 75,
						width: 250,
						margin: '0 10px 10px 0',
						readOnly: true
					},
					layout: {
						columns: 4,
						type: 'table'
					},
					fieldLabel: 'Graph Parameters',
					items: [
						{
							xtype: 'textfield',
							fieldLabel: 'Graph Type *',
							labelWidth: 90,
							name: 'graphType',
							submitValue: false,
							allowBlank: false
						},
						{
							xtype: 'numberfield',
							fieldLabel: 'Minimum Weight',
							name: 'minWeight',
							submitValue: false,
							allowBlank: false
						},
						{
							xtype: 'textfield',
							cls: 'dropTarget',
							fieldLabel: 'Run *',
							name: 'run_id',
							submitValue: false,
							readOnly: true
						},
						{
							xtype: 'checkboxfield',
							width: 130,
							fieldLabel: 'No edges',
							name: 'no_edges',
							submitValue: false
						}
					]
				},
				{
					xtype: 'container',
					itemId: 'image_container',
					style: {
						'text-align': 'center',
						color: '#157fcc'
					},
					width: 700
				},
				{
					xtype: 'displayfield',
					renderer: function(value, displayField) {
						if (value.indexOf('') !== -1) {
							return value;
						}
						if (value.length > 0) {
							var showValueArray = value.split('/');
							var showValue = showValueArray.length > 0 ? showValueArray.pop() : value;
							return ''+showValue+'';
						}
					},
					anchor: '100%',
					fieldLabel: 'Pajek file',
					name: 'pajek'
				},
				{
					xtype: 'fieldcontainer',
					formBind: false,
					itemId: 'clusterContainer',
					margin: '20 0 0 0',
					defaults: {
						labelWidth: 75,
						width: 250,
						margin: '0 10px 10px 0'
					},
					layout: {
						columns: 2,
						type: 'table'
					},
					fieldLabel: 'Cluster Parameters',
					items: [
						{
							xtype: 'textfield',
							fieldLabel: 'Name',
							name: 'name'
						},
						{
							xtype: 'combobox',
							fieldLabel: 'Cluster Based On *',
							name: 'clusterbasedon',
							allowBlank: false,
							displayField: 'basedonName',
							queryMode: 'local',
							store: 'ClusterBasedonStore',
							valueField: 'basedonTag'
						},
						{
							xtype: 'combobox',
							fieldLabel: 'Cluster Method *',
							labelWidth: 75,
							name: 'clustermethod',
							allowBlank: false,
							displayField: 'methodName',
							queryMode: 'local',
							store: 'ClusterMethodStore',
							valueField: 'methodTag'
						},
						{
							xtype: 'numberfield',
							fieldLabel: 'n (number of clusters) *',
							name: 'n',
							allowBlank: false,
							allowDecimals: false,
							minValue: 0
						},
						{
							xtype: 'button',
							handler: function(button, event) {
								var myFormCmp = this.up('form');
								var myForm = myFormCmp.getForm();
								var values = myForm.getFieldValues();
								var node = C.app.getNodeFromTree(myForm.getRecord().internalId);
								var record = C.app.getRecordByNode(node);

								if(myForm.isValid()){

									var clusterRecord = {
										'name': values.name,
										'clustermethod' : values.clustermethod,
										'clusterbasedon' : values.clusterbasedon,
										'graph_id': record.get('_id'),
										'n': values.n
									};

									/*if (myFormCmp.clusterRecord) {
									clusterRecord._id = myFormCmp.clusterRecord._id;
									clusterRecord.run_id = myFormCmp.clusterRecord.run_id;
									clusterRecord.clusters = myFormCmp.clusterRecord.clusters;
									}*/

									Ext.Ajax.request({
										url: '/cassandra/api/csnclusters',
										jsonData: clusterRecord,
										method: /*myFormCmp.clusterRecord ? 'PUT': */'POST',
										scope: this,
										success: function(response, opts) {
											var response_obj = Ext.JSON.decode(response.responseText);
											var data_obj = /*myFormCmp.clusterRecord ? response_obj.data[0] : */response_obj.data;
											var successMsg = response_obj.message;

											Ext.sliding_box.msg('Success', JSON.stringify(successMsg));

											//update
											myFormCmp.setImageContainerHtml(data_obj.img, "Csn Clusters");
											//update pajek
											myForm.setValues({'pajek': data_obj.pajek});

											if (!myFormCmp.clusterRecord) {
												var clusterGrid = new C.view.ClustersGrid({
													plugins: [{
														ptype: 'rowexpander',
														rowBodyTpl : new Ext.XTemplate('
Installations:
 {installations_}')
													}],
													store: new C.store.ClustersStore({storeId : 'clusterStore_' + data_obj._id})
												});
												//add grid to form
												myFormCmp.down("#clusterPricingContainer").insert(0, clusterGrid);
												//check if clusters array has data
											}
											//save current record in form and delete img from record since it is not included in the schema
											myFormCmp.clusterRecord = data_obj;
											delete myFormCmp.clusterRecord.img;

											if (data_obj.clusters.length > 0) {
												//if so populate clusters grid
												myFormCmp.down('grid').store.loadData(data_obj.clusters);
											}
											else {
												//else load empty array
												myFormCmp.down('grid').store.loadData([]);
											}

											//show clusters grid
											myFormCmp.down("#clusterPricingContainer").show();
										},
										failure: function(response, opts) {
											var response_obj = Ext.JSON.decode(response.responseText);
											Ext.MessageBox.show({title:'Error', msg: JSON.stringify(response_obj.errors), icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK});
										}
									});

								}

							},
							margin: '20 0 0 0',
							width: 120,
							text: 'Create clusters'
						}
					]
				},
				{
					xtype: 'fieldcontainer',
					hidden: true,
					itemId: 'clusterPricingContainer',
					margin: '20 0 0 0',
					width: 100,
					fieldLabel: 'Clusters - Pricing Scheme Correlation',
					items: [
						{
							xtype: 'button',
							handler: function(button, event) {
								var myFormCmp = button.up('form');
								var clusterStore = myFormCmp.down('grid').store;
								var clusterRecord = myFormCmp.clusterRecord;
								var clusters = clusterRecord.clusters;

								Ext.each(clusters, function(cluster){
									var cluster_grid_record = clusterStore.getById(cluster.name);
									if (!cluster_grid_record)
									return;
									cluster.pricing_id = cluster_grid_record.get("pricing_id");
									cluster.base_prc_id = cluster_grid_record.get("base_prc_id");

								});

								Ext.Ajax.request({
									url: '/cassandra/api/csnclusters',
									jsonData: clusterRecord,
									method: 'PUT',
									scope: this,
									success: function(response, opts) {
										var response_obj = Ext.JSON.decode(response.responseText);

										var successMsg = response_obj.message;
										Ext.sliding_box.msg('Success', JSON.stringify(successMsg));
										myFormCmp.clusterRecord = response_obj.data[0];
									},
									failure: function(response, opts) {
										var response_obj = Ext.JSON.decode(response.responseText);
										Ext.MessageBox.show({title:'Error', msg: JSON.stringify(response_obj.errors), icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK});
									}
								});
							},
							margin: '20 0 20 0',
							width: 150,
							text: 'Add pricing schemes'
						}
					]
				}
			]
		});

		me.callParent(arguments);
	},

	setImageContainerHtml: function(img, graph_desc) {
		html = "
" + graph_desc + " Graph" + "
";
		if (!img)
		html += "

No " + graph_desc + " Graph Data Available

";
		else
		html += "";

		this.down("#image_container").update(html);
	}

});<commit_msg>Minor csn layout changes<commit_after>/*
 * File: app/view/CsnClusterForm.js
 *
 * This file was generated by Sencha Architect version 2.2.2.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 4.2.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 4.2.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('C.view.CsnClusterForm', {
	extend: 'Ext.form.Panel',

	bodyPadding: 10,
	title: 'My Form',

	initComponent: function() {
		var me = this;

		Ext.applyIf(me, {
			items: [
				{
					xtype: 'fieldcontainer',
					formBind: false,
					itemId: 'graphContainer',
					defaults: {
						labelWidth: 75,
						width: 250,
						margin: '0 10px 10px 0',
						readOnly: true
					},
					layout: {
						columns: 4,
						type: 'table'
					},
					fieldLabel: 'Graph Parameters',
					items: [
						{
							xtype: 'textfield',
							fieldLabel: 'Graph Type *',
							labelWidth: 90,
							name: 'graphType',
							submitValue: false,
							allowBlank: false
						},
						{
							xtype: 'numberfield',
							fieldLabel: 'Minimum Weight',
							name: 'minWeight',
							submitValue: false,
							allowBlank: false
						},
						{
							xtype: 'textfield',
							cls: 'dropTarget',
							fieldLabel: 'Run *',
							name: 'run_id',
							submitValue: false,
							readOnly: true
						},
						{
							xtype: 'checkboxfield',
							width: 130,
							fieldLabel: 'No edges',
							name: 'no_edges',
							submitValue: false
						}
					]
				},
				{
					xtype: 'container',
					cls: 'gridbg',
					itemId: 'image_container',
					style: {
						'text-align': 'center',
						color: '#157fcc'
					},
					width: 700
				},
				{
					xtype: 'displayfield',
					renderer: function(value, displayField) {
						if (value.indexOf('') !== -1) {
							return value;
						}
						if (value.length > 0) {
							var showValueArray = value.split('/');
							var showValue = showValueArray.length > 0 ? showValueArray.pop() : value;
							return ''+showValue+'';
						}
					},
					anchor: '100%',
					fieldLabel: 'Pajek file',
					name: 'pajek'
				},
				{
					xtype: 'fieldcontainer',
					formBind: false,
					itemId: 'clusterContainer',
					margin: '20 0 0 0',
					defaults: {
						labelWidth: 75,
						width: 250,
						margin: '0 10px 10px 0'
					},
					layout: {
						columns: 2,
						type: 'table'
					},
					fieldLabel: 'Cluster Parameters',
					items: [
						{
							xtype: 'textfield',
							fieldLabel: 'Name',
							name: 'name'
						},
						{
							xtype: 'combobox',
							fieldLabel: 'Cluster Based On *',
							name: 'clusterbasedon',
							allowBlank: false,
							displayField: 'basedonName',
							queryMode: 'local',
							store: 'ClusterBasedonStore',
							valueField: 'basedonTag'
						},
						{
							xtype: 'combobox',
							fieldLabel: 'Cluster Method *',
							labelWidth: 75,
							name: 'clustermethod',
							allowBlank: false,
							displayField: 'methodName',
							queryMode: 'local',
							store: 'ClusterMethodStore',
							valueField: 'methodTag'
						},
						{
							xtype: 'numberfield',
							fieldLabel: 'n (number of clusters) *',
							name: 'n',
							allowBlank: false,
							allowDecimals: false,
							minValue: 0
						},
						{
							xtype: 'button',
							handler: function(button, event) {
								var myFormCmp = this.up('form');
								var myForm = myFormCmp.getForm();
								var values = myForm.getFieldValues();
								var node = C.app.getNodeFromTree(myForm.getRecord().internalId);
								var record = C.app.getRecordByNode(node);

								if(myForm.isValid()){

									var clusterRecord = {
										'name': values.name,
										'clustermethod' : values.clustermethod,
										'clusterbasedon' : values.clusterbasedon,
										'graph_id': record.get('_id'),
										'n': values.n
									};

									/*if (myFormCmp.clusterRecord) {
									clusterRecord._id = myFormCmp.clusterRecord._id;
									clusterRecord.run_id = myFormCmp.clusterRecord.run_id;
									clusterRecord.clusters = myFormCmp.clusterRecord.clusters;
									}*/

									Ext.Ajax.request({
										url: '/cassandra/api/csnclusters',
										jsonData: clusterRecord,
										method: /*myFormCmp.clusterRecord ? 'PUT': */'POST',
										scope: this,
										success: function(response, opts) {
											var response_obj = Ext.JSON.decode(response.responseText);
											var data_obj = /*myFormCmp.clusterRecord ? response_obj.data[0] : */response_obj.data;
											var successMsg = response_obj.message;

											Ext.sliding_box.msg('Success', JSON.stringify(successMsg));

											//update
											myFormCmp.setImageContainerHtml(data_obj.img, "Csn Clusters");
											//update pajek
											myForm.setValues({'pajek': data_obj.pajek});

											if (!myFormCmp.clusterRecord) {
												var clusterGrid = new C.view.ClustersGrid({
													plugins: [{
														ptype: 'rowexpander',
														rowBodyTpl : new Ext.XTemplate('
Installations:
 {installations_}')
													}],
													store: new C.store.ClustersStore({storeId : 'clusterStore_' + data_obj._id})
												});
												//add grid to form
												myFormCmp.down("#clusterPricingContainer").insert(0, clusterGrid);
												//check if clusters array has data
											}
											//save current record in form and delete img from record since it is not included in the schema
											myFormCmp.clusterRecord = data_obj;
											delete myFormCmp.clusterRecord.img;

											if (data_obj.clusters.length > 0) {
												//if so populate clusters grid
												myFormCmp.down('grid').store.loadData(data_obj.clusters);
											}
											else {
												//else load empty array
												myFormCmp.down('grid').store.loadData([]);
											}

											//show clusters grid
											myFormCmp.down("#clusterPricingContainer").show();
										},
										failure: function(response, opts) {
											var response_obj = Ext.JSON.decode(response.responseText);
											Ext.MessageBox.show({title:'Error', msg: JSON.stringify(response_obj.errors), icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK});
										}
									});

								}

							},
							margin: '20 0 0 0',
							width: 120,
							text: 'Create clusters'
						}
					]
				},
				{
					xtype: 'fieldcontainer',
					hidden: true,
					itemId: 'clusterPricingContainer',
					margin: '20 0 0 0',
					width: 100,
					fieldLabel: 'Clusters - Pricing Scheme Correlation',
					items: [
						{
							xtype: 'button',
							handler: function(button, event) {
								var myFormCmp = button.up('form');
								var clusterStore = myFormCmp.down('grid').store;
								var clusterRecord = myFormCmp.clusterRecord;
								var clusters = clusterRecord.clusters;

								Ext.each(clusters, function(cluster){
									var cluster_grid_record = clusterStore.getById(cluster.name);
									if (!cluster_grid_record)
									return;
									cluster.pricing_id = cluster_grid_record.get("pricing_id");
									cluster.base_prc_id = cluster_grid_record.get("base_prc_id");

								});

								Ext.Ajax.request({
									url: '/cassandra/api/csnclusters',
									jsonData: clusterRecord,
									method: 'PUT',
									scope: this,
									success: function(response, opts) {
										var response_obj = Ext.JSON.decode(response.responseText);

										var successMsg = response_obj.message;
										Ext.sliding_box.msg('Success', JSON.stringify(successMsg));
										myFormCmp.clusterRecord = response_obj.data[0];
									},
									failure: function(response, opts) {
										var response_obj = Ext.JSON.decode(response.responseText);
										Ext.MessageBox.show({title:'Error', msg: JSON.stringify(response_obj.errors), icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK});
									}
								});
							},
							margin: '20 0 20 0',
							width: 150,
							text: 'Add pricing schemes'
						}
					]
				}
			]
		});

		me.callParent(arguments);
	},

	setImageContainerHtml: function(img, graph_desc) {
		html = "
" + graph_desc + " Graph" + "
";
		if (!img)
		html += "

No " + graph_desc + " Graph Data Available

";
		else
		html += "";

		this.down("#image_container").update(html);
	}

});<|endoftext|>


<commit_before>/*
 * あくまでも例です
 */
loadExternalFile([
 {
  type:"css",
  list:["//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css","/~virus/lib/bootstrap/css/bootstrap.min.css"]
 },
 {
  type:"javascript",
  list:["//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js","/~virus/lib/jquery.js"]
 },
 {
  type:"javascript",
  list:["//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js","/~virus/lib/bootstrap/js/bootstrap.min.js"]
 },
 {
  type:"javascript",
  list:["./javascript/loadExternalQuestionData.js"]
 },
 {
  type:"javascript",
  list:["./javascript/main.js"]
 },
]);
<commit_msg>delete load.example.js<commit_after><|endoftext|>