<commit_before>var csrftoken = $('meta[name=csrf-token]').attr('content');

$(document).ready(function () {
    "use strict";

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto top'
    });

    $('#li-boot').addClass('active');

    $.ajax({
        'url': '/_ajax/boot',
        'traditional': true,
        'cache': true,
        'dataType': 'json',
        'data': {
            'id': $('#board-id').val() + '-' + $('#job-id').val() + '-' +
                $('#kernel-id').val() + '-' + $('#defconfig-id').val()
        },
        'dataFilter': function (data, type) {
            if (type === 'json') {
                return JSON.parse(data).result;
            }
            return data;
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $('#container-content').empty().load(
                    '/static/html/404-content.html'
                );
            },
            500: function () {
                $('#container-content').empty().load(
                    '/static/html/500-content.html'
                );
            }
        }
    }).done(function (data) {
        var boot_time = new Date(data.time['$date']),
            displ = '',
            file_server = $('#file-server').val(),
            non_avail = '' +
                '';

        $('#dd-board-board').empty().append(data.board);
        $('#dd-board-defconfig').empty().append(
            '' +
                data.defconfig +
                ' '
        );
        $('#dd-board-kernel').empty().append(
            '' + data.kernel +
                ' '
        );
        $('#dd-board-tree').empty().append(
            '' + data.job +
                ' '
        );

        if (data.endian !== null) {
            $('#dd-board-endianness').empty().append(data.endian);
        } else {
            $('#dd-board-endianness').empty().append(non_avail);
        }

        if (data.boot_log !== null) {
            $('#dd-board-boot-log').empty().append(
                '' + data.boot_log +
                    ' '
            );
        } else {
            $('#dd-board-boot-log').empty().append(non_avail);
        }

        switch (data.status) {
            case 'PASS':
                displ = '';
                break;
            case 'FAIL':
                displ = '' +
                        '';
                break;
            case 'OFFLINE':
                displ = '<span rel="tooltip" data-toggle="tooltip"' +
                    'title="Board offline" ' +
                    '';
                break;
            default:
                displ = '' +
                        '';
                break;
        }

        $('#dd-board-status').empty().append(displ);
        $('#dd-board-boot-time').empty().append(boot_time.getCustomTime());

        if (data.warnings !== null) {
            $('#dd-board-warnings').empty().append(data.warnings);
        } else {
            $('#dd-board-warnings').empty().append(0);
        }

        if (data.dtb !== null && data.dtb !== '') {
            $('#dd-board-dtb').empty().append(data.dtb);
        } else {
            $('#dd-board-dtb').empty().append(non_avail);
        }

        if (data.dtb_addr !== null && data.dtb_addr !== '') {
            $('#dd-board-dtb-address').empty().append(data.dtb_addr);
        } else {
            $('#dd-board-dtb-address').empty().append(non_avail);
        }

        if (data.initrd_addr !== null && data.initrd_addr !== '') {
            $('#dd-board-initrd-address').empty().append(data.initrd_addr);
        } else {
            $('#dd-board-initrd-address').empty().append(non_avail);
        }

        if (data.load_addr !== null && data.load_addr !== '') {
            $('#dd-board-load-address').empty().append(data.load_addr);
        } else {
            $('#dd-board-load-address').empty().append(non_avail);
        }

        if (data.kernel_image !== null && data.kernel_image !== '') {
            $('#dd-board-kernel-image').empty().append(data.kernel_image);
        } else {
            $('#dd-board-kernel-image').empty().append(non_avail);
        }
    });
});
<commit_msg>Add link to build and job details, remove lense icons.<commit_after>var csrftoken = $('meta[name=csrf-token]').attr('content');

