<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var Database = require('./db');
var db = new Database();

var app = express();
app.use(bodyParser.json());

app.get('/api/', function (req, res) {
    var payload = {};
    db.find(payload, function(results){
        return res.json(results);
    });
});

app.get('/api/:user_id', function (req, res) {
    var payload = {user: req.params.user_id};
    db.find(payload, function(results){
        return res.json(results);
    });
});

function updateData(req, res) {
    var payload = {user: req.params.user_id};
    var data = {user: req.params.user_id, led: true};
    if (req.body.led === true) {
        data.led = true;
    }

    db.find(payload, function (results) {
        if (results.length > 0) {
            db.update(data);
            res.send({db: "update"});
        } else {
            db.insert(data);
            res.send({db: "insert"});
        }
    });
}

app.post('/api/:user_id', function (req, res) {
    updateData(req, res);
});

app.put('/api/:user_id', function (req, res) {
    updateData(req, res);
});

app.delete('/api/:user_id', function (req, res) {
    res.send({});
});

app.listen(3000);<commit_msg>fix default value issue<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var Database = require('./db');
var db = new Database();

var app = express();
app.use(bodyParser.json());

app.get('/api/', function (req, res) {
    var payload = {};
    db.find(payload, function(results){
        return res.json(results);
    });
});

app.get('/api/:user_id', function (req, res) {
    var payload = {user: req.params.user_id};
    db.find(payload, function(results){
        return res.json(results);
    });
});

function updateData(req, res) {
    var payload = {user: req.params.user_id};
    var data = {user: req.params.user_id, led: false};
    if (req.body.led === true) {
        data.led = true;
    }

    db.find(payload, function (results) {
        if (results.length > 0) {
            db.update(data);
            res.send({db: "update"});
        } else {
            db.insert(data);
            res.send({db: "insert"});
        }
    });
}

app.post('/api/:user_id', function (req, res) {
    updateData(req, res);
});

app.put('/api/:user_id', function (req, res) {
    updateData(req, res);
});

app.delete('/api/:user_id', function (req, res) {
    res.send({});
});

app.listen(3000);<|endoftext|>


<commit_before>/*
 *  ShotgunPoker.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//namespace tiger
shotgun = {
    core: null,
};

tm.define("shotgun.CanvasApp", {
    superClass: tm.app.CanvasApp,

    //ＢＧＭ＆効果音
    bgm: null,
    bgmIsPlay: false,
    volumeBGM: 3,
    volumeSE: 3,

    //スコア保存
    lastScore: 0,
    highScore: 0,

    //各種設定
    useJoker: USE_JOKER,
    returnJoker: RETURN_JOKER,
    returnJokerTuen: RETURN_JOKER_TURN,
    handList: null,

    //バックグラウンドカラー
    bgColor: 'rgba(50, 110, 50, 1)',

    //言語設定
    language: JAPANESE,

    init: function(id) {
        this.superInit(id);
        this.resize(SC_W, SC_H).fitWindow();
        this.fps = fps;
        this.background = "rgba(0, 0, 0, 0)";
        this.keyboard = tm.input.Keyboard(window);

        shotgun.core = this;

        var loadingScene = tm.ui["LoadingScene"]({
            assets: assets,
            width: SC_W,
            height: SC_H,
            bgColor: "black",
            nextScene: function() {
                this._onLoadAssets();
                return shotgun.WaitScene();
//                return shotgun.TitleScene();
            }.bind(this),
        });
        this.replaceScene(loadingScene);

        //役名一覧
        this.handList = [];
        this.handList[0]  = {name: "MISS", point: MISS};
        this.handList[1]  = {name: "NO HAND", point: NOHAND};
        this.handList[2]  = {name: "ONE PAIR", point: ONEPAIR};
        this.handList[3]  = {name: "TWO PAIR", point: TWOPAIR};
        this.handList[4]  = {name: "FLASH", point: FLASH};
        this.handList[5]  = {name: "THREE CARD", point: THREECARD};
        this.handList[6]  = {name: "FULL HOUSE", point: FULLHOUSE};
        this.handList[7]  = {name: "STRAIGHT", point: STRAIGHT};
        this.handList[8]  = {name: "FOUR CARD", point: FOURCARD};
        this.handList[9]  = {name: "FIVE CARD", point: FIVECARD};
        this.handList[10] = {name: "STRAIGHT FLASH", point: STRAIGHTFLASH};
        this.handList[11] = {name: "R.STRAIGHT FLASH", point: ROYALSTRAIGHTFLASH};

        //設定情報の読み込み
        this.loadConfig();
    },

    _onLoadAssets: function() {
    },

    exitApp: function() {
        this.stop();
    },

    //設定データの保存
    saveConfig: function() {
        var saveObj = {
            "language": this.language,
            "lastScore": this.lastScore,
            "highScore": this.highScore,
            "volumeBGM": this.volumeBGM,
            "volumeSE": this.volumeSE,
        };
        localStorage.setItem("config", JSON.stringify(saveObj));
        return this;
    },

    //設定データの読み込み
    loadConfig: function() {
        var cfg = localStorage.getItem("config");
        if (cfg) {
            var c = JSON.parse(cfg);
            this.language = c.language;
            this.lastScore = c.lastScore;
            this.highScore = c.highScore;
            this.volumeBGM = c.volumeBGM;
            this.volumeSE = c.volumeSE;
        }
        return this;
    },

    playBGM: function(asset) {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
        this.bgm = tm.asset.AssetManager.get(asset).clone();
        if (this.bgm) {
            this.bgm.loop = true;
            this.bgm.volume = this.volumeBGM*0.34;
            this.bgm.play();
            this.bgmIsPlay = true;
        }
        return this;
    },

    stopBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
            this.bgm = null;
        }
        return this;
    },

    pauseBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.pause();
                this.bgmIsPlay = false;
            }
        }
        return this;
    },

    resumeBGM: function() {
        if (this.bgm) {
            if (!this.bgmIsPlay) {
                this.bgm.volume = this.volumeBGM*0.34;
                this.bgm.resume();
                this.bgmIsPlay = true;
            }
        }
        return this;
    },

    setVolumeBGM: function(v) {
        this.pauseBGM();
        this.volumeBGM = v;
        this.resumeBGM();
        return this;
    },

    playSE: function(asset) {
        var se = tm.asset.AssetManager.get(asset).clone();
        if (se) {
            se.loop = false;
            se.volume = this.volumeSE*0.34;
            se.play();
        }
        return this;
    },

    setVolumeSE: function(v) {
        this.volumSE = v;
        return this;
    },
});

<commit_msg>英語役名表示変更<commit_after>/*
 *  ShotgunPoker.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//namespace tiger
shotgun = {
    core: null,
};

tm.define("shotgun.CanvasApp", {
    superClass: tm.app.CanvasApp,

    //ＢＧＭ＆効果音
    bgm: null,
    bgmIsPlay: false,
    volumeBGM: 3,
    volumeSE: 3,

    //スコア保存
    lastScore: 0,
    highScore: 0,

    //各種設定
    useJoker: USE_JOKER,
    returnJoker: RETURN_JOKER,
    returnJokerTuen: RETURN_JOKER_TURN,
    handList: null,

    //バックグラウンドカラー
    bgColor: 'rgba(50, 110, 50, 1)',

    //言語設定
    language: JAPANESE,

    init: function(id) {
        this.superInit(id);
        this.resize(SC_W, SC_H).fitWindow();
        this.fps = fps;
        this.background = "rgba(0, 0, 0, 0)";
        this.keyboard = tm.input.Keyboard(window);

        shotgun.core = this;

        var loadingScene = tm.ui["LoadingScene"]({
            assets: assets,
            width: SC_W,
            height: SC_H,
            bgColor: "black",
            nextScene: function() {
                this._onLoadAssets();
                return shotgun.WaitScene();
//                return shotgun.TitleScene();
            }.bind(this),
        });
        this.replaceScene(loadingScene);

        //役名一覧
        this.handList = [];
        this.handList[0]  = {name: "MISS", point: MISS};
        this.handList[1]  = {name: "NO HAND", point: NOHAND};
        this.handList[2]  = {name: "ONE PAIR", point: ONEPAIR};
        this.handList[3]  = {name: "TWO PAIR", point: TWOPAIR};
        this.handList[4]  = {name: "FLASH", point: FLASH};
        this.handList[5]  = {name: "THREE CARD", point: THREECARD};
        this.handList[6]  = {name: "FULL HOUSE", point: FULLHOUSE};
        this.handList[7]  = {name: "STRAIGHT", point: STRAIGHT};
        this.handList[8]  = {name: "FOUR CARD", point: FOURCARD};
        this.handList[9]  = {name: "FIVE CARD", point: FIVECARD};
        this.handList[10] = {name: "STRAIGHT FLASH", point: STRAIGHTFLASH};
        this.handList[11] = {name: "R.STRAIGHT FLASH", point: ROYALSTRAIGHTFLASH};
        if (appMain.language == ENGLISH) {
            this.handList[5]  = {name: "THREE OF A KIND", point: THREECARD};
            this.handList[8]  = {name: "FOUR OF A KIND", point: FOURCARD};
            this.handList[9]  = {name: "FIVE OF A KIND", point: FIVECARD};
        }

        //設定情報の読み込み
        this.loadConfig();
    },

    _onLoadAssets: function() {
    },

    exitApp: function() {
        this.stop();
    },

    //設定データの保存
    saveConfig: function() {
        var saveObj = {
            "language": this.language,
            "lastScore": this.lastScore,
            "highScore": this.highScore,
            "volumeBGM": this.volumeBGM,
            "volumeSE": this.volumeSE,
        };
        localStorage.setItem("config", JSON.stringify(saveObj));
        return this;
    },

    //設定データの読み込み
    loadConfig: function() {
        var cfg = localStorage.getItem("config");
        if (cfg) {
            var c = JSON.parse(cfg);
            this.language = c.language;
            this.lastScore = c.lastScore;
            this.highScore = c.highScore;
            this.volumeBGM = c.volumeBGM;
            this.volumeSE = c.volumeSE;
        }
        return this;
    },

    playBGM: function(asset) {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
        this.bgm = tm.asset.AssetManager.get(asset).clone();
        if (this.bgm) {
            this.bgm.loop = true;
            this.bgm.volume = this.volumeBGM*0.34;
            this.bgm.play();
            this.bgmIsPlay = true;
        }
        return this;
    },

    stopBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
            this.bgm = null;
        }
        return this;
    },

    pauseBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.pause();
                this.bgmIsPlay = false;
            }
        }
        return this;
    },

    resumeBGM: function() {
        if (this.bgm) {
            if (!this.bgmIsPlay) {
                this.bgm.volume = this.volumeBGM*0.34;
                this.bgm.resume();
                this.bgmIsPlay = true;
            }
        }
        return this;
    },

    setVolumeBGM: function(v) {
        this.pauseBGM();
        this.volumeBGM = v;
        this.resumeBGM();
        return this;
    },

    playSE: function(asset) {
        var se = tm.asset.AssetManager.get(asset).clone();
        if (se) {
            se.loop = false;
            se.volume = this.volumeSE*0.34;
            se.play();
        }
        return this;
    },

    setVolumeSE: function(v) {
        this.volumSE = v;
        return this;
    },
});

<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+relay
 * @flow strict-local
 * @format
 */

