<commit_before>// TODO I suppose my attitude is to use an event emitter very sparingly, because
// I want to use one to emit Kibitzer events, the paxos log, but I don't want to
// create an interface that looks like one of the EventEmitter heavy interfaces.
//
// One of the challenges here is that events are going to flow immediately,
// unless I do something compliacated like only emit events when there is a
// listener. Having looked at that, it is not actually that complicated.
//
// Now we can fuss about some terminate logic.
//
// Put it out again, I prefer to program with error-first callbacks, but events
// happen. They are generally a way in which information enters the system. They
// are synchronous. Here is more information. Generally, they shouldn't block.
//
// That's how I use EventEmitters, but I'm not in for a penny, in for a pound.
// If there is a source of events, I treat that as a stream of events. Not in
// the Node.js streams sense, but I create an event emitter that emits a
// homogenous series of events terminated by a specific termination event.
//
// Then I stop. I don't go on to implement multi-interfaces that could take an
// error-first callback, or maybe register an event handler, or maybe use some
// other form of asynchronous notification.
//
// TODO Which is why I've made the event emitter in this class a separate
// object. Which is such a good idea, I belive I'll go and do it Happenstance.
//
// TODO Here I am, back to remove the EventEmitter. Not sure how anyone is able
// to program that way, treating everything in your application as a stream.
// Pushing log entires as events, hard to reason about this firehose events, and
// it makes any asynchronous calls in response to an event require subsequent
// queuing of events, so why not use this queue that already exists?

// Quality control.
var assert = require('assert')

// EventEmitter API.
var events = require('events')
var util = require('util')
var departure = require('departure')

// Common utiltieis.
var util = require('util')
var nop = require('nop')

// Control-flow libraries.
var abend = require('abend')
var cadence = require('cadence')
var Timer = require('happenstance').Timer
var Queue = require('procession')

// Paxos libraries.
var Paxos = require('paxos')
var Islander = require('islander')
var Monotonic = require('monotonic').asString

var Destructor = require('destructible')

// Logging.
var logger = require('prolific.logger').createLogger('kibitz')

// Message queue.
var Requester = require('conduit/requester')

// The `Kibitzer` object contains an islander, which will submit messages to
// Paxos, track the log generated by Paxos and resubit any messages that might
// have been dropped.

//
function Kibitzer (options) {
    // Log used to drain Islander.
    this.log = new Queue

    // Set option defaults.
    options || (options = {})

    options.ping || (options.ping = 250)
    options.timeout || (options.timeout = 1000)

    // Time obtained from optional `Date` for unit testing.
    this._Date = options.Date || Date

    this.paxos = new Paxos(options.id, {
        ping: options.ping,
        timeout: options.timeout
    })

    // Submission queue with resubmission logic.
    this.islander = new Islander(options.id)

    // Paxos sends messages to islander.
    this.paxos.log.shifter().pump(this.islander)

    this._shifters = null

    // Requesters to make network requests.
    this._requester = new Requester('kibitz')
    this.spigot = this._requester.spigot

    this.played = new Queue

    this.islander.log.pump(this.log)

    this._destructor = new Destructor
    this._destructor.markDestroyed(this, 'destroyed')
    this._destructor.addDestructor('scheduler', this.paxos.scheduler.clear.bind(this.paxos.scheduler))

    this.destruction = this._destructor.events
}

Kibitzer.prototype.listen = cadence(function (async) {
    // TODO Pass an "operation" to `Procession.pump`.
    var timer = new Timer(this.paxos.scheduler)
    timer.events.pump(function (envelope) {
        this.play('event', envelope, abend)
    }.bind(this))
    this.paxos.scheduler.events.pump(timer)
    this._shifters = {
        paxos: this.paxos.outbox.shifter(),
        islander: this.islander.outbox.shifter()
    }
    this._publish(async())
    this._send(async())
})

// You can just as easily use POSIX time for the `republic`.
Kibitzer.prototype.bootstrap = function (republic, properties) {
    this.play('bootstrap', { republic: republic, properties: properties }, abend)
}

// Enqueue a user message into the `Islander`. The `Islander` will submit the
// message, monitor the atomic log, and then resubmit the message if it detects
// that the message was lost.
Kibitzer.prototype.publish = function (entry) {
    this.play('publish', entry, abend)
}

// Called by your network implementation with messages enqueued from another
// Kibitz.
Kibitzer.prototype.request = cadence(function (async, envelope) {
    switch (envelope.method) {
    case 'immigrate':
        this._immigrate(envelope.body, async())
        break
    case 'receive':
        this.play('receive', envelope.body, async())
        break
    case 'enqueue':
        this.play('enqueue', envelope.body, async())
        break
    }
})

Kibitzer.prototype.play = function (method, body, callback) {
    var envelope = {
        module: 'kibitz',
        method: method,
        when: this._Date.now(),
        body: body
    }
    this.replay(envelope, callback)
}

Kibitzer.prototype.replay = cadence(function (async, envelope) {
    this.played.push(envelope)
    switch (envelope.method) {
    case 'bootstrap':
        this.paxos.bootstrap(envelope.when, envelope.body.republic, envelope.body.properties)
        break
    case 'join':
        this._join(envelope.body.leader, envelope.body.properties, envelope.when, async())
        break
    case 'event':
        this.paxos.event(envelope.body)
        break
    case 'immigrate':
        var body = envelope.body
        return [ this.paxos.immigrate(envelope.when, body.republic, body.id, body.cookie, body.properties) ]
        break
    case 'receive':
        // TODO Split pulse from messages somehow, make them siblings, not nested.
        return [ this.paxos.receive(envelope.when, envelope.body, envelope.body.messages) ]
        break
    case 'enqueue':
        return [ this._enqueue(envelope.when, envelope.body) ]
    case 'publish':
        this.islander.publish(envelope.body)
        break
    case 'published':
        this.islander.sent(envelope.body.promises)
        break
    case 'sent':
        this.paxos.sent(envelope.when, envelope.body.pulse, envelope.body.responses)
        break
    }
})

// Stop timers, and stop timers only. We're not in a position to notify clients
// that there will be no more messages.
Kibitzer.prototype.destroy = function () {
    this._destructor.destroy()
}

Kibitzer.prototype.join = cadence(function (async, leader, properties) {
    this.play('join', { leader: leader, properties: properties }, async())
})

Kibitzer.prototype._join = cadence(function (async, leader, properties, when) {
// TODO Should this be or should this not be? It should be. You're sending your
// enqueue messages until you immigrate. You don't know when that will be.
// You're only going to know if you've succeeded if your legislator has
// immigrated. That's the only way.
    if (this.paxos.government.promise != '0/0') {
        // TODO This should be rejected when you enqueue, it shoudln't matter.
        console.log('Hey! I got a government.')
        return
    }
    // throw new Error
    async(function () {
        this.paxos.join(when, leader.republic)
        this._requester.request('kibitz', {
            module: 'kibitz',
            method: 'immigrate',
            to: leader,
            body: {
                republic: leader.republic,
                id: this.paxos.id,
                cookie: this.paxos.cookie,
                properties: properties,
                hops: 0
            }
        }, async())
    }, function (response) {
        return response != null && response.enqueued
    })
})

// Publish to consensus algorithm from islander retryable client.
Kibitzer.prototype._publish = cadence(function (async) {
    this._destructor.async(async, 'publish')(function () {
        this._destructor.addDestructor('publish', this._shifters.islander.destroy.bind(this._shifters.islander))
        var loop = async(function () {
            this._shifters.islander.dequeue(async())
        }, function (messages) {
            if (messages == null) {
                return [ loop.break ]
            }
            async(function () {
                var properties = this.paxos.government.properties[this.paxos.government.majority[0]]
                this._requester.request('kibitz', {
                    module: 'kibitz',
                    method: 'enqueue',
                    to: properties,
                    body: {
                        republic: this.paxos.republic,
                        entries: messages
                    }
                }, async())
            }, function (promises) {
                this.play('published', { promises: promises }, async())
            })
        })()
    })
})

// TODO Annoying how difficult it is to stop this crazy thing. There are going
// to be race conditions where we have a termination, come in, we shut things
// down, but then we continue with processing a pulse which triggers a timer.
// Sending messages to paxos can restart it's scheduler.
//
// TODO We could kill the timer in the scheduler, set the boolean we added to
// tell it to no longer schedule.
Kibitzer.prototype._send = cadence(function (async) {
    this._destructor.async(async, 'send')(function () {
        this._destructor.addDestructor('send', this._shifters.paxos.destroy.bind(this._shifters.paxos))
        var loop = async(function () {
            this._shifters.paxos.dequeue(async())
        }, function (pulse) {
            if (pulse == null) {
                return [ loop.break ]
            }
            var responses = []
            async(function () {
                pulse.route.forEach(function (id) {
                    async(function () {
                        if (id == this.paxos.id) {
                            this.request({ method: 'receive', body: pulse }, async())
                        } else {
                            var properties = this.paxos.government.properties[id]
                            this._requester.request('kibitz', {
                                module: 'kibitz',
                                method: 'receive',
                                to: properties,
                                body: pulse
                            }, async())
                        }
                    }, function (response) {
                        responses[id] = response
                    })
                }, this)
            }, function () {
                this.play('sent', { pulse: pulse, responses: responses }, async())
            })
        })()
    })
})