$(document).ready(function () {
    "use strict";

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto top'
    });

    $('#li-boot').addClass('active');

    $.ajax({
        'url': '/_ajax/boot',
        'traditional': true,
        'cache': true,
        'dataType': 'json',
        'data': {
            'id': $('#board-id').val() + '-' + $('#job-id').val() + '-' +
                $('#kernel-id').val() + '-' + $('#defconfig-id').val()
        },
        'dataFilter': function (data, type) {
            if (type === 'json') {
                return JSON.parse(data).result;
            }
            return data;
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $('#container-content').empty().load(
                    '/static/html/404-content.html'
                );
            },
            500: function () {
                $('#container-content').empty().load(
                    '/static/html/500-content.html'
                );
            }
        }
    }).done(function (data) {
        var boot_time = new Date(data.time['$date']),
            displ = '',
            file_server = $('#file-server').val(),
            non_avail = '' +
                '';

        $('#dd-board-board').empty().append(data.board);
        $('#dd-board-defconfig').empty().append(
            data.defconfig + ' — ' +
                '' +
                ''
        );
        $('#dd-board-kernel').empty().append(
            '' + data.kernel +
                '' +
                ' — ' +
                ''
        );
        $('#dd-board-tree').empty().append(
            '' +
                '' + data.job +
                '' +
                ' — ' +
                ''
        );

        if (data.endian !== null) {
            $('#dd-board-endianness').empty().append(data.endian);
        } else {
            $('#dd-board-endianness').empty().append(non_avail);
        }

        if (data.boot_log !== null) {
            $('#dd-board-boot-log').empty().append(
                '' + data.boot_log +
                    ' '
            );
        } else {
            $('#dd-board-boot-log').empty().append(non_avail);
        }

        switch (data.status) {
            case 'PASS':
                displ = '';
                break;
            case 'FAIL':
                displ = '' +
                        '';
                break;
            case 'OFFLINE':
                displ = '<span rel="tooltip" data-toggle="tooltip"' +
                    'title="Board offline" ' +
                    '';
                break;
            default:
                displ = '' +
                        '';
                break;
        }

        $('#dd-board-status').empty().append(displ);
        $('#dd-board-boot-time').empty().append(boot_time.getCustomTime());

        if (data.warnings !== null) {
            $('#dd-board-warnings').empty().append(data.warnings);
        } else {
            $('#dd-board-warnings').empty().append(0);
        }

        if (data.dtb !== null && data.dtb !== '') {
            $('#dd-board-dtb').empty().append(data.dtb);
        } else {
            $('#dd-board-dtb').empty().append(non_avail);
        }

        if (data.dtb_addr !== null && data.dtb_addr !== '') {
            $('#dd-board-dtb-address').empty().append(data.dtb_addr);
        } else {
            $('#dd-board-dtb-address').empty().append(non_avail);
        }

        if (data.initrd_addr !== null && data.initrd_addr !== '') {
            $('#dd-board-initrd-address').empty().append(data.initrd_addr);
        } else {
            $('#dd-board-initrd-address').empty().append(non_avail);
        }

        if (data.load_addr !== null && data.load_addr !== '') {
            $('#dd-board-load-address').empty().append(data.load_addr);
        } else {
            $('#dd-board-load-address').empty().append(non_avail);
        }

        if (data.kernel_image !== null && data.kernel_image !== '') {
            $('#dd-board-kernel-image').empty().append(data.kernel_image);
        } else {
            $('#dd-board-kernel-image').empty().append(non_avail);
        }
    });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2016, Lorenzo Mangani (lorenzo.mangani@gmail.com)
 * Copyright 2015, Rao Chenlin (rao.chenlin@gmail.com)
 *
 * This file is part of Sentinl (http://github.com/sirensolutions/sentinl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import _ from 'lodash';
import later from 'later';
import doActions from './actions';

var Schedule = [];

function getCount(client) {
  return client.count({
    index:'watcher',
    type:"watch"
  });
}

function getWatcher(count,client) {
  return client.search({
    index:'watcher',
    type:"watch",
    size:count
  });
}

function doalert(server,client) {
  server.log(['status', 'debug', 'Sentinl'], 'Reloading Watchers...');
  getCount(client).then(function(resp){
    getWatcher(resp.count,client).then(function(resp){
      /* Orphanizer */
        var orphans = _.difference(_.each(Object.keys( Schedule )), _.map(resp.hits.hits, '_id')  );
        _.each(orphans, function(orphan){
                server.log(['status', 'info', 'Sentinl'],'Deleting orphan watcher: '+orphan);
                Schedule[orphan].later.clear();
                delete Schedule[orphan];
        });

      /* Scheduler */
      _.each(resp.hits.hits, function(hit){

        if (Schedule[hit._id]) {
          if (_.isEqual(Schedule[hit._id].hit, hit)) { return; }
          else { server.log(['status', 'info', 'Sentinl'],'Clearing watcher: '+hit._id); Schedule[hit._id].later.clear(); }
        }

          Schedule[hit._id] = {};
          Schedule[hit._id].hit = hit;

          if(hit._source.trigger.schedule.later){
            // https://bunkat.github.io/later/parsers.html#text
            var interval = later.parse.text(hit._source.trigger.schedule.later);
            Schedule[hit._id].interval = hit._source.trigger.schedule.later;
          }
          else if(hit._source.trigger.schedule.interval % 1 === 0){
            // max 60 seconds!
            var interval = later.parse.recur().every(hit._source.trigger.schedule.interval).second();
            Schedule[hit._id].interval = hit._source.trigger.schedule.interval;
          }

          if (hit._source.report) {
            /* Report */
            Schedule[hit._id].later = later.setInterval(function(){ reporting(hit,interval) }, interval);
            server.log(['status', 'info', 'Sentinl'], 'Scheduled Report: '+hit._id+' every '+Schedule[hit._id].interval );
          } else {
            /* Watcher */
            Schedule[hit._id].later = later.setInterval(function(){ watching(hit,interval) }, interval);
            server.log(['status', 'info', 'Sentinl'], 'Scheduled Watch: '+hit._id+' every '+Schedule[hit._id].interval );
          }

          function watching(task,interval) {

			if (!task._source || task._source.disable) {
			server.log(['status', 'debug', 'Sentinl'], 'Non-Executing Disabled Watch: '+task._id);
				return;
			}

				server.log(['status', 'info', 'Sentinl'], 'Executing watch: '+task._id);
			server.log(['status', 'debug', 'Sentinl', 'WATCHER DEBUG'], task);

				var watch = task._source;
				var request = watch.input.search.request;
				var condition = watch.condition.script.script;
				var transform = watch.transform ? watch.transform : {};
				var actions = watch.actions;

			if (JSON.stringify(request).indexOf('filterjoin') !== -1) {
			/* Kibi Join Query */
			client.coordinate_search(request).then(function(payload){
				  if (!payload || !condition || !actions) {
					server.log(['status', 'debug', 'Sentinl', 'WATCHER TASK'], 'Join Watcher Malformed or Missing Key Parameters!');
					return;
				  }

				  server.log(['status', 'debug', 'Sentinl', 'PAYLOAD DEBUG'], payload);

				  /* Validate Condition */
				  try { var ret = eval(condition); } catch (err) {
					  server.log(['status', 'info', 'Sentinl'], 'Condition Error for '+task._id+': '+err);
				  }
				  if (ret) {
				  if (transform.script) {
					  try { eval(transform.script.script); } catch (err) {
					  server.log(['status', 'info', 'Sentinl'], 'Transform Script Error for '+task._id+': '+err);
					  }
					  doActions(server,actions,payload);
				  } else if (transform.search) {
					  client.search(transform.search.request).then(function(payload) {
					  if (!payload) return;
					  doActions(server,actions,payload);
					  });
				  } else {
					  doActions(server,actions,payload);
				  }
				  }
				});
			} else {
			/* Normal ES Query */
			client.search(request).then(function(payload){
				  if (!payload || !condition || !actions) {
					server.log(['status', 'debug', 'Sentinl', 'WATCHER TASK'], 'Watcher Malformed or Missing Key Parameters!');
					return;
				  }

				  server.log(['status', 'debug', 'Sentinl', 'PAYLOAD DEBUG'], payload);

				  /* Validate Condition */
				  try { var ret = eval(condition); } catch (err) {
					  server.log(['status', 'info', 'Sentinl'], 'Condition Error for '+task._id+': '+err);
				  }
				  if (ret) {
				  if (transform.script) {
					  try { eval(transform.script.script); } catch (err) {
					  server.log(['status', 'info', 'Sentinl'], 'Transform Script Error for '+task._id+': '+err);
					  }
					  doActions(server,actions,payload);
				  } else if (transform.search) {
					  client.search(transform.search.request).then(function(payload) {
					  if (!payload) return;
					  doActions(server,actions,payload);
					  });
				  } else {
					  doActions(server,actions,payload);
				  }
				  }
				});
			}
        }
        function reporting(task,interval) {
	  if (!task._source || task._source.disable) {
		server.log(['status', 'debug', 'Sentinl'], 'Non-Executing Disabled report: '+task._id);
          	return;
 	  }
          server.log(['status', 'info', 'Sentinl'], 'Executing report: '+task._id );
          var actions = task._source.actions;
          var payload = { "_id": task._id };
          if (!actions) { server.log(['status', 'info', 'Sentinl'], 'Condition Error for '+task._id); return; }
          doActions(server,actions,payload);
        }
      });
    });
  });
}

module.exports = {
  doalert: doalert,
  getCount: getCount,
  getWatcher: getWatcher
};
<commit_msg>Use client.kibi_search if available<commit_after>/*
 * Copyright 2016, Lorenzo Mangani (lorenzo.mangani@gmail.com)
 * Copyright 2015, Rao Chenlin (rao.chenlin@gmail.com)
 *
 * This file is part of Sentinl (http://github.com/sirensolutions/sentinl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import _ from 'lodash';
import later from 'later';
import doActions from './actions';

var Schedule = [];

function getCount(client) {
  return client.count({
    index: 'watcher',
    type: "watch"
  });
}

function getWatcher(count, client) {
  return client.search({
    index: 'watcher',
    type: "watch",
    size: count
  });
}

function doalert(server, client) {
  server.log(['status', 'debug', 'Sentinl'], 'Reloading Watchers...');
  getCount(client).then(function (resp) {
    getWatcher(resp.count, client).then(function (resp) {
      /* Orphanizer */
      var orphans = _.difference(_.each(Object.keys(Schedule)), _.map(resp.hits.hits, '_id'));
      _.each(orphans, function (orphan) {
        server.log(['status', 'info', 'Sentinl'], 'Deleting orphan watcher: ' + orphan);
        Schedule[orphan].later.clear();
        delete Schedule[orphan];
      });

      /* Scheduler */
      _.each(resp.hits.hits, function (hit) {

        if (Schedule[hit._id]) {
          if (_.isEqual(Schedule[hit._id].hit, hit)) {
            return;
          }
          else {
            server.log(['status', 'info', 'Sentinl'], 'Clearing watcher: ' + hit._id);
            Schedule[hit._id].later.clear();
          }
        }

        Schedule[hit._id] = {};
        Schedule[hit._id].hit = hit;

        if (hit._source.trigger.schedule.later) {
          // https://bunkat.github.io/later/parsers.html#text
          var interval = later.parse.text(hit._source.trigger.schedule.later);
          Schedule[hit._id].interval = hit._source.trigger.schedule.later;
        }
        else if (hit._source.trigger.schedule.interval % 1 === 0) {
          // max 60 seconds!
          var interval = later.parse.recur().every(hit._source.trigger.schedule.interval).second();
          Schedule[hit._id].interval = hit._source.trigger.schedule.interval;
        }

        if (hit._source.report) {
          /* Report */
          Schedule[hit._id].later = later.setInterval(function () {
            reporting(hit, interval)
          }, interval);
          server.log(['status', 'info', 'Sentinl'], 'Scheduled Report: ' + hit._id + ' every ' + Schedule[hit._id].interval);
        } else {
          /* Watcher */
          Schedule[hit._id].later = later.setInterval(function () {
            watching(hit, interval)
          }, interval);
          server.log(['status', 'info', 'Sentinl'], 'Scheduled Watch: ' + hit._id + ' every ' + Schedule[hit._id].interval);
        }

        function watching(task, interval) {

          if (!task._source || task._source.disable) {
            server.log(['status', 'debug', 'Sentinl'], 'Non-Executing Disabled Watch: ' + task._id);
            return;
          }

          server.log(['status', 'info', 'Sentinl'], 'Executing watch: ' + task._id);
          server.log(['status', 'debug', 'Sentinl', 'WATCHER DEBUG'], task);

          var watch = task._source;
          var request = watch.input.search.request;
          var condition = watch.condition.script.script;
          var transform = watch.transform ? watch.transform : {};
          var actions = watch.actions;

          let method;
          for (let candidate of ['kibi_search', 'coordinate_search', 'search']) {
            if (client[candidate]) {
              method = candidate;
              break;
            }
          }

          client[method](request)
          .then(function (payload) {
            if (!payload || !condition || !actions) {
              server.log(['status', 'debug', 'Sentinl', 'WATCHER TASK'], 'Watcher Malformed or Missing Key Parameters!');
              return;
            }

            server.log(['status', 'debug', 'Sentinl', 'PAYLOAD DEBUG'], payload);

            /* Validate Condition */
            try {
              var ret = eval(condition);
            } catch (err) {
              server.log(['status', 'info', 'Sentinl'], 'Condition Error for ' + task._id + ': ' + err);
            }
            if (ret) {
              if (transform.script) {
                try {
                  eval(transform.script.script);
                } catch (err) {
                  server.log(['status', 'info', 'Sentinl'], 'Transform Script Error for ' + task._id + ': ' + err);
                }
                doActions(server, actions, payload);
              } else if (transform.search) {
                client[method](transform.search.request).then(function (payload) {
                  if (!payload) return;
                  doActions(server, actions, payload);
                });
              } else {
                doActions(server, actions, payload);
              }
            }
          })
          .catch((error) => {
            server.log(['error', 'Sentinl'], `An error occurred while executing the watch: ${error}`);
          })

        }

        function reporting(task, interval) {
          if (!task._source || task._source.disable) {
            server.log(['status', 'debug', 'Sentinl'], 'Non-Executing Disabled report: ' + task._id);
            return;
          }
          server.log(['status', 'info', 'Sentinl'], 'Executing report: ' + task._id);
          var actions = task._source.actions;
          var payload = {"_id": task._id};
          if (!actions) {
            server.log(['status', 'info', 'Sentinl'], 'Condition Error for ' + task._id);
            return;
          }
          doActions(server, actions, payload);
        }
      });
    });
  });
}

module.exports = {
  doalert: doalert,
  getCount: getCount,
  getWatcher: getWatcher
};
<|endoftext|>


