<commit_before>Ext.define('devilry.extjshelpers.assignmentgroup.DeliveriesGroupedByDeadline', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.deliveriesgroupedbydeadline',
    cls: 'widget-deliveriesgroupedbydeadline',
    requires: [
        'devilry.administrator.models.Deadline',
        'devilry.administrator.models.Delivery',
        'devilry.administrator.models.StaticFeedback',
        'devilry.examiner.models.Deadline',
        'devilry.examiner.models.Delivery',
        'devilry.examiner.models.StaticFeedback',
        'devilry.student.models.Deadline',
        'devilry.student.models.Delivery',
        'devilry.student.models.StaticFeedback',

        'devilry.extjshelpers.RestFactory',
        'devilry.extjshelpers.assignmentgroup.DeliveriesGrid',
        'devilry.extjshelpers.assignmentgroup.DeliveriesPanel',
        'devilry.extjshelpers.assignmentgroup.CreateNewDeadlineWindow'
    ],

    title: 'Deliveries grouped by deadline',

    layout: {
        type: 'accordion'
    },

    config: {
        role: undefined,
        assignmentgroup_recordcontainer: undefined,

        /**
         * @cfg
         * A {@link devilry.extjshelpers.SingleRecordContainer} for Delivery.
         * The record is changed when a user selects a delivery.
         */
        delivery_recordcontainer: undefined
    },

    constructor: function(config) {
        this.initConfig(config);
        this.callParent([config]);
        this.isLoading = true;
        this.assignmentgroup_recordcontainer.on('setRecord', this.loadAllDeadlines, this);
    },

    initComponent: function() {
        if(this.role != 'student') {
            this.bbar = [{
                xtype: 'button',
                text: 'New deadline',
                iconCls: 'icon-add-16',
                listeners: {
                    scope: this,
                    click: this.onCreateNewDeadline
                }
            }];
        }
        this.callParent(arguments);
        this.on('render', function() {
            Ext.defer(function() {
                this.addLoadMask();
            }, 100, this);
        }, this);
    },

    /**
     * @private
     */
    addLoadMask: function() {
        if(this.rendered && this.isLoading) {
            this.getEl().mask('Loading deliveries ...');
        }
    },

    /**
     * @private
     */
    loadAllDeadlines: function() {
        this.isLoading = true;
        this._tmp_deliveriespanels = [];
        this._tmp_active_feedbacks = [];
        this.addLoadMask();
        this.removeAll();
        var deadlinestore = devilry.extjshelpers.RestFactory.createStore(this.role, 'Deadline', {
            filters: [{
                property: 'assignment_group',
                value: this.assignmentgroup_recordcontainer.record.data.id
            }]
        });
        deadlinestore.proxy.setDevilryOrderby(['-deadline']);
        deadlinestore.loadAll({
            scope: this,
            callback: this.onLoadAllDeadlines
        });
    },

    /**
     * @private
     */
    onLoadAllDeadlines: function(deadlineRecords) {
        Ext.each(deadlineRecords, this.handleSingleDeadline, this);
    },

    /**
     * @private
     */
    handleSingleDeadline: function(deadlineRecord, index, deadlineRecords) {
        var deliveriesStore = deadlineRecord.deliveries();
        //deliveriesStore.pageSize = 1; // Uncomment to test paging
        deliveriesStore.load({
            scope: this,
            callback: function(deliveryRecords) {
                if(index === 0) {
                    this._handleLatestDeadline(deadlineRecords[0], deliveryRecords);
                }

                if(deliveryRecords.length === 0) {
                    this.addDeliveriesPanel(deadlineRecords, deadlineRecord, deliveriesStore);
                } else {
                    this.findLatestFeebackInDeadline(deadlineRecords, deadlineRecord, deliveriesStore, deliveryRecords)
                }
            }
        });
    },

    _handleLatestDeadline: function(deadlineRecord, deliveryRecords) {
        var is_open = this.assignmentgroup_recordcontainer.record.get('is_open');
        if(this.role != 'student' && deliveryRecords.length === 0 && deadlineRecord.get('deadline') < Ext.Date.now() && is_open) {
            this._onExpiredNoDeliveries();
        }
    },

    findLatestFeebackInDeadline: function(deadlineRecords, deadlineRecord, deliveriesStore, deliveryRecords) {
        var allStaticFeedbacks = [];
        var loadedStaticFeedbackStores = 0;
        Ext.each(deliveryRecords, function(deliveryRecord, index) {
            var staticfeedbackStore = deliveryRecord.staticfeedbacks();
            staticfeedbackStore.load({
                scope: this,
                callback: function(staticFeedbackRecords) {
                    loadedStaticFeedbackStores ++;
                    if(staticFeedbackRecords.length > 0) {
                        allStaticFeedbacks.push(staticFeedbackRecords[0]);
                    }
                    if(loadedStaticFeedbackStores === deliveryRecords.length) {
                        this.sortStaticfeedbacks(allStaticFeedbacks);
                        var activeFeedback = allStaticFeedbacks[0];
                        this.addDeliveriesPanel(deadlineRecords, deadlineRecord, deliveriesStore, activeFeedback);
                    }
                }
            })
        }, this);
    },

    /**
     * @private
     */
    sortStaticfeedbacks: function(allStaticFeedbacks) {
        allStaticFeedbacks.sort(function(a, b) {
            if(a.data.save_timestamp > b.data.save_timestamp) {
                return -1;
            } else if(a.data.save_timestamp === b.data.save_timestamp) {
                return 0;
            } else {
                return 1;
            }
        });
    },

    /**
     * @private
     */
    addDeliveriesPanel: function(deadlineRecords, deadlineRecord, deliveriesStore, activeFeedback) {
        this._tmp_deliveriespanels.push({
            xtype: 'deliveriespanel',
            delivery_recordcontainer: this.delivery_recordcontainer,
            deadlineRecord: deadlineRecord,
            deliveriesStore: deliveriesStore,
            assignmentgroup_recordcontainer: this.assignmentgroup_recordcontainer,
            activeFeedback: activeFeedback
        });
        this._tmp_active_feedbacks.push(activeFeedback);

        if(this._tmp_deliveriespanels.length === deadlineRecords.length) {
            this.sortDeliveryPanels();
            this.sortStaticfeedbacks(this._tmp_active_feedbacks);
            var latestStaticFeedback = this._tmp_active_feedbacks[0];
            Ext.each(this._tmp_deliveriespanels, function(deliveriespanel, index) {
                Ext.each(deliveriespanel.deliveriesStore.data.items, function(deliveryRecord, index) {
                    if(deliveryRecord.data.id === latestStaticFeedback.get('delivery')) {
                        deliveryRecord.hasLatestFeedback = true;
                    }
                }, this);
            }, this);
            this.add(this._tmp_deliveriespanels);
            this.getEl().unmask();
            this.isLoading = false;
        }
    },

    /**
     * @private
     * Sort delivery panels, since they are added on response from an
     * asynchronous operation. Sorted descending by deadline datetime.
     */
    sortDeliveryPanels: function() {
        this._tmp_deliveriespanels.sort(function(a, b) {
            if(a.deadlineRecord.data.deadline > b.deadlineRecord.data.deadline) {
                return -1;
            } else if(a.deadlineRecord.data.deadline === b.deadlineRecord.data.deadline) {
                return 0;
            } else {
                return 1;
            }
        });
    },

    /**
     * @private
     */
    onCreateNewDeadline: function() {
        var me = this;
        var createDeadlineWindow = Ext.widget('createnewdeadlinewindow', {
            assignmentgroupid: this.assignmentgroup_recordcontainer.record.data.id,
            deadlinemodel: Ext.String.format('devilry.{0}.models.Deadline', this.role),
            onSaveSuccess: function(record) {
                this.close();
                me.loadAllDeadlines();
            }
        });
        createDeadlineWindow.show();
    },

    /**
     * @private
     */
    _onExpiredNoDeliveries: function() {
        var win = Ext.MessageBox.show({
            title: 'This group has no deliveries, and their active deadline has expired',
            msg: '
Would you like to give the group a new deadline?

' +
                '
Choose yes to create a new deadline
' +
                '
Choose no to close the group. This fails the student on this assignment. You can re-open the group at any time.
' +
                '
Choose cancel to close this window without doing anything.
' +
                '
',
            buttons: Ext.Msg.YESNOCANCEL,
            scope: this,
            closable: false,
            fn: function(buttonId) {
                if(buttonId == 'yes') {
                    this.onCreateNewDeadline()
                } else if (buttonId == 'no') {
                    devilry.extjshelpers.assignmentgroup.IsOpen.closeGroup(this.assignmentgroup_recordcontainer);
                }
            }
        });
    },
});
<commit_msg>apps.extjshelpers...assignmentgroup: Code cleanup.<commit_after>Ext.define('devilry.extjshelpers.assignmentgroup.DeliveriesGroupedByDeadline', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.deliveriesgroupedbydeadline',
    cls: 'widget-deliveriesgroupedbydeadline',
    requires: [
        'devilry.administrator.models.Deadline',
        'devilry.administrator.models.Delivery',
        'devilry.administrator.models.StaticFeedback',
        'devilry.examiner.models.Deadline',
        'devilry.examiner.models.Delivery',
        'devilry.examiner.models.StaticFeedback',
        'devilry.student.models.Deadline',
        'devilry.student.models.Delivery',
        'devilry.student.models.StaticFeedback',

        'devilry.extjshelpers.RestFactory',
        'devilry.extjshelpers.assignmentgroup.DeliveriesGrid',
        'devilry.extjshelpers.assignmentgroup.DeliveriesPanel',
        'devilry.extjshelpers.assignmentgroup.CreateNewDeadlineWindow'
    ],

    title: 'Deliveries grouped by deadline',

    layout: {
        type: 'accordion'
    },

    config: {
        role: undefined,
        assignmentgroup_recordcontainer: undefined,

        /**
         * @cfg
         * A {@link devilry.extjshelpers.SingleRecordContainer} for Delivery.
         * The record is changed when a user selects a delivery.
         */
        delivery_recordcontainer: undefined
    },

    constructor: function(config) {
        this.initConfig(config);
        this.callParent([config]);
        this.isLoading = true;
        this.assignmentgroup_recordcontainer.on('setRecord', this.loadAllDeadlines, this);
    },

    initComponent: function() {
        if(this.role != 'student') {
            this.bbar = [{
                xtype: 'button',
                text: 'New deadline',
                iconCls: 'icon-add-16',
                listeners: {
                    scope: this,
                    click: this.onCreateNewDeadline
                }
            }];
        }
        this.callParent(arguments);
        this.on('render', function() {
            Ext.defer(function() {
                this.addLoadMask();
            }, 100, this);
        }, this);
    },

    /**
     * @private
     */
    addLoadMask: function() {
        if(this.rendered && this.isLoading) {
            this.getEl().mask('Loading deliveries ...');
        }
    },

    /**
     * @private
     */
    loadAllDeadlines: function() {
        this.isLoading = true;
        this._tmp_deliveriespanels = [];
        this._tmp_active_feedbacks = [];
        this.addLoadMask();
        this.removeAll();
        var deadlinestore = devilry.extjshelpers.RestFactory.createStore(this.role, 'Deadline', {
            filters: [{
                property: 'assignment_group',
                value: this.assignmentgroup_recordcontainer.record.data.id
            }]
        });
        deadlinestore.proxy.setDevilryOrderby(['-deadline']);
        deadlinestore.loadAll({
            scope: this,
            callback: this.onLoadAllDeadlines
        });
    },

    /**
     * @private
     */
    onLoadAllDeadlines: function(deadlineRecords) {
        Ext.each(deadlineRecords, this.handleSingleDeadline, this);
    },

    /**
     * @private
     */
    handleSingleDeadline: function(deadlineRecord, index, deadlineRecords) {
        var deliveriesStore = deadlineRecord.deliveries();
        //deliveriesStore.pageSize = 1; // Uncomment to test paging
        deliveriesStore.load({
            scope: this,
            callback: function(deliveryRecords) {
                if(index === 0) {
                    this._handleLatestDeadline(deadlineRecords[0], deliveryRecords);
                }

                if(deliveryRecords.length === 0) {
                    this.addDeliveriesPanel(deadlineRecords, deadlineRecord, deliveriesStore);
                } else {
                    this.findLatestFeebackInDeadline(deadlineRecords, deadlineRecord, deliveriesStore, deliveryRecords)
                }
            }
        });
    },

    _handleLatestDeadline: function(deadlineRecord, deliveryRecords) {
        var is_open = this.assignmentgroup_recordcontainer.record.get('is_open');
        if(this.role != 'student' && deliveryRecords.length === 0 && deadlineRecord.get('deadline') < Ext.Date.now() && is_open) {
            this._onExpiredNoDeliveries();
        }
    },

    findLatestFeebackInDeadline: function(deadlineRecords, deadlineRecord, deliveriesStore, deliveryRecords) {
        var allStaticFeedbacks = [];
        var loadedStaticFeedbackStores = 0;
        Ext.each(deliveryRecords, function(deliveryRecord, index) {
            var staticfeedbackStore = deliveryRecord.staticfeedbacks();
            staticfeedbackStore.load({
                scope: this,
                callback: function(staticFeedbackRecords) {
                    loadedStaticFeedbackStores ++;
                    if(staticFeedbackRecords.length > 0) {
                        allStaticFeedbacks.push(staticFeedbackRecords[0]);
                    }
                    if(loadedStaticFeedbackStores === deliveryRecords.length) {
                        this._sortStaticfeedbacks(allStaticFeedbacks);
                        var activeFeedback = allStaticFeedbacks[0];
                        this.addDeliveriesPanel(deadlineRecords, deadlineRecord, deliveriesStore, activeFeedback);
                    }
                }
            })
        }, this);
    },

    /**
     * @private
     */
    _sortStaticfeedbacks: function(allStaticFeedbacks) {
        allStaticFeedbacks.sort(function(a, b) {
            if(a.data.save_timestamp > b.data.save_timestamp) {
                return -1;
            } else if(a.data.save_timestamp === b.data.save_timestamp) {
                return 0;
            } else {
                return 1;
            }
        });
    },

    /**
     * @private
     */
    addDeliveriesPanel: function(deadlineRecords, deadlineRecord, deliveriesStore, activeFeedback) {
        this._tmp_deliveriespanels.push({
            xtype: 'deliveriespanel',
            delivery_recordcontainer: this.delivery_recordcontainer,
            deadlineRecord: deadlineRecord,
            deliveriesStore: deliveriesStore,
            assignmentgroup_recordcontainer: this.assignmentgroup_recordcontainer,
            activeFeedback: activeFeedback
        });
        this._tmp_active_feedbacks.push(activeFeedback);

        if(this._tmp_deliveriespanels.length === deadlineRecords.length) {
            this._sortDeliveryPanels();
            this._findAndMarkActiveFeedback();
            this.add(this._tmp_deliveriespanels);
            this.getEl().unmask();
            this.isLoading = false;
        }
    },

    _findAndMarkActiveFeedback: function() {
        this._sortStaticfeedbacks(this._tmp_active_feedbacks);
        var latestStaticFeedback = this._tmp_active_feedbacks[0];
        Ext.each(this._tmp_deliveriespanels, function(deliveriespanel, index) {
            Ext.each(deliveriespanel.deliveriesStore.data.items, function(deliveryRecord, index) {
                if(deliveryRecord.data.id === latestStaticFeedback.get('delivery')) {
                    deliveryRecord.hasLatestFeedback = true;
                }
            }, this);
        }, this);
    },

    /**
     * @private
     * Sort delivery panels, since they are added on response from an
     * asynchronous operation. Sorted descending by deadline datetime.
     */
    _sortDeliveryPanels: function() {
        this._tmp_deliveriespanels.sort(function(a, b) {
            if(a.deadlineRecord.data.deadline > b.deadlineRecord.data.deadline) {
                return -1;
            } else if(a.deadlineRecord.data.deadline === b.deadlineRecord.data.deadline) {
                return 0;
            } else {
                return 1;
            }
        });
    },

    /**
     * @private
     */
    onCreateNewDeadline: function() {
        var me = this;
        var createDeadlineWindow = Ext.widget('createnewdeadlinewindow', {
            assignmentgroupid: this.assignmentgroup_recordcontainer.record.data.id,
            deadlinemodel: Ext.String.format('devilry.{0}.models.Deadline', this.role),
            onSaveSuccess: function(record) {
                this.close();
                me.loadAllDeadlines();
            }
        });
        createDeadlineWindow.show();
    },

    /**
     * @private
     */
    _onExpiredNoDeliveries: function() {
        var win = Ext.MessageBox.show({
            title: 'This group has no deliveries, and their active deadline has expired',
            msg: '
Would you like to give the group a new deadline?

' +
                '
Choose yes to create a new deadline
' +
                '
Choose no to close the group. This fails the student on this assignment. You can re-open the group at any time.
' +
                '
Choose cancel to close this window without doing anything.
' +
                '
',
            buttons: Ext.Msg.YESNOCANCEL,
            scope: this,
            closable: false,
            fn: function(buttonId) {
                if(buttonId == 'yes') {
                    this.onCreateNewDeadline()
                } else if (buttonId == 'no') {
                    devilry.extjshelpers.assignmentgroup.IsOpen.closeGroup(this.assignmentgroup_recordcontainer);
                }
            }
        });
    },
});
<|endoftext|>