Kibitzer.prototype._immigrate = cadence(function (async, post) {
    async(function () {
        assert(post.hops != null)
        this.play('immigrate', post, async())
    }, function (outcome) {
        if (!outcome.enqueued && outcome.leader != null && post.hops == 0) {
            var properties = this.paxos.government.properties[outcome.leader]
            post.hops++
            this._requester.request('kibitz', {
                module: 'kibtiz',
                method: 'immigrate',
                to: properties,
                body: post
            }, async())
        } else {
            return [ outcome ]
        }
    })
})

Kibitzer.prototype._enqueue = function (when, post) {
    var promises = {}
    for (var i = 0, I = post.entries.length; i < I; i++) {
        var entry = post.entries[i]
        var outcome = this.paxos.enqueue(when, post.republic, entry)
        if (!outcome.enqueued) {
            entries = null
            break
        }
        promises[entry.cookie] = outcome.promise
    }
    return promises
}

Kibitzer.prototype._receive = cadence(function (async, pulse, when) {
    return [ this.paxos.receive(when, pulse, pulse.messages) ]
})

module.exports = Kibitzer
<commit_msg>Correctly record `join`.<commit_after>// TODO I suppose my attitude is to use an event emitter very sparingly, because
// I want to use one to emit Kibitzer events, the paxos log, but I don't want to
// create an interface that looks like one of the EventEmitter heavy interfaces.
//
// One of the challenges here is that events are going to flow immediately,
// unless I do something compliacated like only emit events when there is a
// listener. Having looked at that, it is not actually that complicated.
//
// Now we can fuss about some terminate logic.
//
// Put it out again, I prefer to program with error-first callbacks, but events
// happen. They are generally a way in which information enters the system. They
// are synchronous. Here is more information. Generally, they shouldn't block.
//
// That's how I use EventEmitters, but I'm not in for a penny, in for a pound.
// If there is a source of events, I treat that as a stream of events. Not in
// the Node.js streams sense, but I create an event emitter that emits a
// homogenous series of events terminated by a specific termination event.
//
// Then I stop. I don't go on to implement multi-interfaces that could take an
// error-first callback, or maybe register an event handler, or maybe use some
// other form of asynchronous notification.
//
// TODO Which is why I've made the event emitter in this class a separate
// object. Which is such a good idea, I belive I'll go and do it Happenstance.
//
// TODO Here I am, back to remove the EventEmitter. Not sure how anyone is able
// to program that way, treating everything in your application as a stream.
// Pushing log entires as events, hard to reason about this firehose events, and
// it makes any asynchronous calls in response to an event require subsequent
// queuing of events, so why not use this queue that already exists?

// Quality control.
var assert = require('assert')

// EventEmitter API.
var events = require('events')
var util = require('util')
var departure = require('departure')

// Common utiltieis.
var util = require('util')
var nop = require('nop')

// Control-flow libraries.
var abend = require('abend')
var cadence = require('cadence')
var Timer = require('happenstance').Timer
var Queue = require('procession')

// Paxos libraries.
var Paxos = require('paxos')
var Islander = require('islander')
var Monotonic = require('monotonic').asString

var Destructor = require('destructible')

// Logging.
var logger = require('prolific.logger').createLogger('kibitz')

// Message queue.
var Requester = require('conduit/requester')

// The `Kibitzer` object contains an islander, which will submit messages to
// Paxos, track the log generated by Paxos and resubit any messages that might
// have been dropped.

//
function Kibitzer (options) {
    // Log used to drain Islander.
    this.log = new Queue

    // Set option defaults.
    options || (options = {})

    options.ping || (options.ping = 250)
    options.timeout || (options.timeout = 1000)

    // Time obtained from optional `Date` for unit testing.
    this._Date = options.Date || Date

    this.paxos = new Paxos(options.id, {
        ping: options.ping,
        timeout: options.timeout
    })

    // Submission queue with resubmission logic.
    this.islander = new Islander(options.id)

    // Paxos sends messages to islander.
    this.paxos.log.shifter().pump(this.islander)

    this._shifters = null

    // Requesters to make network requests.
    this._requester = new Requester('kibitz')
    this.spigot = this._requester.spigot

    this.played = new Queue

    this.islander.log.pump(this.log)

    this._destructor = new Destructor
    this._destructor.markDestroyed(this, 'destroyed')
    this._destructor.addDestructor('scheduler', this.paxos.scheduler.clear.bind(this.paxos.scheduler))

    this.destruction = this._destructor.events
}

Kibitzer.prototype.listen = cadence(function (async) {
    // TODO Pass an "operation" to `Procession.pump`.
    var timer = new Timer(this.paxos.scheduler)
    timer.events.pump(function (envelope) {
        this.play('event', envelope, abend)
    }.bind(this))
    this.paxos.scheduler.events.pump(timer)
    this._shifters = {
        paxos: this.paxos.outbox.shifter(),
        islander: this.islander.outbox.shifter()
    }
    this._publish(async())
    this._send(async())
})

// You can just as easily use POSIX time for the `republic`.
Kibitzer.prototype.bootstrap = function (republic, properties) {
    this.play('bootstrap', { republic: republic, properties: properties }, abend)
}

// Enqueue a user message into the `Islander`. The `Islander` will submit the
// message, monitor the atomic log, and then resubmit the message if it detects
// that the message was lost.
Kibitzer.prototype.publish = function (entry) {
    this.play('publish', entry, abend)
}

// Called by your network implementation with messages enqueued from another
// Kibitz.
Kibitzer.prototype.request = cadence(function (async, envelope) {
    switch (envelope.method) {
    case 'immigrate':
        this._immigrate(envelope.body, async())
        break
    case 'receive':
        this.play('receive', envelope.body, async())
        break
    case 'enqueue':
        this.play('enqueue', envelope.body, async())
        break
    }
})

Kibitzer.prototype.play = function (method, body, callback) {
    var envelope = {
        module: 'kibitz',
        method: method,
        when: this._Date.now(),
        body: body
    }
    this.replay(envelope, callback)
}

Kibitzer.prototype.replay = cadence(function (async, envelope) {
    this.played.push(envelope)
    switch (envelope.method) {
    case 'bootstrap':
        this.paxos.bootstrap(envelope.when, envelope.body.republic, envelope.body.properties)
        break
    case 'join':
        this.paxos.join(envelope.when, envelope.body.republic)
        break
    case 'event':
        this.paxos.event(envelope.body)
        break
    case 'immigrate':
        var body = envelope.body
        return [ this.paxos.immigrate(envelope.when, body.republic, body.id, body.cookie, body.properties) ]
        break
    case 'receive':
        // TODO Split pulse from messages somehow, make them siblings, not nested.
        return [ this.paxos.receive(envelope.when, envelope.body, envelope.body.messages) ]
        break
    case 'enqueue':
        return [ this._enqueue(envelope.when, envelope.body) ]
    case 'publish':
        this.islander.publish(envelope.body)
        break
    case 'published':
        this.islander.sent(envelope.body.promises)
        break
    case 'sent':
        this.paxos.sent(envelope.when, envelope.body.pulse, envelope.body.responses)
        break
    }
})

// Stop timers, and stop timers only. We're not in a position to notify clients
// that there will be no more messages.
Kibitzer.prototype.destroy = function () {
    this._destructor.destroy()
}

Kibitzer.prototype.join = cadence(function (async, leader, properties) {
// TODO Should this be or should this not be? It should be. You're sending your
// enqueue messages until you immigrate. You don't know when that will be.
// You're only going to know if you've succeeded if your legislator has
// immigrated. That's the only way.
    if (this.paxos.government.promise != '0/0') {
        // TODO This should be rejected when you enqueue, it shoudln't matter.
        console.log('Hey! I got a government.')
        return
    }
    // throw new Error
    async(function () {
        this.play('join', { republic: leader.republic  }, async())
        this._requester.request('kibitz', {
            module: 'kibitz',
            method: 'immigrate',
            to: leader,
            body: {
                republic: leader.republic,
                id: this.paxos.id,
                cookie: this.paxos.cookie,
                properties: properties,
                hops: 0
            }
        }, async())
    }, function (response) {
        return response != null && response.enqueued
    })
})