<commit_before>Meteor.methods({
    /*
    Send a confirmation email based on
        - registrant ID
    */
    'sendConfirmationEmail': function (registrantId) {
        // Get the registration document
        var registration = Registrants.findOne(registrantId);

        // If SMTP is configured, send email when registration is added
        // Check whether email sending is enabled
        var emailEnabled = process.env.ENABLE_SMTP;

        if (emailEnabled) {
            // Set up email message and send

            // Email address from registration
            var to = registration.createdByEmail;

            // From address from mail configuration
            var from = process.env.MAIL_FROM;

            // HTML message
            var html = '
We have received your event registration for PYM 2015.
 \

View your registration(s) by visiting:
\
\
http://register.pacificyearlymeeting.org/view
\

If you are through entering the registrations for yourself and your family, \
please write a check for at least 25% of the total for all persons \
(100% if you are claiming the early registration discount), minus \
expected assistance, payable to Pacific Yearly Meeting.
\

Note your family email address (where you received this email), for identification.
\

For each person under age 18, enclose both the \
parental permission and medical release forms.
\

Mail all registration items to:
\

Berkeley Registration Team
\
2151 Vine St.
\
Berkeley, CA., 94709
';
>>>>>>> origin/master

            Email.send({
                from: from,
                to: to,
                subject: "[PYM 2015] Registration success!",
                html: html
            });
        }
    }
});
<commit_msg>Cleanup.<commit_after>Meteor.methods({
    /*
    Send a confirmation email based on
        - registrant ID
    */
    'sendConfirmationEmail': function (registrantId) {
        // Get the registration document
        var registration = Registrants.findOne(registrantId);

        // If SMTP is configured, send email when registration is added
        // Check whether email sending is enabled
        var emailEnabled = process.env.ENABLE_SMTP;

        if (emailEnabled) {
            // Set up email message and send

            // Email address from registration
            var to = registration.createdByEmail;

            // From address from mail configuration
            var from = process.env.MAIL_FROM;

            // HTML message
            var html = '
We have received your event registration for PYM 2015.
 \

View your registration(s) by visiting:
\
\
http://register.pacificyearlymeeting.org/view
\

If you are through entering the registrations for yourself and your family, \
please write a check for at least 25% of the total for all persons \
(100% if you are claiming the early registration discount), minus \
expected assistance, payable to Pacific Yearly Meeting.
\

Note your family email address (where you received this email), for identification.
\

For each person under age 18, enclose both the \
parental permission and medical release forms.
\

Mail all registration items to:
\

Berkeley Registration Team
\
2151 Vine St.
\
Berkeley, CA., 94709
';

            Email.send({
                from: from,
                to: to,
                subject: "[PYM 2015] Registration success!",
                html: html
            });
        }
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';
import RSVP from 'rsvp';

import config from '../../config/environment';

export default Ember.Component.extend({
    layout,
    authRequest: Ember.inject.service(),
    internalState: Ember.inject.service(),

    datasources: Ember.A(),

    num_results: -1,
    error: false,
    errorMessage: '',
    searching: false,
    searchDataId: '',
    dataId: '',
    doi: '',
    name: '',
    repository: '',
    size: '',

    disableRegister() {
        Ember.$('.icon.register').removeClass('checkmark');
        Ember.$('.ui.positive.register.button').addClass('disabled');
    },

    enableRegister(dataId) {
        let ds = this.datasources.find(ds => {
            return (dataId == ds.dataId || dataId == ds.doi);
        });

        this.set('dataId', ds.dataId);
        this.set('doi', ds.doi);
        this.set('name', ds.name);
        this.set('repository', ds.repository);
        this.set('size', ds.size);

        Ember.$('.icon.register').addClass('checkmark');
        Ember.$('.ui.positive.register.button').removeClass('disabled');
    },

    clearModal() {
        Ember.$('.ui.dropdown').dropdown('clear');
        Ember.$('#results').addClass('hidden');
        Ember.$('#searchbox').val('');

        this.set('datasources', Ember.A());
        this.set('error', false);
        this.set('errorMessage', '');
        this.set('num_results', -1);
        this.set('dataId', '');
        this.set('doi', '');
        this.set('name', '');
        this.set('repository', '');
        this.set('size', '');
    },

    didRender() {
        let self = this;
        Ember.$('.ui.dropdown').dropdown({
            onChange: function(dataId) {
                if(!dataId || dataId === "") {
                    self.disableRegister();
                    return;
                }
                self.enableRegister(dataId);
            }
        });
    },

    actions: {
        register() {
            this.set('error', false);

            let folderId = this.get('internalState').getCurrentFolderID();
            let parentType, parentId;
            console.log(folderId);
            if(folderId !== "null") {
                console.log("should not see me");
                parentType = "folder";
                parentId = folderId;
            }
            else {
                parentType = "collection";
                parentId = this.get('internalState').getCurrentCollectionID();
            }

            let queryParams = "?"+[
                "parentType="+parentType,
                "parentId="+parentId,
                "public=false"
            ].join('&');

            let dataMap = JSON.stringify([{
                name: this.name,
                dataId: this.dataId,
                repository: this.repository
            }]);

            let url = config.apiUrl + '/folder/register' + queryParams;
            let options = {
                method: 'POST',
                data: {
                    dataMap: dataMap
                }
            };
            this.get('authRequest').send(url, options)
                .then(rep => {
                    alert("Primitive notification to tell you that your dataset registration has completed!");
                })
                .catch(e => {
                    console.log(e);
                });

            this.clearModal();
            this.disableRegister();
        },

        cancel() {
            this.clearModal();
            this.disableRegister();
        },

        search() {
            this.clearModal();
            this.set('searching', true);
            Ember.$('#results').removeClass('hidden');

            let url = config.apiUrl + '/repository/lookup';
            let options = {
                method: 'GET',
                data: {
                    dataId: JSON.stringify(this.searchDataId.split())
                }
            };

            let self = this;
            return self.get('authRequest').send(url, options)
                .then(rep => {
                    self.set('error', false);
                    self.set('num_results', rep.length);
                    self.datasources.pushObjects(rep);

                    if(rep.length === 1) {
                        Ember.$('.ui.dropdown').dropdown('set text', self.datasources[0].name);
                        Ember.$('.ui.dropdown').dropdown('set value', self.datasources[0].dataId);
                    }
                    else {
                        Ember.$('.ui.dropdown').dropdown('set visible');
                        Ember.$('.ui.dropdown').dropdown('set active');
                        let menu = Ember.$('.ui.dropdown .menu');
                        menu.removeClass('hidden');
                        menu.addClass('transition visible');
                    }
                })
                .catch(e => {
                    console.log("Error: " + e);
                    self.set('error', true);
                    self.set('errorMessage', 'No matching results found.');
                    self.disableRegister();
                })
                .finally((_) => {
                    self.set('searching', false);
                });
        }
    }
});
<commit_msg>got rid of debug residue<commit_after>import Ember from 'ember';
import layout from './template';
import RSVP from 'rsvp';

import config from '../../config/environment';

export default Ember.Component.extend({
    layout,
    authRequest: Ember.inject.service(),
    internalState: Ember.inject.service(),

    datasources: Ember.A(),

    num_results: -1,
    error: false,
    errorMessage: '',
    searching: false,
    searchDataId: '',
    dataId: '',
    doi: '',
    name: '',
    repository: '',
    size: '',

    disableRegister() {
        Ember.$('.icon.register').removeClass('checkmark');
        Ember.$('.ui.positive.register.button').addClass('disabled');
    },

    enableRegister(dataId) {
        let ds = this.datasources.find(ds => {
            return (dataId == ds.dataId || dataId == ds.doi);
        });

        this.set('dataId', ds.dataId);
        this.set('doi', ds.doi);
        this.set('name', ds.name);
        this.set('repository', ds.repository);
        this.set('size', ds.size);

        Ember.$('.icon.register').addClass('checkmark');
        Ember.$('.ui.positive.register.button').removeClass('disabled');
    },

    clearModal() {
        Ember.$('.ui.dropdown').dropdown('clear');
        Ember.$('#results').addClass('hidden');
        Ember.$('#searchbox').val('');

        this.set('datasources', Ember.A());
        this.set('error', false);
        this.set('errorMessage', '');
        this.set('num_results', -1);
        this.set('dataId', '');
        this.set('doi', '');
        this.set('name', '');
        this.set('repository', '');
        this.set('size', '');
    },

    didRender() {
        let self = this;
        Ember.$('.ui.dropdown').dropdown({
            onChange: function(dataId) {
                if(!dataId || dataId === "") {
                    self.disableRegister();
                    return;
                }
                self.enableRegister(dataId);
            }
        });
    },

    actions: {
        register() {
            this.set('error', false);

            let folderId = this.get('internalState').getCurrentFolderID();
            let parentType, parentId;

            if(folderId !== "null") {
                parentType = "folder";
                parentId = folderId;
            }
            else {
                parentType = "collection";
                parentId = this.get('internalState').getCurrentCollectionID();
            }

            let queryParams = "?"+[
                "parentType="+parentType,
                "parentId="+parentId,
                "public=false"
            ].join('&');

            let dataMap = JSON.stringify([{
                name: this.name,
                dataId: this.dataId,
                repository: this.repository
            }]);

            let url = config.apiUrl + '/folder/register' + queryParams;
            let options = {
                method: 'POST',
                data: {
                    dataMap: dataMap
                }
            };
            this.get('authRequest').send(url, options)
                .then(rep => {
                    alert("Primitive notification to tell you that your dataset registration has completed!");
                })
                .catch(e => {
                    alert("[Error] Primitive notification to tell you that your dataset registration has failed!");
                    console.log(e);
                });

            this.clearModal();
            this.disableRegister();
        },

        cancel() {
            this.clearModal();
            this.disableRegister();
        },

        search() {
            this.clearModal();
            this.set('searching', true);
            Ember.$('#results').removeClass('hidden');

            let url = config.apiUrl + '/repository/lookup';
            let options = {
                method: 'GET',
                data: {
                    dataId: JSON.stringify(this.searchDataId.split())
                }
            };

            let self = this;
            return self.get('authRequest').send(url, options)
                .then(rep => {
                    self.set('error', false);
                    self.set('num_results', rep.length);
                    self.datasources.pushObjects(rep);

                    if(rep.length === 1) {
                        Ember.$('.ui.dropdown').dropdown('set text', self.datasources[0].name);
                        Ember.$('.ui.dropdown').dropdown('set value', self.datasources[0].dataId);
                    }
                    else {
                        Ember.$('.ui.dropdown').dropdown('set visible');
                        Ember.$('.ui.dropdown').dropdown('set active');
                        let menu = Ember.$('.ui.dropdown .menu');
                        menu.removeClass('hidden');
                        menu.addClass('transition visible');
                    }
                })
                .catch(e => {
                    console.log("Error: " + e);
                    self.set('error', true);
                    self.set('errorMessage', 'No matching results found.');
                    self.disableRegister();
                })
                .finally((_) => {
                    self.set('searching', false);
                });
        }
    }
});
<|endoftext|>


<commit_before>/**
 *
 * GeneralSearch
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

import TextField from 'material-ui/TextField';
import { MenuItem } from 'material-ui/Menu';
import { InputLabel } from 'material-ui/Input';
import Select from 'material-ui/Select';

import { FormControl } from 'material-ui/Form';
import Button from 'material-ui/Button';
import { MdClear, MdSearch } from 'react-icons/lib/md';

import axios from 'axios';
import { graphQLRoot } from 'utils/constants';

const MButton = styled(Button)`
  margin: 12px;
`;

class GeneralSearch extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      free_text: '',
      year: '',
      authors: '',
      article_title: '',
      journal_title: '',
      facet: '',
      site: '',
      composition: '',
    };
    // Workaround, instead of calling .bind in every render
    this.submitQuery = this.submitQuery.bind(this);
    this.clearForm = this.clearForm.bind(this);
  }
  submitQuery() {
    axios.post(graphQLRoot, {
      query: `query{systems {
  edges {
    node {
        uniqueId
        Formula
        volume
        Facet
    }
  }
  }}`,
    }).then((response) => {
      this.props.receiveResults(response.data.data.systems.edges);
    });
  }

  handleChange(name) {
    return (event) => {
      this.setState({
        [name]: event.target.value,
      });
    };
  }
  clearForm() {
    this.setState({
      free_text: '',
      composition: '',
      year: '',
      authors: '',
      article_title: '',
      journal_title: '',
      facet: '',
      site: '',
      results: [],
    });
  }
  render() {
    return (

General Search

        <TextField label="Free Text Search" value={this.state.free_text} onChange={this.handleChange('free_text')} />
        {'\t '}
        <TextField label="Composition" value={this.state.composition} onChange={this.handleChange('composition')} />
        {'\t '}
        <TextField label="Year" value={this.state.year} onChange={this.handleChange('year')} />

        <TextField label="Authors" value={this.state.authors} onChange={this.handleChange('authors')} />
        {'\t '}
        <TextField label="Title of Article" value={this.state.article_title} onChange={this.handleChange('article_title')} />
        {'\t '}
        <TextField label="Title of Journal" value={this.state.journal_title} onChange={this.handleChange('journal_title')} />

        <FormControl
          style={{ minWidth: 120, margin: 12 }}
        >
          <InputLabel>Facet</InputLabel>
          <Select
            onChange={this.handleChange('facet')}
            value={this.state.facet}
          >
            <MenuItem value="any">any</MenuItem>
            <MenuItem value="111">111</MenuItem>
            <MenuItem value="100">100</MenuItem>
            <MenuItem value="110">110</MenuItem>
            <MenuItem value="211">211</MenuItem>
            <MenuItem value="311">311</MenuItem>
            <MenuItem value="other">other</MenuItem>
          </Select>
        </FormControl>
        {'   '}
        <FormControl
          style={{ minWidth: 120 }}
        >
          <InputLabel>Site</InputLabel>
          <Select
            onChange={this.handleChange('site')}
            value={this.state.site}
          >
            <MenuItem value="any">any</MenuItem>
            <MenuItem value="fcc">fcc</MenuItem>
            <MenuItem value="hcp">hcp</MenuItem>
            <MenuItem value="bridge">bridge</MenuItem>
            <MenuItem value="hollow">hollow</MenuItem>
            <MenuItem value="top">top</MenuItem>
            <MenuItem value="other">other</MenuItem>
          </Select>
        </FormControl>
        <MButton raised onClick={this.clearForm}><MdClear /> Clear</MButton>
        <MButton raised onClick={this.submitQuery} color="primary"><MdSearch /> Search</MButton>

    );
  }
}

GeneralSearch.propTypes = {
  receiveResults: PropTypes.func,
};

export default GeneralSearch;
<commit_msg>Prettied up printing of publications list<commit_after>/**
 *
 * GeneralSearch
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

import TextField from 'material-ui/TextField';
import { MenuItem } from 'material-ui/Menu';
import { InputLabel } from 'material-ui/Input';
import Select from 'material-ui/Select';

import { FormControl } from 'material-ui/Form';
import Button from 'material-ui/Button';
import { MdClear, MdSearch } from 'react-icons/lib/md';
import { LinearProgress } from 'material-ui/Progress';

import axios from 'axios';
import { graphQLRoot } from 'utils/constants';

const MButton = styled(Button)`
  margin: 12px;
`;

class GeneralSearch extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      free_text: '',
      year: '',
      authors: '',
      article_title: '',
      journal_title: '',
      facet: '',
      site: '',
      composition: '',
      loading: false,
    };
    // Workaround, instead of calling .bind in every render
    this.submitQuery = this.submitQuery.bind(this);
    this.clearForm = this.clearForm.bind(this);
  }
  submitQuery() {
    this.setState({
      loading: true,
    });
    axios.post(graphQLRoot, {
      query: `query{systems {
  edges {
    node {
        uniqueId
        Formula
        volume
        Facet
    }
  }
  }}`,
    }).then((response) => {
      this.setState({
        loading: false,
      });
      this.props.receiveResults(response.data.data.systems.edges);
    });
  }

  handleChange(name) {
    return (event) => {
      this.setState({
        [name]: event.target.value,
      });
    };
  }
  clearForm() {
    this.setState({
      free_text: '',
      composition: '',
      year: '',
      authors: '',
      article_title: '',
      journal_title: '',
      facet: '',
      site: '',
      results: [],
    });
  }
  render() {
    return (

General Search

        <TextField label="Free Text Search" value={this.state.free_text} onChange={this.handleChange('free_text')} />
        {'\t '}
        <TextField label="Composition" value={this.state.composition} onChange={this.handleChange('composition')} />
        {'\t '}
        <TextField label="Year" value={this.state.year} onChange={this.handleChange('year')} />

        <TextField label="Authors" value={this.state.authors} onChange={this.handleChange('authors')} />
        {'\t '}
        <TextField label="Title of Article" value={this.state.article_title} onChange={this.handleChange('article_title')} />
        {'\t '}
        <TextField label="Title of Journal" value={this.state.journal_title} onChange={this.handleChange('journal_title')} />

        <FormControl
          style={{ minWidth: 120, margin: 12 }}
        >
          <InputLabel>Facet</InputLabel>
          <Select
            onChange={this.handleChange('facet')}
            value={this.state.facet}
          >
            <MenuItem value="any">any</MenuItem>
            <MenuItem value="111">111</MenuItem>
            <MenuItem value="100">100</MenuItem>
            <MenuItem value="110">110</MenuItem>
            <MenuItem value="211">211</MenuItem>
            <MenuItem value="311">311</MenuItem>
            <MenuItem value="other">other</MenuItem>
          </Select>
        </FormControl>
        {'   '}
        <FormControl
          style={{ minWidth: 120 }}
        >
          <InputLabel>Site</InputLabel>
          <Select
            onChange={this.handleChange('site')}
            value={this.state.site}
          >
            <MenuItem value="any">any</MenuItem>
            <MenuItem value="fcc">fcc</MenuItem>
            <MenuItem value="hcp">hcp</MenuItem>
            <MenuItem value="bridge">bridge</MenuItem>
            <MenuItem value="hollow">hollow</MenuItem>
            <MenuItem value="top">top</MenuItem>
            <MenuItem value="other">other</MenuItem>
          </Select>
        </FormControl>
        <MButton raised onClick={this.clearForm}><MdClear /> Clear</MButton>
        <MButton raised onClick={this.submitQuery} color="primary"><MdSearch /> Search</MButton>
        {this.state.loading ? <LinearProgress color="primary" /> : null }

    );
  }
}

GeneralSearch.propTypes = {
  receiveResults: PropTypes.func,
};

export default GeneralSearch;
<|endoftext|>


<commit_before>import mongoose from 'mongoose';

const schema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  userIds: [Schema.Types.ObjectId]
});

export default function getChanelModel() {
  return mongoose.model('Chanel', schema);
}
<commit_msg>Resolve eslint errors<commit_after>import mongoose from 'mongoose';

const schema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  userIds: [Schema.Types.ObjectId],
});

export default function getChanelModel() {
  return mongoose.model('Chanel', schema);
}
<|endoftext|>


<commit_before>app.controller('DashboardCtrl', DashboardCtrl);

DashboardCtrl.$inject = ['$scope', '$q', 'hub', 'printer', 'sensor'];

function DashboardCtrl($scope, $q, hub,  printer, sensor) {
  $scope.printer = {};
  var defaultHubId = $scope.user._user.default_hub_id;
  console.log('using hub: ' + defaultHubId);

  $scope.chartData = [
    {label: 'Download Sales', value: 12},
    {label: 'In-Store Sales', value: 30},
    {label: 'Mail-Order Sales', value: 20},
  ];
  $scope.chartColors = ['#31C0BE', '#c7254e', '#98a0d3'];
  $scope.myFormatter = function(input) {
    return input + '%';
  };

  /********************************************************
   * Methods and chart handling
   */

  /**
   * SetPrinter
   * sets the $scope.printer to the printer with the id passed in
   * Used for the printer well
   *
   * @param id
   * @returns {undefined}
   */
  $scope.setPrinter = function(id) {
    for (var i = 0; i < $scope.printers.length; i++) {
      if ($scope.printers[i].id === id) {
        $scope.printer = $scope.printers[i];
        $scope.getCurrentJob();
      }
    }
  };

  $scope.getCurrentJob = function() {
    printer.getCurrentJob($scope.printer.id)
    .success(function(response) {
      $scope.printer.currentJob = response;
    })
    .error(function(response) {
      console.log('Unable to retrieve current job.');
      console.log(response);
    });
  };

  /********************************************************
   * Promise Handling
   * Fetching all objects
   */
  var defaultHubPromise = hub.getHub(defaultHubId);
  defaultHubPromise.then(function(_hub) {
    $scope.hub = _hub;
  });

  var statsPromise = hub.getStatistics(defaultHubId);
  statsPromise.then(function(_stats) {
    $scope.stats = _stats;
  });

  var printersPromise = hub.getPrinters(defaultHubId);
  printersPromise .then(function(_printers) {
    var currentJobsPromise = [];
    $scope.printers = _printers;
    $scope.printer = $scope.printers[0];
    $scope.getCurrentJob($scope.printer.id);
  });

  /*
   * Retrieving all sensors that are connected to the hub
   *  $scope.sensors {object}[]
   * Handling the promise for retrieving the sensor data and assigning that data to the associated sensor
   *  $scope.sensors.data {object}
   *  $scope.sensors.newestDatum
   */
  var sensorsPromise = hub.getSensors(defaultHubId);
  sensorsPromise.then(function(_sensors) {
    var sensorDataPromises = [];
    $scope.sensors = _sensors;

    for (var i = 0; i < $scope.sensors.length; i++) {
      sensorDataPromises.push(sensor.getData($scope.sensors[i].id));
    }

    // Execute all promises
    $q.all(sensorDataPromises).then(function(_data) {
      var sensorData = _data;
      var tempSensors = [];
      var humidSensors = [];

      for (var j = 0; j < sensorData.length; j++) {
        // Bind to a variable in the sensor itself
        $scope.sensors[j].data = sensorData[j];
        if ($scope.sensors[j].category === 'temperature') {
          populateTempGraph($scope.sensors[j].data);
          // Populate temperature data for graph

        } else if ($scope.sensors[j].category === 'humidity') {
          // Populate humidity graph
        }
      }
    });
  });

  /********************************************************
   * Local functions
   */

  var truncateData = function(object) {
    // $scope.sensors[j].data[j].value = parseFloat($scope.sensors[j].data[j].value.toFixed(2));
  };
}
<commit_msg>Don't look at this is horrible.  I must be drugged rn<commit_after>app.controller('DashboardCtrl', DashboardCtrl);

DashboardCtrl.$inject = ['$scope', '$q', 'hub', 'printer', 'sensor'];

function DashboardCtrl($scope, $q, hub,  printer, sensor) {
  $scope.printer = {};
  var defaultHubId = $scope.user._user.default_hub_id;
  console.log('using hub: ' + defaultHubId);

  $scope.chartData = [
    {label: 'Download Sales', value: 12},
    {label: 'In-Store Sales', value: 30},
    {label: 'Mail-Order Sales', value: 20},
  ];
  $scope.chartColors = ['#31C0BE', '#c7254e', '#98a0d3'];
  $scope.myFormatter = function(input) {
    return input + '%';
  };

  /********************************************************
   * Methods and chart handling
   */

  /**
   * SetPrinter
   * sets the $scope.printer to the printer with the id passed in
   * Used for the printer well
   *
   * @param id
   * @returns {undefined}
   */
  $scope.setPrinter = function(id) {
    for (var i = 0; i < $scope.printers.length; i++) {
      if ($scope.printers[i].id === id) {
        $scope.printer = $scope.printers[i];
        $scope.getCurrentJob();
      }
    }
  };

  $scope.getCurrentJob = function() {
    printer.getCurrentJob($scope.printer.id)
    .success(function(response) {
      $scope.printer.currentJob = response;
    })
    .error(function(response) {
      console.log('Unable to retrieve current job.');
      console.log(response);
    });
  };

  /********************************************************
   * Promise Handling
   * Fetching all objects
   */
  var defaultHubPromise = hub.getHub(defaultHubId);
  defaultHubPromise.then(function(_hub) {
    $scope.hub = _hub;
  });

  var statsPromise = hub.getStatistics(defaultHubId);
  statsPromise.then(function(_stats) {
    $scope.stats = _stats;
  });

  var printersPromise = hub.getPrinters(defaultHubId);
  printersPromise .then(function(_printers) {
    var currentJobsPromise = [];
    $scope.printers = _printers;
    $scope.printer = $scope.printers[0];
    $scope.getCurrentJob($scope.printer.id);
  });

  /*
   * Retrieving all sensors that are connected to the hub
   *  $scope.sensors {object}[]
   * Handling the promise for retrieving the sensor data and assigning that data to the associated sensor
   *  $scope.sensors.data {object}
   *  $scope.sensors.newestDatum
   */
  var sensorsPromise = hub.getSensors(defaultHubId);
  sensorsPromise.then(function(_sensors) {
    var sensorDataPromises = [];
    $scope.sensors = _sensors;

    for (var i = 0; i < $scope.sensors.length; i++) {
      sensorDataPromises.push(sensor.getData($scope.sensors[i].id));
    }

    // Execute all promises
    $q.all(sensorDataPromises).then(function(_data) {
      var sensorData = _data;
      var tempSensors = [];
      var humidSensors = [];

      for (var j = 0; j < sensorData.length; j++) {
        // Bind to a variable in the sensor itself
        $scope.sensors[j].data = sensorData[j];
        if ($scope.sensors[j].category === 'temperature') {
          // $scope.sensors[j].data = truncateData($scope.sensors[j].data);
          // $scope.sensors[j] = truncateData($scope.sensors[j]);
          truncateData($scope.sensors[j]);

          // Console.log($scope.sensors[j].data);
          // TempSensor.push($scope.sensors[j]);
          // PopulateTempGraph($scope.sensors[j]);
          // Populate temperature data for graph

        } else if ($scope.sensors[j].category === 'humidity') {
          // Populate humidity graph
        }
      }
    });
  });

  /********************************************************
   * Local functions
   */
  function truncateData(_sensor) {
    for (var i; i < _sensor.data.length; i++) {
      // _sensor.data[i].value = parseFloat(_sensor.data[i].value.toFixed(2));
      _sensor.data[i].value = 5;
      console.log('Truncated data ' + _sensor.data[i].value);
    }
    console.log('Truncated');
    console.log(_sensor.data);
  }

}
<|endoftext|>


<commit_before>'use strict';

//FIXME separate to multiple files

var Sequelize = require('sequelize'),
  nconf = require('nconf'),
  _ = require('lodash'),
  Promise = require('sequelize/node_modules/bluebird'),
  queries = require('./queries'),
  db = nconf.get('development');

var sequelize = new Sequelize(db.database, db.username, db.development, {
  host: db.host,
  dialect: db.dialect,
  define:{
    underscored: true,
    freezeTableName:true
  }
});
global.sequelize = sequelize;

var User = sequelize.define('users', {
  linkedin: Sequelize.STRING
});

var Job = sequelize.define('jobs', {
  money: Sequelize.STRING, // Number? (dealing with hourly-rate, gig budget, salary)
  company: Sequelize.STRING,
  description: Sequelize.TEXT,
  //id: Sequelize.STRING,
  key: Sequelize.STRING,
  location: Sequelize.STRING,
  source: Sequelize.STRING,
  title: Sequelize.STRING,
  url: Sequelize.STRING,
  remote: Sequelize.BOOLEAN
},
{
  classMethods: {
    filterByUser(user_id) {
      return sequelize.query(queries.filterJobs, { replacements: {user_id}, type: sequelize.QueryTypes.SELECT });
    },
    bulkCreateWithTags(jobs){
      //FIXME upsert
      //FIXME look into bulk-create (can do with associations?)
      //FIXME return promise (see require("bluebird"))
      //var tags = _(_.pluck(jobs, 'tags')).flatten().unique().value();

      jobs.forEach((job)=> {
        Job.findOrCreate({where:{key:job.key}, defaults:job}).spread((_job) => {
          job.tags.forEach((tag)=> {

            var key = tag.toLowerCase().replace(/\s/g, ''); // Angular JS, AngularJS => 'angularjs'
            if (key!='js') key = key.replace(/\.?js$/g, ''); // nodejs, node js, node.js, node => 'node'

            Tag.findOrCreate({where:{key}, defaults:{key, text:tag}}).spread((_tag)=>{
              _job.addTag(_tag);
            })
          })
        })
      })
    },
    addCustom(user_id, job){
      this.create(job).then((_job)=>{
        UserJob.create({user_id,job_id:_job.id,note:job.note,status:'applied'});
        //TODO add tags
      })
    },
    score(user_id, job_id, status, force){
      //TODO this can likely be cleaned up into a few efficient raw queries
      this.findOne({
        where:{id:job_id},
        include:[
          {model:Tag, include:[User]},
          User
        ]
      }).then(job=>{

        // First set its status
        var uj = job.users[0];
        if (uj) {
          uj.user_jobs.status= status;
          uj.user_jobs.save();
        } else {
          UserJob.create({user_id,job_id,status});
        }

        // then score attributes, unless setting to 'inbox' or req.params.force
        // force means "hide this post, but don't hurt it" (maybe repeats of something you've already applied to)
        var dir = (status=='inbox' || force==true) ? 0 : status=='hidden' ? -1 : +1;
        if (!dir) return;

        UserCompany.findOrCreate({where:{title:job.company,user_id}, defaults:{title:job.company,user_id}}).then(_userCompany=>{
          sequelize.query(`update user_companies set score=score+:score where title=:title and user_id=:user_id`,
            { replacements: {user_id, title:job.company, score:dir}, type: sequelize.QueryTypes.UPDATE });
          //fixme: `_userCompany.save is not a function` wtf??
          //_userCompany.score += dir;
          //_userCompany.save();
        })

        _.each(job.tags, tag=>{
          var user_tag = tag.users[0] && tag.users[0].user_tags;
          if (user_tag) {
            user_tag.score += dir;
            user_tag.save();
          }
          else {
            UserTag.create({user_id, tag_id:tag.id, score:dir});
          }
        })
      })
      //fixme return promise
    }
  },
  indexes: [
    {unique: true, fields: ['key']}
  ]
});

var Tag = sequelize.define('tags', {
  key: Sequelize.STRING,
  text: Sequelize.STRING
}, {
  indexes: [
    {unique:true, fields:['key']}
  ]
});

var UserJob = sequelize.define('user_jobs', {
  status: {type:Sequelize.ENUM('inbox','hidden','saved','applied'), defaultValue:'inbox'},
  note: Sequelize.TEXT
});

var UserCompany = sequelize.define('user_companies', {
  title: Sequelize.TEXT,
  score: {type:Sequelize.INTEGER, defaultValue:0}
});

var UserTag = sequelize.define('user_tags', {
  score: {type:Sequelize.INTEGER, defaultValue:0},
  locked: {type:Sequelize.BOOLEAN, defaultValue:false},
},
{
  classMethods: {
    lock(user_id, tag_id){
      return sequelize.query(`UPDATE user_tags SET locked = NOT locked WHERE user_id=:user_id AND tag_id=:tag_id`,
        { replacements: {user_id, tag_id:+tag_id}, type: sequelize.QueryTypes.UPDATE });
    }
  }
});

Tag.belongsToMany(Job, {through: 'job_tags'});
Job.belongsToMany(Tag, {through: 'job_tags'});

User.belongsToMany(Job, {through: UserJob});
Job.belongsToMany(User, {through: UserJob});

User.belongsToMany(Tag, {through: UserTag});
Tag.belongsToMany(User, {through: UserTag});

User.hasMany(UserCompany);

//sequelize.sync({force:true});
sequelize.sync();

module.exports = {User,Job,Tag,UserJob,UserTag};<commit_msg>add some table constraints<commit_after>'use strict';

//FIXME separate to multiple files

var Sequelize = require('sequelize'),
  nconf = require('nconf'),
  _ = require('lodash'),
  Promise = require('sequelize/node_modules/bluebird'),
  queries = require('./queries'),
  db = nconf.get('development');

var sequelize = new Sequelize(db.database, db.username, db.development, {
  host: db.host,
  dialect: db.dialect,
  define:{
    underscored: true,
    freezeTableName:true
  }
});
global.sequelize = sequelize;

var User = sequelize.define('users', {
  linkedin: {type:Sequelize.STRING, unique:true},
});

var Job = sequelize.define('jobs', {
  money: Sequelize.STRING, // Number? (dealing with hourly-rate, gig budget, salary)
  company: Sequelize.STRING,
  description: Sequelize.TEXT,
  //id: Sequelize.STRING,
  key: {type:Sequelize.STRING, allowNull:false, unique:true},
  location: Sequelize.STRING,
  source: {type:Sequelize.STRING, allowNull:false},
  title: {type:Sequelize.STRING, allowNull:false},
  url: {type:Sequelize.STRING, allowNull:false, unique:true},
  remote: Sequelize.BOOLEAN
},
{
  classMethods: {
    filterByUser(user_id) {
      return sequelize.query(queries.filterJobs, { replacements: {user_id}, type: sequelize.QueryTypes.SELECT });
    },
    bulkCreateWithTags(jobs){
      //FIXME upsert
      //FIXME look into bulk-create (can do with associations?)
      //FIXME return promise (see require("bluebird"))
      //var tags = _(_.pluck(jobs, 'tags')).flatten().unique().value();

      jobs.forEach((job)=> {
        Job.findOrCreate({where:{key:job.key}, defaults:job}).spread((_job) => {
          job.tags.forEach((tag)=> {

            var key = tag.toLowerCase().replace(/\s/g, ''); // Angular JS, AngularJS => 'angularjs'
            if (key!='js') key = key.replace(/\.?js$/g, ''); // nodejs, node js, node.js, node => 'node'

            Tag.findOrCreate({where:{key}, defaults:{key, text:tag}}).spread((_tag)=>{
              _job.addTag(_tag);
            })
          })
        })
      })
    },
    addCustom(user_id, job){
      this.create(job).then((_job)=>{
        UserJob.create({user_id,job_id:_job.id,note:job.note,status:'applied'});
        //TODO add tags
      })
    },
    score(user_id, job_id, status, force){
      //TODO this can likely be cleaned up into a few efficient raw queries
      this.findOne({
        where:{id:job_id},
        include:[
          {model:Tag, include:[User]},
          User
        ]
      }).then(job=>{

        // First set its status
        var uj = job.users[0];
        if (uj) {
          uj.user_jobs.status= status;
          uj.user_jobs.save();
        } else {
          UserJob.create({user_id,job_id,status});
        }

        // then score attributes, unless setting to 'inbox' or req.params.force
        // force means "hide this post, but don't hurt it" (maybe repeats of something you've already applied to)
        var dir = (status=='inbox' || force==true) ? 0 : status=='hidden' ? -1 : +1;
        if (!dir) return;

        UserCompany.findOrCreate({where:{title:job.company,user_id}, defaults:{title:job.company,user_id}}).then(_userCompany=>{
          sequelize.query(`update user_companies set score=score+:score where title=:title and user_id=:user_id`,
            { replacements: {user_id, title:job.company, score:dir}, type: sequelize.QueryTypes.UPDATE });
          //fixme: `_userCompany.save is not a function` wtf??
          //_userCompany.score += dir;
          //_userCompany.save();
        })

        _.each(job.tags, tag=>{
          var user_tag = tag.users[0] && tag.users[0].user_tags;
          if (user_tag) {
            user_tag.score += dir;
            user_tag.save();
          }
          else {
            UserTag.create({user_id, tag_id:tag.id, score:dir});
          }
        })
      })
      //fixme return promise
    }
  },
  indexes: [
    {unique: true, fields: ['key']}
  ]
});

var Tag = sequelize.define('tags', {
  key: {type:Sequelize.STRING, allowNull:false, unique:true},
  text: Sequelize.STRING
}, {
  indexes: [
    {unique:true, fields:['key']}
  ]
});

var UserJob = sequelize.define('user_jobs', {
  status: {type:Sequelize.ENUM('inbox','hidden','saved','applied'), defaultValue:'inbox', allowNull:false},
  note: Sequelize.TEXT
});

var UserCompany = sequelize.define('user_companies', {
  title: Sequelize.TEXT,
  score: {type:Sequelize.INTEGER, defaultValue:0, allowNull:false}
});

var UserTag = sequelize.define('user_tags', {
  score: {type:Sequelize.INTEGER, defaultValue:0, allowNull:false},
  locked: {type:Sequelize.BOOLEAN, defaultValue:false},
},
{
  classMethods: {
    lock(user_id, tag_id){
      return sequelize.query(`UPDATE user_tags SET locked = NOT locked WHERE user_id=:user_id AND tag_id=:tag_id`,
        { replacements: {user_id, tag_id:+tag_id}, type: sequelize.QueryTypes.UPDATE });
    }
  }
});

Tag.belongsToMany(Job, {through: 'job_tags'});
Job.belongsToMany(Tag, {through: 'job_tags'});

User.belongsToMany(Job, {through: UserJob});
Job.belongsToMany(User, {through: UserJob});

User.belongsToMany(Tag, {through: UserTag});
Tag.belongsToMany(User, {through: UserTag});

User.hasMany(UserCompany);

//sequelize.sync({force:true});
sequelize.sync();

module.exports = {User,Job,Tag,UserJob,UserTag};<|endoftext|>


<commit_before>import React from 'react';

import BrowserWarning from './BrowserWarning';
import { shallowWithIntl } from 'utils/testUtils';

describe('pages/browser-warning/BrowserWarning', () => {
  function getWrapper() {
    return shallowWithIntl(<BrowserWarning />);
  }

  test('renders a browser warning div', () => {
    const div = getWrapper().find('div');
    expect(div.length).toBe(1);
  });

  test('renders a browser warning paragraph', () => {
    const p = getWrapper().find('p');
    expect(p.length).toBe(2);
  });

  test('renders all specified browser links', () => {
    const a = getWrapper().find('a');
    expect(a.length).toBe(6);
  });
});
<commit_msg>Update test for browser warning component<commit_after>import React from 'react';

import BrowserWarning from './BrowserWarning';
import { shallowWithIntl } from 'utils/testUtils';

describe('pages/browser-warning/BrowserWarning', () => {
  function getWrapper() {
    return shallowWithIntl(<BrowserWarning />);
  }

  test('renders a browser warning div', () => {
    const div = getWrapper().find('div');
    expect(div.length).toBe(1);
  });

  test('renders a browser warning paragraph', () => {
    const p = getWrapper().find('p');
    expect(p.length).toBe(3);
  });

  test('renders all specified browser links', () => {
    const a = getWrapper().find('a');
    expect(a.length).toBe(9);
  });
});
<|endoftext|>


<commit_before>// robot.js -- OMG ROBOTS

var
  sys         = require('sys'),
  assert      = require('assert'),
  fieldobject = require('./fieldobject'),
  vec         = require('./vector'),
  NORTH       = new vec.Vector(0, 1);

function Robot(name, location, field) {
  this.name = name;
  this.field = field;
  this.location = new vec.Vector(location[0], location[1]);
  this.rotation = vec.normalizeAngle(Math.random() * 2 * Math.PI);
  this.wantedRotation = this.rotation;

  this.engine = 1;
  this.turretRot = 0;
  this.scanMode = "";
  this.scanWidth = Math.PI / 6;
  this.scanRange = 500;
  this.speed = 0;
  this.throttle = 0;
  this.armor = 100;
}
sys.inherits(Robot, fieldobject.FieldObject);

// Return enough information for a client to draw us on the screen.
Robot.prototype.renderInfo = function() {
  return {
    type: 'robot',
    name: this.name,
    location: [this.location.x, this.location.y],
    rotation: this.rotation,
    turret_rot: this.turretRot,
    scan_mode: this.scanMode,
    scan_width: this.scanWidth,
    scanrange: this.scanRange,
    speed: this.speed
  };
};

Robot.prototype.toJSON = function() {
  return {
    name: this.name,
    armor: this.armor
  };
};

Robot.prototype.pump = function() {
  // Calculate our physics: turn, move, or whatever.
  // First, we'll turn.
  var angleDiff = vec.normalizeAngle(this.wantedRotation - this.rotation),
      rotAccel = this.engine/5;
  if (Math.abs(angleDiff) < rotAccel) {
    this.rotation = this.wantedRotation;
  } else {
    this.rotation += angleDiff>0? rotAccel : -rotAccel;
  }
  this.rotation = vec.normalizeAngle(this.rotation);

  // Now, do throttle!
  var speedDiff = this.throttle - this.speed,
      accel = this.engine * 3;
  if (Math.abs(speedDiff) < accel) {
    this.speed += speedDiff;
  } else {
    this.speed += speedDiff>0? accel : -accel;
  }

  // Now, change our location!
  this.field.move(this,
    new vec.Vector(
      Math.sin(this.rotation),
      Math.cos(this.rotation)
    ).multiply(this.speed));
};

Robot.prototype.turn = function(amount) {
  this.wantedRotation = this.rotation + amount;
  return amount;
};

Robot.prototype.bearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |
    // |
    // |-.  this angle
    // |  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - this.rotation
    );
};