<commit_before>require('proof')(3, require('cadence')(prove))

function prove (async, okay) {
    var cadence = require('cadence')
    var Procession = require('procession')

    var Procedure = require('conduit/procedure')
    var Caller = require('conduit/caller')

    var Destructible = require('destructible')

    var Timer = require('happenstance').Timer

    var Kibitzer = require('..')
    var kibitzers = []

    var shifter

    var destructible = new Destructible('t/kibitzer.t.js')

    destructible.completed.wait(async())

    var createKibitzer = cadence(function (async, destructible, id, republic) {
        var kibitzer = new Kibitzer({
            republic: republic,
            id: id,
            ua: {
                send: cadence(function (async, envelope) {
                    kibitzers.filter(function (kibitzer) {
                        return kibitzer.paxos.id == envelope.to.location
                    }).pop().request(JSON.parse(JSON.stringify(envelope)), async())
                })
            }
        })
        async(function () {
            destructible.monitor('kibitzer', kibitzer, 'listen', async())
        }, function () {
            return kibitzer
        })
    })

    async([function () {
        console.log('destructed')
    }], function () {
        destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '0', 0, async())
    }, function (kibitzer) {
        kibitzers.push(kibitzer)
        okay(kibitzers[0], 'construct')
        kibitzers[0].bootstrap(1, { location: '0' })

        shifter = kibitzers[0].paxos.log.shifter()
    }, function () {
        destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '1', 0, async())
    }, function (kibitzer) {
        kibitzers.push(kibitzer)
        kibitzers[1].join(1)
        kibitzers[0].embark(1, '1', kibitzers[1].paxos.cookie, { location: '1' })
    }, function () {
        setTimeout(async(), 100)
    }, function () {
        destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '2', 0, async())
    }, function (kibitzer) {
        kibitzers.push(kibitzer)
        kibitzers[2].join(1)
        kibitzers[0].embark(1, '2', kibitzers[2].paxos.cookie, { location: '2' })
        kibitzers[2].paxos.log.shifter().join(function (entry) {
            return entry.promise == '3/0'
        }, async())
    }, function () {
        kibitzers[2].acclimate()
        kibitzers[2].publish(1)
        kibitzers[0].publish(1)
    }, function () {
        shifter.join(function (entry) {
            return entry.promise == '3/1'
        }, async())
    }, function (entry) {
        okay(entry.body.body, 1, 'published')
        kibitzers[2].request({
            method: 'enqueue',
            body: { cookie: '1', republic: 0, entries: [ '1' ] }
        }, async())
    }, function (response) {
        okay(response, null, 'failed submission')
        destructible.destroy()
    })
}
<commit_msg>Update unit test structure._<commit_after>require('proof')(3, prove)