'use strict';

const MatchContainer = require('./MatchContainer');
const ProfilerContext = require('./ProfilerContext');
const RelayEnvironmentProvider = require('./RelayEnvironmentProvider');

const fetchQuery = require('./fetchQuery');
const useBlockingPaginationFragment = require('./useBlockingPaginationFragment');
const useFragment = require('./useFragment');
const useLazyLoadQuery = require('./useLazyLoadQuery');
const useLegacyPaginationFragment = require('./useLegacyPaginationFragment');
const useRefetchableFragment = require('./useRefetchableFragment');
const useRelayEnvironment = require('./useRelayEnvironment');

export type {MatchContainerProps, MatchPointer} from './MatchContainer';
export type {ProfilerContextType} from './ProfilerContext';
export type {FetchPolicy, RenderPolicy} from './QueryResource';
export type {Direction, LoadMoreFn} from './useLoadMoreFunction';
export type {
  RefetchFn,
  Options as RefetchOptions,
} from './useRefetchableFragmentNode';

module.exports = {
  MatchContainer: MatchContainer,
  ProfilerContext: ProfilerContext,
  RelayEnvironmentProvider: RelayEnvironmentProvider,

  fetchQuery: fetchQuery,

  useLazyLoadQuery: useLazyLoadQuery,
  useFragment: useFragment,
  useBlockingPaginationFragment: useBlockingPaginationFragment,
  usePaginationFragment: useLegacyPaginationFragment,
  useRefetchableFragment: useRefetchableFragment,
  useRelayEnvironment: useRelayEnvironment,
  useLegacyPaginationFragment: useLegacyPaginationFragment,
};
<commit_msg>Export RefetchFnDynamic Flow type<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+relay
 * @flow strict-local
 * @format
 */

'use strict';

const MatchContainer = require('./MatchContainer');
const ProfilerContext = require('./ProfilerContext');
const RelayEnvironmentProvider = require('./RelayEnvironmentProvider');

const fetchQuery = require('./fetchQuery');
const useBlockingPaginationFragment = require('./useBlockingPaginationFragment');
const useFragment = require('./useFragment');
const useLazyLoadQuery = require('./useLazyLoadQuery');
const useLegacyPaginationFragment = require('./useLegacyPaginationFragment');
const useRefetchableFragment = require('./useRefetchableFragment');
const useRelayEnvironment = require('./useRelayEnvironment');

export type {MatchContainerProps, MatchPointer} from './MatchContainer';
export type {ProfilerContextType} from './ProfilerContext';
export type {FetchPolicy, RenderPolicy} from './QueryResource';
export type {Direction, LoadMoreFn} from './useLoadMoreFunction';
export type {
  RefetchFn,
  RefetchFnDynamic,
  Options as RefetchOptions,
} from './useRefetchableFragmentNode';

module.exports = {
  MatchContainer: MatchContainer,
  ProfilerContext: ProfilerContext,
  RelayEnvironmentProvider: RelayEnvironmentProvider,

  fetchQuery: fetchQuery,

  useLazyLoadQuery: useLazyLoadQuery,
  useFragment: useFragment,
  useBlockingPaginationFragment: useBlockingPaginationFragment,
  usePaginationFragment: useLegacyPaginationFragment,
  useRefetchableFragment: useRefetchableFragment,
  useRelayEnvironment: useRelayEnvironment,
  useLegacyPaginationFragment: useLegacyPaginationFragment,
};
<|endoftext|>


<commit_before><commit_msg>tin roof<commit_after>var cheerio = require('cheerio')
  , request = require('request')
  , url = 'https://www.reverbnation.com/venue/tinroofwashley'

module.exports = function() {
  request(url, function(err, response, body) {

  })
}<|endoftext|>