Robot.prototype.turretBearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |   /turret angle
    // |  /
    // | /. return this angle
    // |/  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - (this.rotation + this.turretRot)
    );
};

Robot.prototype.distanceTo = function(location) {
    return this.location.sub(location).dist();
};

Robot.prototype.getTurretRot = function() {
  return this.turretRot;
};

Robot.prototype.setTurretRot = function(newRot) {
  this.turretRot = vec.normalizeAngle(newRot);
  return newRot;
};

Robot.prototype.getLocation = function() {
  return [this.location.x, this.location.y];
};

Robot.prototype.setThrottle = function(throttle) {
  // Set throttle. The minimum we can have is -self.engine*5 and the max we
  // can have is self.engine*10.
  // This expects a number between -50 and 100.
  var amount = Math.max(-50, Math.min(throttle, 100));
  this.throttle = 10 * this.engine * amount/100;
  return this.throttle;
};

Robot.prototype.getThrottle = function() {
  return this.throttle;
};

Robot.prototype.scanRobots = function(scanWidth) {
    // Scan for robots! Returns a function that, when called, will scan for
    // other robots.
    // Steps:
    //  - Find all objects within scanRange of us
    //  - Of these, only keep robots that aren't ourselves that are within our
    //    scan arc
    //  - Then, return this list to the client, mixing in bearing and distance
    //    information wrt our turret
    assert.ok(scanWidth <= Math.PI/2, "You can only scan 90° to one side.");
    assert.equal(this.scanMode, "", "You are already scanning for something!");
    // Do this right away so the client knows to draw the scan arc
    this.scanMode = "robots";
    this.scanWidth = scanWidth;

    // The gamelogic will call this function later.
    var self = this; // for closure
    return function finishScan() {
      // Tell the client to stop drawing a scan arc
      self.scanMode = "";
      // Find all objects within our radius...
      return self.field.allObjectsWithin(self.location, self.scanRange).filter(
        function filter(obj) {
          // Only keep the robots that aren't ourselves and that are within
          // our scan arc
          return (obj instanceof Robot) &&
                 (obj !== self) &&
                 (Math.abs(self.turretBearingTo(obj.location)) <
                   self.scanWidth);
        }).map(function (obj) {
          // Now, take the resulting list of robots and augment them with
          // distance and angle information. Return this list to the client.
          return process.mixin(obj.toJSON(),
            {
              distance: Math.floor(self.distanceTo(obj.location)/20)*20,
              bearing: Math.round(
                self.turretBearingTo(obj.location)*2/self.scanWidth)/2
            }
          );
        });
    };
};