// Publish to consensus algorithm from islander retryable client.
Kibitzer.prototype._publish = cadence(function (async) {
    this._destructor.async(async, 'publish')(function () {
        this._destructor.addDestructor('publish', this._shifters.islander.destroy.bind(this._shifters.islander))
        var loop = async(function () {
            this._shifters.islander.dequeue(async())
        }, function (messages) {
            if (messages == null) {
                return [ loop.break ]
            }
            async(function () {
                var properties = this.paxos.government.properties[this.paxos.government.majority[0]]
                this._requester.request('kibitz', {
                    module: 'kibitz',
                    method: 'enqueue',
                    to: properties,
                    body: {
                        republic: this.paxos.republic,
                        entries: messages
                    }
                }, async())
            }, function (promises) {
                this.play('published', { promises: promises }, async())
            })
        })()
    })
})

// TODO Annoying how difficult it is to stop this crazy thing. There are going
// to be race conditions where we have a termination, come in, we shut things
// down, but then we continue with processing a pulse which triggers a timer.
// Sending messages to paxos can restart it's scheduler.
//
// TODO We could kill the timer in the scheduler, set the boolean we added to
// tell it to no longer schedule.
Kibitzer.prototype._send = cadence(function (async) {
    this._destructor.async(async, 'send')(function () {
        this._destructor.addDestructor('send', this._shifters.paxos.destroy.bind(this._shifters.paxos))
        var loop = async(function () {
            this._shifters.paxos.dequeue(async())
        }, function (pulse) {
            if (pulse == null) {
                return [ loop.break ]
            }
            var responses = []
            async(function () {
                pulse.route.forEach(function (id) {
                    async(function () {
                        if (id == this.paxos.id) {
                            this.request({ method: 'receive', body: pulse }, async())
                        } else {
                            var properties = this.paxos.government.properties[id]
                            this._requester.request('kibitz', {
                                module: 'kibitz',
                                method: 'receive',
                                to: properties,
                                body: pulse
                            }, async())
                        }
                    }, function (response) {
                        responses[id] = response
                    })
                }, this)
            }, function () {
                this.play('sent', { pulse: pulse, responses: responses }, async())
            })
        })()
    })
})

Kibitzer.prototype._immigrate = cadence(function (async, post) {
    async(function () {
        assert(post.hops != null)
        this.play('immigrate', post, async())
    }, function (outcome) {
        if (!outcome.enqueued && outcome.leader != null && post.hops == 0) {
            var properties = this.paxos.government.properties[outcome.leader]
            post.hops++
            this._requester.request('kibitz', {
                module: 'kibtiz',
                method: 'immigrate',
                to: properties,
                body: post
            }, async())
        } else {
            return [ outcome ]
        }
    })
})

Kibitzer.prototype._enqueue = function (when, post) {
    var promises = {}
    for (var i = 0, I = post.entries.length; i < I; i++) {
        var entry = post.entries[i]
        var outcome = this.paxos.enqueue(when, post.republic, entry)
        if (!outcome.enqueued) {
            entries = null
            break
        }
        promises[entry.cookie] = outcome.promise
    }
    return promises
}

Kibitzer.prototype._receive = cadence(function (async, pulse, when) {
    return [ this.paxos.receive(when, pulse, pulse.messages) ]
})

module.exports = Kibitzer
<|endoftext|>