function prove (okay, callback) {
    var cadence = require('cadence')
    var Procession = require('procession')

    var Procedure = require('conduit/procedure')
    var Caller = require('conduit/caller')

    var Destructible = require('destructible')

    var Timer = require('happenstance').Timer

    var Kibitzer = require('..')
    var kibitzers = []

    var shifter

    var destructible = new Destructible('t/kibitzer.t.js')

    destructible.completed.wait(callback)

    var createKibitzer = cadence(function (async, destructible, id, republic) {
        var kibitzer = new Kibitzer({
            republic: republic,
            id: id,
            ua: {
                send: cadence(function (async, envelope) {
                    kibitzers.filter(function (kibitzer) {
                        return kibitzer.paxos.id == envelope.to.location
                    }).pop().request(JSON.parse(JSON.stringify(envelope)), async())
                })
            }
        })
        async(function () {
            destructible.monitor('kibitzer', kibitzer, 'listen', async())
        }, function () {
            return kibitzer
        })
    })

    cadence(function (async) {
        async(function () {
            destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '0', 0, async())
        }, function (kibitzer) {
            kibitzers.push(kibitzer)
            okay(kibitzers[0], 'construct')
            kibitzers[0].bootstrap(1, { location: '0' })

            shifter = kibitzers[0].paxos.log.shifter()
        }, function () {
            destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '1', 0, async())
        }, function (kibitzer) {
            kibitzers.push(kibitzer)
            kibitzers[1].join(1)
            kibitzers[0].embark(1, '1', kibitzers[1].paxos.cookie, { location: '1' })
        }, function () {
            setTimeout(async(), 100)
        }, function () {
            destructible.monitor([ 'kibitzer', 0 ], true, createKibitzer, '2', 0, async())
        }, function (kibitzer) {
            kibitzers.push(kibitzer)
            kibitzers[2].join(1)
            kibitzers[0].embark(1, '2', kibitzers[2].paxos.cookie, { location: '2' })
            kibitzers[2].paxos.log.shifter().join(function (entry) {
                return entry.promise == '3/0'
            }, async())
        }, function () {
            kibitzers[2].acclimate()
            kibitzers[2].publish(1)
            kibitzers[0].publish(1)
        }, function () {
            shifter.join(function (entry) {
                return entry.promise == '3/1'
            }, async())
        }, function (entry) {
            okay(entry.body.body, 1, 'published')
            kibitzers[2].request({
                method: 'enqueue',
                body: { cookie: '1', republic: 0, entries: [ '1' ] }
            }, async())
        }, function (response) {
            okay(response, null, 'failed submission')
            destructible.destroy()
        })
    })(destructible.monitor('test'))
}
<|endoftext|>


<commit_before><commit_msg>Updated script to create overdue user<commit_after><|endoftext|>


<commit_before>// @flow
// $FlowMeteor
import { Meteor } from "meteor/meteor";
import Layout from "./Layout";

const Home = () => (
  <Layout />
);

export const Hai = () => (

Your Giving So Far

);

const Routes = [
  { path: "home",
    component: Home,
    rightComponent: <Hai />,
    onEnter: (nextState: Object, replace: Function) => {
      if (!Meteor.userId()) {
        replace("/give/now");
      }
    },
  },
];

export default {
  Home,
  Routes,
};
<commit_msg>updated to use setRightProps<commit_after>// @flow
import { Component } from "react";
// $FlowMeteor
import { Meteor } from "meteor/meteor";
import Layout from "./Layout";

type IHome = {
  setRightProps: Function,
};

class Home extends Component {
  props: IHome;
  componentWillMount() {
    this.props.setRightProps({
      background: "//s3.amazonaws.com/ns.images/all/heroes/a2617.stepuphero.1x2.nologo.jpg",
    });
  }
  render() {
    return <Layout />;
  }
}

export const Hai = () => (

Your Giving So Far

);

const Routes = [
  { path: "home",
    component: Home,
    rightComponent: <Hai />,
    onEnter: (nextState: Object, replace: Function) => {
      if (!Meteor.userId()) {
        replace("/give/now");
      }
    },
  },
];

export default {
  Home,
  Routes,
};
<|endoftext|>


<commit_before>/*
 * `compile` task
 * ==============
 *
 * Compile scripts in production mode using Webpack.
 */

import logger from 'gulplog';
import PluginError from 'plugin-error';
import webpack from '../lib/webpack';

const compile = done => {
  return webpack('production').run((err, stats) => {
    if (err) {
      throw new PluginError('webpack', err);
    }
    logger.info(`[webpack]\n${stats.toString({colors: true})}`);
    done();
  });
};
compile.description = `Compile scripts in production mode using Webpack.`;

export default compile;
<commit_msg>Make compile task a bit less verbose too.<commit_after>/*
 * `compile` task
 * ==============
 *
 * Compile scripts in production mode using Webpack.
 */

import logger from 'gulplog';
import PluginError from 'plugin-error';
import webpack from '../lib/webpack';

const compile = done => {
  return webpack('production').run((err, stats) => {
    if (err) {
      throw new PluginError('webpack', err);
    }
    logger.info(`[webpack]\n${stats.toString({
      colors: true,
      modules: false
    })}`);
    done();
  });
};
compile.description = `Compile scripts in production mode using Webpack.`;

export default compile;
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import {
  Button,
  Dimmer,
  Container,
  Header,
  Segment,
  Label,
  Loader,
  Progress,
  List,
  Menu,
  Input,
} from 'semantic-ui-react';
import * as _ from 'lodash';
import Highlight from 'react-highlight';
import {services} from '../../actions/services';
import {
  mergeState,
  mgrUpdateGen,
} from '../../util/localStateOperations';
import TerminatedAgreements from './terminatedAgreements'

class Dashboard extends Component {

  constructor(props) {
    super(props);

    const init = {
      ephemeral: {
        fetching: true,
        interval: undefined,
      },
      activeItem: 'active',
      services: [], // enriched
      terminatedAgreementsFilter: '',
    };

    this.state = init;

    this.handleItemClick = this.handleItemClick.bind(this);
    this.updateTerminatedAgreementsFilter = this.updateTerminatedAgreementsFilter.bind(this);
  }

  componentWillMount() {
    document.title += ' - Dashboard';

    const {onAttributesGet, onAgreementsGet, onDeviceGet, onServicesGet, router} = this.props;

    // to get something as soon as possible
    onAttributesGet()
      .then((data) => {
        if (!!data && 'attributes' in data) {
          this.setState(mergeState(this.state, {services: _.filter(data.attributes, {id: 'compute'}), ephemeral: { fetching: false}}));

          const enrichFn = this.enrich([onServicesGet, onAgreementsGet], router);
          // get it started
          enrichFn();

          // schedule
          this.setState(mergeState(this.state, {ephemeral: {interval: setInterval(enrichFn, 2000)}}));
        }
      });
    onDeviceGet();
  }

  componentWillUnmount() {
    clearInterval(this.state.ephemeral.interval);
  }

  enrich(fns, router) {

    let hydrate = (computeAttrs, serviceData, agreementData) => {
      return _.map(computeAttrs, (compute) => {

        // TODO: expand to accommodate more sensor urls and more applicable enrichments
        const policy = _.filter(serviceData, (d) => { return compute.sensor_urls[0] === d.policy.apiSpec[0].specRef;});
        const active = _.filter(agreementData.agreements.active, (a) => { return compute.sensor_urls[0] === a.sensor_url;});
        const archived = _.filter(agreementData.agreements.archived, (a) => { return compute.sensor_urls[0] === a.sensor_url;});

        return {...compute, ...policy[0], agreements: {active, archived}};
      });
    }

    return () => {
      // TODO: do this better; componentWillUnmount isn't doing it but that's the right way to handle this
      if (!router.isActive({pathname: '/dashboard'})) {
        return;
      }

      Promise.all(_.map(fns, (fn) => {return fn();})).then((responses) => {

        this.setState(mergeState(this.state, {
          services: hydrate(this.state.services, responses[0], responses[1])
        }));
      });
    };
  }

  sortedTerminatedAgreementsByTime() {
    return _.orderBy(this.props.agreements.archived, (ag) => ag.agreement_terminated_time, ['desc'])
  }

  handleItemClick(e, {name}) {
    let that = this;
    this.setState({ activeItem: name }, () => {
    });
  }

  updateTerminatedAgreementsFilter = _.debounce((e, data) => {
    this.setState({terminatedAgreementsFilter: data.value}, () => {
    });
  }, 500)