process.mixin(exports,
  {
    Robot: Robot
  }
);
<commit_msg>Minor formatting change to test github's postreceive hooks<commit_after>// robot.js -- OMG ROBOTS

var
  sys         = require('sys'),
  assert      = require('assert'),
  fieldobject = require('./fieldobject'),
  vec         = require('./vector'),
  NORTH       = new vec.Vector(0, 1);

function Robot(name, location, field) {
  this.name = name;
  this.field = field;
  this.location = new vec.Vector(location[0], location[1]);
  this.rotation = vec.normalizeAngle(Math.random() * 2 * Math.PI);
  this.wantedRotation = this.rotation;

  this.engine = 1;
  this.turretRot = 0;
  this.scanMode = "";
  this.scanWidth = Math.PI / 6;
  this.scanRange = 500;
  this.speed = 0;
  this.throttle = 0;
  this.armor = 100;
}
sys.inherits(Robot, fieldobject.FieldObject);

// Return enough information for a client to draw us on the screen.
Robot.prototype.renderInfo = function() {
  return {
    type: 'robot',
    name: this.name,
    location: [this.location.x, this.location.y],
    rotation: this.rotation,
    turret_rot: this.turretRot,
    scan_mode: this.scanMode,
    scan_width: this.scanWidth,
    scanrange: this.scanRange,
    speed: this.speed
  };
};