<commit_before>'use strict';
angular.module('copayApp.services').factory('bitcoincomService', function($http, $log, lodash, moment, storageService, configService, platformInfo, nextStepsService, homeIntegrationsService) {
  var root = {};
  var credentials = {};

  /*
   * Development: 'testnet'
   * Production: 'livenet'
   */
  credentials.NETWORK = 'livenet';
  //credentials.NETWORK = 'testnet';

  if (credentials.NETWORK == 'testnet') {
    credentials.BITPAY_API_URL = "https://test.bitpay.com";
  } else {
    credentials.BITPAY_API_URL = "https://bitpay.com";
  };

  var cashGamesItem = {
    name: 'games',
    title: 'Bitcoin Cash Games',
    icon: 'icon-games',
    href: 'http://cashgames.bitcoin.com'
  };

  var newsItem = {
    name: 'news',
    title: 'News',
    icon: 'icon-news',
    href: 'http://news.bitcoin.com'
  };

  var poolItem = {
    name: 'pool',
    title: 'Mining Pool',
    icon: 'icon-mining',
    href: 'http://pool.bitcoin.com'
  };

  var toolsItem = {
    name: 'tools',
    title: 'Tools',
    icon: 'icon-tools',
    href: 'http://tools.bitcoin.com'
  }

  var _getBitPay = function(endpoint) {
    return {
      method: 'GET',
      url: credentials.BITPAY_API_URL + endpoint,
      headers: {
        'content-type': 'application/json'
      }
    };
  };

  var _postBitPay = function(endpoint, data) {
    return {
      method: 'POST',
      url: credentials.BITPAY_API_URL + endpoint,
      headers: {
        'content-type': 'application/json'
      },
      data: data
    };
  };

  root.getNetwork = function() {
    return credentials.NETWORK;
  };

  var register = function() {
    nextStepsService.register(cashGamesItem);
    nextStepsService.register(newsItem);
    nextStepsService.register(poolItem);
    nextStepsService.register(toolsItem);
  };

  register();
  return root;
});
<commit_msg>missing semicolon<commit_after>'use strict';
angular.module('copayApp.services').factory('bitcoincomService', function($http, $log, lodash, moment, storageService, configService, platformInfo, nextStepsService, homeIntegrationsService) {
  var root = {};
  var credentials = {};

  /*
   * Development: 'testnet'
   * Production: 'livenet'
   */
  credentials.NETWORK = 'livenet';
  //credentials.NETWORK = 'testnet';

  if (credentials.NETWORK == 'testnet') {
    credentials.BITPAY_API_URL = "https://test.bitpay.com";
  } else {
    credentials.BITPAY_API_URL = "https://bitpay.com";
  };

  var cashGamesItem = {
    name: 'games',
    title: 'Bitcoin Cash Games',
    icon: 'icon-games',
    href: 'http://cashgames.bitcoin.com'
  };

  var newsItem = {
    name: 'news',
    title: 'News',
    icon: 'icon-news',
    href: 'http://news.bitcoin.com'
  };

  var poolItem = {
    name: 'pool',
    title: 'Mining Pool',
    icon: 'icon-mining',
    href: 'http://pool.bitcoin.com'
  };

  var toolsItem = {
    name: 'tools',
    title: 'Tools',
    icon: 'icon-tools',
    href: 'http://tools.bitcoin.com'
  };

  var _getBitPay = function(endpoint) {
    return {
      method: 'GET',
      url: credentials.BITPAY_API_URL + endpoint,
      headers: {
        'content-type': 'application/json'
      }
    };
  };

  var _postBitPay = function(endpoint, data) {
    return {
      method: 'POST',
      url: credentials.BITPAY_API_URL + endpoint,
      headers: {
        'content-type': 'application/json'
      },
      data: data
    };
  };

  root.getNetwork = function() {
    return credentials.NETWORK;
  };

  var register = function() {
    nextStepsService.register(cashGamesItem);
    nextStepsService.register(newsItem);
    nextStepsService.register(poolItem);
    nextStepsService.register(toolsItem);
  };

  register();
  return root;
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('chaise.authen', ['chaise.utils'])

    .factory('Session', ['$http', '$q', '$window', 'UriUtils', '$uibModal', '$interval', '$cookies','messageMap', function ($http, $q, $window, UriUtils, $uibModal, $interval, $cookies, messageMap) {

        // authn API no longer communicates through ermrest, removing the need to check for ermrest location
        var serviceURL = $window.location.origin;

        // Private variable to store current session object
        var _session = null;

        var _changeCbs = {};

        var _counter = 0;

        var _executeListeners = function() {
            for (var k in _changeCbs) {
                _changeCbs[k]();
            }
        };

        var loginWindowCb = function (params, referrerId, cb, type){
            if(type.indexOf('modal')!== -1){
                if (_session) {
                    params.title = messageMap.sessionExpired.title;
                    params.message = messageMap.sessionExpired.message;
                } else {
                    params.title = messageMap.noSession.title;
                    params.message = messageMap.noSession.message;
                }
                var modalInstance, closed = false;
                modalInstance = $uibModal.open({
                    windowClass: "modal-login-instruction",
                    templateUrl: "../common/templates/loginDialog.modal.html",
                    controller: 'LoginDialogController',
                    controllerAs: 'ctrl',
                    resolve: {
                        params: params
                    },
                    openedClass: 'modal-login',
                    backdrop: 'static',
                    keyboard: false
                });

                var onModalClose = function() {
                    $interval.cancel(intervalId);
                    $cookies.remove("chaise-" + referrerId, { path: "/" });
                    closed = true;
                };

                // To avoid problems when user explicitly close the modal
                modalInstance.result.then(onModalClose, onModalClose);
            }

            /* if browser is IE then add explicit handler to watch for changes in localstorage for a particular
             * variable
             */
            if (UriUtils.isBrowserIE()) {
                $cookies.put("chaise-" + referrerId, true, { path: "/" });
                var intervalId;
                var watchChangeInReferrerId = function () {
                    if (!$cookies.get("chaise-" + referrerId)) {
                        $interval.cancel(intervalId);
                        if (typeof cb== 'function') {
                            if(type.indexOf('modal')!== -1){
                                intervalId = $interval(watchChangeInReferrerId, 50);
                                modalInstance.close("Done");
                                cb();
                                closed = true;
                            }
                            else{
                                cb();
                            }
                        }
                        return;
                    }
                }
            }
            else {
                window.addEventListener('message', function(args) {
                    if (args && args.data && (typeof args.data == 'string')) {
                        var obj = UriUtils.queryStringToJSON(args.data);
                        if (obj.referrerid == referrerId && (typeof cb== 'function')) {
                            if(type.indexOf('modal')!== -1){
                                modalInstance.close("Done");
                                cb();
                                closed = true;
                            }
                            else{
                                cb();
                            }
                        }
                    }
                });
            }
        };

        var logInHelper = function(logInTypeCb, win, cb, type){
            var referrerId = (new Date().getTime());
            var url = serviceURL + '/authn/preauth?referrer=' + UriUtils.fixedEncodeURIComponent(window.location.href.substring(0,window.location.href.indexOf('chaise')) + "chaise/login?referrerid=" + referrerId);
            var config = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'Accept': 'application/json'
                }
            };

            $http.get(url, config).then(function(response){
                var data = response.data;

                var login_url = "";
                if (data['redirect_url'] !== undefined) {
                    login_url = data['redirect_url'];
                } else if (data['login_form'] !== undefined) {
                    var login_form = data['login_form'];
                    login_url = '../login?referrer=' + UriUtils.fixedEncodeURIComponent(referrer);
                    var method = login_form['method'];
                    var action = UriUtils.fixedEncodeURIComponent(login_form['action']);
                    var text = '';
                    var hidden = '';
                    for (var i = 0; i < login_form['input_fields'].length; i++) {
                        var field = login_form['input_fields'][i];
                        if (field.type === 'text') {
                            text = UriUtils.fixedEncodeURIComponent(field.name);
                        } else {
                            hidden = UriUtils.fixedEncodeURIComponent(field.name);
                        }
                    }
                    login_url += '&method=' + method + '&action=' + action + '&text=' + text + '&hidden=' + hidden + '&?referrerid=' + referrerId;
                }

                var params = {
                    login_url: login_url
                };
                if(win){
                        win.location=params.login_url;
                }
                logInTypeCb(params,referrerId, cb, type);
            }, function(error) {
                throw error;
            });
        };

        return {

            getSession: function() {
                return $http.get(serviceURL + "/authn/session").then(function(response) {
                    _session = response.data;
                    _executeListeners();
                    return response.data;
                }, function(response) {
                    _session = null;
                    _executeListeners();
                    return $q.reject(response);
                });
            },

            getSessionValue: function() {
                return _session;
            },

            subscribeOnChange: function(fn) {
                // To avoid same ids for an instance we add counter
                var id = new Date().getTime() + (++_counter);

                if (typeof fn  == 'function') {
                    _changeCbs[id] = fn;
                }
                return id;
            },

            unsubscribeOnChange: function(id) {
                delete _changeCbs[id];
            },

            loginInAPopUp: function(win,reloadCb) {
                logInHelper(loginWindowCb,win,reloadCb,'popUp');
            },

            loginInAModal: function(notifyErmrestCB) {
                logInHelper(loginWindowCb,"",notifyErmrestCB,'modal');
            },

            logout: function() {
                var logoutURL = chaiseConfig['logoutURL'] ? chaiseConfig['logoutURL'] : '/';
                var url = serviceURL + "/authn/session";

                url += '?logout_url=' + UriUtils.fixedEncodeURIComponent(logoutURL);

                $http.delete(url).then(function(response) {
                    $window.location = response.data.logout_url;
                }, function(error) {
                    // if the logout fails for some reason, send the user to the logout url as defined above
                    $window.location = logoutURL;
                });
            }
        }
    }])

    var pathname = window.location.pathname;

    // If app is not search, viewer and login then attach the unauthorised 401 http handler to ermrestjs

    if (pathname.indexOf('/search/') == -1 && pathname.indexOf('/viewer/') == -1 && pathname.indexOf('/login') == -1) {

        angular.module('chaise.authen')
        .run(['ERMrest', '$injector', '$q', function runRecordEditApp(ERMrest, $injector, $q) {

            var Session = $injector.get("Session");

            // Bind callback function by invoking setHttpUnauthorizedFn handler passing the callback
            // This callback will be called whenever 401 HTTP error is encountered unless there is
            // already login flow in progress
            ERMrest.setHttpUnauthorizedFn(function() {
                var defer = $q.defer();

                // Call login in a new modal window to perform authentication
                // and return a promise to notify ermrestjs that the user has loggedin
                Session.loginInAModal(function() {

                    // Once the user has logged in fetch the new session and set the session value
                    // and resolve the promise to notify ermrestjs that the user has logged in
                    // and it can continue firing other queued calls
                    Session.getSession().then(function(_session) {
                        defer.resolve();
                    }, function(exception) {
                        throw exception;
                    });

                });

                return defer.promise;
            });

        }]);

    }

})();
<commit_msg>Changes to remove hardcoding of chaise in url<commit_after>(function() {
    'use strict';

    angular.module('chaise.authen', ['chaise.utils'])

    .factory('Session', ['$http', '$q', '$window', 'UriUtils', '$uibModal', '$interval', '$cookies','messageMap', function ($http, $q, $window, UriUtils, $uibModal, $interval, $cookies, messageMap) {

        // authn API no longer communicates through ermrest, removing the need to check for ermrest location
        var serviceURL = $window.location.origin;

        // Private variable to store current session object
        var _session = null;

        var _changeCbs = {};

        var _counter = 0;

        var _executeListeners = function() {
            for (var k in _changeCbs) {
                _changeCbs[k]();
            }
        };

        var loginWindowCb = function (params, referrerId, cb, type){
            if(type.indexOf('modal')!== -1){
                if (_session) {
                    params.title = messageMap.sessionExpired.title;
                    params.message = messageMap.sessionExpired.message;
                } else {
                    params.title = messageMap.noSession.title;
                    params.message = messageMap.noSession.message;
                }
                var modalInstance, closed = false;
                modalInstance = $uibModal.open({
                    windowClass: "modal-login-instruction",
                    templateUrl: "../common/templates/loginDialog.modal.html",
                    controller: 'LoginDialogController',
                    controllerAs: 'ctrl',
                    resolve: {
                        params: params
                    },
                    openedClass: 'modal-login',
                    backdrop: 'static',
                    keyboard: false
                });

                var onModalClose = function() {
                    $interval.cancel(intervalId);
                    $cookies.remove("chaise-" + referrerId, { path: "/" });
                    closed = true;
                };

                // To avoid problems when user explicitly close the modal
                modalInstance.result.then(onModalClose, onModalClose);
            }

            /* if browser is IE then add explicit handler to watch for changes in localstorage for a particular
             * variable
             */
            if (UriUtils.isBrowserIE()) {
                $cookies.put("chaise-" + referrerId, true, { path: "/" });
                var intervalId;
                var watchChangeInReferrerId = function () {
                    if (!$cookies.get("chaise-" + referrerId)) {
                        $interval.cancel(intervalId);
                        if (typeof cb== 'function') {
                            if(type.indexOf('modal')!== -1){
                                intervalId = $interval(watchChangeInReferrerId, 50);
                                modalInstance.close("Done");
                                cb();
                                closed = true;
                            }
                            else{
                                cb();
                            }
                        }
                        return;
                    }
                }
            }
            else {
                window.addEventListener('message', function(args) {
                    if (args && args.data && (typeof args.data == 'string')) {
                        var obj = UriUtils.queryStringToJSON(args.data);
                        if (obj.referrerid == referrerId && (typeof cb== 'function')) {
                            if(type.indexOf('modal')!== -1){
                                modalInstance.close("Done");
                                cb();
                                closed = true;
                            }
                            else{
                                cb();
                            }
                        }
                    }
                });
            }
        };

        var logInHelper = function(logInTypeCb, win, cb, type){
            var referrerId = (new Date().getTime());
            var location = window.location;
            var subUrl =  location.pathname.split('/')[1].indexOf('~')!= -1 ? location.pathname.split('/')[2]: location.pathname.split('/')[1];
            var url = serviceURL + '/authn/preauth?referrer='+UriUtils.fixedEncodeURIComponent(location.origin+"/"+subUrl + "/login?referrerid=" + referrerId);
            var config = {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'Accept': 'application/json'
                }
            };

            $http.get(url, config).then(function(response){
                var data = response.data;

                var login_url = "";
                if (data['redirect_url'] !== undefined) {
                    login_url = data['redirect_url'];
                } else if (data['login_form'] !== undefined) {
                    var login_form = data['login_form'];
                    login_url = '../login?referrer=' + UriUtils.fixedEncodeURIComponent(referrer);
                    var method = login_form['method'];
                    var action = UriUtils.fixedEncodeURIComponent(login_form['action']);
                    var text = '';
                    var hidden = '';
                    for (var i = 0; i < login_form['input_fields'].length; i++) {
                        var field = login_form['input_fields'][i];
                        if (field.type === 'text') {
                            text = UriUtils.fixedEncodeURIComponent(field.name);
                        } else {
                            hidden = UriUtils.fixedEncodeURIComponent(field.name);
                        }
                    }
                    login_url += '&method=' + method + '&action=' + action + '&text=' + text + '&hidden=' + hidden + '&?referrerid=' + referrerId;
                }

                var params = {
                    login_url: login_url
                };
                if(win){
                        win.location=params.login_url;
                }
                logInTypeCb(params,referrerId, cb, type);
            }, function(error) {
                throw error;
            });
        };

        return {

            getSession: function() {
                return $http.get(serviceURL + "/authn/session").then(function(response) {
                    _session = response.data;
                    _executeListeners();
                    return response.data;
                }, function(response) {
                    _session = null;
                    _executeListeners();
                    return $q.reject(response);
                });
            },

            getSessionValue: function() {
                return _session;
            },

            subscribeOnChange: function(fn) {
                // To avoid same ids for an instance we add counter
                var id = new Date().getTime() + (++_counter);

                if (typeof fn  == 'function') {
                    _changeCbs[id] = fn;
                }
                return id;
            },

            unsubscribeOnChange: function(id) {
                delete _changeCbs[id];
            },

            loginInAPopUp: function(win,reloadCb) {
                logInHelper(loginWindowCb,win,reloadCb,'popUp');
            },

            loginInAModal: function(notifyErmrestCB) {
                logInHelper(loginWindowCb,"",notifyErmrestCB,'modal');
            },

            logout: function() {
                var logoutURL = chaiseConfig['logoutURL'] ? chaiseConfig['logoutURL'] : '/';
                var url = serviceURL + "/authn/session";

                url += '?logout_url=' + UriUtils.fixedEncodeURIComponent(logoutURL);

                $http.delete(url).then(function(response) {
                    $window.location = response.data.logout_url;
                }, function(error) {
                    // if the logout fails for some reason, send the user to the logout url as defined above
                    $window.location = logoutURL;
                });
            }
        }
    }])

    var pathname = window.location.pathname;

    // If app is not search, viewer and login then attach the unauthorised 401 http handler to ermrestjs

    if (pathname.indexOf('/search/') == -1 && pathname.indexOf('/viewer/') == -1 && pathname.indexOf('/login') == -1) {

        angular.module('chaise.authen')
        .run(['ERMrest', '$injector', '$q', function runRecordEditApp(ERMrest, $injector, $q) {

            var Session = $injector.get("Session");

            // Bind callback function by invoking setHttpUnauthorizedFn handler passing the callback
            // This callback will be called whenever 401 HTTP error is encountered unless there is
            // already login flow in progress
            ERMrest.setHttpUnauthorizedFn(function() {
                var defer = $q.defer();

                // Call login in a new modal window to perform authentication
                // and return a promise to notify ermrestjs that the user has loggedin
                Session.loginInAModal(function() {

                    // Once the user has logged in fetch the new session and set the session value
                    // and resolve the promise to notify ermrestjs that the user has logged in
                    // and it can continue firing other queued calls
                    Session.getSession().then(function(_session) {
                        defer.resolve();
                    }, function(exception) {
                        throw exception;
                    });

                });

                return defer.promise;
            });

        }]);

    }

})();
<|endoftext|>