  render() {
    const { attributes, device, router } = this.props;

    let prettyTime = (stamp) => {
      const d = new Date(0);
      d.setUTCSeconds(stamp);

      return moment(d).format('MMMM DD, hh:mm A');
    }

    let view;

    if (_.isEmpty(this.state.services)) {
      view = (
        <Segment padded>

Your device is not configured to execute any services.

          <Button fluid primary color="blue" onClick={() => {router.push('/setup');}}>Begin Setup</Button>
        </Segment>
      );
    } else {
      const reduceNum = (n) => {
        return n > 0 ? 1 : 0;
      }
      const sVal = (serv) => {
        if ('agreements' in serv && serv.agreements.active.length > 0) {
          const ag = serv.agreements.active[0];
          return reduceNum(ag.agreement_creation_time) +
                 reduceNum(ag.agreement_accepted_time) +
                 reduceNum(ag.agreement_finalized_time) +
                 reduceNum(ag.agreement_execution_start_time) +
                 reduceNum(ag.agreement_data_received_time);
        } else {
          return 0;
        }
      }

      const sortedServ = this.state.services.slice(0).sort((o, o2) => {
        const s = sVal(o);
        const s2 = sVal(o2);

        // reverse sort
        if (s > s2) {
          return -1;
        } else if (s < s2) {
          return 1;
        } else {
          return 0;
        }
      });

      view = (_.map(sortedServ, (it) => {

          // can't assume there is one
          var newestArch = null;
          let color, percent, tag;

          if (!'policy' in it) {
            color = 'yellow';
            percent = 0;
            tag = 'Initializing';
          } else if ('agreements' in it) {
            // assume only a single agreement here, this may change in the future

            if (it.agreements.active.length > 0) {
              const ag = it.agreements.active[0];

              if (ag.agreement_execution_start_time > 0) {
                color = 'blue';
                percent = 100;
                tag = 'Executing';
              } else if (ag.agreement_accepted_time > 0) {
                color = 'teal';
                percent = 70;
                tag = 'In Agreement';
              } else {
                color = 'orange';
                percent = 50;
                tag = 'Agreement Proposed';
              }
            } else {
              color = 'grey';
              percent = 40;
              tag = 'Available for Agreement';
            }

            if (it.agreements.archived.length > 0) {
              newestArch = it.agreements.archived[it.agreements.archived.length-1];
            }
          }

          return (
            <Segment key={it.sensor_urls.join('/')}>

              {it.label}
              <Progress percent={percent} attached="top" color={color} />
              {tag}

              <List divided relaxed>
                <List.Item>
                  <List.Content>
                    <List.Header>Compute Resources</List.Header>
                    <List.Description>CPUs: {it.mappings.cpus}, RAM: {it.mappings.ram} MB</List.Description>
                  </List.Content>
                </List.Item>
                {'agreements' in it ?
                <List.Item>
                  <List.Content>
                    {it.agreements.active.length > 0 ?

                        <List.Header>Active Agreement</List.Header>

                            <List.Description>Id: {it.agreements.active[0].current_agreement_id}</List.Description>

                            <List.Description>Counterparty: {it.agreements.active[0].consumer_id}</List.Description>
                            {it.agreements.active[0].agreement_accepted_time > 0 ?
                                <List.Description>Counterparty accepted at: {prettyTime(it.agreements.active[0].agreement_accepted_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_execution_start_time > 0 ?
                                <List.Description>Workload pattern deployed at: {prettyTime(it.agreements.active[0].agreement_execution_start_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_data_received_time > 0 ?
                                <List.Description>Agreement data received by counterparty at: {prettyTime(it.agreements.active[0].agreement_data_received_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_finalized_time > 0 ?
                                <List.Description>Agreement finalized at: {prettyTime(it.agreements.active[0].agreement_finalized_time)}</List.Description>
                                :

                            }

                        :

                    }

                    <List.Description>Archived Agreements: {it.agreements.archived.length}</List.Description>
                    {newestArch !== null ?

                          <List.Description>Terminated Time: {prettyTime(newestArch.agreement_terminated_time)}, Terminated Reason: {newestArch.terminated_reason}, Terminated Description: {newestArch.terminated_description}</List.Description>

                        :

                    }
                  </List.Content>
                </List.Item>
                    :

                }
              </List>
            </Segment>
          );
        })
      );
    }

    return (

        {'name' in device ? `${device.name} ` : '' }
        {!this.state.ephemeral.fetching ?

            <Menu pointing secondary>
              <Menu.Item name='active' active={this.state.activeItem === 'active'} onClick={this.handleItemClick} />
              <Menu.Item name='terminated-agreements' active={this.state.activeItem === 'terminated-agreements'} onClick={this.handleItemClick} />
              { this.state.activeItem === 'terminated-agreements' &&
                <Menu.Menu position='right'>
                  <Menu.Item>
                    <Input icon='search' placeholder='Search...' onChange={this.updateTerminatedAgreementsFilter} />
                  </Menu.Item>
                </Menu.Menu>
              }
            </Menu>
            { this.state.activeItem === 'active' && view }
            { this.state.activeItem === 'terminated-agreements' && <TerminatedAgreements agreements={this.sortedTerminatedAgreementsByTime()} filter={this.state.terminatedAgreementsFilter} /> }

          : ''}

    );
  }
}

export default Dashboard;
<commit_msg>add metering information to terminated agreements segment<commit_after>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import {
  Button,
  Dimmer,
  Container,
  Header,
  Segment,
  Label,
  Loader,
  Progress,
  List,
  Menu,
  Input,
} from 'semantic-ui-react';
import * as _ from 'lodash';
import Highlight from 'react-highlight';
import {services} from '../../actions/services';
import {
  mergeState,
  mgrUpdateGen,
} from '../../util/localStateOperations';
import TerminatedAgreements from './terminatedAgreements';

class Dashboard extends Component {

  constructor(props) {
    super(props);

    const init = {
      ephemeral: {
        fetching: true,
        interval: undefined,
      },
      activeItem: 'active',
      services: [], // enriched
      terminatedAgreementsFilter: '',
    };

    this.state = init;

    this.handleItemClick = this.handleItemClick.bind(this);
    this.updateTerminatedAgreementsFilter = this.updateTerminatedAgreementsFilter.bind(this);
  }

  componentWillMount() {
    document.title += ' - Dashboard';

    const {onAttributesGet, onAgreementsGet, onDeviceGet, onServicesGet, router} = this.props;

    // to get something as soon as possible
    onAttributesGet()
      .then((data) => {
        if (!!data && 'attributes' in data) {
          this.setState(mergeState(this.state, {services: _.filter(data.attributes, {id: 'compute'}), ephemeral: { fetching: false}}));

          const enrichFn = this.enrich([onServicesGet, onAgreementsGet], router);
          // get it started
          enrichFn();

          // schedule
          this.setState(mergeState(this.state, {ephemeral: {interval: setInterval(enrichFn, 2000)}}));
        }
      });
    onDeviceGet();
  }

  componentWillUnmount() {
    clearInterval(this.state.ephemeral.interval);
  }

  enrich(fns, router) {

    let hydrate = (computeAttrs, serviceData, agreementData) => {
      return _.map(computeAttrs, (compute) => {

        // TODO: expand to accommodate more sensor urls and more applicable enrichments
        const policy = _.filter(serviceData, (d) => { return compute.sensor_urls[0] === d.policy.apiSpec[0].specRef;});
        const active = _.filter(agreementData.agreements.active, (a) => { return compute.sensor_urls[0] === a.sensor_url;});
        const archived = _.filter(agreementData.agreements.archived, (a) => { return compute.sensor_urls[0] === a.sensor_url;});

        return {...compute, ...policy[0], agreements: {active, archived}};
      });
    }

    return () => {
      // TODO: do this better; componentWillUnmount isn't doing it but that's the right way to handle this
      if (!router.isActive({pathname: '/dashboard'})) {
        return;
      }

      Promise.all(_.map(fns, (fn) => {return fn();})).then((responses) => {

        this.setState(mergeState(this.state, {
          services: hydrate(this.state.services, responses[0], responses[1])
        }));
      });
    };
  }

  sortedTerminatedAgreementsByTime() {
    return _.orderBy(this.props.agreements.archived, (ag) => ag.agreement_terminated_time, ['desc'])
  }

  handleItemClick(e, {name}) {
    let that = this;
    this.setState({ activeItem: name }, () => {
    });
  }

  updateTerminatedAgreementsFilter = _.debounce((e, data) => {
    this.setState({terminatedAgreementsFilter: data.value}, () => {
    });
  }, 500)

  render() {
    const { attributes, device, router } = this.props;

    let prettyTime = (stamp) => {
      const d = new Date(0);
      d.setUTCSeconds(stamp);

      return moment(d).format('MMMM DD, hh:mm A');
    }

    let view;

    if (_.isEmpty(this.state.services)) {
      view = (
        <Segment padded>

Your device is not configured to execute any services.

          <Button fluid primary color="blue" onClick={() => {router.push('/setup');}}>Begin Setup</Button>
        </Segment>
      );
    } else {
      const reduceNum = (n) => {
        return n > 0 ? 1 : 0;
      }
      const sVal = (serv) => {
        if ('agreements' in serv && serv.agreements.active.length > 0) {
          const ag = serv.agreements.active[0];
          return reduceNum(ag.agreement_creation_time) +
                 reduceNum(ag.agreement_accepted_time) +
                 reduceNum(ag.agreement_finalized_time) +
                 reduceNum(ag.agreement_execution_start_time) +
                 reduceNum(ag.agreement_data_received_time);
        } else {
          return 0;
        }
      }

      const sortedServ = this.state.services.slice(0).sort((o, o2) => {
        const s = sVal(o);
        const s2 = sVal(o2);

        // reverse sort
        if (s > s2) {
          return -1;
        } else if (s < s2) {
          return 1;
        } else {
          return 0;
        }
      });

      view = (_.map(sortedServ, (it) => {

          // can't assume there is one
          var newestArch = null;
          let color, percent, tag;

          if (!'policy' in it) {
            color = 'yellow';
            percent = 0;
            tag = 'Initializing';
          } else if ('agreements' in it) {
            // assume only a single agreement here, this may change in the future

            if (it.agreements.active.length > 0) {
              const ag = it.agreements.active[0];

              if (ag.agreement_execution_start_time > 0) {
                color = 'blue';
                percent = 100;
                tag = 'Executing';
              } else if (ag.agreement_accepted_time > 0) {
                color = 'teal';
                percent = 70;
                tag = 'In Agreement';
              } else {
                color = 'orange';
                percent = 50;
                tag = 'Agreement Proposed';
              }
            } else {
              color = 'grey';
              percent = 40;
              tag = 'Available for Agreement';
            }

            if (it.agreements.archived.length > 0) {
              newestArch = it.agreements.archived[it.agreements.archived.length-1];
            }
          }

          return (
            <Segment key={it.sensor_urls.join('/')}>

              {it.label}
              <Progress percent={percent} attached="top" color={color} />
              {tag}

              <List divided relaxed>
                <List.Item>
                  <List.Content>
                    <List.Header>Compute Resources</List.Header>
                    <List.Description>CPUs: {it.mappings.cpus}, RAM: {it.mappings.ram} MB</List.Description>
                  </List.Content>
                </List.Item>
                {'agreements' in it ?
                <List.Item>
                  <List.Content>
                    {it.agreements.active.length > 0 ?

                        <List.Header>Active Agreement</List.Header>

                            <List.Description>Id: {it.agreements.active[0].current_agreement_id}</List.Description>

                            <List.Description>Counterparty: {it.agreements.active[0].consumer_id}</List.Description>
                            {it.agreements.active[0].agreement_accepted_time > 0 ?
                                <List.Description>Counterparty accepted at: {prettyTime(it.agreements.active[0].agreement_accepted_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_execution_start_time > 0 ?
                                <List.Description>Workload pattern deployed at: {prettyTime(it.agreements.active[0].agreement_execution_start_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_data_received_time > 0 ?
                                <List.Description>Agreement data received by counterparty at: {prettyTime(it.agreements.active[0].agreement_data_received_time)}</List.Description>
                                :

                            }
                            {it.agreements.active[0].agreement_finalized_time > 0 ?
                                <List.Description>Agreement finalized at: {prettyTime(it.agreements.active[0].agreement_finalized_time)}</List.Description>
                                :

                            }

                        :

                    }

                    <List.Description>Archived Agreements: {it.agreements.archived.length}</List.Description>
                    {newestArch !== null ?

                          <List.Description>Terminated Time: {prettyTime(newestArch.agreement_terminated_time)}, Terminated Reason: {newestArch.terminated_reason}, Terminated Description: {newestArch.terminated_description}</List.Description>

                        :

                    }

                    {it.agreements.active[0].metering_notification.start_time > 0 &&

                        <List.Description>Metering Information</List.Description>
                        <div style={{paddingLeft: `2%`}}>
                          <List.Description>Token Amount: {it.agreements.active[0].metering_notification.amount}</List.Description>
                          <List.Description>Start Time: {prettyTime(it.agreements.active[0].metering_notification.start_time)}</List.Description>
                          <List.Description>Current Time: {prettyTime(it.agreements.active[0].metering_notification.current_time)}</List.Description>
                          <List.Description>Times Missed: {it.agreements.active[0].metering_notification.missed_time}</List.Description>

                    }
                  </List.Content>
                </List.Item>
                    :

                }
              </List>
            </Segment>
          );
        })
      );
    }

    return (

        {'name' in device ? `${device.name} ` : '' }
        {!this.state.ephemeral.fetching ?

            <Menu pointing secondary>
              <Menu.Item name='active' active={this.state.activeItem === 'active'} onClick={this.handleItemClick} />
              <Menu.Item name='terminated-agreements' active={this.state.activeItem === 'terminated-agreements'} onClick={this.handleItemClick} />
              { this.state.activeItem === 'terminated-agreements' &&
                <Menu.Menu position='right'>
                  <Menu.Item>
                    <Input icon='search' placeholder='Search...' onChange={this.updateTerminatedAgreementsFilter} />
                  </Menu.Item>
                </Menu.Menu>
              }
            </Menu>
            { this.state.activeItem === 'active' && view }
            { this.state.activeItem === 'terminated-agreements' && <TerminatedAgreements agreements={this.sortedTerminatedAgreementsByTime()} filter={this.state.terminatedAgreementsFilter} /> }

          : ''}

    );
  }
}

export default Dashboard;
<|endoftext|>


<commit_before>/*
 * grunt-angular-templates
 * https://github.com/ericclemmons/grunt-angular-templates
 *
 * Copyright (c) 2013 Eric Clemmons
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');

module.exports.init = function(grunt) {

  var concat = function(options, files, callback) {
    grunt.util.async.concatSeries(files, function(file, next) {
      var id        = (options.prepend || '') + path.relative(options.base || '.', file).replace( /\\/g, '/');
      var template  = '\n  $templateCache.put("<%= id %>",\n    <%= content %>\n  );\n';
      var cleaned   = grunt.file.read(file).split(/^/gm).map(function(line) { return JSON.stringify(line); }).join(' +\n    ');
      var cached    = process(template, id, cleaned);

      next(null, cached);
    }, callback);
  };

  var compile = function(id, noConflict, options, files, callback) {
    var template = '<%= noConflict %>.module("<%= id %>").run(["$templateCache", function($templateCache) {\n<%= content %>\n}]);\n';

    concat(options, files, function(err, concated) {
      var compiled = process(template, id, concated.join(''), noConflict);

      callback(false, compiled);
    });
  };

  var process = function(template, id, content, noConflict) {
    return grunt.template.process(template, {
      data: {
        id:         id,
        content:    content,
        noConflict: noConflict
      }
    });
  };

  return {
    compile: compile
  };

};
<commit_msg>When template file is empty (0 size), use an empty string as template.<commit_after>/*
 * grunt-angular-templates
 * https://github.com/ericclemmons/grunt-angular-templates
 *
 * Copyright (c) 2013 Eric Clemmons
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');

module.exports.init = function(grunt) {

  var concat = function(options, files, callback) {
    grunt.util.async.concatSeries(files, function(file, next) {
      var id        = (options.prepend || '') + path.relative(options.base || '.', file).replace( /\\/g, '/');
      var template  = '\n  $templateCache.put("<%= id %>",\n    <%= content %>\n  );\n';
      var cleaned   = grunt.file.read(file).split(/^/gm).map(function(line) { return JSON.stringify(line); }).join(' +\n    ');
      var cached    = process(template, id, cleaned);

      next(null, cached);
    }, callback);
  };

  var compile = function(id, noConflict, options, files, callback) {
    var template = '<%= noConflict %>.module("<%= id %>").run(["$templateCache", function($templateCache) {\n<%= content %>\n}]);\n';

    concat(options, files, function(err, concated) {
      var compiled = process(template, id, concated.join(''), noConflict);

      callback(false, compiled);
    });
  };

  var process = function(template, id, content, noConflict) {
    return grunt.template.process(template, {
      data: {
        id:         id,
        content:    content.length ? content : '""',
        noConflict: noConflict
      }
    });
  };

  return {
    compile: compile
  };

};
<|endoftext|>


<commit_before>/* eslint-ignore no-multiple-empty-lines */

// License header should be at the top of the file within the first 5 lines.

/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// EXPORTS //

module.exports = 'beep boop';
<commit_msg>Add empty line<commit_after>/* eslint-ignore no-multiple-empty-lines */

// License header should be at the top of the file within the first 5 lines.

/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// EXPORTS //

module.exports = 'beep boop';
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 * 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.
 * =============================================================================
 */

var dl = deeplearn;
var Graph = dl.Graph;
var Tensor = dl.Tensor;
var Scalar = dl.Scalar;
var NDArrayMathGPU = dl.NDArrayMathGPU;
var Session = dl.Session;
var track = dl.track;
var keep = dl.keep;
var InCPUMemoryShuffledInputProviderBuilder = dl.InCPUMemoryShuffledInputProviderBuilder;
var SGDOptimizer = dl.SGDOptimizer;
var CostReduction = dl.CostReduction;
var Array1D = dl.Array1D;

/**
 * This implementation of computing the complementary color came from an
 * answer by Edd https://stackoverflow.com/a/37657940
 */
function computeComplementaryColor(rgbColor) {
    let r = rgbColor[0];
    let g = rgbColor[1];
    let b = rgbColor[2];

    // Convert RGB to HSL
    // Adapted from answer by 0x000f http://stackoverflow.com/a/34946092/4939630
    r /= 255.0;
    g /= 255.0;
    b /= 255.0;
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h = (max + min) / 2.0;
    let s = h;
    const l = h;

    if (max === min) {
        h = s = 0; // achromatic
    } else {
        const d = max - min;
        s = (l > 0.5 ? d / (2.0 - max - min) : d / (max + min));

        if (max === r && g >= b) {
            h = 1.0472 * (g - b) / d;
        } else if (max === r && g < b) {
            h = 1.0472 * (g - b) / d + 6.2832;
        } else if (max === g) {
            h = 1.0472 * (b - r) / d + 2.0944;
        } else if (max === b) {
            h = 1.0472 * (r - g) / d + 4.1888;
        }
    }

    h = h / 6.2832 * 360.0 + 0;

    // Shift hue to opposite side of wheel and convert to [0-1] value
    h += 180;
    if (h > 360) {
        h -= 360;
    }
    h /= 360;

    // Convert h s and l values into r g and b values
    // Adapted from answer by Mohsen http://stackoverflow.com/a/9493060/4939630
    if (s === 0) {
        r = g = b = l; // achromatic
    } else {
        const hue2rgb = (p, q, t) => {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p + (q - p) * 6 * t;
            if (t < 1 / 2) return q;
            if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
            return p;
        };

        const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        const p = 2 * l - q;

        r = hue2rgb(p, q, h + 1 / 3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1 / 3);
    }

    return [r, g, b].map(v => Math.round(v * 255));
}

function generateRandomChannelValue() {
    return Math.floor(Math.random() * 256);
}

function normalizeColor(rgbColor) {
    return rgbColor.map(v => v / 255);
}

function denormalizeColor(normalizedRgbColor) {
    return normalizedRgbColor.map(v => v * 255);
}

function createFullyConnectedLayer(
    graph, inputLayer, layerIndex,
    sizeOfThisLayer, includeRelu = true, includeBias = true) {
    return graph.layers.dense(
        'fully_connected_' + layerIndex, inputLayer, sizeOfThisLayer,
        includeRelu ? (x) => graph.relu(x) : undefined, includeBias);
}

//////////////////////
///Train and Predict//
//////////////////////

function injectNoise(feedEntries, costTensor) {

    class FeedDictionary {
        /**
         * Optionally construct a FeedDictionary from an array of entries.
         * @param feedEntries Optional array of FeedEntry objects.
         */
        constructor(feedEntries = null) {
            this.dict = {};
            if (feedEntries) {
                feedEntries.forEach(entry => this.dict[entry.tensor.id] = entry);
            }
        }
    }

    class VariableNode extends Node {
        constructor(graph, name, data) {
            super(graph, name, {}, new Tensor(data.shape));
        }
        validate() {
            util.assert(
                this.data != null,
                'Error adding variable op: Data for variable \'' + this.name +
                '\' is null or undefined');
        }
    }

    function getVariableNodesFromEvaluationSet(evaluationSet) {
        const nodes = [];
        evaluationSet.forEach(node => {
            if (node instanceof VariableNode) {
                nodes.push(node);
            }
        });
        return nodes;
    }

    var feed = new FeedDictionary(feedEntries);
    var runtime = session.getOrCreateRuntime([costTensor], feed);
    var variableNodes = optimizer.specifiedVariableNodes == null ?
        getVariableNodesFromEvaluationSet(runtime.nodes) :
        this.specifiedVariableNodes;

    variableNodes.forEach(node => {
        const oldVariable = session.activationArrayMap.get(node.output);
        // const gradient = this.variableGradients.get(node.output);
        const noise = NDArray.randUniform(node.output.shape, -1 * noiseScale, 1 * noiseScale); // min max

        const variable = math.scaledArrayAdd(this.one, noise, this.one, oldVariable);
        session.activationArrayMap.set(node.output, keep(variable));
        node.data = variable;

        oldVariable.dispose();
    });
}

function train1Batch(shouldFetchCost, shouldInjectNoise) {
    // Every 42 steps, lower the learning rate by 15%.
    const learningRate =
        initialLearningRate * Math.pow(0.95, Math.floor(step / 82));
    optimizer.setLearningRate(learningRate);

    // Train 1 batch.
    let costValue = -1;
    math.scope(() => {
        const cost = session.train(
            costTensor, feedEntries, batchSize, optimizer,
            shouldFetchCost ? CostReduction.MEAN : CostReduction.NONE);

        if (shouldInjectNoise) {
            injectNoise(feedEntries, costTensor);
            //inject only once
            shouldInjectNoise = false;
        }

        if (!shouldFetchCost) {
            // We only train. We do not compute the cost.
            return;
        }

        // Compute the cost (by calling get), which requires transferring data
        // from the GPU.
        costValue = cost.get();
    });

    return costValue;
}

function predict(rgbColor) {
    let complementColor = [];
    math.scope((keep, track) => {
        const mapping = [{
            tensor: inputTensor,
            data: Array1D.new(normalizeColor(rgbColor)),
        }];
        const evalOutput = session.eval(predictionTensor, mapping);
        const values = evalOutput.getValues();
        const colors = denormalizeColor(Array.prototype.slice.call(values));

        // Make sure the values are within range.
        complementColor = colors.map(
            v => Math.round(Math.max(Math.min(v, 255), 0)));
    });
    return complementColor;
}

function populateContainerWithColor(
    container, r, g, b) {
    const originalColorString = 'rgb(' + [r, g, b].join(',') + ')';
    container.textContent = originalColorString;

    const colorBox = document.createElement('div');
    colorBox.classList.add('color-box');
    colorBox.style.background = originalColorString;
    container.appendChild(colorBox);
}

var updateNetParamDisplay = function () {
    document.getElementById('learning-rate-input').value = initialLearningRate;
    document.getElementById('noise-scale-input').value = noiseScale;
    document.getElementById('egdiv').innerHTML = 'step = ' + step;
    // document.getElementById('batch_size_input').value = batchSize;
    // // document.getElementById('decay_input').value = trainer.l2_decay;
}

// user settings
var changeNetParam = function () {
    if (noiseScale !== parseFloat(document.getElementById("noise-scale-input").value)) {
        noiseScale = parseFloat(document.getElementById("noise-scale-input").value);

        console.log('noise scale changed to' + noiseScale);
    }
    initialLearningRate = parseFloat(document.getElementById("learning-rate-input").value);
    if (optimizer != null && initialLearningRate !== optimizer.learningRate) {
        optimizer.learningRate = initialLearningRate;

        console.log('learning rate changed to' + initialLearningRate);
    }
    updateNetParamDisplay();
}

function initializeUi() {
    const colorRows = document.querySelectorAll('tr[data-original-color]');
    for (let i = 0; i < colorRows.length; i++) {
        const rowElement = colorRows[i];
        const tds = rowElement.querySelectorAll('td');
        const originalColor =
            (rowElement.getAttribute('data-original-color'))
            .split(',')
            .map(v => parseInt(v, 10));

        // Visualize the original color.
        populateContainerWithColor(
            tds[0], originalColor[0], originalColor[1], originalColor[2]);

        // Visualize the complementary color.
        const complement =
            computeComplementaryColor(originalColor);
        populateContainerWithColor(
            tds[1], complement[0], complement[1], complement[2]);
    }

    UI_initialized = true
}

function make_plot_responsive() {

    (function () {
        var d3 = Plotly.d3;
        var WIDTH_IN_PERCENT_OF_PARENT = 100,
            HEIGHT_IN_PERCENT_OF_PARENT = 90;
        var gd3 = d3.selectAll(".responsive-plot")
            .style({
                width: WIDTH_IN_PERCENT_OF_PARENT + '%',
                'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%',
                height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
                'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + 'vh'
            });
        var nodes_to_resize = gd3[0]; //not sure why but the goods are within a nested array

        function resize_plot() {
            for (var i = 0; i < nodes_to_resize.length; i++) {
                Plotly.Plots.resize(nodes_to_resize[i]);
            }
        }
        resize_plot();
        window.onresize = resize_plot;
    })();

}

function create_plot3d(init_x, init_y, init_z) {

    Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/3d-line1.csv', function (err, rows) {

        var data = [{
            type: 'scatter3d',
            mode: 'lines',
            x: init_x,
            y: init_y,
            z: init_z,
            opacity: 1,
            line: {
                width: 5,
                // color: c,
                reversescale: false
            },
            displayModeBar: false
        }];
        var layout = {

            scene: {
                xaxis: {
                    nticks: 5,
                    title: 'R',
                    backgroundcolor: "rgb(200, 200, 230)",
                    gridcolor: "rgb(255, 255, 255)",
                    showbackground: true,
                    zerolinecolor: "rgb(255, 255, 255)",
                },
                yaxis: {
                    nticks: 5,
                    title: 'G',
                    backgroundcolor: "rgb(230, 200,230)",
                    gridcolor: "rgb(255, 255, 255)",
                    showbackground: true,
                    zerolinecolor: "rgb(255, 255, 255)"
                },
                zaxis: {
                    nticks: 5,
                    title: 'B',
                    backgroundcolor: "rgb(230, 230,200)",
                    gridcolor: "rgb(255, 255, 255)",
                    showbackground: true,
                    zerolinecolor: "rgb(255, 255, 255)"
                }
            },
            autosize: true,
            // height: 300,
            margin: {
                l: 2,
                r: 2,
                b: 2,
                t: 2,
                pad: 0
            },
            paper_bgcolor: '#ffffff',
            plot_bgcolor: '#c7c7c7'
        };

        Plotly.newPlot('graph-color', data, layout);

        make_plot_responsive()

    });

}

function update_plot3d(new_x, new_y, new_z) {

    Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/3d-line1.csv', function (err, rows) {
        Plotly.animate('graph-color', {
            data: [{
                x: new_x,
                y: new_y,
                z: new_z
            }],
            traces: [0],
            layout: {}
        }, {
            transition: {
                duration: 300,
                easing: 'cubic-in-out'
            }
        })

    });

}

function createChart(canvasId, label, data, min = 0, max = null) {

    const canvas = document.getElementById(canvasId);

    const context = canvas.getContext('2d');

    config.data.datasets[0].data = data;
    config.data.datasets[0].label = label;

    return new Chart(context, config);

}

function train_per() {
    if (step > 4242) {
        // Stop training.
        return;
    }

    if (paused) return;

    // We only fetch the cost every 10 steps because doing so requires a transfer
    // of data from the GPU.

    cost = train1Batch(step % 10 === 0, shouldInjectNoise);

    var d = document.getElementById('egdiv');
    d.innerHTML = 'step = ' + step;

    if (step % 10 === 0) {

        chartData.push({
            x: step,
            y: cost
        });

        config.data.datasets[0].data = chartData;
        chart.update();

        // Print data to console so the user can inspect.
        console.log('step', step - 1, 'cost', cost);

        // Visualize the predicted complement.
        const colorRows = document.querySelectorAll('tr[data-original-color]');
        for (let i = 0; i < colorRows.length; i++) {
            const rowElement = colorRows[i];
            const tds = rowElement.querySelectorAll('td');
            const originalColor =
                (rowElement.getAttribute('data-original-color'))
                .split(',')
                .map(v => parseInt(v, 10));

            // Visualize the predicted color.
            const predictedColor = predict(originalColor);
            populateContainerWithColor(
                tds[2], predictedColor[0], predictedColor[1], predictedColor[2]);

            if (i === 0) {
                data_x.push(predictedColor[0])
                data_y.push(predictedColor[1])
                data_z.push(predictedColor[2])
                if (plot_exist === false) {
                    create_plot3d(data_x, data_y, data_z);
                    plot_exist = true
                } else {
                    update_plot3d(data_x, data_y, data_z);
                }
            }

        }
    }

    step++;
}

function toggle_pause() {
    paused = !paused;
    var btn = document.getElementById('buttontp');
    if (paused) {
        btn.value = 'Resume'
    } else {
        btn.value = 'Pause';
    }
}

function run() {

    updateNetParamDisplay();

    if (UI_initialized) {
        console.log('starting!');
        setInterval(train_per, 5); // lets go!
    } else {
        console.log('waiting!');
        setTimeout(run, 1000); // run again after 1second
    } // keep checking
}

var chartData;
var chart;
var chart_exist;

var paused;

// On every frame, we train and then maybe update the UI.
var step;

var plot_exist;

var data_x;
var data_y;
var data_z;

var UI_initialized;

var rawInputs;

var math;

var graph;

// This tensor contains the input. In this case, it is a scalar.
var inputTensor;

// This tensor contains the target.
var targetTensor;

var inputArray;
var targetArray;

var shuffledInputProviderBuilder;
var inputProvider;
var targetProvider;

var feedEntries;

// Create 3 fully connected layers, each with half the number of nodes of
// the previous layer. The first one has 16 nodes.
var fullyConnectedLayer;

var predictionTensor;

var costTensor;

var session;

var batchSize;
var initialLearningRate;
var optimizer;

var learningRateBtn;

// helper functions and variables to inject noise
var noiseScale;
var shouldInjectNoise;
var injectNoiseBtn;

var config = {
    type: 'line',
    data: {
        datasets: [{
            data: [],
            fill: false,
            label: ' ',
            // pointRadius: 0,
            borderColor: 'rgba(75,192,192,1)',
            backgroundColor: 'rgba(75,192,192,1)',
            borderWidth: 1,
            // lineTension: 0,
            // pointHitRadius: 8
        }]
    },
    options: {
        animation: {
            duration: 0
        },
        responsive: false,
        scales: {
            xAxes: [{
                type: 'linear',
                position: 'bottom'
            }],
            yAxes: [{
                ticks: {
                    min: null,
                    callback: (label, index, labels) => {
                        let num = Number(label).toFixed(2);
                        return `${num}`;
                    }
                }
            }]
        }
    }
};

function start() {

    supported = detect_support();

    if (supported) {
        console.log('device & webgl supported')
        document.getElementById("buttontp").disabled = false;
    } else {
        console.log('device/webgl not supported')
        document.getElementById("buttontp").disabled = true;
    }

    UI_initialized = false
    initializeUi();

    chartData = []

    chart = createChart('plot', 'cost', chartData, 0, chartData.y);
    chart.update();
    chart_exist = true;

    paused = true;

    // On every frame, we train and then maybe update the UI.
    step = 0;

    plot_exist = false

    data_x = [];
    data_y = [];
    data_z = [];

    rawInputs = new Array(1e5);
    for (let i = 0; i < 1e5; i++) {
        rawInputs[i] = [
            generateRandomChannelValue(), generateRandomChannelValue(),
            generateRandomChannelValue()
        ];
    }

    math = new NDArrayMathGPU();

    graph = new Graph();

    // This tensor contains the input. In this case, it is a scalar.
    inputTensor = graph.placeholder('input RGB value', [3]);

    // This tensor contains the target.
    targetTensor = graph.placeholder('output RGB value', [3]);

    inputArray =
        rawInputs.map(c => Array1D.new(normalizeColor(c)));
    targetArray = rawInputs.map(
        c => Array1D.new(
            normalizeColor(computeComplementaryColor(c))));

    shuffledInputProviderBuilder = new InCPUMemoryShuffledInputProviderBuilder([inputArray, targetArray]);
    [inputProvider, targetProvider] = shuffledInputProviderBuilder.getInputProviders();

    feedEntries = [{
            tensor: inputTensor,
            data: inputProvider
        },
        {
            tensor: targetTensor,
            data: targetProvider
        }
    ];

    // Create 3 fully connected layers, each with half the number of nodes of
    // the previous layer. The first one has 16 nodes.
    fullyConnectedLayer =
        createFullyConnectedLayer(graph, inputTensor, 0, 64);

    // Create fully connected layer 1, which has 8 nodes.
    fullyConnectedLayer =
        createFullyConnectedLayer(graph, fullyConnectedLayer, 1, 32);

    // Create fully connected layer 2, which has 4 nodes.
    fullyConnectedLayer =
        createFullyConnectedLayer(graph, fullyConnectedLayer, 2, 16);

    predictionTensor =
        createFullyConnectedLayer(graph, fullyConnectedLayer, 3, 3);

    costTensor =
        graph.meanSquaredCost(targetTensor, predictionTensor);

    session = new Session(graph, math);

    batchSize = 100;
    initialLearningRate = 0.5;
    optimizer = new SGDOptimizer(initialLearningRate);

    learningRateBtn = document.getElementById("learningRateBtn");
    learningRateBtn.addEventListener('click', () => {
        // Activate, deactivate hyper parameter inputs.
        changeNetParam();
    });

    // helper functions and variables to inject noise
    noiseScale = 0.3;
    shouldInjectNoise = false;
    injectNoiseBtn = document.getElementById("injectNoiseBtn");
    injectNoiseBtn.addEventListener('click', () => {
        // Activate, deactivate hyper parameter inputs.
        shouldInjectNoise = true;
        changeNetParam();
        console.log(`injected noise once with scale ${noiseScale}`);
    });

    run();

}<commit_msg>Delete complementary_color.js<commit_after><|endoftext|>


<commit_before>jQuery(function($){
	var $giveOptionLabel = $('.ways-to-give-option label'),
		$defaultValue = "100",
		$giveOtherField = $('.give-value-other-input');

		$giveOtherField.on({
			keydown: function(e) {
				var keyPressed = (e.keyCode) ? e.keyCode : e.which;

				/* LIST OF ALLOWED KEYS
				 * - Select All(Ctrl/Cmd+A) [65]
				 * - Paste (Ctrl/Cmd+V) [86]
				 * - Navigation Keys (Up, Down, Left, Right, Home, End) [35 ~ 40]
				 * - Num Row Keys (Only when shift key is not pressed.) [48 ~ 57]
				 * - Numpad Keys [96 ~ 105]
				 * - Delete [45]
				 * - Insert [46]
				 * - Backspace [8]
				 * - Tab [9]
				 * - Refresh Key [116]
				 */

				if( (( keyPressed == 65 || keyPressed == 86) && ( e.ctrlKey || e.metaKey  ))
					|| (keyPressed >= 35 && keyPressed <= 40)
					|| (keyPressed >= 48 && keyPressed <= 57 && !(e.shiftKey || e.altKey))
					|| (keyPressed >= 96 && keyPressed <= 105)
					|| (keyPressed == 45) || (keyPressed == 46)
					|| (keyPressed == 8) || (keyPressed== 9)
					|| (keyPressed == 116)
					) {
					return true;
				}

				return false;
			},
			change: function(e) {
				var currentValue = $(this).val();
				if(!new RegExp('^[0-9]*$').test(currentValue)) {
					$(this).val(currentValue.replace(/\D/g, ""));
				}
			},
			keyup: function(e) {
				var currentValue = $(this).val();
				if(!new RegExp('^[0-9]*$').test(currentValue)) {
					$(this).val(currentValue.replace(/\D/g, ""));
				}
				if( currentValue != '' ) {
					$(this).addClass('selected');
					$(this).removeClass('empty');
				} else {
					$(this).removeClass('selected');
					$(this).addClass('empty');
				}
			},
			focusin: function(e) {
				e.preventDefault();
				$(this).parent().parent().find('.ways-to-give-option').each(function(){
					var $radioChecked = $(this).find('input[type="radio"]:checked');
					$radioChecked.prop('checked',false);
				});
				$(this).prev().prev().prop('checked', true);
				var val = $(this).val(),
				$label = $(this).next().find('.label-text');

				if( '' != val) {
					 return;
				}
				$label.hide();
			},
			focusout: function(e) {
				e.preventDefault();
				var val = $(this).val(),
				$label = $(this).next().find('.label-text');
				if( '' != val) {
					 return;
				}
				$(this).prev().prev().prop('checked', false);
				// $defaultValueObj.prop('checked', true);
				$(this).parent().parent().find('.ways-to-give-option').each(function(){
					var $radioDefault = $(this).find('input[type="radio"]');
					if( $radioDefault.val() == $defaultValue ) {
						$radioDefault.prop('checked',true);
					}
				});
				$(this).removeClass('empty');
				$label.show();
			}
		});

		$giveOptionLabel.on('click',function(){
			$(this).prev().prop('checked',true);
			$(this).parent().parent().find('.ways-to-give-option').each(function(){
				var $radioOther = $(this).find('input[type="radio"]'),
					$radioParent = $radioOther.parent();
				if($radioOther.val() == "other") {
					$radioParent.find('.selected').removeClass('selected').val('');
					$radioParent.find('.empty').removeClass('empty').val('');
					$radioParent.find('input[type="text"]').next().find('.label-text').show()
				}
			});

		});

		$('form[name="ways-to-give"').on('submit',function(e) {
			e.preventDefault();
			var action = $(this).attr('action');
			var selectedValue;
			var params;

			if($giveOtherField.val() != '') {
				selectedValue = $giveOtherField.val();
				params = "&Amount="+selectedValue;
			} else {
				selectedValue = $('input[type="radio"][name="GiftChoice"]:checked').val();
				params = "&GiftChoice="+selectedValue;
			}

			var finalUrl = action+params;

			window.location = finalUrl;
		});

});
<commit_msg>Removed typo, on wtg form<commit_after>jQuery(function($){
	var $giveOptionLabel = $('.ways-to-give-option label'),
		$defaultValue = "100",
		$giveOtherField = $('.give-value-other-input');

		$giveOtherField.on({
			keydown: function(e) {
				var keyPressed = (e.keyCode) ? e.keyCode : e.which;

				/* LIST OF ALLOWED KEYS
				 * - Select All(Ctrl/Cmd+A) [65]
				 * - Paste (Ctrl/Cmd+V) [86]
				 * - Navigation Keys (Up, Down, Left, Right, Home, End) [35 ~ 40]
				 * - Num Row Keys (Only when shift key is not pressed.) [48 ~ 57]
				 * - Numpad Keys [96 ~ 105]
				 * - Delete [45]
				 * - Insert [46]
				 * - Backspace [8]
				 * - Tab [9]
				 * - Refresh Key [116]
				 */

				if( (( keyPressed == 65 || keyPressed == 86) && ( e.ctrlKey || e.metaKey  ))
					|| (keyPressed >= 35 && keyPressed <= 40)
					|| (keyPressed >= 48 && keyPressed <= 57 && !(e.shiftKey || e.altKey))
					|| (keyPressed >= 96 && keyPressed <= 105)
					|| (keyPressed == 45) || (keyPressed == 46)
					|| (keyPressed == 8) || (keyPressed== 9)
					|| (keyPressed == 116)
					) {
					return true;
				}

				return false;
			},
			change: function(e) {
				var currentValue = $(this).val();
				if(!new RegExp('^[0-9]*$').test(currentValue)) {
					$(this).val(currentValue.replace(/\D/g, ""));
				}
			},
			keyup: function(e) {
				var currentValue = $(this).val();
				if(!new RegExp('^[0-9]*$').test(currentValue)) {
					$(this).val(currentValue.replace(/\D/g, ""));
				}
				if( currentValue != '' ) {
					$(this).addClass('selected');
					$(this).removeClass('empty');
				} else {
					$(this).removeClass('selected');
					$(this).addClass('empty');
				}
			},
			focusin: function(e) {
				e.preventDefault();
				$(this).parent().parent().find('.ways-to-give-option').each(function(){
					var $radioChecked = $(this).find('input[type="radio"]:checked');
					$radioChecked.prop('checked',false);
				});
				$(this).prev().prev().prop('checked', true);
				var val = $(this).val(),
				$label = $(this).next().find('.label-text');

				if( '' != val) {
					 return;
				}
				$label.hide();
			},
			focusout: function(e) {
				e.preventDefault();
				var val = $(this).val(),
				$label = $(this).next().find('.label-text');
				if( '' != val) {
					 return;
				}
				$(this).prev().prev().prop('checked', false);
				// $defaultValueObj.prop('checked', true);
				$(this).parent().parent().find('.ways-to-give-option').each(function(){
					var $radioDefault = $(this).find('input[type="radio"]');
					if( $radioDefault.val() == $defaultValue ) {
						$radioDefault.prop('checked',true);
					}
				});
				$(this).removeClass('empty');
				$label.show();
			}
		});

		$giveOptionLabel.on('click',function(){
			$(this).prev().prop('checked',true);
			$(this).parent().parent().find('.ways-to-give-option').each(function(){
				var $radioOther = $(this).find('input[type="radio"]'),
					$radioParent = $radioOther.parent();
				if($radioOther.val() == "other") {
					$radioParent.find('.selected').removeClass('selected').val('');
					$radioParent.find('.empty').removeClass('empty').val('');
					$radioParent.find('input[type="text"]').next().find('.label-text').show()
				}
			});

		});

		$('form[name="ways-to-give"]').on('submit',function(e) {
			e.preventDefault();
			var action = $(this).attr('action');
			var selectedValue;
			var params;

			if($giveOtherField.val() != '') {
				selectedValue = $giveOtherField.val();
				params = "&Amount="+selectedValue;
			} else {
				selectedValue = $('input[type="radio"][name="GiftChoice"]:checked').val();
				params = "&GiftChoice="+selectedValue;
			}

			var finalUrl = action+params;

			window.location = finalUrl;
		});

});
<|endoftext|>


<commit_before>describe("mocking ajax", function () {
    beforeEach(function () {
        jasmine.Ajax.install();
    });
    afterEach(function () {
        jasmine.Ajax.uninstall();
    });

    it("specifying response when you need it", function (done) {
        var doneFn = jasmine.createSpy("success");

        lettuce.get('/some/cool/url', function (result) {
            expect(result).toEqual("awesome response");
            done();
        });

        expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
        expect(doneFn).not.toHaveBeenCalled();

        jasmine.Ajax.requests.mostRecent().respondWith({
            "status": 200,
            "contentType": 'text/plain',
            "responseText": 'awesome response'
        });
    });

    it("should be post to some where", function (done) {
        var doneFn = jasmine.createSpy("success");

        lettuce.post('/some/cool/url', [], function (result) {
            expect(result).toEqual("awesome response");
            done();
        });

        expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
        expect(doneFn).not.toHaveBeenCalled();

        jasmine.Ajax.requests.mostRecent().respondWith({
            "status": 200,
            "contentType": 'text/plain',
            "responseText": 'awesome response'
        });
    });
});

<commit_msg>rename description<commit_after>describe("Ajax", function () {
    beforeEach(function () {
        jasmine.Ajax.install();
    });
    afterEach(function () {
        jasmine.Ajax.uninstall();
    });

    it("specifying response when you need it", function (done) {
        var doneFn = jasmine.createSpy("success");

        lettuce.get('/some/cool/url', function (result) {
            expect(result).toEqual("awesome response");
            done();
        });

        expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
        expect(doneFn).not.toHaveBeenCalled();

        jasmine.Ajax.requests.mostRecent().respondWith({
            "status": 200,
            "contentType": 'text/plain',
            "responseText": 'awesome response'
        });
    });

    it("should be post to some where", function (done) {
        var doneFn = jasmine.createSpy("success");

        lettuce.post('/some/cool/url', [], function (result) {
            expect(result).toEqual("awesome response");
            done();
        });

        expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
        expect(doneFn).not.toHaveBeenCalled();

        jasmine.Ajax.requests.mostRecent().respondWith({
            "status": 200,
            "contentType": 'text/plain',
            "responseText": 'awesome response'
        });
    });
});

<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

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.
*/

'use strict';

import Matrix from 'matrix-js-sdk';

const localStorage = window.localStorage;

function deviceId() {
    // XXX: is Math.random()'s deterministicity a problem here?
    var id = Math.floor(Math.random()*16777215).toString(16);
    id = "W" + "000000".substring(id.length) + id;
    if (localStorage) {
        id = localStorage.getItem("mx_device_id") || id;
        localStorage.setItem("mx_device_id", id);
    }
    return id;
}

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs but no credentials
     */
    replaceUsingUrls(hs_url, is_url) {
        this.replaceUsingAccessToken(hs_url, is_url);
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs and active credentials
     */
    replaceUsingAccessToken(hs_url, is_url, user_id, access_token, isGuest) {
        if (localStorage) {
            try {
                localStorage.clear();
            } catch (e) {
                console.warn("Error clearing local storage", e);
            }
        }
        this._createClient(hs_url, is_url, user_id, access_token);
        this.matrixClient.setGuest(Boolean(isGuest));

        if (localStorage) {
            try {
                localStorage.setItem("mx_hs_url", hs_url);
                localStorage.setItem("mx_is_url", is_url);

                if (user_id !== undefined && access_token !== undefined) {
                    localStorage.setItem("mx_user_id", user_id);
                    localStorage.setItem("mx_access_token", access_token);
                    localStorage.setItem("mx_is_guest", JSON.stringify(isGuest));
                    console.log("Session persisted for %s", user_id);
                }
            } catch (e) {
                console.warn("Error using local storage: can't persist session!", e);
            }
        } else {
            console.warn("No local storage available: can't persist session!");
        }
    }

    getCredentials() {
        return [
            this.matrixClient.baseUrl,
            this.matrixClient.idBaseUrl,
            this.matrixClient.credentials.userId,
            this.matrixClient.getAccessToken(),
            this.matrixClient.isGuest(),
        ];
    }

    tryRestore() {
        if (localStorage) {
            const hs_url = localStorage.getItem("mx_hs_url");
            const is_url = localStorage.getItem("mx_is_url") || 'https://matrix.org';
            const access_token = localStorage.getItem("mx_access_token");
            const user_id = localStorage.getItem("mx_user_id");

            let is_guest;
            if (localStorage.getItem("mx_is_guest") !== null) {
                is_guest = localStorage.getItem("mx_is_guest") === "true";
            } else {
                // legacy key name
                is_guest = localStorage.getItem("matrix-is-guest") === "true";
            }

            if (access_token && user_id && hs_url) {
                console.log("Restoring session for %s", user_id);
                this._createClient(hs_url, is_url, user_id, access_token);
                this.matrixClient.setGuest(is_guest);
            } else {
                console.log("Session not found.");
            }
        }
    }

    _createClient(hs_url, is_url, user_id, access_token) {
        var opts = {
            baseUrl: hs_url,
            idBaseUrl: is_url,
            accessToken: access_token,
            userId: user_id,
            timelineSupport: true,
        };

        if (localStorage) {
            opts.sessionStore = new Matrix.WebStorageSessionStore(localStorage);
            opts.deviceId = deviceId();
        }

        this.matrixClient = Matrix.createClient(opts);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
    global.mxMatrixClientPeg.tryRestore();
}
module.exports = global.mxMatrixClientPeg;
<commit_msg>This may as wel go in createclient<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

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.
*/

'use strict';

import Matrix from 'matrix-js-sdk';

const localStorage = window.localStorage;

function deviceId() {
    // XXX: is Math.random()'s deterministicity a problem here?
    var id = Math.floor(Math.random()*16777215).toString(16);
    id = "W" + "000000".substring(id.length) + id;
    if (localStorage) {
        id = localStorage.getItem("mx_device_id") || id;
        localStorage.setItem("mx_device_id", id);
    }
    return id;
}

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs but no credentials
     */
    replaceUsingUrls(hs_url, is_url) {
        this.replaceUsingAccessToken(hs_url, is_url);
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs and active credentials
     */
    replaceUsingAccessToken(hs_url, is_url, user_id, access_token, isGuest) {
        if (localStorage) {
            try {
                localStorage.clear();
            } catch (e) {
                console.warn("Error clearing local storage", e);
            }
        }
        this._createClient(hs_url, is_url, user_id, access_token);

        if (localStorage) {
            try {
                localStorage.setItem("mx_hs_url", hs_url);
                localStorage.setItem("mx_is_url", is_url);

                if (user_id !== undefined && access_token !== undefined) {
                    localStorage.setItem("mx_user_id", user_id);
                    localStorage.setItem("mx_access_token", access_token);
                    localStorage.setItem("mx_is_guest", JSON.stringify(isGuest));
                    console.log("Session persisted for %s", user_id);
                }
            } catch (e) {
                console.warn("Error using local storage: can't persist session!", e);
            }
        } else {
            console.warn("No local storage available: can't persist session!");
        }
    }

    getCredentials() {
        return [
            this.matrixClient.baseUrl,
            this.matrixClient.idBaseUrl,
            this.matrixClient.credentials.userId,
            this.matrixClient.getAccessToken(),
            this.matrixClient.isGuest(),
        ];
    }

    tryRestore() {
        if (localStorage) {
            const hs_url = localStorage.getItem("mx_hs_url");
            const is_url = localStorage.getItem("mx_is_url") || 'https://matrix.org';
            const access_token = localStorage.getItem("mx_access_token");
            const user_id = localStorage.getItem("mx_user_id");

            let is_guest;
            if (localStorage.getItem("mx_is_guest") !== null) {
                is_guest = localStorage.getItem("mx_is_guest") === "true";
            } else {
                // legacy key name
                is_guest = localStorage.getItem("matrix-is-guest") === "true";
            }

            if (access_token && user_id && hs_url) {
                console.log("Restoring session for %s", user_id);
                this._createClient(hs_url, is_url, user_id, access_token);
                this.matrixClient.setGuest(is_guest);
            } else {
                console.log("Session not found.");
            }
        }
    }

    _createClient(hs_url, is_url, user_id, access_token) {
        var opts = {
            baseUrl: hs_url,
            idBaseUrl: is_url,
            accessToken: access_token,
            userId: user_id,
            timelineSupport: true,
        };

        if (localStorage) {
            opts.sessionStore = new Matrix.WebStorageSessionStore(localStorage);
            opts.deviceId = deviceId();
        }

        this.matrixClient = Matrix.createClient(opts);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);

        this.matrixClient.setGuest(Boolean(isGuest));
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
    global.mxMatrixClientPeg.tryRestore();
}
module.exports = global.mxMatrixClientPeg;
<|endoftext|>