Robot.prototype.toJSON = function() {
  return {
    name: this.name,
    armor: this.armor
  };
};

Robot.prototype.pump = function() {
  // Calculate our physics: turn, move, or whatever.
  // First, we'll turn.
  var angleDiff = vec.normalizeAngle(this.wantedRotation - this.rotation),
      rotAccel = this.engine/5;
  if (Math.abs(angleDiff) < rotAccel) {
    this.rotation = this.wantedRotation;
  } else {
    this.rotation += angleDiff>0? rotAccel : -rotAccel;
  }
  this.rotation = vec.normalizeAngle(this.rotation);

  // Now, do throttle!
  var speedDiff = this.throttle - this.speed,
      accel = this.engine * 3;
  if (Math.abs(speedDiff) < accel) {
    this.speed += speedDiff;
  } else {
    this.speed += speedDiff>0? accel : -accel;
  }

  // Now, change our location!
  this.field.move(this,
    new vec.Vector(
      Math.sin(this.rotation),
      Math.cos(this.rotation)
    ).multiply(this.speed));
};

Robot.prototype.turn = function(amount) {
  this.wantedRotation = this.rotation + amount;
  return amount;
};

Robot.prototype.bearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |
    // |
    // |-.  this angle
    // |  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - this.rotation
    );
};