<commit_before>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	// $('#loading-circle').addClass('animated bounceIn');

            	int_loading_count = 0;
            	arr_colors = Array('rgba(52, 152, 219, 1)', 'rgba(255, 140, 0, 1)', 'rgba(231, 76, 60, 1)', 'rgba(0, 128, 0, .9)', 'rgba(0, 154, 136, .9)', 'rgba(164, 121, 228, 1)');

            	// bool_kill_next_loop = false;

        		// $('#loading-circle').addClass('animated pulse');

        		pulsing_circle_interval = setInterval(function() {

        			// $('#loading-circle').css('opacity', '.7');

        			$('#L').css('opacity', '.8');
        			$('#L').css('-webkit-transition', '.5s');
        			$('#L').css('-webkit-transform', 'scale(.5)');

        			setTimeout(function() {
        				$('#L').css('opacity', '1');
        				$('#L').css('-webkit-transform', 'scale(1)');
        			}, 500);

        			setTimeout(function() {
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '.8');
        			}, 200);

        			setTimeout(function() {
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '.8');
        			}, 300);

        			setTimeout(function() {
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '.8');
        			}, 400);

        			setTimeout(function() {
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '.8');
        			}, 500);

        			setTimeout(function() {
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '.75');
        			}, 600);

        			setTimeout(function() {
        				$('#G').css('opacity', '1');
        			}, 700);*/

        			// $('#loading-circle').css('background-color', arr_colors[int_loading_count]);
        			int_loading_count += 1;
        			if (int_loading_count == 4) {
        				clearInterval(pulsing_circle_interval);
        				setTimeout(function() {
        					$('#loading-circle').addClass('animated slideOutUp');
        					$('#loading-circle').fadeOut(300);
        				}, 500);
        				setTimeout(function() {
        					$('#content').fadeIn(300);
        					$('#content').addClass('animated slideInUp');
        				}, 750);
        			}

        			/*setTimeout(function() {
        				$('#loading-circle').css('opacity', '1');
        			}, 500);*/

        		}, 1000);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<commit_msg>Update upvote.js<commit_after>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	// $('#loading-circle').addClass('animated bounceIn');

            	int_loading_count = 0;
            	arr_colors = Array('rgba(52, 152, 219, 1)', 'rgba(255, 140, 0, 1)', 'rgba(231, 76, 60, 1)', 'rgba(0, 128, 0, .9)', 'rgba(0, 154, 136, .9)', 'rgba(164, 121, 228, 1)');

            	// bool_kill_next_loop = false;

        		// $('#loading-circle').addClass('animated pulse');

        		pulsing_circle_interval = setInterval(function() {

        			// $('#loading-circle').css('opacity', '.7');

        			$('#L').css('opacity', '.8');
        			$('#L').css('-webkit-transition', '.5s');
        			$('#L').css('-webkit-transform', 'scale(.5)');

        			setTimeout(function() {
        				$('#L').css('opacity', '1');
        				$('#L').css('-webkit-transform', 'scale(1)');
        			}, 500);

        			setTimeout(function() {
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '.8');
        			}, 200);

        			setTimeout(function() {
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '.8');
        			}, 300);

        			setTimeout(function() {
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '.8');
        			}, 400);

        			setTimeout(function() {
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '.8');
        			}, 500);

        			setTimeout(function() {
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '.75');
        			}, 600);

        			setTimeout(function() {
        				$('#G').css('opacity', '1');
        			}, 700);

        			// $('#loading-circle').css('background-color', arr_colors[int_loading_count]);
        			int_loading_count += 1;
        			if (int_loading_count == 4) {
        				clearInterval(pulsing_circle_interval);
        				setTimeout(function() {
        					$('#loading-circle').addClass('animated slideOutUp');
        					$('#loading-circle').fadeOut(300);
        				}, 500);
        				setTimeout(function() {
        					$('#content').fadeIn(300);
        					$('#content').addClass('animated slideInUp');
        				}, 750);
        			}

        			/*setTimeout(function() {
        				$('#loading-circle').css('opacity', '1');
        			}, 500);*/

        		}, 1000);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<|endoftext|>


<commit_before>var gulp = require("gulp");
var tsc=require('gulp-typescript');
var clean=require('gulp-clean');
var merge=require('merge2');
var concat=require('gulp-concat');
var sourcemaps=require('gulp-sourcemaps');
var using=require('gulp-using');
var webpack=require('gulp-webpack');
var ignore=require('gulp-ignore');
var watch=require('gulp-watch');
var connect=require('gulp-connect');
var minify=require('gulp-uglify');
var copy=require('gulp-copy');
var typedoc=require('gulp-typedoc');
var eol=require('gulp-eol');
var args=require('yargs').argv;
var bower_files=['jquery/dist/jquery.js','jQuery/dist/jquery.js'];
var bower_prefix='bower_components/';
var tsSourceTarget=['jThree/src/**/*.ts'];
var branch=args.branch||'unknown';
console.log('branch-name='+args.branch);
/***********************************
* Typescript compile configuration**
************************************/
var tsProj=tsc.createProject({
  target:"ES5",
  module:"commonjs",
  declarationFiles:true,
  sourceRoot:"jThree/src/",
  noExternalResolve:true,
  noEmitOnError:true,
  typescript:require('typescript')
});