<commit_before>$(function(){
	'use strict';
	$('audio[controls]').before(function(){
		var song = this;
			song.controls=false;
		var player_box = document.createElement('div');
			$(player_box).addClass('well span4');
		var data_sec = document.createElement('section');
			$(data_sec).addClass('collapse');
		var data_toggle = document.createElement('a');
			$(data_toggle).text('Details');
			$(data_toggle).addClass('btn btn-mini');
			$(data_toggle).click(function (){$(data_sec).collapse('toggle');});
		var data_table = document.createElement('table');
			$(data_table).addClass('table table-condensed');
		var player = document.createElement('section');
			$(player).addClass('btn-group row-fluid clearfix playa');
		var load_error = function(){
			console.log('error');
			$(player_box).find('.btn').addClass('disabled');
			$(player_box).find('input[type="range"]').hide();
			$(player_box).find('.icon-spin').text('Error');
			$(player_box).find('.icon-spin').parent().attr('title', 'There was an error loading the audio.');
			$(player_box).find('.icon-spin').parent().tooltip('fixTitle');
			$(player_box).find('.icon-spin').removeClass('icon-spinner icon-spin');
		};
		var addPlay = function() {
			var play = document.createElement('button');
				$(play).addClass('btn disabled span2');
			play.setPlayState = function(toggle){
					$(play).removeClass('disabled');
				if (toggle === 'play') {
					$(play).html('');
					$(play).click(function () {
						song.play();
					});
				}
				if (toggle === 'pause') {
					$(play).html('');
					$(play).click(function () {
						song.pause();
					});
				}
			};
			$(song).on('play', function(){play.setPlayState('pause');});
			$(song).on('canplay', function(){play.setPlayState('play');});
			$(song).on('pause', function(){play.setPlayState('play');});
			var timeout = 0;
			var loadCheck = setInterval(function() {
				if(isNaN(song.duration) === false){
					play.setPlayState('play');
					clearInterval(loadCheck);
					return true;
				}
				if(song.networkState === 3 || timeout === 75){
					load_error();
					clearInterval(loadCheck);
					return false;
				}
				timeout++;
			}, 50);

			$(player).append(play);
		};
		var addSeek = function() {
			var seek = document.createElement('input');
				$(seek).attr({
					'type': 'range',
					'min': 0,
					'value': 0,
					'class': 'seek'
				});
			seek.progress = function () {
				var bg = 'rgba(223, 240, 216, 1) 0%';
				bg += ', rgba(223, 240, 216, 1) ' + ((song.currentTime/song.duration) * 100) + '%';
				bg += ', rgba(223, 240, 216, 0) ' + ((song.currentTime/song.duration) * 100) + '%';
				for (var i=0; i<song.buffered.length; i++){
					if (song.buffered.end(i) > song.currentTime && isNaN(song.buffered.end(i)) === false && isNaN(song.buffered.start(i)) === false){
						var bufferedstart;
						var bufferedend;
						if (song.buffered.end(i) < song.duration) {
							bufferedend = ((song.buffered.end(i)/song.duration) * 100);
						}
						else {
							bufferedend = 100;
						}
						if (song.buffered.start(i) > song.currentTime){
							bufferedstart = ((song.buffered.start(i)/song.duration) * 100);
						}
						else {
							bufferedstart = ((song.currentTime/song.duration) * 100);
						}
						bg += ', rgba(217, 237, 247, 0) ' + bufferedstart + '%';
						bg += ', rgba(217, 237, 247, 1) ' + bufferedstart + '%';
						bg += ', rgba(217, 237, 247, 1) ' + bufferedend + '%';
						bg += ', rgba(217, 237, 247, 0) ' + bufferedend + '%';
					}
				}
				$(seek).css('background', '-webkit-linear-gradient(left, ' + bg + ')');
				//These may be re-enabled when/if other browsers support the background like webkit
				//$(seek).css('background','-o-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','-moz-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','-ms-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','linear-gradient(to right,  ' + bg + ')');
				$(seek).css('background-color', '#ddd');
			};
			seek.set = function () {
				$(seek).val(song.currentTime);
				seek.progress();
			};
			seek.slide = function () {
				song.currentTime = $(seek).val();
				seek.progress();
			};
			seek.init = function () {
				$(seek).attr({
					'max': song.duration,
					'step': song.duration / 100
				});
				$(seek).val(0);
				seek.progress();
			};
			seek.reset = function () {
				$(seek).val(0);
				song.currentTime = $(seek).val();
				if(!song.loop){song.pause();}
				else {song.play();}
			};
			var seek_wrapper = document.createElement('div');
				$(seek_wrapper).addClass('btn disabled span3');

			$(seek_wrapper).append(seek);
			$(seek).on('change', seek.slide);
			$(song).on('timeupdate', seek.set);
			$(song).on('loadedmetadata', seek.init);
			$(song).on('loadeddata', seek.init);
			$(song).on('progress', seek.init);
			$(song).on('canplay', seek.init);
			$(song).on('canplaythrough', seek.init);
			$(song).on('ended', seek.reset);
			if(song.readyState > 0){
				seek.init();
			}
			$(player).append(seek_wrapper);
		};
		var addTime = function() {
			var time = document.createElement('a');
				$(time).addClass('btn span3');
				$(time).tooltip({'container': 'body', 'placement': 'right', 'html': true});
			time.twodigit = function (myNum) {
				return ("0" + myNum).slice(-2);
			};
			time.timesplit = function (a) {
				if (isNaN(a)){return '';}
				var hours = Math.floor(a / 3600);
				var minutes = Math.floor(a / 60) - (hours * 60);
				var seconds = Math.floor(a) - (hours * 3600) - (minutes * 60);
				var timeStr = time.twodigit(minutes) + ':' + time.twodigit(seconds);
				if (hours > 0) {
					timeStr = hours + ':' + timeStr;
				}
				return timeStr;
			};
			time.showtime = function () {
				$(time).html(time.timesplit(song.duration));
				$(time).attr({'title': 'Click to Reset
Position: ' + (time.timesplit(song.currentTime))});
				if (!song.paused){
					$(time).html(time.timesplit(song.currentTime));
					$(time).attr({'title': 'Click to Reset
Length: ' + (time.timesplit(song.duration))});
				}
				$(time).tooltip('fixTitle');
			};
			$(time).click(function () {
				song.pause();
				song.currentTime = 0;
				time.showtime();
				$(time).tooltip('fixTitle');
				$(time).tooltip('show');
			});
			$(time).tooltip('show');
			$(song).on('loadedmetadata', time.showtime);
			$(song).on('loadeddata', time.showtime);
			$(song).on('progress', time.showtime);
			$(song).on('canplay', time.showtime);
			$(song).on('canplaythrough', time.showtime);
			$(song).on('timeupdate', time.showtime);
			if(song.readyState > 0){
				time.showtime();
			}
			else {
				$(time).html('');
			}
			$(player).append(time);
		};
		var addMute = function() {
			var mute = document.createElement('button');
				$(mute).addClass('btn span2');
			mute.checkVolume = function () {
				if (song.volume > 0.5 && !song.muted) {
					$(mute).html('');
				} else if (song.volume < 0.5 && song.volume > 0 && !song.muted) {
					$(mute).html('');
				} else {
					$(mute).html('');
				}
			};
			mute.click(function () {
				if (song.muted) {
					song.muted = false;
					song.volume = song.oldvolume;
				} else {
					song.muted = true;
					song.oldvolume = song.volume;
					song.volume = 0;
				}
				mute.checkVolume();
			});
			mute.checkVolume();
			$(song).on('volumechange', mute.checkVolume);
			$(player).append(mute);
		};
		var addVolume = function() {
			var volume = document.createElement('input');
				$(volume).attr({
					'type': 'range',
					'min': 0,
					'max': 1,
					'step': 1 / 100,
					'value': 1
				});
			volume.slide = function () {
				song.muted = false;
				song.volume = $(volume).val();
			};
			volume.set = function () {
				$(volume).val(song.volume);
			};
			var vol_wrapper = document.createElement('div');
				$(vol_wrapper).addClass('btn disabled span3');
			$(vol_wrapper).append(volume);
			$(volume).on("change", volume.slide);
			$(song).on('volumechange', volume.set);
			$(player).append(vol_wrapper);
		};
		var addAlbumArt = function() {
			var albumArt = document.createElement('img');
				$(albumArt).addClass('thumbnail');
				$(albumArt).attr('src', $(song).data('infoAlbumArt'));
			$(data_sec).append(albumArt);
		};
		var addInfo = function(title, dataId) {
			var row = document.createElement('tr');
			var head = document.createElement('th');
			var data = document.createElement('td');
			$(head).html(title);
			$(data).html($(song).data(dataId));
			$(row).append(head);
			$(row).append(data);
			$(data_table).append(row);
		};
		var addData = function() {
			if (typeof($(song).data('infoAlbumArt')) !== 'undefined'){ addAlbumArt();}
			if (typeof($(song).data('infoArtist')) !== 'undefined'){ addInfo('Artist', 'infoArtist');}
			if (typeof($(song).data('infoTitle')) !== 'undefined'){ addInfo('Title', 'infoTitle');}
			if (typeof($(song).data('infoAlbumTitle')) !== 'undefined'){ addInfo('Album', 'infoAlbumTitle');}
			if (typeof($(song).data('infoLabel')) !== 'undefined'){ addInfo('Label', 'infoLabel');}
			if (typeof($(song).data('infoYear')) !== 'undefined'){ addInfo('Year', 'infoYear');}
			if ($(data_table).html() !== ""){
				$(data_sec).append(data_table);
				$(player_box).append(data_toggle);
				$(player_box).append(data_sec);
			}
		};
		var addPlayer = function() {
			if ($(song).data('play') !== 'off'){ addPlay();}
			if ($(song).data('seek') !== 'off'){ addSeek();}
			if ($(song).data('time') !== 'off'){ addTime();}
			if ($(song).data('mute') !== 'off'){ addMute();}
			if ($(song).data('volume') !== 'off'){ addVolume();}
			$(player_box).append(player);
		};
		var addAttribution = function() {
			var infoAtt = $('');
			if (typeof($(song).data('infoAttLink')) !== 'undefined'){
				var infoAttLink = $('');
				infoAttLink.attr('href', $(song).data('infoAttLink'));
				infoAttLink.html($(song).data('infoAtt'));
				infoAtt.append(infoAttLink);
			}
			else {
				infoAtt.html($(song).data('infoAtt'));
			}
			$(player_box).append(infoAtt);
		};
		var fillPlayerBox = function() {
			addData();
			addPlayer();
			if (typeof($(song).data('infoAtt')) !== 'undefined'){ addAttribution();}
		};
		fillPlayerBox();
		$(song).on('error', function(){
			load_error();
		});
		return player_box;
	});
});<commit_msg>Fixed jittery seek bar.<commit_after>$(function(){
	'use strict';
	$('audio[controls]').before(function(){
		var song = this;
			song.controls=false;
		var player_box = document.createElement('div');
			$(player_box).addClass('well span4');
		var data_sec = document.createElement('section');
			$(data_sec).addClass('collapse');
		var data_toggle = document.createElement('a');
			$(data_toggle).text('Details');
			$(data_toggle).addClass('btn btn-mini');
			$(data_toggle).click(function (){$(data_sec).collapse('toggle');});
		var data_table = document.createElement('table');
			$(data_table).addClass('table table-condensed');
		var player = document.createElement('section');
			$(player).addClass('btn-group row-fluid clearfix playa');
		var load_error = function(){
			console.log('error');
			$(player_box).find('.btn').addClass('disabled');
			$(player_box).find('input[type="range"]').hide();
			$(player_box).find('.icon-spin').text('Error');
			$(player_box).find('.icon-spin').parent().attr('title', 'There was an error loading the audio.');
			$(player_box).find('.icon-spin').parent().tooltip('fixTitle');
			$(player_box).find('.icon-spin').removeClass('icon-spinner icon-spin');
		};
		var addPlay = function() {
			var play = document.createElement('button');
				$(play).addClass('btn disabled span2');
			play.setPlayState = function(toggle){
					$(play).removeClass('disabled');
				if (toggle === 'play') {
					$(play).html('');
					$(play).click(function () {
						song.play();
					});
				}
				if (toggle === 'pause') {
					$(play).html('');
					$(play).click(function () {
						song.pause();
					});
				}
			};
			$(song).on('play', function(){play.setPlayState('pause');});
			$(song).on('canplay', function(){play.setPlayState('play');});
			$(song).on('pause', function(){play.setPlayState('play');});
			var timeout = 0;
			var loadCheck = setInterval(function() {
				if(isNaN(song.duration) === false){
					play.setPlayState('play');
					clearInterval(loadCheck);
					return true;
				}
				if(song.networkState === 3 || timeout === 75){
					load_error();
					clearInterval(loadCheck);
					return false;
				}
				timeout++;
			}, 50);

			$(player).append(play);
		};
		var addSeek = function() {
			var seek = document.createElement('input');
				$(seek).attr({
					'type': 'range',
					'min': 0,
					'value': 0,
					'class': 'seek'
				});
			seek.progress = function () {
				var bg = 'rgba(223, 240, 216, 1) 0%';
				bg += ', rgba(223, 240, 216, 1) ' + ((song.currentTime/song.duration) * 100) + '%';
				bg += ', rgba(223, 240, 216, 0) ' + ((song.currentTime/song.duration) * 100) + '%';
				for (var i=0; i<song.buffered.length; i++){
					if (song.buffered.end(i) > song.currentTime && isNaN(song.buffered.end(i)) === false && isNaN(song.buffered.start(i)) === false){
						var bufferedstart;
						var bufferedend;
						if (song.buffered.end(i) < song.duration) {
							bufferedend = ((song.buffered.end(i)/song.duration) * 100);
						}
						else {
							bufferedend = 100;
						}
						if (song.buffered.start(i) > song.currentTime){
							bufferedstart = ((song.buffered.start(i)/song.duration) * 100);
						}
						else {
							bufferedstart = ((song.currentTime/song.duration) * 100);
						}
						bg += ', rgba(217, 237, 247, 0) ' + bufferedstart + '%';
						bg += ', rgba(217, 237, 247, 1) ' + bufferedstart + '%';
						bg += ', rgba(217, 237, 247, 1) ' + bufferedend + '%';
						bg += ', rgba(217, 237, 247, 0) ' + bufferedend + '%';
					}
				}
				$(seek).css('background', '-webkit-linear-gradient(left, ' + bg + ')');
				//These may be re-enabled when/if other browsers support the background like webkit
				//$(seek).css('background','-o-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','-moz-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','-ms-linear-gradient(left,  ' + bg + ')');
				//$(seek).css('background','linear-gradient(to right,  ' + bg + ')');
				$(seek).css('background-color', '#ddd');
			};
			seek.set = function () {
				$(seek).val(song.currentTime);
				seek.progress();
			};
			seek.slide = function () {
				song.currentTime = $(seek).val();
				seek.progress();
			};
			seek.init = function () {
				$(seek).attr({
					'max': song.duration,
					'step': song.duration / 100
				});
				seek.set();
			};
			seek.reset = function () {
				$(seek).val(0);
				song.currentTime = $(seek).val();
				if(!song.loop){song.pause();}
				else {song.play();}
			};
			var seek_wrapper = document.createElement('div');
				$(seek_wrapper).addClass('btn disabled span3');

			$(seek_wrapper).append(seek);
			$(seek).on('change', seek.slide);
			$(song).on('timeupdate', seek.init);
			$(song).on('loadedmetadata', seek.init);
			$(song).on('loadeddata', seek.init);
			$(song).on('progress', seek.init);
			$(song).on('canplay', seek.init);
			$(song).on('canplaythrough', seek.init);
			$(song).on('ended', seek.reset);
			if(song.readyState > 0){
				seek.init();
			}
			$(player).append(seek_wrapper);
		};
		var addTime = function() {
			var time = document.createElement('a');
				$(time).addClass('btn span3');
				$(time).tooltip({'container': 'body', 'placement': 'right', 'html': true});
			time.twodigit = function (myNum) {
				return ("0" + myNum).slice(-2);
			};
			time.timesplit = function (a) {
				if (isNaN(a)){return '';}
				var hours = Math.floor(a / 3600);
				var minutes = Math.floor(a / 60) - (hours * 60);
				var seconds = Math.floor(a) - (hours * 3600) - (minutes * 60);
				var timeStr = time.twodigit(minutes) + ':' + time.twodigit(seconds);
				if (hours > 0) {
					timeStr = hours + ':' + timeStr;
				}
				return timeStr;
			};
			time.showtime = function () {
				$(time).html(time.timesplit(song.duration));
				$(time).attr({'title': 'Click to Reset
Position: ' + (time.timesplit(song.currentTime))});
				if (!song.paused){
					$(time).html(time.timesplit(song.currentTime));
					$(time).attr({'title': 'Click to Reset
Length: ' + (time.timesplit(song.duration))});
				}
				$(time).tooltip('fixTitle');
			};
			$(time).click(function () {
				song.pause();
				song.currentTime = 0;
				time.showtime();
				$(time).tooltip('fixTitle');
				$(time).tooltip('show');
			});
			$(time).tooltip('show');
			$(song).on('loadedmetadata', time.showtime);
			$(song).on('loadeddata', time.showtime);
			$(song).on('progress', time.showtime);
			$(song).on('canplay', time.showtime);
			$(song).on('canplaythrough', time.showtime);
			$(song).on('timeupdate', time.showtime);
			if(song.readyState > 0){
				time.showtime();
			}
			else {
				$(time).html('');
			}
			$(player).append(time);
		};
		var addMute = function() {
			var mute = document.createElement('button');
				$(mute).addClass('btn span2');
			mute.checkVolume = function () {
				if (song.volume > 0.5 && !song.muted) {
					$(mute).html('');
				} else if (song.volume < 0.5 && song.volume > 0 && !song.muted) {
					$(mute).html('');
				} else {
					$(mute).html('');
				}
			};
			mute.click(function () {
				if (song.muted) {
					song.muted = false;
					song.volume = song.oldvolume;
				} else {
					song.muted = true;
					song.oldvolume = song.volume;
					song.volume = 0;
				}
				mute.checkVolume();
			});
			mute.checkVolume();
			$(song).on('volumechange', mute.checkVolume);
			$(player).append(mute);
		};
		var addVolume = function() {
			var volume = document.createElement('input');
				$(volume).attr({
					'type': 'range',
					'min': 0,
					'max': 1,
					'step': 1 / 100,
					'value': 1
				});
			volume.slide = function () {
				song.muted = false;
				song.volume = $(volume).val();
			};
			volume.set = function () {
				$(volume).val(song.volume);
			};
			var vol_wrapper = document.createElement('div');
				$(vol_wrapper).addClass('btn disabled span3');
			$(vol_wrapper).append(volume);
			$(volume).on("change", volume.slide);
			$(song).on('volumechange', volume.set);
			$(player).append(vol_wrapper);
		};
		var addAlbumArt = function() {
			var albumArt = document.createElement('img');
				$(albumArt).addClass('thumbnail');
				$(albumArt).attr('src', $(song).data('infoAlbumArt'));
			$(data_sec).append(albumArt);
		};
		var addInfo = function(title, dataId) {
			var row = document.createElement('tr');
			var head = document.createElement('th');
			var data = document.createElement('td');
			$(head).html(title);
			$(data).html($(song).data(dataId));
			$(row).append(head);
			$(row).append(data);
			$(data_table).append(row);
		};
		var addData = function() {
			if (typeof($(song).data('infoAlbumArt')) !== 'undefined'){ addAlbumArt();}
			if (typeof($(song).data('infoArtist')) !== 'undefined'){ addInfo('Artist', 'infoArtist');}
			if (typeof($(song).data('infoTitle')) !== 'undefined'){ addInfo('Title', 'infoTitle');}
			if (typeof($(song).data('infoAlbumTitle')) !== 'undefined'){ addInfo('Album', 'infoAlbumTitle');}
			if (typeof($(song).data('infoLabel')) !== 'undefined'){ addInfo('Label', 'infoLabel');}
			if (typeof($(song).data('infoYear')) !== 'undefined'){ addInfo('Year', 'infoYear');}
			if ($(data_table).html() !== ""){
				$(data_sec).append(data_table);
				$(player_box).append(data_toggle);
				$(player_box).append(data_sec);
			}
		};
		var addPlayer = function() {
			if ($(song).data('play') !== 'off'){ addPlay();}
			if ($(song).data('seek') !== 'off'){ addSeek();}
			if ($(song).data('time') !== 'off'){ addTime();}
			if ($(song).data('mute') !== 'off'){ addMute();}
			if ($(song).data('volume') !== 'off'){ addVolume();}
			$(player_box).append(player);
		};
		var addAttribution = function() {
			var infoAtt = $('');
			if (typeof($(song).data('infoAttLink')) !== 'undefined'){
				var infoAttLink = $('');
				infoAttLink.attr('href', $(song).data('infoAttLink'));
				infoAttLink.html($(song).data('infoAtt'));
				infoAtt.append(infoAttLink);
			}
			else {
				infoAtt.html($(song).data('infoAtt'));
			}
			$(player_box).append(infoAtt);
		};
		var fillPlayerBox = function() {
			addData();
			addPlayer();
			if (typeof($(song).data('infoAtt')) !== 'undefined'){ addAttribution();}
		};
		fillPlayerBox();
		$(song).on('error', function(){
			load_error();
		});
		return player_box;
	});
});<|endoftext|>


<commit_before>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

number.prototype.getHex = function()
{
	var hexString = "";
	var quotient = new number(this.positive, this.value);
	var divisor = new number( true, 16 );

	for(var i = 0; i < this.value.length; i++)
	{
		var result = quotient.divideBy( divisor );
		quotient = result.quotient;
		hexString = numVals[result.remainder] + hexString;
	}

	return hexString;
}

function complexNumber( realPositive, realValue, iPositive, iValue)
{
	this.real = new number( realPositive, realValue );
	this.i = new number( iPositive, iValue );
	this.toString = function()
	{
		var realSign = this.real.positive ? "+" : "-";
		var iSign = this.i.positive ? "+" : "-";
		return realSign + this.real.value + iSign + this.i.value + "i";
	}
}

complexNumber.prototype.plus = function(otherComplexNum)
{
	var newReal = this.real.plus(otherComplexNum.real);
	var newI = this.i.plus(otherComplexNum.i);

	return new complexNumber( newReal.positive, newReal.value, newI.positive, newI.value );
}

complexNumber.prototype.minus = function(otherComplexNum)
{
	var newReal = this.real.minus(otherComplexNum.real);
	var newI = this.i.minus(otherComplexNum.i);

	return new complexNumber( newReal.positive, newReal.value, newI.positive, newI.value );
}
<commit_msg>Update number.js<commit_after>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

number.prototype.getHex = function()
{
	var hexString = "";
	var quotient = new number(this.positive, this.value);
	var divisor = new number( true, 16 );

	for(var i = 0; i < this.value.length; i++)
	{
		var result = quotient.divideBy( divisor );
		quotient = result.quotient;
		hexString = numVals[result.remainder] + hexString;
	}

	return hexString;
}
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';

import local from '../utilities/local';

const REQUEST_METHODS = {
  DELETE: 'DELETE',
  GET: 'GET',
  PATCH: 'PATCH',
  POST: 'POST',
};

class Base {
  constructor () {
    const { host, origin } = global.window.location;

    this.baseURL = `${origin}/api`;
    this.websocketBaseURL = `wss://${host}/api`;
    this.bearerToken = local.getItem('auth_token');
  }

  static _request (method, endpoint, body, overrideHeaders) {
    const credentials = 'same-origin';
    const { GET } = REQUEST_METHODS;
    const headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      ...overrideHeaders,
    };
    const requestAttrs = method === GET
      ? { credentials, method, headers }
      : { credentials, method, body, headers };

    return fetch(endpoint, requestAttrs)
      .then((response) => {
        return response.json()
          .then((jsonResponse) => {
            if (response.ok) {
              return jsonResponse;
            }

            const error = new Error(response.statusText);
            error.error = jsonResponse.error;
            error.message = jsonResponse;
            error.response = jsonResponse;
            error.status = response.status;

            throw error;
          });
      });
  }

  static post (endpoint, body = {}, overrideHeaders = {}) {
    const { POST } = REQUEST_METHODS;

    return Base._request(POST, endpoint, body, overrideHeaders);
  }

  endpoint (pathname) {
    return this.baseURL + pathname;
  }

  setBearerToken (bearerToken) {
    this.bearerToken = bearerToken;
  }

  authenticatedDelete (endpoint, overrideHeaders = {}) {
    const { DELETE } = REQUEST_METHODS;

    return this._authenticatedRequest(DELETE, endpoint, {}, overrideHeaders);
  }

  authenticatedGet (endpoint, overrideHeaders = {}) {
    const { GET } = REQUEST_METHODS;

    return this._authenticatedRequest(GET, endpoint, {}, overrideHeaders);
  }

  authenticatedPatch (endpoint, body = {}, overrideHeaders = {}) {
    const { PATCH } = REQUEST_METHODS;

    return this._authenticatedRequest(PATCH, endpoint, body, overrideHeaders);
  }

  authenticatedPost (endpoint, body = JSON.stringify({}), overrideHeaders = {}) {
    const { POST } = REQUEST_METHODS;

    return this._authenticatedRequest(POST, endpoint, body, overrideHeaders);
  }

  _authenticatedHeaders = (headers) => {
    return {
      ...headers,
      Authorization: `Bearer ${this.bearerToken}`,
    };
  }

  _authenticatedRequest(method, endpoint, body, overrideHeaders) {
    const headers = this._authenticatedHeaders(overrideHeaders);

    return Base._request(method, endpoint, body, headers);
  }
}

export default Base;

<commit_msg>Improve format of delete requests (#1258)<commit_after>import fetch from 'isomorphic-fetch';

import local from '../utilities/local';

const DEFAULT_BODY = JSON.stringify({});
const REQUEST_METHODS = {
  DELETE: 'DELETE',
  GET: 'GET',
  PATCH: 'PATCH',
  POST: 'POST',
};

class Base {
  constructor () {
    const { host, origin } = global.window.location;

    this.baseURL = `${origin}/api`;
    this.websocketBaseURL = `wss://${host}/api`;
    this.bearerToken = local.getItem('auth_token');
  }

  static _handleResponse (response, jsonResponse) {
    if (response.ok) {
      return jsonResponse;
    }

    const error = new Error(response.statusText);
    error.error = jsonResponse.error;
    error.message = jsonResponse;
    error.response = jsonResponse;
    error.status = response.status;

    throw error;
  }

  static _sendRequest (endpoint, params) {
    return fetch(endpoint, params)
      .then((response) => {
        return response.json()
          .then((jsonResponse) => {
            return Base._handleResponse(response, jsonResponse);
          });
      });
  }

  static _deleteRequest (endpoint, headers) {
    const credentials = 'same-origin';
    const { DELETE } = REQUEST_METHODS;
    const requestAttrs = { credentials, method: DELETE, headers };

    return Base._sendRequest(endpoint, requestAttrs);
  }

  static _request (method, endpoint, body, overrideHeaders) {
    const credentials = 'same-origin';
    const { GET } = REQUEST_METHODS;
    const headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      ...overrideHeaders,
    };
    const requestAttrs = method === GET
      ? { credentials, method, headers }
      : { credentials, method, body, headers };

    return Base._sendRequest(endpoint, requestAttrs);
  }

  static post (endpoint, body = {}, overrideHeaders = {}) {
    const { POST } = REQUEST_METHODS;

    return Base._request(POST, endpoint, body, overrideHeaders);
  }

  endpoint (pathname) {
    return this.baseURL + pathname;
  }

  setBearerToken (bearerToken) {
    this.bearerToken = bearerToken;
  }

  authenticatedDelete (endpoint, overrideHeaders = {}) {
    const headers = this._authenticatedHeaders(overrideHeaders);

    return Base._deleteRequest(endpoint, headers);
  }

  authenticatedGet (endpoint, overrideHeaders = {}) {
    const { GET } = REQUEST_METHODS;

    return this._authenticatedRequest(GET, endpoint, {}, overrideHeaders);
  }

  authenticatedPatch (endpoint, body = {}, overrideHeaders = {}) {
    const { PATCH } = REQUEST_METHODS;

    return this._authenticatedRequest(PATCH, endpoint, body, overrideHeaders);
  }

  authenticatedPost (endpoint, body = DEFAULT_BODY, overrideHeaders = {}) {
    const { POST } = REQUEST_METHODS;

    return this._authenticatedRequest(POST, endpoint, body, overrideHeaders);
  }

  _authenticatedHeaders = (headers) => {
    return {
      ...headers,
      Authorization: `Bearer ${this.bearerToken}`,
    };
  }

  _authenticatedRequest(method, endpoint, body, overrideHeaders) {
    const headers = this._authenticatedHeaders(overrideHeaders);

    return Base._request(method, endpoint, body, headers);
  }
}

export default Base;

<|endoftext|>


<commit_before>var locomotivePrimus = {
    boot: {}
};

locomotivePrimus.boot.httpServer = function (port, address, options)
{
    var http = require('http');

    if (typeof address === 'object')
    {
        options = address;
        address = undefined;
    }
    else if (typeof port === 'object')
    {
        options = port;
        address = undefined;
        port    = undefined;
    }

    options = options || {};
    port    = port || options.port || 3000;
    address = address || options.address || '0.0.0.0';

    return function httpServer(done)
    {
        this.server = http.createServer(this.express);
        this.server.listen(port, address, function () {
            var addr = this.address();
            console.info('HTTP server listening on %s:%d', addr.address, addr.port);
            return done();
        });
    };
};

locomotivePrimus.boot.httpServerCluster = function (port, address, options)
{
    var os = require('os'),
        http = require('http'),
        cluster = require('cluster'),
        debug = require('debug')('locomotive');

    if (typeof address === 'object')
    {
        options = address;
        address = undefined;
    }
    else if (typeof port === 'object')
    {
        options = port;
        address = undefined;
        port    = undefined;
    }

    options = options || {};
    port    = port || options.port || 3000;
    address = address || options.address || '0.0.0.0';

    var size = options.size || os.cpus().length;

    return function httpServerCluster(done)
    {
        if (cluster.isMaster)
        {
            console.info('[m] Creating HTTP server cluster with %d workers', size);

            for (var i = 0; i < size; ++i)
            {
                debug('spawning worker process %d', (i + 1));
                cluster.fork();
            }

            cluster.on('fork', function (worker) {
                debug('worker %s spawned', worker.id);
            });
            cluster.on('online', function (worker) {
                debug('worker %s online', worker.id);
            });
            cluster.on('listening', function (worker, addr) {
                debug('worker %s listening on %s:%d', worker.id, addr.address, addr.port);
            });
            cluster.on('disconnect', function (worker) {
                debug('worker %s disconnected', worker.id);
            });
            cluster.on('exit', function (worker, code, signal)
            {
                debug('worker %s died (%s)', worker.id, signal || code);
                if (!worker.suicide)
                {
                    debug('restarting worker');
                    cluster.fork();
                }
            });
        }
        else
        {
            this.server = http.createServer(this.express);
            this.server.listen(port, address, function () {
                var addr = this.address();
                console.info('[w:%d] HTTP server listening on %s:%d', cluster.worker.id, addr.address, addr.port);
                return done();
            });
        }
    };
};

locomotivePrimus.boot.primusServer = function (Primus, options)
{
    options = options || {};

    var primusOptions   = options.primus || { transformer: 'sockjs' };
    var clientLocation  = options.clientLocation || '/public/js/libs/primus-client.js';
    var authorizeFunc   = options.authorizeFunction || null;
    var sparkHandler    = options.sparkHandler || function (spark) {};

    return function primusServer()
    {
        this.primus = new Primus(this.server, primusOptions);
        this.primus.save(clientLocation);
        if (authorizeFunc !== null && typeof authorizeFunc === 'function')
            this.primus.authorize(authorizeFunc.bind(this));

        this.primus.on('connection', sparkHandler.bind(this));
    };
};

module.exports = locomotivePrimus;
<commit_msg>Added disconnectionHandler option<commit_after>var locomotivePrimus = {
    boot: {}
};

locomotivePrimus.boot.httpServer = function (port, address, options)
{
    var http = require('http');

    if (typeof address === 'object')
    {
        options = address;
        address = undefined;
    }
    else if (typeof port === 'object')
    {
        options = port;
        address = undefined;
        port    = undefined;
    }

    options = options || {};
    port    = port || options.port || 3000;
    address = address || options.address || '0.0.0.0';

    return function httpServer(done)
    {
        this.server = http.createServer(this.express);
        this.server.listen(port, address, function () {
            var addr = this.address();
            console.info('HTTP server listening on %s:%d', addr.address, addr.port);
            return done();
        });
    };
};

locomotivePrimus.boot.httpServerCluster = function (port, address, options)
{
    var os = require('os'),
        http = require('http'),
        cluster = require('cluster'),
        debug = require('debug')('locomotive');

    if (typeof address === 'object')
    {
        options = address;
        address = undefined;
    }
    else if (typeof port === 'object')
    {
        options = port;
        address = undefined;
        port    = undefined;
    }

    options = options || {};
    port    = port || options.port || 3000;
    address = address || options.address || '0.0.0.0';

    var size = options.size || os.cpus().length;

    return function httpServerCluster(done)
    {
        if (cluster.isMaster)
        {
            console.info('[m] Creating HTTP server cluster with %d workers', size);

            for (var i = 0; i < size; ++i)
            {
                debug('spawning worker process %d', (i + 1));
                cluster.fork();
            }

            cluster.on('fork', function (worker) {
                debug('worker %s spawned', worker.id);
            });
            cluster.on('online', function (worker) {
                debug('worker %s online', worker.id);
            });
            cluster.on('listening', function (worker, addr) {
                debug('worker %s listening on %s:%d', worker.id, addr.address, addr.port);
            });
            cluster.on('disconnect', function (worker) {
                debug('worker %s disconnected', worker.id);
            });
            cluster.on('exit', function (worker, code, signal)
            {
                debug('worker %s died (%s)', worker.id, signal || code);
                if (!worker.suicide)
                {
                    debug('restarting worker');
                    cluster.fork();
                }
            });
        }
        else
        {
            this.server = http.createServer(this.express);
            this.server.listen(port, address, function () {
                var addr = this.address();
                console.info('[w:%d] HTTP server listening on %s:%d', cluster.worker.id, addr.address, addr.port);
                return done();
            });
        }
    };
};

locomotivePrimus.boot.primusServer = function (Primus, options)
{
    options = options || {};

    var primusOptions   = options.primus || { transformer: 'sockjs' };
    var clientLocation  = options.clientLocation || '/public/js/libs/primus-client.js';
    var authorizeFunc   = options.authorizeFunction || null;
    var sparkHandler    = options.sparkHandler || function () {};
    var disconnectionHandler = options.disconnectionHandler || function() {};

    return function primusServer()
    {
        this.primus = new Primus(this.server, primusOptions);
        this.primus.save(clientLocation);
        if (authorizeFunc !== null && typeof authorizeFunc === 'function')
            this.primus.authorize(authorizeFunc.bind(this));

        this.primus.on('connection', sparkHandler.bind(this));
        this.primus.on('disconnection', disconnectionHandler.bind(this));
    };
};

module.exports = locomotivePrimus;
<|endoftext|>


<commit_before>/**
 * Local dependencies
 */
const normalize = require('./algorithms/normalize')
const CryptoKey = require('./CryptoKey')
const CryptoKeyPair = require('./CryptoKeyPair')
const InvalidAccessError = require('./errors/InvalidAccessError')

/**
 * SubtleCrypto
 */
class SubtleCrypto {

  /**
   * encrypt
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  encrypt (algorithm, key, data) {
    return new Promise()
  }

  /**
   * decrypt
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  decrypt (algorithm, key, data) {
    return new Promise()
  }

  /**
   * sign
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  sign (algorithm, key, data) {
    data = data.slice()

    let normalizedAlgorithm = normalize.algorithm('sign', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      if (normalizedAlgorithm.name !== key.algorithm.name) {
        throw new InvalidAccessError('Algorithm does not match key')
      }

      if (!key.usages.includes('sign')) {
        throw new InvalidAccessError('Key usages must include "sign"')
      }

      let result = normalizedAlgorithm.sign(key, data)

      resolve(result)
    })
  }

  /**
   * verify
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} signature
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  verify (alg, key, signature, data) {
    signature = signature.slice()

    let normalizedAlgorithm = normalize.algorithm('verify', alg)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    data = data.slice()

    return new Promise((resolve, reject) => {
      if (normalizedAlgorithm.name !== key.algorithm.name) {
        throw new InvalidAccessError('Algorithm does not match key')
      }

      if (!key.usages.includes('verify')) {
        throw new InvalidAccessError('Key usages must include "verify"')
      }

      let result = normalizedAlgorithm.verify(key, signature, data)
      resolve(result)
    })
  }

  /**
   * digest
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  digest (algorithm, data) {
    return new Promise()
  }

  /**
   * generateKey
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  generateKey (algorithm, extractable, keyUsages) {
    let normalizedAlgorithm = normalize.algorithm('generateKey', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      try {
        let result = normalizedAlgorithm.generateKey(algorithm, extractable, keyUsages)

        if (result instanceof CryptoKey) {
          let {type,usages} = result
          let restricted = (type === 'secret' || type === 'private')
          let emptyUsages = (!usages || usages.length === 0)

          if (restricted && emptyUsages) {
            throw new SyntaxError()
          }
        }

        if (result instanceof CryptoKeyPair) {
          let {privateKey:{usages}} = result

          if (!usages || usages.length === 0) {
            throw new SyntaxError()
          }
        }

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * deriveKey
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} baseKey
   * @param {AlgorithmIdentifier} derivedKeyType
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   * @returns {Promise}
   */
  deriveKey (algorithm, baseKey, derivedKeyType, extractable, keyUsages) {
    return new Promise()
  }

  /**
   * deriveBits
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} baseKey
   * @param {number} length
   *
   * @returns {Promise}
   */
  deriveBits (algorithm, baseKey, length) {
    return new Promise()
  }

  /**
   * importKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {BufferSource|JWK} keyData
   * @param {AlgorithmIdentifier} algorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  importKey (format, keyData, algorithm, extractable, keyUsages) {
    let normalizedAlgorithm = normalize.algorithm('importKey', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      if (format === 'raw' || format === 'pkcs8' || format === 'spki') {
        if (keyData instanceof JsonWebKey) {
          throw new TypeError()
        }

        keyData = keyData.slice()
      }

      if (format === 'jwk') {
        if (!(keyData instanceof JsonWebKey)) {
          throw new TypeError()
        }
      }

      try {
        let result = normalizedAlgorithm
          .importKey(format, keyData, algorithm, extractable, keyUsages)

        if (result.type === 'secret' || result.type === 'private') {
          if (!result.usages || result.usages.length === 0) {
            throw new SyntaxError()
          }
        }

        result.extractable = extractable
        result.usages = normalize.usages(usages)

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * exportKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {CryptoKey} key
   *
   * @returns {Promise}
   */
  exportKey (format, key) {
    return new Promise((resolve, reject) => {
      try {
        if (!registeredAlgorithms[key.algorithm.name]) {
          throw new NotSupportedError()
        }

        if (key.extractable === false) {
          throw new InvalidAccessError()
        }

        let result = key.algorithm.exportKey(format, key)

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * wrapKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {CryptoKey} key
   * @param {CryptoKey} wrappingKey
   * @param {AlgorithmIdentifier} wrapAlgorithm
   *
   * @returns {Promise}
   */
  wrapKey (format, key, wrappingKey, wrapAlgorithm) {
    return new Promise()
  }

  /**
   * unwrapKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {BufferSource} wrappedKey
   * @param {CryptoKey} unwrappingKey
   * @param {AlgorithmIdentifier} unwrapAlgorithm
   * @param {AlgorithmIdentifier} unwrappedKeyAlgorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  unwrapKey (format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, exractable, keyUsages) {
    return new Promise()
  }
}

/**
 * Export
 */
module.exports = SubtleCrypto
<commit_msg>refactor(SubtleCrypto): use supportedAlgorithms.normalize<commit_after>/**
 * Local dependencies
 */
const CryptoKey = require('./CryptoKey')
const CryptoKeyPair = require('./CryptoKeyPair')
const supportedAlgorithms = require('./algorithms/supportedAlgorithms')
const InvalidAccessError = require('./errors/InvalidAccessError')

/**
 * SubtleCrypto
 */
class SubtleCrypto {

  /**
   * encrypt
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  encrypt (algorithm, key, data) {
    return new Promise()
  }

  /**
   * decrypt
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  decrypt (algorithm, key, data) {
    return new Promise()
  }

  /**
   * sign
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  sign (algorithm, key, data) {
    data = data.slice()

    let normalizedAlgorithm = supportedAlgorithms.normalize('sign', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      if (normalizedAlgorithm.name !== key.algorithm.name) {
        throw new InvalidAccessError('Algorithm does not match key')
      }

      if (!key.usages.includes('sign')) {
        throw new InvalidAccessError('Key usages must include "sign"')
      }

      let result = normalizedAlgorithm.sign(key, data)

      resolve(result)
    })
  }

  /**
   * verify
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} key
   * @param {BufferSource} signature
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  verify (alg, key, signature, data) {
    signature = signature.slice()

    let normalizedAlgorithm = supportedAlgorithms.normalize('verify', alg)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    data = data.slice()

    return new Promise((resolve, reject) => {
      if (normalizedAlgorithm.name !== key.algorithm.name) {
        throw new InvalidAccessError('Algorithm does not match key')
      }

      if (!key.usages.includes('verify')) {
        throw new InvalidAccessError('Key usages must include "verify"')
      }

      let result = normalizedAlgorithm.verify(key, signature, data)
      resolve(result)
    })
  }

  /**
   * digest
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {BufferSource} data
   *
   * @returns {Promise}
   */
  digest (algorithm, data) {
    return new Promise()
  }

  /**
   * generateKey
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  generateKey (algorithm, extractable, keyUsages) {
    let normalizedAlgorithm = supportedAlgorithms.normalize('generateKey', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      try {
        let result = normalizedAlgorithm.generateKey(algorithm, extractable, keyUsages)

        if (result instanceof CryptoKey) {
          let {type,usages} = result
          let restricted = (type === 'secret' || type === 'private')
          let emptyUsages = (!usages || usages.length === 0)

          if (restricted && emptyUsages) {
            throw new SyntaxError()
          }
        }

        if (result instanceof CryptoKeyPair) {
          let {privateKey:{usages}} = result

          if (!usages || usages.length === 0) {
            throw new SyntaxError()
          }
        }

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * deriveKey
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} baseKey
   * @param {AlgorithmIdentifier} derivedKeyType
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   * @returns {Promise}
   */
  deriveKey (algorithm, baseKey, derivedKeyType, extractable, keyUsages) {
    return new Promise()
  }

  /**
   * deriveBits
   *
   * @description
   *
   * @param {AlgorithmIdentifier} algorithm
   * @param {CryptoKey} baseKey
   * @param {number} length
   *
   * @returns {Promise}
   */
  deriveBits (algorithm, baseKey, length) {
    return new Promise()
  }

  /**
   * importKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {BufferSource|JWK} keyData
   * @param {AlgorithmIdentifier} algorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  importKey (format, keyData, algorithm, extractable, keyUsages) {
    let normalizedAlgorithm = normalize.algorithm('importKey', algorithm)

    if (normalizedAlgorithm instanceof Error) {
      return Promise.reject(normalizedAlgorithm)
    }

    return new Promise((resolve, reject) => {
      if (format === 'raw' || format === 'pkcs8' || format === 'spki') {
        if (keyData instanceof JsonWebKey) {
          throw new TypeError()
        }

        keyData = keyData.slice()
      }

      if (format === 'jwk') {
        if (!(keyData instanceof JsonWebKey)) {
          throw new TypeError()
        }
      }

      try {
        let result = normalizedAlgorithm
          .importKey(format, keyData, algorithm, extractable, keyUsages)

        if (result.type === 'secret' || result.type === 'private') {
          if (!result.usages || result.usages.length === 0) {
            throw new SyntaxError()
          }
        }

        result.extractable = extractable
        result.usages = normalize.usages(usages)

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * exportKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {CryptoKey} key
   *
   * @returns {Promise}
   */
  exportKey (format, key) {
    return new Promise((resolve, reject) => {
      try {
        if (!registeredAlgorithms[key.algorithm.name]) {
          throw new NotSupportedError()
        }

        if (key.extractable === false) {
          throw new InvalidAccessError()
        }

        let result = key.algorithm.exportKey(format, key)

        resolve(result)
      } catch (error) {
        return reject(error)
      }
    })
  }

  /**
   * wrapKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {CryptoKey} key
   * @param {CryptoKey} wrappingKey
   * @param {AlgorithmIdentifier} wrapAlgorithm
   *
   * @returns {Promise}
   */
  wrapKey (format, key, wrappingKey, wrapAlgorithm) {
    return new Promise()
  }

  /**
   * unwrapKey
   *
   * @description
   *
   * @param {KeyFormat} format
   * @param {BufferSource} wrappedKey
   * @param {CryptoKey} unwrappingKey
   * @param {AlgorithmIdentifier} unwrapAlgorithm
   * @param {AlgorithmIdentifier} unwrappedKeyAlgorithm
   * @param {Boolean} extractable
   * @param {Array} keyUsages
   *
   * @returns {Promise}
   */
  unwrapKey (format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, exractable, keyUsages) {
    return new Promise()
  }
}

/**
 * Export
 */
module.exports = SubtleCrypto
<|endoftext|>


<commit_before>
var fs = require('fs');
var util = require('util');
var stream = require('stream');
var endpoint = require('endpoint');

function BundleStream(box, startpath, acquired) {
  stream.Transform.call(this);

  this.box = box;

  this._acquired = acquired;
  this._query = [ startpath ];

  this._first = true;
  this._prepend = false;
  this._append = false;

  this._file = null;
  this._next();
}
util.inherits(BundleStream, stream.Transform);
module.exports = BundleStream;

BundleStream.prototype._transform = function (chunk, send, callback) {
  this._writeHeader(send);
  this._writeFileEnd(send);
  this._writeFileStart(send);

  callback(null, chunk);
};

BundleStream.prototype._flush = function (send, callback) {
  this._writeFileEnd(send);
  this._writeFooter(send);

  callback(null);
};

BundleStream.prototype._writeHeader = function (send) {
  if (!this._first) return;
  this._first = false;

  send(new Buffer('<module>'));
};

BundleStream.prototype._writeFooter = function (send) {
  send(new Buffer('</module>'));
};

BundleStream.prototype._writeFileStart = function (send) {
  if (!this._prepend) return;
  this._prepend = false;

  send(new Buffer('<file>\n'));
};

BundleStream.prototype._writeFileEnd = function (send) {
  if (!this._append) return;
  this._append = false;

  send(new Buffer('</file>\n'));
};

// add dependencies to query
BundleStream.prototype._push = function (dependencies) {
  var keys = Object.keys(dependencies);
  var filepath;

  for (var i = 0; i < keys.length; i++) {
    filepath = dependencies[ keys[i] ];

    if (this._acquired.indexOf(filepath) === -1) {
      this._query.push(filepath);
    }
  }
};

// start next file stream
BundleStream.prototype._next = function () {
  var self = this;

  // first flag, set to false when the first chunk is writen
  var first = this._first;

  // prepear for read, by setting flags
  if (!first) this._append = true;
  this._prepend = true;

  // this._flush will be called if there are no more files in the query
  if (this._query.length === 0) return this.emit('finish');

  // get the next filepath
  var filepath = this._query.shift();
  var realpath = this.box._realpath(filepath);

  // create a new file read stream
  this._file = fs.createReadStream(realpath);

  // if dependencies for this file hasn't been resolved before, buffer the
  // result and resolve/save them.
  if (this.box._getDependencies(filepath) === null) {
    this._file.pipe(endpoint(function (err, content) {
      // this error will be emitted by the other pipe, so just ignore
      if (err) return;

      // construct resolve map from filepath and file content
      self.box._scanFile(filepath, content, function (err, resolveMap) {
        if (err) return self.emit('error', err);

        // save resolved dependencies in cache
        self.box._setDependencies(filepath, resolveMap);

        nextFile();
      });
    }));
  } else {
    this._file.once('end', nextFile);
  }

  // pipe the file to this stream, thereby calling this._transform
  // since it is unknown if there are more dependencies, the end event is not
  // relayed.
  this._file.pipe(this, {end: false});

  // once the file read is done, dependencies should be added to the query
  // and the next file should be read
  function nextFile() {
    self._push(self.box._getDependencies(filepath));
    self._next();
  }
};
<commit_msg>[fix] use standard WriteStream.end<commit_after>
var fs = require('fs');
var util = require('util');
var stream = require('stream');
var endpoint = require('endpoint');

function BundleStream(box, startpath, acquired) {
  stream.Transform.call(this);

  this.box = box;

  this._acquired = acquired;
  this._query = [ startpath ];

  this._first = true;
  this._prepend = false;
  this._append = false;

  this._file = null;
  this._next();
}
util.inherits(BundleStream, stream.Transform);
module.exports = BundleStream;

BundleStream.prototype._transform = function (chunk, send, callback) {
  this._writeHeader(send);
  this._writeFileEnd(send);
  this._writeFileStart(send);

  callback(null, chunk);
};

BundleStream.prototype._flush = function (send, callback) {
  this._writeFileEnd(send);
  this._writeFooter(send);

  callback(null);
};

BundleStream.prototype._writeHeader = function (send) {
  if (!this._first) return;
  this._first = false;

  send(new Buffer('<module>'));
};

BundleStream.prototype._writeFooter = function (send) {
  send(new Buffer('</module>'));
};

BundleStream.prototype._writeFileStart = function (send) {
  if (!this._prepend) return;
  this._prepend = false;

  send(new Buffer('<file>\n'));
};

BundleStream.prototype._writeFileEnd = function (send) {
  if (!this._append) return;
  this._append = false;

  send(new Buffer('</file>\n'));
};

// add dependencies to query
BundleStream.prototype._push = function (dependencies) {
  var keys = Object.keys(dependencies);
  var filepath;

  for (var i = 0; i < keys.length; i++) {
    filepath = dependencies[ keys[i] ];

    if (this._acquired.indexOf(filepath) === -1) {
      this._query.push(filepath);
    }
  }
};

// start next file stream
BundleStream.prototype._next = function () {
  var self = this;

  // first flag, set to false when the first chunk is writen
  var first = this._first;

  // prepear for read, by setting flags
  if (!first) this._append = true;
  this._prepend = true;

  // this._flush will be called if there are no more files in the query
  if (this._query.length === 0) return this.end();

  // get the next filepath
  var filepath = this._query.shift();
  var realpath = this.box._realpath(filepath);

  // create a new file read stream
  this._file = fs.createReadStream(realpath);

  // if dependencies for this file hasn't been resolved before, buffer the
  // result and resolve/save them.
  if (this.box._getDependencies(filepath) === null) {
    this._file.pipe(endpoint(function (err, content) {
      // this error will be emitted by the other pipe, so just ignore
      if (err) return;

      // construct resolve map from filepath and file content
      self.box._scanFile(filepath, content, function (err, resolveMap) {
        if (err) return self.emit('error', err);

        // save resolved dependencies in cache
        self.box._setDependencies(filepath, resolveMap);

        nextFile();
      });
    }));
  } else {
    this._file.once('end', nextFile);
  }

  // pipe the file to this stream, thereby calling this._transform
  // since it is unknown if there are more dependencies, the end event is not
  // relayed.
  this._file.pipe(this, {end: false});

  // once the file read is done, dependencies should be added to the query
  // and the next file should be read
  function nextFile() {
    self._push(self.box._getDependencies(filepath));
    self._next();
  }
};
<|endoftext|>