Robot.prototype.turretBearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |   /turret angle
    // |  /
    // | /. return this angle
    // |/  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - (this.rotation + this.turretRot)
    );
};

Robot.prototype.distanceTo = function(location) {
    return this.location.sub(location).dist();
};

Robot.prototype.getTurretRot = function() {
  return this.turretRot;
};

Robot.prototype.setTurretRot = function(newRot) {
  this.turretRot = vec.normalizeAngle(newRot);
  return newRot;
};

Robot.prototype.getLocation = function() {
  return [this.location.x, this.location.y];
};

Robot.prototype.setThrottle = function(throttle) {
  // Set throttle. The minimum we can have is -self.engine*5 and the max we
  // can have is self.engine*10.
  // This expects a number between -50 and 100.
  var amount = Math.max(-50, Math.min(throttle, 100));
  this.throttle = 10 * this.engine * amount/100;
  return this.throttle;
};

Robot.prototype.getThrottle = function() {
  return this.throttle;
};

Robot.prototype.scanRobots = function(scanWidth) {
    // Scan for robots! Returns a function that, when called, will scan for
    // other robots.
    // Steps:
    //  - Find all objects within scanRange of us
    //  - Of these, only keep robots that aren't ourselves that are within our
    //    scan arc
    //  - Then, return this list to the client, mixing in bearing and distance
    //    information wrt our turret
    assert.ok(scanWidth <= Math.PI/2, "You can only scan 90° to one side.");
    assert.equal(this.scanMode, "", "You are already scanning for something!");
    // Do this right away so the client knows to draw the scan arc
    this.scanMode = "robots";
    this.scanWidth = scanWidth;

    // The gamelogic will call this function later.
    var self = this; // for closure
    return function finishScan() {
      // Tell the client to stop drawing a scan arc
      self.scanMode = "";
      // Find all objects within our radius...
      return self.field.allObjectsWithin(self.location, self.scanRange).filter(
        function filter(obj) {
          // Only keep the robots that aren't ourselves and that are within
          // our scan arc
          return (obj instanceof Robot) &&
                 (obj !== self) &&
                 (Math.abs(self.turretBearingTo(obj.location)) <
                   self.scanWidth);
        }).map(function (obj) {
          // Now, take the resulting list of robots and augment them with
          // distance and angle information. Return this list to the client.
          return process.mixin(obj.toJSON(),
            {
              distance: Math.floor(self.distanceTo(obj.location)/20)*20,
              bearing: Math.round(
                self.turretBearingTo(obj.location)*2/self.scanWidth) /2
            }
          );
        });
    };
};

process.mixin(exports,
  {
    Robot: Robot
  }
);
<|endoftext|>


<commit_before>'use strict';

angular.module('ngQuestionnaires.questionnaireNewController', [
        'ng'
    ])
    .controller('questionnaireNewController', [
        '$scope',
        '$cacheFactory',
        function ($scope, $cacheFactory) {
            $scope.action = 'New';

            $scope.questions = $cacheFactory.get('data').get('questions');

            $scope.addQuestion = function () {
                // store questionnaire inputs in cache service
                // store return to new questionnaire in cache service
                // navigate to new question form
                // on save new question,
                //  persist state and check for return to value in cache service,
                //  then navigate there
                // on cancel new question,
                //  check for return to value in cache service,
                //  then navigate there
                // on returning to new questionnaire form,
                //  check cache service for questionnaire inputs and display them,
                //  then remove from cache service
            };
        }]);<commit_msg>Use cache factory to save questionnaire and return url on add new question<commit_after>'use strict';

angular.module('ngQuestionnaires.questionnaireNewController', [
        'ng'
    ])
    .controller('questionnaireNewController', [
        '$scope',
        '$cacheFactory',
        '$location',
        function ($scope, $cacheFactory, $location) {
            $scope.action = 'New';

            var questionnaire = $cacheFactory.get('data').get('questionnaire');
            if (questionnaire !== undefined) {
                $scope.questionnaire = questionnaire;
                $cacheFactory.get('data').remove('questionnaire');
            }

            $scope.questions = $cacheFactory.get('data').get('questions');

            $scope.addQuestion = function () {
                $cacheFactory.get('data').put('questionnaire', $scope.questionnaire);
                $cacheFactory.get('data').put('returnTo', $location.url());
                $location.url('/questions/new');
            };
        }]);<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Offering = mongoose.model('Offering'),
	_ = require('lodash');

/**
 * Create a Offering
 */