gulp.task('compile',function(){
  console.log('Typescript Compile Task');
  var tsResult=gulp.src(tsSourceTarget).pipe(using({})).pipe(tsc(tsProj));
  return merge([
    tsResult.dts.pipe(gulp.dest('jThree/bin/def')),
    tsResult.js.pipe(gulp.dest('jThree/bin/js'))
  ]);
});

//Move bower files into build directory
gulp.task('move-bower',function(){
  for (var i = 0; i < bower_files.length; i++) {
    bower_files[i]=bower_prefix+bower_files[i];
  };
  return gulp.src(bower_files).pipe(using({})).pipe(gulp.dest("jThree/bin/js"));
});

gulp.task('move-static',function(){
  return gulp.src('jThree/src/static/**/*.*').pipe(gulp.dest("jThree/bin/js/static"));
});

gulp.task('make-modules',['compile','move-bower','move-static'],function(){

});

gulp.task('gen-doc',function(){
  gulp.src(tsSourceTarget).pipe(typedoc({
    module:'commonjs',
    out:'./jThree/docs',
    name:'jThree',
    target:'es5',
    includeDeclarations:true,
    json:'./jThree/docs/doc.json'
  }));
});
//Document generation executed by travis
gulp.task('gen-doc-travis',function(){
  gulp.src(tsSourceTarget).pipe(typedoc({
    module:'commonjs',
    out:'./ci/docs/'+branch,
    name:'jThree',
    target:'es5',
    includeDeclarations:true,
    json:'./ci/docs/'+branch+'/doc.json',
    mode:'module'
  }));
});

gulp.task('webpack',['make-modules'],function(){
  console.log('Webpack Task');
  return gulp.src(['jThree/bin/js/**/*.js','jThree/bin/js/**/*.json','!jThree/bin/js/jThree.js'])
    .pipe(using({}))
    .pipe(webpack({
      entry:{
        jThree:'./jThree/bin/js/jThree.js'
      },
      output:{
        filename:'j3.js'
      },
      resolve:{
        alias:{
        'j3':'Core/JThreeContext.js',
        'jquery':'jquery.js'
      },
      root:'./jThree/bin/js'
    }
    ,
    module:{
      loaders:[
        {test:/\.json$/,loader:'json'}
      ]
    }
    }))
    .pipe(gulp.dest("jThree/bin/product")).pipe(connect.reload());
});

gulp.task('clean',function(){
  gulp.src("jThree/src/*.js").pipe(clean());
  gulp.src("jThree/src/*.js.map").pipe(clean());
  gulp.src("jThree/src/**/*.js").pipe(clean());
  gulp.src("jThree/src/**/*.js").pipe(clean());
  gulp.src("jThree/bin/js/**/*.*").pipe(clean());
  gulp.src("jThree/bin/def/**/*.*").pipe(clean());
});

gulp.task('watch',['server'],function()
{
  gulp.watch('jThree/src/**/*.ts',['build']);
  gulp.watch(['jThree/*.html','jThree/*.css','jThree/**/*.goml'],['reload']);

});

gulp.task('reload',function()
{
  gulp.src('jThree/**.*').pipe(connect.reload());
});

gulp.task('build',['webpack'],function(){
  gulp.src('jThree/bin/product/j3.js').pipe(gulp.dest('jThree/'));
});

gulp.task('minify',['build'],function(){
  return gulp.src('bin/product/j3.js').
    pipe(minify())
    .pipe(gulp.dest('jThree/bin/product/min'));
});

gulp.task('fix-eol',function(){
  return gulp.src('.travis.yml').pipe(eol('\n',true)).pipe(gulp.dest('./'));
});

gulp.task('server',['build'],function(){
  connect.server({
    root:'./jThree',
    livereload:true
  });
});

gulp.task('travis',['build'],function(){
  gulp.start('gen-doc-travis');
});

gulp.task('rebuild',['clean'],function(){
  gulp.start('build');
});
<commit_msg>fix travis to generate document<commit_after>var gulp = require("gulp");
var tsc=require('gulp-typescript');
var clean=require('gulp-clean');
var merge=require('merge2');
var concat=require('gulp-concat');
var sourcemaps=require('gulp-sourcemaps');
var using=require('gulp-using');
var webpack=require('gulp-webpack');
var ignore=require('gulp-ignore');
var watch=require('gulp-watch');
var connect=require('gulp-connect');
var minify=require('gulp-uglify');
var copy=require('gulp-copy');
var typedoc=require('gulp-typedoc');
var eol=require('gulp-eol');
var args=require('yargs').argv;
var bower_files=['jquery/dist/jquery.js','jQuery/dist/jquery.js'];
var bower_prefix='bower_components/';
var tsSourceTarget=['jThree/src/**/*.ts'];
var branch=args.branch||'unknown';
console.log('branch-name='+args.branch);
/***********************************
* Typescript compile configuration**
************************************/
var tsProj=tsc.createProject({
  target:"ES5",
  module:"commonjs",
  declarationFiles:true,
  sourceRoot:"jThree/src/",
  noExternalResolve:true,
  noEmitOnError:true,
  typescript:require('typescript')
});

gulp.task('compile',function(){
  console.log('Typescript Compile Task');
  var tsResult=gulp.src(tsSourceTarget).pipe(using({})).pipe(tsc(tsProj));
  return merge([
    tsResult.dts.pipe(gulp.dest('jThree/bin/def')),
    tsResult.js.pipe(gulp.dest('jThree/bin/js'))
  ]);
});

//Move bower files into build directory
gulp.task('move-bower',function(){
  for (var i = 0; i < bower_files.length; i++) {
    bower_files[i]=bower_prefix+bower_files[i];
  };
  return gulp.src(bower_files).pipe(using({})).pipe(gulp.dest("jThree/bin/js"));
});

gulp.task('move-static',function(){
  return gulp.src('jThree/src/static/**/*.*').pipe(gulp.dest("jThree/bin/js/static"));
});

gulp.task('make-modules',['compile','move-bower','move-static'],function(){

});

gulp.task('gen-doc',function(){
  gulp.src(tsSourceTarget).pipe(typedoc({
    module:'commonjs',
    out:'./jThree/docs',
    name:'jThree',
    target:'es5',
    includeDeclarations:true,
    json:'./jThree/docs/doc.json',
    mode:'modules'
  }));
});
//Document generation executed by travis
gulp.task('gen-doc-travis',function(){
  gulp.src(tsSourceTarget).pipe(typedoc({
    module:'commonjs',
    out:'./ci/docs/'+branch,
    name:'jThree',
    target:'es5',
    includeDeclarations:true,
    json:'./ci/docs/'+branch+'/doc.json',
    mode:'modules'
  }));
});

gulp.task('webpack',['make-modules'],function(){
  console.log('Webpack Task');
  return gulp.src(['jThree/bin/js/**/*.js','jThree/bin/js/**/*.json','!jThree/bin/js/jThree.js'])
    .pipe(using({}))
    .pipe(webpack({
      entry:{
        jThree:'./jThree/bin/js/jThree.js'
      },
      output:{
        filename:'j3.js'
      },
      resolve:{
        alias:{
        'j3':'Core/JThreeContext.js',
        'jquery':'jquery.js'
      },
      root:'./jThree/bin/js'
    }
    ,
    module:{
      loaders:[
        {test:/\.json$/,loader:'json'}
      ]
    }
    }))
    .pipe(gulp.dest("jThree/bin/product")).pipe(connect.reload());
});

gulp.task('clean',function(){
  gulp.src("jThree/src/*.js").pipe(clean());
  gulp.src("jThree/src/*.js.map").pipe(clean());
  gulp.src("jThree/src/**/*.js").pipe(clean());
  gulp.src("jThree/src/**/*.js").pipe(clean());
  gulp.src("jThree/bin/js/**/*.*").pipe(clean());
  gulp.src("jThree/bin/def/**/*.*").pipe(clean());
});

gulp.task('watch',['server'],function()
{
  gulp.watch('jThree/src/**/*.ts',['build']);
  gulp.watch(['jThree/*.html','jThree/*.css','jThree/**/*.goml'],['reload']);

});

gulp.task('reload',function()
{
  gulp.src('jThree/**.*').pipe(connect.reload());
});

gulp.task('build',['webpack'],function(){
  gulp.src('jThree/bin/product/j3.js').pipe(gulp.dest('jThree/'));
});

gulp.task('minify',['build'],function(){
  return gulp.src('bin/product/j3.js').
    pipe(minify())
    .pipe(gulp.dest('jThree/bin/product/min'));
});

gulp.task('fix-eol',function(){
  return gulp.src('.travis.yml').pipe(eol('\n',true)).pipe(gulp.dest('./'));
});

gulp.task('server',['build'],function(){
  connect.server({
    root:'./jThree',
    livereload:true
  });
});

gulp.task('travis',['build'],function(){
  gulp.start('gen-doc-travis');
});

gulp.task('rebuild',['clean'],function(){
  gulp.start('build');
});
<|endoftext|>