exports.create = function(req, res) {
	var offering = new Offering(req.body);
	console.log('POST request body is ',req.body);
	console.log('POST request body.id is ',req.body._id);
	offering.user = req.user;

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Show the current Offering
 */
exports.read = function(req, res) {
	console.log('read route',req.query);
	res.jsonp(req.offering);
};

/**
 * Update a Offering
 */
exports.update = function(req, res) {
	var offering = req.offering ;
	console.log('PUT request body is ',req.body);
	console.log('PUT request body.id is ',req.body._id);
	console.log('req.offering is ',req.offering);

	offering = _.extend(offering , req.body);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Delete an Offering
 */
exports.delete = function(req, res) {
	var offering = req.offering ;

	offering.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * List of Offerings and search based on user entered input
 */
exports.list = function(req, res) {
	var keyNames = Object.keys(req.query);

	//error handling function
	var offeringsErr = function (err, offerings) {
		if (err) {
			return res.status(400).send({
			message: errorHandler.getErrorMessage(err)
		});
		}
		else {
			res.jsonp(offerings);
		}
	};

	// if no search key is specified, get full list of offerings, since no query is specified
	if (keyNames.length === 0) {
		Offering.find().sort('-created').populate('user', 'displayName').sort('-created').exec(offeringsErr);
	}
	 	// if first key is price, get all offerings with price <= the value in the pair
 	else if (keyNames[0] === 'price'){
 		Offering.where('price').lte(req.query[keyNames[0]]).sort('-created').exec(offeringsErr);
 	}
	// search the list of offerings with the first key:value pair in the query
	else if (keyNames[0] === 'user') {
		Offering.find().where(keyNames[0]).equals(req.query[keyNames[0]]).populate('interested', 'displayName').sort('-created').exec(function(err, offerings) {
		// Offering.find().where(keyNames[0]).equals(req.query[keyNames[0]]).sort('-created').populate('interested').exec(function(err, offerings) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(offerings);
			}
		});
	}
	// otherwise search index
	else {
		Offering.find({ $text: { $search: req.query[keyNames[0]] }}).sort('-created').exec(offeringsErr);
	}
};

/**
 * List of Offerings by this User
 * added by Marc
 */
exports.listByUser = function(req, res) {
	Offering.find().where('user').equals(req.user).sort('-created').exec(function(err, offerings) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offerings);
		}
	});
};

/**
 * Update an Offering to register the user's interest in purchasing it.
 * This function performs the document modification, then saves it to the database and returns
 * the result to the user/client.
 */
exports.addInterested = function(req, res) {
	var offering = req.offering ;
	var userId = req.user._id;

	offering.interested.push(userId);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

exports.addRating = function(req, res) {
	var offering = req.offering ;
	// The req.body contains the updated offering.
	offering = _.extend(offering , req.body);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Offering middleware
 */
exports.offeringByID = function(req, res, next, id) {
	Offering.findById(id).populate('user', 'displayName').populate('interested', 'displayName').populate('rater', 'displayName').populate('rating.comments').exec(function(err, offering) {
		console.log('offeringByID status is ',req.params);
		if (err) return next(err);
		if (! offering) return next(new Error('Failed to load Offering ' + id));
		req.offering = offering ;
		next();
	});
};

/**
 * Offering authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.offering.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>Modified standard offering query to populate the rating array.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Offering = mongoose.model('Offering'),
	User = mongoose.model('User'),
	_ = require('lodash');

/**
 * Create a Offering
 */
exports.create = function(req, res) {
	var offering = new Offering(req.body);
	console.log('POST request body is ',req.body);
	console.log('POST request body.id is ',req.body._id);
	offering.user = req.user;

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Show the current Offering
 */
exports.read = function(req, res) {
	console.log('read route',req.query);
	res.jsonp(req.offering);
};

/**
 * Update a Offering
 */
exports.update = function(req, res) {
	var offering = req.offering ;
	console.log('PUT request body is ',req.body);
	console.log('PUT request body.id is ',req.body._id);
	console.log('req.offering is ',req.offering);

	offering = _.extend(offering , req.body);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Delete an Offering
 */
exports.delete = function(req, res) {
	var offering = req.offering ;

	offering.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * List of Offerings and search based on user entered input
 */
exports.list = function(req, res) {
	var keyNames = Object.keys(req.query);

	//error handling function
	var offeringsErr = function (err, offerings) {
		if (err) {
			return res.status(400).send({
			message: errorHandler.getErrorMessage(err)
		});
		}
		else {
			res.jsonp(offerings);
		}
	};

	// if no search key is specified, get full list of offerings, since no query is specified
	if (keyNames.length === 0) {
		Offering.find().sort('-created').populate('user', 'displayName').sort('-created').exec(offeringsErr);
	}
	 	// if first key is price, get all offerings with price <= the value in the pair
 	else if (keyNames[0] === 'price'){
 		Offering.where('price').lte(req.query[keyNames[0]]).sort('-created').exec(offeringsErr);
 	}
	// search the list of offerings with the first key:value pair in the query
	else if (keyNames[0] === 'user') {
		Offering.find().where(keyNames[0]).equals(req.query[keyNames[0]]).populate('interested', 'displayName').sort('-created').exec(function(err, offerings) {
		// Offering.find().where(keyNames[0]).equals(req.query[keyNames[0]]).sort('-created').populate('interested').exec(function(err, offerings) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(offerings);
			}
		});
	}
	// otherwise search index
	else {
		Offering.find({ $text: { $search: req.query[keyNames[0]] }}).sort('-created').exec(offeringsErr);
	}
};

/**
 * List of Offerings by this User
 * added by Marc
 */
exports.listByUser = function(req, res) {
	Offering.find().where('user').equals(req.user).sort('-created').exec(function(err, offerings) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offerings);
		}
	});
};

/**
 * Update an Offering to register the user's interest in purchasing it.
 * This function performs the document modification, then saves it to the database and returns
 * the result to the user/client.
 */
exports.addInterested = function(req, res) {
	var offering = req.offering ;
	var userId = req.user._id;

	offering.interested.push(userId);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

exports.addRating = function(req, res) {
	var offering = req.offering ;
	// The req.body contains the updated offering.
	offering = _.extend(offering , req.body);

	offering.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(offering);
		}
	});
};

/**
 * Offering middleware
 */
exports.offeringByID = function(req, res, next, id) {
	Offering.findById(id).populate({
			path: 'user interested rater',
			select: 'displayName'
		}).populate('rating.comments').exec(function(err, offering) {
		   var options = {
		        path: 'rating.comments.user',
		        model: 'User',
		        select: 'displayName'
    		};
		  		User.populate(offering, options, function(err, offering) {
				console.log('offeringByID status is ',req.params);
				if (err) return next(err);
				if (! offering) return next(new Error('Failed to load Offering ' + id));
				req.offering = offering ;
				next();
			});
    });
};

/**
 * Offering authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.offering.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name eagleEyeApp.directive:eagleeye
 * @description
 * # eagleeye
 */
angular.module('eagleeye')
  .directive('eeGoogleChart', [
    '$timeout',
    'GoogleChartsService',
    function ($timeout, GoogleChartsService) {
      var defaultChartOptions = GoogleChartsService.getDefaultChartOptions();

      return {
        template: '
<md-progress-circular class="ee-progress-circular" md-diameter="40"></md-progress-circular>
',
        scope: {
          chartDataTable: '=',
          chartOptions: '=',
          chartType: '='
        },
        restrict: 'E',
        link: function postLink(scope, element) {
          var chartNode = element[0];

          function drawChart() {
            google.charts.setOnLoadCallback(function drawOnLoad() {
              if (!scope.chartType || !scope.chartDataTable) {
                return;
              }

              var chart = new google.visualization[scope.chartType](chartNode);
              var chartDataTable = new google.visualization.DataTable(angular.copy(scope.chartDataTable, {}));
              var chartOptions = angular.extend(scope.chartOptions, defaultChartOptions[scope.chartType.toLowerCase()]);

              $timeout(chart.draw(chartDataTable, chartOptions), 0);
            });
          }

          var unwatchChartType = scope.$watch('chartType', drawChart);
          var unwatchChartOptions = scope.$watch('chartOptions', drawChart);
          var unwatchChartDataTable = scope.$watch('chartDataTable', drawChart);

          scope.$on('$destroy', function() {
            unwatchChartType();
            unwatchChartOptions();
            unwatchChartDataTable();
          });
        }
      };
    }
  ]);
<commit_msg>Redraw google charts when browser window is resized<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name eagleEyeApp.directive:eagleeye
 * @description
 * # eagleeye
 */
angular.module('eagleeye')
  .directive('eeGoogleChart', [
    '$timeout',
    '$window',
    'GoogleChartsService',
    function($timeout, $window, GoogleChartsService) {
      var defaultChartOptions = GoogleChartsService.getDefaultChartOptions();

      return {
        template: '
<md-progress-circular class="ee-progress-circular" md-diameter="40"></md-progress-circular>
',
        scope: {
          chartDataTable: '=',
          chartOptions: '=',
          chartType: '='
        },
        restrict: 'E',
        link: postLinkFn
      };

      function postLinkFn(scope, element) {
        var chartNode = element[0],
          redrawDelayOnResizeInMs = 200,
          timeoutID = -1;

        function drawChart() {
          google.charts.setOnLoadCallback(function drawOnLoad() {
            if (!scope.chartType || !scope.chartDataTable) {
              return;
            }

            var chart = new google.visualization[scope.chartType](chartNode);
            var chartDataTable = new google.visualization.DataTable(angular.copy(scope.chartDataTable, {}));
            var chartOptions = angular.extend(scope.chartOptions, defaultChartOptions[scope.chartType.toLowerCase()]);

            $timeout(chart.draw(chartDataTable, chartOptions), 0);
          });
        }

        function windowResizeHandler() {
          $window.clearTimeout(timeoutID);
          timeoutID = $window.setTimeout(function() {
            drawChart();
          }, redrawDelayOnResizeInMs);
        }

        var unwatchChartType = scope.$watch('chartType', drawChart);
        var unwatchChartOptions = scope.$watch('chartOptions', drawChart);
        var unwatchChartDataTable = scope.$watch('chartDataTable', drawChart);

        angular.element($window).on('resize', windowResizeHandler);

        scope.$on('$destroy', function() {
          unwatchChartType();
          unwatchChartOptions();
          unwatchChartDataTable();
        });
      }
    }
  ]);
<|endoftext|>