<commit_before>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/platform.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    //gravity:
    game.physics.arcade.gravity.y = this.GRAVITY;

    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //create platforms
    this.platformsCreate();

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.game.physics.arcade.collide(this.player, this.ground);

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     //console.log(onTheGround);
     if(onTheGround && this.upInputIsActive()){
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds( 0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange );

 };//END UPDATE

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<commit_msg>asdasD<commit_after>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/pixel_1.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    this.player.anchor.set(0.5);

    this.player.yOrig = this.player.y;
    this.player.yChange = 0;

    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    this.physics.arcade.enable(this.player);
    this.player.body.gravity.y = 500;
    this.player.body.checkCollision.up = false;
    this.player.body.checkCollision.left = false;
    this.player.body.checkCollision.right = false;

    //gravity:
    //game.physics.arcade.gravity.y = this.GRAVITY;

    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //create platforms
    this.platformsCreate();

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.game.physics.arcade.collide(this.player, this.ground);
     this.game.physics.arcade.collide(this.player, this.platforms);

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     //console.log(onTheGround);
     if (onTheGround && this.upInputIsActive()) {
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds(0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange);

     /*this.cameraYMin = Math.min( this.cameraYMin, this.hero.y - this.game.height + 130 );
      this.camera.y = this.cameraYMin;*/

     this.platforms.forEachAlive(function (elem) {
         this.platformYMin = Math.min(this.platformYMin, elem.y);
         if (elem.y > this.camera.y + this.game.height) {
             elem.kill();
             this.platformsCreateOne(this.rnd.integerInRange(0, this.world.width - 50), this.platformYMin - 100, 50);
         }
     }, this);
 },

     GameState.prototype.shutdown = function () {
         this.world.setBounds( 0, 0, this.game.width, this.game.height );
         this.cursor = null;
         this.player.destroy();
         this.player = null;
         this.platforms.destroy();
         this.platforms = null;

     },

     GameState.prototype.platformsCreate = function(){
         //FUCK EVERYTHING
         this.platforms = this.add.group();
         this.platforms.enableBody = true;
         this.platforms.createMultiple( 10, 'block' );

         // create the base platform, with buffer on either side so that the hero doesn't fall through
         this.platformsCreateOne( -16, this.world.height - 16, this.world.width + 16 );
         // create a batch of platforms that start to move up the level
         for( var i = 0; i < 9; i++ ) {
             this.platformsCreateOne( this.rnd.integerInRange( 0, this.world.width - 50 ), this.world.height - 100 - 100 * i, 50 );
         }
     },

     GameState.prototype.platformsCreateOne = function( x, y) {
    // this is a helper function since writing all of this out can get verbose elsewhere
    var platform = this.platforms.getFirstDead();
    platform.reset( x, y );
    platform.scale.y = 16;
    platform.body.immovable = true;
    return platform;
     };

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<|endoftext|>


<commit_before>import { TABS_RECEIVE } from '../../actions/types';

const initialState = {
  loadedTabs: [],
};

export default function tabsReducer(state = initialState, action) {
  const { payload } = action;
  switch (action.type) {
    case TABS_RECEIVE:
      return Object.assign({}, state, { loadedTabs: payload });
    // case UPDATE_ACTIVE_TAB:
    //   return Object.assign({}, state, { activeTab: payload });
    default:
      return state;
  }
}
<commit_msg>Separate tabs by window<commit_after>import {
  WINDOW_TABS_RECEIVE,
  WINDOW_CLOSE,
  TAB_DELETE,
  TAB_CREATE,
} from '../../actions/types';

const initialState = {
  windowTabs: {},
};

export default function tabsReducer(state = initialState, action) {
  const { windowTabs } = state;
  const { payload, type } = action;
  switch (type) {
    case WINDOW_TABS_RECEIVE: {
      const { windowId, tabs } = payload;
      // Only store the tab id, which is guaranteed to be unique across
      // browser sessions
      // TODO: store sessionId as well
      const nextWindowTabs = Object.assign({}, windowTabs, {
        [String(windowId)]: tabs.map(({ id }) => ({ id })),
      });
      return Object.assign({}, state, { windowTabs: nextWindowTabs });
    }
    case WINDOW_CLOSE: {
      // Nums get coerced to string in when used as object keys
      const closedWindowId = String(payload);
      const activeWindows = Object.keys(windowTabs)
        .reduce((acc, windowId) => {
          if (windowId !== closedWindowId) {
            return Object.assign({}, acc, { [windowId]: windowTabs[windowId] });
          }
          return acc;
        }, {});
      return Object.assign({}, state, { windowTabs: activeWindows });
    }
    case TAB_DELETE: {
      const { tabId, windowId } = payload;
      const nextWindowTabs = windowTabs[windowId].filter(({ id }) => id !== tabId);
      return Object.assign({}, state, {
        windowTabs: Object.assign({}, windowTabs, { [windowId]: nextWindowTabs }),
      });
    }
    case TAB_CREATE: {
      const { tabId, windowId } = payload;
      const nextTabs = [...windowTabs[windowId], tabId];
      const nextWindows = Object.assign({}, windowTabs, { [windowId]: nextTabs });
      return Object.assign({}, state, { windowTabs: nextWindows });
    }
    // case UPDATE_ACTIVE_TAB:
    //   return Object.assign({}, state, { activeTab: payload });
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>var url = require('url')
var util = require('util')
var zlib = require('zlib')
var http = require('http')
var https = require('https')
var Netrc = require('netrc')
var write = require('write-to')
var status = require('statuses')
var rawBody = require('raw-body')
var debug = require('debug')('cogent')

var inspect = util.inspect

exports = module.exports = extend()
exports.extend = extend

function extend(defaults) {
  defaults = defaults || {}
  defaults.retries = defaults.retries || 0
  defaults.redirects = 'redirects' in defaults ? defaults.redirects : 3
  defaults.timeout = defaults.timeout || 5000
  defaults.method = defaults.method || 'GET'
  defaults.gunzip = defaults.gunzip === false ? false : true
  defaults.netrc = Netrc(defaults.netrc)

  return cogent

  function* cogent(uri, options) {
    // options type checking stuff
    if (options === true)
      options = { json: true }
    else if (typeof options === 'string')
      options = { destination: options }
    else if (!options)
      options = {}

    // setup defaults
    var redirects = options.redirects || defaults.redirects
    var timeout = options.timeout || defaults.timeout
    var netrc = options.netrc ? Netrc(options.netrc) : defaults.netrc

    // setup headers
    var headers = options.headers = options.headers || {}
    headers['accept-encoding'] = headers['accept-encoding'] || 'gzip'
    headers['user-agent'] = headers['user-agent'] || 'https://github.com/cojs/cogent'
    if (options.json) headers.accept = 'application/json'

    // keep a history of redirect urls
    var urls = []

    var o, req, res, code, stream, securrrr, retries
    // while loop to handle redirects
    while (true) {
      // create the request options object
      urls.push(o = url.parse(uri))
      securrrr = o.protocol === 'https:'
      o.headers = options.headers
      o.method = options.method || defaults.method

      // auth, either by .auth or by .netrc
      if (options.auth || defaults.auth) {
        o.auth = options.auth || defaults.auth
      } else {
        var auth = netrc[o.hostname]
        if (auth) o.auth =
            (auth.login || auth.user || auth.username)
          + ':'
          + (auth.pass || auth.password)
      }

      // setup agent or proxy agent
      if ('agent' in options) {
        o.agent = options.agent
      } else if (defaults.agent != null) {
        o.agent = defaults.agent
      }

      // retries is on a per-URL-request basis
      retries = options.retries || defaults.retries

      debug('options: %s', inspect(o))

      res = yield request
      code = res.statusCode

      // redirect
      if (redirects-- && status.redirect[code]) {
        debug('redirecting from %s to %s', uri, res.headers.location)
        uri = url.resolve(uri, res.headers.location)
        res.resume() // dump this stream
        continue
      }

      // return early on HEAD requests
      if (o.method.toUpperCase() === 'HEAD') {
        res.req = req
        res.resume()
        return res
      }

      // unzip
      var gunzip = typeof options.gunzip === 'boolean'
        ? options.gunzip
        : defaults.gunzip
      if (!gunzip && (options.buffer || options.string || options.json))
        throw new Error('must gunzip if buffering the response')
      if (res.headers['content-encoding'] === 'gzip' && gunzip) {
        stream = res.pipe(zlib.createGunzip())
        stream.res = res
        // pass useful response stuff
        stream.statusCode = code
        stream.headers = res.headers
        // forward errors
        res.on('error', stream.emit.bind(stream, 'error'))
        // forward close
        // creates the following error:
        // Assertion failed: (!write_in_progress_ && "write in progress"), function Close, file ../src/node_zlib.cc, line 99.
        // make: *** [test] Abort trap: 6
        // res.on('close', stream.close.bind(stream))
        // forward destroy
        // note: if zlib adds a .destroy method, we have to change this
        stream.destroy = res.destroy.bind(res)
        res = stream
      } else {
        res.res = res
      }

      res.req = req
      res.urls = urls

      // save the file
      if (code === 200 && options.destination) {
        yield write(res, options.destination)
        res.destination = options.destination
        return res
      }

      // buffer the response
      if (options.buffer)
        res.buffer = yield rawBody(res)
      // buffer the response as a string or object
      if (options.string || options.json)
        res.text = res.buffer
          ? res.buffer.toString('utf8')
          : yield rawBody(res, { encoding: options.string || true })
      // buffer the response as JSON
      if (options.json) try {
        res.body = JSON.parse(res.text)
      } catch (err) {
        debug('"%s" is not valid JSON', uri)
      }

      return res
    }

    // to do: move this entire section to a separate repo #9
    function request(done) {
      var called = false

      // timeout
      // note: timeout is only for the response,
      // not the entire request
      var id = setTimeout(function () {
        debug('timeout exceeded for %s %s', o.method, o.href)
        var err = new Error('timeout of ' + timeout + 'ms exceeded for "' + o.href + '"')
        err.url = o
        next(err)
      }, timeout)

      req = (securrrr ? https : http).request(o)
      req.once('response', next.bind(null, null))
      req.once('error', next)
      req.end()

      function next(err, res) {
        if (called) {
          // dump the stream in case there are any
          // to avoid any possible leaks
          if (res) res.resume()
          return
        }

        called = true
        clearTimeout(id)

        // kill the request, specifically for timeouts
        // to do: tests for this #7
        if (err) req.abort()

        if (retries && (err
          || (res && status.retry[res.statusCode])
        )) {
          debug('retrying %s %s', o.method, o.href)
          retries--
          request(done)
        } else if (err) {
          debug('received error "%s" with "%s"', err.message, o.href)
          done(err)
        } else {
          done(null, res)
        }
      }
    }
  }
}
<commit_msg>convert request() to a promise<commit_after>var url = require('url')
var util = require('util')
var zlib = require('zlib')
var http = require('http')
var https = require('https')
var Netrc = require('netrc')
var write = require('write-to')
var status = require('statuses')
var rawBody = require('raw-body')
var debug = require('debug')('cogent')

var inspect = util.inspect

exports = module.exports = extend()
exports.extend = extend

function extend(defaults) {
  defaults = defaults || {}
  defaults.retries = defaults.retries || 0
  defaults.redirects = 'redirects' in defaults ? defaults.redirects : 3
  defaults.timeout = defaults.timeout || 5000
  defaults.method = defaults.method || 'GET'
  defaults.gunzip = defaults.gunzip === false ? false : true
  defaults.netrc = Netrc(defaults.netrc)

  return cogent

  function* cogent(uri, options) {
    // options type checking stuff
    if (options === true)
      options = { json: true }
    else if (typeof options === 'string')
      options = { destination: options }
    else if (!options)
      options = {}

    // setup defaults
    var redirects = options.redirects || defaults.redirects
    var timeout = options.timeout || defaults.timeout
    var netrc = options.netrc ? Netrc(options.netrc) : defaults.netrc

    // setup headers
    var headers = options.headers = options.headers || {}
    headers['accept-encoding'] = headers['accept-encoding'] || 'gzip'
    headers['user-agent'] = headers['user-agent'] || 'https://github.com/cojs/cogent'
    if (options.json) headers.accept = 'application/json'

    // keep a history of redirect urls
    var urls = []

    var o, req, res, code, stream, securrrr, retries
    // while loop to handle redirects
    while (true) {
      // create the request options object
      urls.push(o = url.parse(uri))
      securrrr = o.protocol === 'https:'
      o.headers = options.headers
      o.method = options.method || defaults.method

      // auth, either by .auth or by .netrc
      if (options.auth || defaults.auth) {
        o.auth = options.auth || defaults.auth
      } else {
        var auth = netrc[o.hostname]
        if (auth) o.auth =
            (auth.login || auth.user || auth.username)
          + ':'
          + (auth.pass || auth.password)
      }

      // setup agent or proxy agent
      if ('agent' in options) {
        o.agent = options.agent
      } else if (defaults.agent != null) {
        o.agent = defaults.agent
      }

      // retries is on a per-URL-request basis
      retries = options.retries || defaults.retries

      debug('options: %s', inspect(o))

      res = yield request()
      code = res.statusCode

      // redirect
      if (redirects-- && status.redirect[code]) {
        debug('redirecting from %s to %s', uri, res.headers.location)
        uri = url.resolve(uri, res.headers.location)
        res.resume() // dump this stream
        continue
      }

      // return early on HEAD requests
      if (o.method.toUpperCase() === 'HEAD') {
        res.req = req
        res.resume()
        return res
      }

      // unzip
      var gunzip = typeof options.gunzip === 'boolean'
        ? options.gunzip
        : defaults.gunzip
      if (!gunzip && (options.buffer || options.string || options.json))
        throw new Error('must gunzip if buffering the response')
      if (res.headers['content-encoding'] === 'gzip' && gunzip) {
        stream = res.pipe(zlib.createGunzip())
        stream.res = res
        // pass useful response stuff
        stream.statusCode = code
        stream.headers = res.headers
        // forward errors
        res.on('error', stream.emit.bind(stream, 'error'))
        // forward close
        // creates the following error:
        // Assertion failed: (!write_in_progress_ && "write in progress"), function Close, file ../src/node_zlib.cc, line 99.
        // make: *** [test] Abort trap: 6
        // res.on('close', stream.close.bind(stream))
        // forward destroy
        // note: if zlib adds a .destroy method, we have to change this
        stream.destroy = res.destroy.bind(res)
        res = stream
      } else {
        res.res = res
      }

      res.req = req
      res.urls = urls

      // save the file
      if (code === 200 && options.destination) {
        yield write(res, options.destination)
        res.destination = options.destination
        return res
      }

      // buffer the response
      if (options.buffer)
        res.buffer = yield rawBody(res)
      // buffer the response as a string or object
      if (options.string || options.json)
        res.text = res.buffer
          ? res.buffer.toString('utf8')
          : yield rawBody(res, { encoding: options.string || true })
      // buffer the response as JSON
      if (options.json) try {
        res.body = JSON.parse(res.text)
      } catch (err) {
        debug('"%s" is not valid JSON', uri)
      }

      return res
    }

    function request() {
      return new Promise(function (resolve, reject) {
        var called = false

        // timeout
        // note: timeout is only for the response,
        // not the entire request
        var id = setTimeout(function () {
          debug('timeout exceeded for %s %s', o.method, o.href)
          var err = new Error('timeout of ' + timeout + 'ms exceeded for "' + o.href + '"')
          err.url = o
          next(err)
        }, timeout)

        req = (securrrr ? https : http).request(o)
        req.once('response', next)
        req.once('error', next)
        req.end()

        function next(err, res) {
          if (called) {
            // dump the stream in case there are any
            // to avoid any possible leaks
            if (res) res.resume()
            return
          }

          called = true
          clearTimeout(id)

          if (!(err instanceof Error)) {
            res = err
            err = null
          }

          // kill the request, specifically for timeouts
          // to do: tests for this #7
          if (err) req.abort()

          if (retries && (err
            || (res && status.retry[res.statusCode])
          )) {
            debug('retrying %s %s', o.method, o.href)
            retries--
            resolve(request())
          } else if (err) {
            debug('received error "%s" with "%s"', err.message, o.href)
            reject(err)
          } else {
            resolve(res)
          }
        }
      })
    }
  }
}
<|endoftext|>


<commit_before>// A tiny library of math functions useful in 2D games.

// WORK IN PROGRESS, NEEDS TEST COVERAGE

function toRadians(degrees){
  return degrees * (Math.PI / 180)
};

function toDegrees(radians){
  return radians / (Math.PI / 180)
};

function toI(number){
	return Math.round(number)
}

function updateRandom(collection, propertyNameAsString)
	console.log("Updating random factors for collection", collection, "on property", propertyNameAsString)
	for (var i = 0; i < collection.length; i++) {
    if (collection[i] != undefined) {
      collection[i][propertyNameAsString] = toI( (Math.random() * 10) + 1 );
   };  <commit_msg>Updated random factor generator. WIP, needs tests<commit_after>// A tiny library of math functions useful in 2D games.

// WORK IN PROGRESS, NEEDS TEST COVERAGE

function toRadians(degrees){
  return degrees * (Math.PI / 180)
};

function toDegrees(radians){
  return radians / (Math.PI / 180)
};

function toI(number){
	return Math.round(number)
};

function updateRandom(collection, propertyNameAsString){
	// console.log("Updating random factors for collection", collection, "on property", propertyNameAsString)
	for (var i = 0; i < collection.length; i++) {
    if (collection[i] != undefined) {
      collection[i][propertyNameAsString] = toI( (Math.random() * 10) + 1 );
    };
  };
};   <|endoftext|>